package cn.net.connor.std.processedit.ldy;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.tree.DefaultMutableTreeNode;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.common.AIFTreeNode;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.common.organization.OrgTreePanel;
import com.teamcenter.rac.common.organization.OrganizationTree;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentGroupMember;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

public class SelectUserDialog extends AbstractAIFDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton b_ok;
	private JButton b_cel;
	private JButton add;
	private JButton remove;
	private OrganizationTree tree;
	private JTree projectTree;
	private JList<String> l_user;
	private DefaultListModel<String> lm_user;
	private JTextField editPropMap;
//	private String group;
	private boolean isMulti;
	private JTable table;
	private int colIndex;
	private int[] rowIndex;
	private TCComponentProject project;
	private HashMap<String, TCComponentUser> userMap;

	public SelectUserDialog(JTextField editPropMap, boolean isMulti) throws Exception {
		super(true);
		this.editPropMap = editPropMap;
		this.isMulti = isMulti;
		initUI();
	}

	private String getValue() {
		String val = "";
		if (editPropMap != null) {
			val = editPropMap.getText();
		} else if (table != null) {
			val = (String) table.getValueAt(rowIndex[0], colIndex);
		}
		return val;
	}

	private void setValue(String text) {
		if (editPropMap != null) {
			editPropMap.setText(text);
		} else if (table != null) {
			for(int i : rowIndex)
				table.setValueAt(text, i, colIndex);
		}
	}

	public SelectUserDialog(JTable table, boolean isMulti, int[] rowIndex, int colIndex, TCComponentProject projectID) throws Exception {
		super(true);
		this.table = table;
		this.isMulti = isMulti;
		this.colIndex = colIndex;
		this.rowIndex = rowIndex;
		this.project = projectID;
		initUI();
	}

	public SelectUserDialog(JTable table, int[] rowIndex, int colIndex, HashMap<String, TCComponentUser> userMap) throws Exception {
		super(true);
		this.table = table;
		this.colIndex = colIndex;
		this.rowIndex = rowIndex;
		this.userMap = userMap;
		initUI();
	}

	private void initUI() throws Exception {
		this.setTitle("选择人员");
		this.setLayout(new BorderLayout());
		int pweight = 440, pheight = 480, mweight = 280, mheight = 320;
		if (isMulti) {
//			this.setPreferredSize(new Dimension(640, 480));
//			this.setMinimumSize(new Dimension(480, 320));
			pweight = 640;
			mweight = 480;
		}
		if(project != null) {
			pheight = 700;
			mheight = 700;
		}
		this.setPreferredSize(new Dimension(pweight, pheight));
		this.setMinimumSize(new Dimension(mweight, mheight));
		OrgTreePanel orgPanel = new OrgTreePanel((TCSession) AIFUtility.getCurrentApplication().getSession());
		this.tree = orgPanel.getOrgTree();

		if(project != null) {
			JPanel panel = new JPanel(new PropertyLayout());
			panel.add("1.1.center.center", orgPanel);
			panel.add("2.1.center.center", initProjectPanel(orgPanel));
//			FlowLayout flow = new FlowLayout();
//			flow.setAlignOnBaseline(true);
//			JPanel panel = new JPanel(flow);
//			panel.add(orgPanel);
//			panel.add(initProjectPanel(orgPanel));
			this.add(BorderLayout.WEST, panel);
		}else {
			this.add(BorderLayout.CENTER, orgPanel);
		}
		this.add(BorderLayout.SOUTH, initBtnPanel());
		if (isMulti) {
			JPanel lp = initListPanel();
			this.add(BorderLayout.EAST, lp);
			initData();
		}
		addListeners();
		this.setAlwaysOnTop(true);
	}

	private void initData() {
		String text = getValue();
		if (text.isEmpty()) {
			return;
		}
		String[] split = text.split(",");
		for (int i = 0; i < split.length; i++) {
			lm_user.addElement(split[i]);
		}
	}

	private JPanel initListPanel() {
		JPanel panel = new JPanel(new BorderLayout());
		FlowLayout flow = new FlowLayout();
		flow.setVgap(100);
		JPanel btnPanel = new JPanel(flow);
		btnPanel.add(this.add);
//		btnPanel.add("2.1.center.center", this.remove);
		this.lm_user = new DefaultListModel<>();
		this.l_user = new JList<>(lm_user);
		l_user.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.l_user.setCellRenderer(new DeleteListRenderer(l_user));
		JScrollPane scroll = new JScrollPane(l_user);
		scroll.setPreferredSize(new Dimension(200, 0));
//		this.add.setPreferredSize(new Dimension(50, 30));
		panel.add(BorderLayout.WEST, btnPanel);
		panel.add(BorderLayout.CENTER, scroll);
		return panel;
	}

	private JPanel initBtnPanel() {
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
		this.b_ok = new JButton("确定");
		this.b_cel = new JButton("取消");
		this.add = new JButton("+");
		this.remove = new JButton("-");
		panel.add(b_ok);
		panel.add(b_cel);
		return panel;
	}

	private JScrollPane initProjectPanel(OrgTreePanel orgPanel) throws Exception {//TODO
		Dimension orgDimension = orgPanel.getPreferredSize();
		orgPanel.setPreferredSize(new Dimension(orgDimension.width*2, orgDimension.height-100));
		DefaultMutableTreeNode root = new DefaultMutableTreeNode(project.getProjectID(), true);
		projectTree = new JTree(root);

		List<Object> team = project.getTeam();
		TCComponent[] members = (TCComponent[])team.get(0);
		for(TCComponent c : members) {
			if(c instanceof TCComponentGroupMember) {
				TCComponentGroupMember member = (TCComponentGroupMember)c;
				DefaultMutableTreeNode childRoot = new DefaultMutableTreeNode(member, true);
				root.add(childRoot);
			}
		}
		
		projectTree.setPreferredSize(new Dimension(orgDimension.width*2, orgDimension.height/2));
//		projectTree.setMaximumSize(new Dimension(orgDimension.width*2, orgDimension.height/2));
		JScrollPane projectPane = new JScrollPane(projectTree);
		return projectPane;
	}

	private TCComponentUser getSelectUser() throws Exception {
//		Object[] comps = tree.getSelectedOrgObjects();
		AIFTreeNode[] comps = tree.getSelectedNodes();
//		System.out.println("comps:"+(comps==null));
		if (comps == null) {
			if(projectTree == null)
				return null;
			else if(projectTree.getSelectionModel() == null)
				return null;
			else if(projectTree.getLastSelectedPathComponent() == null)
				return null;
			DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) projectTree.getLastSelectedPathComponent();
			Object selectObject = selectNode.getUserObject();
			if(selectObject instanceof TCComponentGroupMember) {
//				String member = ((TCComponentGroupMember) selectObject).toString();
//				if(member.indexOf(".")>0)
//					group = member.substring(0, member.indexOf("."));
//				else
//					group = member.substring(0, member.indexOf("/"));
				TCComponentUser user = ((TCComponentGroupMember) selectObject).getUser();
				if (user != null) {
					return user;
				}
			}else
				return null;
		}
//		System.out.println("comps:"+comps.length);
		for (int i = 0; i < comps.length; i++) {
//			OrgObject comp = (OrgObject) comps[i];
			TCComponent gm = (TCComponent) comps[i].getContextComponent().getComponent();
//			System.out.println("gm:"+gm);
			if (gm != null && (gm instanceof TCComponentGroupMember)) {
				TCComponentUser user = ((TCComponentGroupMember) gm).getUser();
				if (user != null) {
//					group = ((DefaultMutableTreeNode)comps[i].getParent().getParent()).getUserObject().toString();
					return user;
				}
			}
		}
		return null;
	}

	private void addListeners() {
		this.b_cel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				disposeDialog();
			}
		});
		this.b_ok.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					if (isMulti) {
						int size = lm_user.getSize();
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < size; i++) {
							String text = lm_user.getElementAt(i);
							if (text != null) {
								sb.append(text).append(";");
							}
						}
						if (sb.length() > 0) {
							sb.setLength(sb.length() - 1);
						}
						setValue(sb.toString());
					} else {
						TCComponentUser user = getSelectUser();
						if (user != null) {
							String value = user.getUserId() +"/"+ user.getUserName();
							userMap.put(value, user);
							setValue(value);
						} else {
							setValue("");
						}
					}
					disposeDialog();
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});

		tree.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					super.mouseClicked(e);
					if(projectTree != null)
						projectTree.clearSelection();
					if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
						TCComponentUser user = getSelectUser();
						System.out.println("user:"+user);
						if (user != null) {
							if (isMulti) {
								if (!lm_user.contains(user.toString())) {
									lm_user.addElement(user.toString());
								}
							} else {
								String value = user.getUserId() +"/"+ user.getUserName();
								userMap.put(value, user);
								setValue(value);
								disposeDialog();
							}
						}
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});
		if(projectTree != null) {
			projectTree.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					try {
						super.mouseClicked(e);
						tree.clearSelection();
						if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
							TCComponentUser user = getSelectUser();
							if (user != null) {
								if (isMulti) {
									if (!lm_user.contains(user.toString())) {
										lm_user.addElement(user.toString());
									}
								} else {
									String value = user.getUserId() +"/"+ user.getUserName();
									userMap.put(value, user);
									setValue(value);
									disposeDialog();
								}
							}
						}
					} catch (Exception e1) {
						e1.printStackTrace();
						MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
					}
				}
			});
		}
		if(l_user!=null) {
			this.l_user.addMouseListener(new MouseAdapter() {

				@Override
				public void mouseClicked(MouseEvent e) {
					super.mouseClicked(e);
					int ind = l_user.getSelectedIndex();
					if (ind >= 0) {
						lm_user.remove(ind);
					}
				}

				@Override
				public void mouseEntered(MouseEvent e) {
					super.mouseEntered(e);
				}

				@Override
				public void mouseExited(MouseEvent e) {
					super.mouseExited(e);
				}

			});
		}
		this.add.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					TCComponentUser user = getSelectUser();
					System.out.println("user:"+user);
					if (user != null) {
						if (!lm_user.contains(user.toString())) {
							lm_user.addElement(user.toString());
						}
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});
		this.remove.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				disposeDialog();
			}
		});
	}
	private class DeleteListRenderer extends JPanel implements ListCellRenderer<String> {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		JButton btn;
		JLabel label;

		public DeleteListRenderer(final JList<? extends String> list) {
			this.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1));
			this.setBackground(Color.WHITE);
			btn = getDeletetBtn();
			label = new JLabel("");
			this.add(btn);
			this.add(label);

			btn.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					int ind = list.getSelectedIndex();
					System.out.println(ind);
					if (ind >= 0) {
						list.remove(ind);
					}
				}
			});

		}
		@Override
		public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, 
				boolean isSelected, boolean cellHasFocus) {
			label.setText(value);
			return this;
		}
		private JButton getDeletetBtn() {
			ImageIcon icon = new ImageIcon(SelectUserDialog.class.getResource("image/delete.png"));
			JButton btn = new JButton(icon);
			btn.setPreferredSize(new Dimension(23, 23));
			btn.setContentAreaFilled(false);
			btn.setFocusPainted(false);
			btn.setBorderPainted(false);
			btn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			return btn;
		}
	}
}
