package com.connor.jingdiao.handlers;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.connor.jingdiao.util.SqlUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.common.AIFTreeNode;
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.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCComponentGroupMember;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentRole;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

@SuppressWarnings("serial")
public class LoginIPSetDialog extends AbstractAIFDialog {

	private TCSession session;
//	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 JList<String> l_ip;
	private DefaultListModel<String> lm_ip;
	
	private String group;
	private String role;
	private boolean isMulti;
//	private boolean isAll;
	private JTable table;
	private int[] colIndex;
	private int rowIndex;
	private TCComponentProject project;
	private HashMap<String, String[]> ipmap = new HashMap<>();
	private TCComponentDataset model;

	public LoginIPSetDialog(TCSession session, TCComponent model, String[] options) throws Exception {
		super(true);
		this.session = session;
		this.isMulti = true;
		this.model = (TCComponentDataset) model;
		getConn("jdbc:oracle:thin:@" + options[0] + ":1521:" + options[3], options[1], options[2]);
		initUI();
	}

	/*public LoginIPSetDialog(JTable table, String text, int[] colIndex, int rowIndex, TCComponentProject projectID) throws Exception {
		super(true);
		this.table = table;
		this.isMulti = text.contains("M");
		this.isAll = text.contains("A");
		this.colIndex = colIndex;
		this.rowIndex = rowIndex;
		this.project = projectID;
		initUI();
	}*/
	
	private void getConn(String url, String user, String password) throws Exception {
//		Class.forName("oracle.jdbc.driver.OracleDriver");
//		Connection connection = DriverManager.getConnection(url, user, password);
//		connection.setAutoCommit(false);
		Connection connection = SqlUtil.getOracleConnection(url, user, password);
		
		String sql = "select PUSER,IP from CONNOR_USER_IP";
		ArrayList<HashMap<String, Object>> results = SqlUtil.getDBInfo(connection, sql);
		for(HashMap<String, Object> map : results) {
			String ips = ""+map.get("IP");
			if(ips.isEmpty() || ips.equals("null"))
				ipmap.put(""+map.get("PUSER"), new String[] {  });
			else
				ipmap.put(""+map.get("PUSER"), ips.split(","));
			System.out.println("PUSER:"+map.get("PUSER"));
		}
	}
	
	private String getValue() {
		String val = "";
		if (table != null) {
			val = (String) table.getValueAt(rowIndex, colIndex[0]);
		}
		System.out.println("getValue:"+val);
		return val;
	}

	/*private void setValue(String text) {
		System.out.println("setValue:"+text);
		if (table != null) {
			if(isAll) {
				for(int i=0; i<table.getRowCount(); i++) {
					table.setValueAt(text, i, colIndex[0]);
					if (colIndex.length>1)
						table.setValueAt(group, i, colIndex[1]);
				}
			}else {
				table.setValueAt(text, rowIndex, colIndex[0]);
				if (colIndex.length>1)
					table.setValueAt(group, rowIndex, colIndex[1]);
			}
		}
	}*/

	private void initUI() throws Exception {//TODO initUI
		this.setTitle("允许用户登录IP设置");
		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 = 1000;
//			mweight = 480;
		}
		if(project != null) {
			pheight = 1200;
//			mheight = 700;
		}
//		this.setPreferredSize(new Dimension(pweight, pheight));
//		this.setMinimumSize(new Dimension(mweight, mheight));
		OrgTreePanel orgPanel = new OrgTreePanel(session);
		this.tree = orgPanel.getOrgTree();

		this.add(BorderLayout.SOUTH, initBtnPanel());
		JPanel lp = initListPanel();
		/*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);
		}
		if (isMulti) {
		}
		this.add(BorderLayout.EAST, lp);*/

		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
		splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
		splitPane.setContinuousLayout(true);// 操作箭头，重绘图形
		splitPane.setLeftComponent(orgPanel);
		splitPane.setRightComponent(lp);
		this.add(BorderLayout.CENTER, splitPane);
		initData();
		
		addListeners();
		pack();
//		centerToScreen();
		setSize(new Dimension(pweight, pheight));
		setDefaultLookAndFeelDecorated(true);
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		setVisible(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 listPanel = new JPanel(new BorderLayout());
		FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
//		flow.setVgap(100);
		flow.setAlignOnBaseline(true);
		JPanel btnPanel = new JPanel(flow);//new PropertyLayout()
		btnPanel.setPreferredSize(new Dimension(40, 100));//.setSize(30, 100);
		btnPanel.add(this.add);
		btnPanel.add(this.remove);//"2.1.center.center", 
		this.lm_user = new DefaultListModel<>();
		this.l_user = new JList<>(lm_user);
		l_user.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//		this.l_user.setCellRenderer(new DeleteListRenderer(l_user));
		JScrollPane scroll = new JScrollPane(l_user);
//		scroll.setPreferredSize(new Dimension(300, 500));
//		this.add.setPreferredSize(new Dimension(50, 30));
		listPanel.add(BorderLayout.NORTH, new JLabel("待设置用户列表"));
		listPanel.add(BorderLayout.WEST, btnPanel);
		listPanel.add(BorderLayout.CENTER, scroll);

		JPanel ipPanel = new JPanel(new BorderLayout());
		lm_ip = new DefaultListModel<>();
		l_ip = new JList<>(lm_ip);
		JScrollPane ipsr = new JScrollPane(l_ip);
//		ipsr.setPreferredSize(new Dimension(300, 0));
		JPanel ibPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JButton editIP = new JButton("编辑IP");
		JButton export = new JButton("导出用户列表");
		editIP.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(lm_user.isEmpty()) {
					MessageBox.post("请先将待设置的用户加入列表！", "ERROR", MessageBox.WARNING);
					return;
				}
				new IPDialog();
			}
		});
		export.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				export();
			}
		});
		ibPanel.add(editIP);
		ibPanel.add(export);
		ipPanel.add(BorderLayout.NORTH, ibPanel);
		ipPanel.add(BorderLayout.CENTER, ipsr);
		
		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
		splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
		splitPane.setContinuousLayout(true);// 操作箭头，重绘图形
		splitPane.setTopComponent(listPanel);
		splitPane.setBottomComponent(ipPanel);
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(BorderLayout.CENTER, splitPane);
//		listPanel.add(BorderLayout.SOUTH, ipPanel);
		
		return panel; 
	}
	
	private void export() {//TODO export
		new Thread() {
			public void run(){
				FileInputStream input = null;
				FileOutputStream output = null;
				try {
					String export = FileSystemView.getFileSystemView().getHomeDirectory().getPath()+"\\允许用户登录IP设置_"+String.format("%tF", new Date())+".xlsx";
					File ef = new File(export);
					if(ef.exists()) {
						int op = JOptionPane.showOptionDialog(LoginIPSetDialog.this, export+"文件已存在，是否替换？", "提示", JOptionPane.YES_NO_OPTION, 
								JOptionPane.INFORMATION_MESSAGE, null, null, null);
						if(op == JOptionPane.YES_OPTION) {
							ef.delete();
						}else {
							return;
						}
					}
//					Enumeration<String> ipe = lm_user.elements();
//					while(ipe.hasMoreElements()) {
//					}
					TCComponentTcFile[] files = model.getTcFiles();
					File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
					input = new FileInputStream(file);
					XSSFWorkbook wb = new XSSFWorkbook(input);
					XSSFSheet sheet = wb.getSheetAt(0);
					XSSFRow row;
					XSSFCell cell;
					ArrayList<String> list = new ArrayList<>();
					group = "";
					role = "";
					recycleNode(tree.getRootNode(), list, 0, true);
					System.out.println("list:"+list.size());
					for(int i=0; i<list.size(); i++) {
						row = getRow(sheet, i+1);
						String u = list.get(i);
						String[] gru = u.split("@@");
						if(gru.length<3)
							System.out.println("gru:"+u);
						String[] user = userString(gru[2]);
//						System.out.println(user[0]+"=>"+user[1]);
						cell = getCell(row, 0);
						cell.setCellValue(i+1);
						cell = getCell(row, 1);
						cell.setCellValue(user[0]);
						cell = getCell(row, 2);
						cell.setCellValue(user[1]);
						cell = getCell(row, 3);
						if(ipmap.containsKey(gru[2])) {
							String[] a = ipmap.get(gru[2]);
							if(a!=null && a.length>0) {
								String ips = Arrays.toString(a);
								cell.setCellValue(ips.substring(1, ips.length()-1));
							}
						}
						cell = getCell(row, 4);
						cell.setCellValue(gru[0]);
						cell = getCell(row, 5);
						cell.setCellValue(gru[1]);
					}
					output = new FileOutputStream(file.getPath());
					wb.write(output);
					input.close();
					output.close();
					
					file.renameTo(new File(export));
					MessageBox.post(LoginIPSetDialog.this, "导出完成！", "提示", MessageBox.INFORMATION);
				} catch (Exception e) {
					e.printStackTrace();
					MessageBox.post("Error:"+e.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					if(input!=null)
						try {
							input.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					if(output!=null)
						try {
							output.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			}
		}.start();
	}

	private JPanel initBtnPanel() {
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
//		this.b_ok = new JButton("OK");
		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 {//
		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 String getSelectUser() throws Exception {
//		Object[] comps = tree.getSelectedOrgObjects();
		AIFTreeNode[] comps = tree.getSelectedNodes();
//		System.out.println("comps:"+(comps==null));
		if (comps == null) {
			return null;
		}
		DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
		if(!selectNode.isLeaf())
			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();
					if(group.indexOf(".")>0)
						group = group.substring(0, group.indexOf("."));
					else if(group.indexOf("\\.")>0)
						group = group.substring(0, group.indexOf("\\."));*/
					return userString(user);
				}
			}
		}
		return null;
	}

	private ArrayList<String> getSelectUsers() throws Exception {//TODO getSelectUsers
		ArrayList<String> list = new ArrayList<>();
		for (AIFTreeNode comp : tree.getSelectedNodes()) {
			recycleNode(comp, list, 0, false);
		}
		
		return list;
	}
	
	private void recycleNode(AIFTreeNode comp, ArrayList<String> list, int level, boolean b) throws Exception {
		System.out.println("recycleNode:"+comp);
		if(comp==null)
			return;
		if(comp.isLeaf()) {
			TCComponent gm = (TCComponent) comp.getContextComponent().getComponent();
			System.out.println("isLeaf:"+gm);
			if (gm != null && (gm instanceof TCComponentGroupMember)) {
				TCComponentUser user = ((TCComponentGroupMember) gm).getUser();
				if (user != null) {
					System.out.println(((TCComponentGroupMember) gm).getGroup()+"=="+((TCComponentGroupMember) gm).getRole());
					String users = userString(user);
					if(b) {
						role = ""+((TCComponentGroupMember) gm).getRole();
						users = group+"@@"+role+"@@"+users;
					}
					if (!lm_user.contains(users) && !list.contains(users)) {
						System.out.println("add1:"+users);
						list.add(users);
					}
				}
			}
		}else {
//			System.out.println("comp:"+comp+"=="+comp.getChildCount());
			if(comp.getChildCount()==0) {
				TCComponent c = (TCComponent) comp.getContextComponent().getComponent();
				System.out.println("getChildCount()==0:"+c);
				if(c instanceof TCComponentRole) {
					System.out.println("parent:"+comp.getParent());
					AIFTreeNode parent = (AIFTreeNode) comp.getParent();
					recycleGroup((TCComponentGroup) parent.getContextComponent().getComponent(), list, level-1, b);
//					for(TCComponentUser user : ((TCComponentRole)c).getUsers((TCComponentGroup) parent.getContextComponent().getComponent())) {
//						String users = userString(user);
//						if(b)
//							users = group+"@@"+role+"@@"+users;
//						if (!lm_user.contains(users) && !list.contains(users))
//							list.add(users);
//					}
				}else {
					TCComponentGroup gm = (TCComponentGroup) comp.getContextComponent().getComponent();
					if(level<=2)
						group = gm.getLocalizedName();
					recycleGroup(gm, list, level+1, b);
				}
			}else {
				if(comp.getContextComponent()==null) {
					System.out.println("AIFTreeNode:"+comp);
					for(int i=0; i<comp.getChildCount(); i++) {
						recycleNode((AIFTreeNode) comp.getChildAt(i), list, level+1, b);
					}
					return;
				}
				TCComponent cp = (TCComponent) comp.getContextComponent().getComponent();
				System.out.println("cp:"+cp);
				if(cp instanceof TCComponentRole) {
					role = ((TCComponentRole)cp).getRoleName();
				}else if(level<=2) {
					group = ((TCComponentGroup)cp).getLocalizedName();
				}
				for (Object c : comp.getChildNodes()) {
					recycleNode((AIFTreeNode) c, list, level+1, b);
				}
			}
		}
	}
	
	private void recycleGroup(TCComponentGroup gm, ArrayList<String> list, int level, boolean b) throws Exception {
		System.out.println("recycleGroup:"+gm);
		for(TCComponentGroup g : gm.getGroups()) {
			if(level<=2)
				group = g.getLocalizedName();
			recycleGroup(g, list, level+1, b);
		}
		for(TCComponentRole role : gm.getRoles()) {
			this.role = role.getRoleName();
			System.out.println("getRoleName:"+role);
			for(TCComponentUser user : role.getUsers(gm)) {
				String users = userString(user);
//				System.out.println("userString:"+users);
				if(b) {
					String[] gs = (""+gm).split("\\.");
					if(gs.length>1)
						group = gs[gs.length-2];
					users = group+"@@"+role+"@@"+users;
				}
				if (!lm_user.contains(users) && !list.contains(users)) {
					System.out.println("add2:"+users);
					list.add(users);
				}
			}
		}
	}

	private void addListeners() {
		this.b_cel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				SqlUtil.free();
				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 {
						String user = getSelectUser();
						if (user != null) {
							setValue(user);
						} else {
							setValue("");
						}
					}
					SqlUtil.free();
					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();
					String user = getSelectUser();
					if(user == null)
						return;
					if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
						System.out.println("user:"+user);
						if (isMulti) {
							if (!lm_user.contains(user)) {
								lm_user.addElement(user);
							}
						} else {
//							setValue(user);
//							disposeDialog();
						}
					}
					lm_ip.removeAllElements();
					if(!ipmap.containsKey(user))
						return;
					String[] ips = ipmap.get(user);
					for(int i=0; i<ips.length; i++) {
						lm_ip.add(i, ips[i]);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});
		//TODO Listener
		this.add.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					ArrayList<String> list = getSelectUsers();
					if(list.size()==0)
						return;
					for(String user : list) {
						lm_user.addElement(user);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});
		this.remove.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int[] ind = l_user.getSelectedIndices();//.getSelectedIndex();
				if(ind==null)
					return;
				for(int i=ind.length-1; i>=0; i--)
					lm_user.remove(ind[i]);
			}
		});
		/*
		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) {
							String user = getSelectUser();
							if (user != null) {
								if (isMulti) {
									if (!lm_user.contains(user)) {
										lm_user.addElement(user);
									}
								} else {
									setValue(user);
									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);
				}

			});
		}*/
	}
	
	private String userString(TCComponentUser user) {
//		return user.getProperty("user_name");
		return user.toString();
	}
	
	private String[] userString(String user) {
		String[] users = new String[2];
		int i = user.indexOf(" (");
		users[0] = user.substring(i+2, user.length()-1);
		users[1] = user.substring(0, i);
		
		return users;
	}

	private XSSFRow getRow(XSSFSheet sheet, int num) throws Exception {
		XSSFRow row = sheet.getRow(num);
		if(row==null)
			row = sheet.createRow(num);
		return row;
	}
	private XSSFCell getCell(XSSFRow row, int col) throws Exception {
		XSSFCell cell = row.getCell(col);
		if(cell==null)
			cell = row.createCell(col);
//		if(row.getRowNum()>1)
//			cell.setCellStyle(getCell(sourceRow, col).getCellStyle());
		return cell;
	}
	
	class IPDialog extends AbstractAIFDialog {

		private JList<String> ipl;
		private DefaultListModel<String> ipm;
		private HashMap<String, JTextField> dmap = new HashMap<>();
		
		IPDialog(){
			super(LoginIPSetDialog.this, true);
			
			setTitle("IP段修改");
			setLayout(new BorderLayout());
			ipm = new DefaultListModel<>();
			ipl = new JList<>(ipm);
			JScrollPane ipsr = new JScrollPane(ipl);
			
			if(lm_user.getSize()==1) {
				String user = lm_user.elementAt(0);
				if(ipmap.containsKey(user)) {
					for(String ip : ipmap.get(user)) {
						ipm.addElement(ip);
					}
				}
			}
			
			KeyAdapter ipcheck = new KeyAdapter() {
				public void keyTyped(KeyEvent e) {
					char in = e.getKeyChar();
					JTextField field = (JTextField) e.getComponent();
//					String name = field.getName();
//					boolean f = name.substring(name.length()-1).equals("1");
					if (in >= KeyEvent.VK_0 && in <= KeyEvent.VK_9) {//数字
						String text = field.getText()+in;
//						System.out.println(name+"=>"+text+"=>"+in);
//						int ip = Integer.parseInt(text);
//						if(f && ip>233) {
//							e.consume();
//							MessageBox.post(text+" 不是有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
//							text = "223";
//							field.setText(text);
//						}else if(!f && ip>255) {
//							e.consume();
//							MessageBox.post(text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
//							text = "255";
//							field.setText(text);
//						}
						if(text.length()==3)
							field.transferFocus();
					}else if(in == KeyEvent.VK_PERIOD) {//点
						e.consume();
						field.transferFocus();
					}else if(in == KeyEvent.VK_BACK_SPACE) {//退格
						super.keyTyped(e);
					}else {
						e.consume();
					}
				}
			};

			JPanel ipPanel = new JPanel(new PropertyLayout());//new FlowLayout(FlowLayout.CENTER)
			ipPanel.add("1.1.center.center", new JLabel("IP："));
			for(int i=1; i<5; i++) {
				JTextField text = new JTextField(3);
				text.setName("ip"+i);
				text.addKeyListener(ipcheck);
				ipPanel.add("1."+(i+1)+".center.center", text);
				dmap.put("ip"+i, text);
			}
			JButton add = new JButton("+");
			add.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					StringBuilder ip = new StringBuilder("");
					for(int i=1; i<5; i++) {
						String text = dmap.get("ip"+i).getText();
						if(text.isEmpty())
							text = "0";
						int ipi = Integer.parseInt(text);
						if(i==1 && ipi>223) {
							MessageBox.post(IPDialog.this, text+" 不是首段有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
							return;
						}
						if(ipi>255) {
							MessageBox.post(IPDialog.this, text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
							return;
						}
						ip.append(".").append(text.isEmpty() ? "0" : Integer.parseInt(text));
					}
					String text = ip.substring(1);
					if(!ipm.contains(text))
						ipm.addElement(text);
					for(int i=1; i<5; i++) {
						dmap.get("ip"+i).setText("");
					}
				}
			});
			ipPanel.add("1.6.center.center", add);
			ipPanel.add("2.1.center.center", new JLabel(" "));
			ipPanel.add("3.1.center.center", new JLabel("IP段："));
			for(int i=1; i<5; i++) {
				JTextField text = new JTextField(3);
				text.setName("ips"+i);
				text.addKeyListener(ipcheck);
				ipPanel.add("3."+(i+1)+".center.center", text);
				dmap.put("ips"+i, text);
			}
			ipPanel.add("4.1.center.center", new JLabel("-"));
			for(int i=5; i<9; i++) {
				JTextField text = new JTextField(3);
				text.setName("ips"+i);
				text.addKeyListener(ipcheck);
				ipPanel.add("4."+(i-3)+".center.center", text);
				dmap.put("ips"+i, text);
			}
			JButton sadd = new JButton("+");
			sadd.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					StringBuilder ip = new StringBuilder("");
					for(int i=1; i<9; i++) {
						String text = dmap.get("ips"+i).getText();
						if(text.isEmpty())
							text = "0";
						int ipi = Integer.parseInt(text);
						if((i==1 || i==5) && ipi>223) {
							MessageBox.post(IPDialog.this, text+" 不是首段有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
							return;
						}
						if(ipi>255) {
							MessageBox.post(IPDialog.this, text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
							return;
						}
						if(i==5)
							ip.append("-");
						else
							ip.append(".");
						ip.append(text.isEmpty() ? 0 : Integer.parseInt(text));
					}
					String text = ip.substring(1);
					String[] ips = text.split("-");
					if(compare(ips[0], ips[1])>=0) {
						MessageBox.post("IP范围无效！", "错误", MessageBox.WARNING);
						return;
					}
					if(!ipm.contains(text))
						ipm.addElement(text);
					for(int i=1; i<9; i++) {
						dmap.get("ips"+i).setText("");
					}
				}
			});
			ipPanel.add("4.6.center.center", sadd);
			
			JButton remove = new JButton("移除IP");
			remove.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					int[] ind = ipl.getSelectedIndices();
					if(ind==null)
						return;
					for(int i=ind.length-1; i>=0; i--)
						ipm.remove(ind[i]);
				}
			});
			JPanel removePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
			removePanel.add(remove);
			JPanel ripPanel = new JPanel(new BorderLayout());
			ripPanel.add(BorderLayout.NORTH, removePanel);
			ripPanel.add(BorderLayout.CENTER, ipPanel);

			JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
			splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
			splitPane.setContinuousLayout(true);// 操作箭头，重绘图形
			splitPane.setTopComponent(ipsr);
			splitPane.setBottomComponent(ripPanel);

			JPanel ibPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
			JButton editIP = new JButton("确认修改");
			JButton cancel = new JButton("取消");
			ibPanel.add(editIP);
			ibPanel.add(cancel);
			
			editIP.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						StringBuilder ips = new StringBuilder("");
						Enumeration<String> ipe = ipm.elements();
						while(ipe.hasMoreElements()) {
							ips.append(",").append(ipe.nextElement());
						}
						if(ips.length()>0)
							ips.deleteCharAt(0);
						String[] ipa = ips.toString().split(",");
						String select = getSelectUser();
						
						StringBuilder sql = new StringBuilder("update CONNOR_USER_IP set IP='");
						sql.append(ips).append("' where PUSER in (");
						boolean update = false;
						Enumeration<String> users = lm_user.elements();
						while(users.hasMoreElements()) {
							String user = users.nextElement();
							if(!ipmap.containsKey(user)) {
								String insert = "insert into CONNOR_USER_IP values('"+user+"','"+ips+"')";
								System.out.println("insert:"+insert);
								SqlUtil.update(insert);
								ipmap.put(user, ipa);
								continue;
							}
							ipmap.put(user, ipa);
							update = true;
							sql.append("'").append(user).append("',");
							if(select!=null && select.equals(user)){
								lm_ip.removeAllElements();
								for(String ip : ipa) {
									lm_ip.addElement(ip);//TODO 
								}
							}
						}
						if(update) {
							sql.deleteCharAt(sql.length()-1).append(")");
							
							System.out.println("update:"+sql);
							SqlUtil.update(sql.toString());
						}
						
						dispose();
					}catch(Exception ex) {
						ex.printStackTrace();
						MessageBox.post("错误:"+ex.getMessage(), "ERROR", MessageBox.ERROR);
					}
				}
			});
			cancel.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					dispose();
				}
			});
			
			add(BorderLayout.CENTER, splitPane);
			add(BorderLayout.SOUTH, ibPanel);
			
			setPreferredSize(new Dimension(400, 500));
			pack();
			centerToScreen();
			setVisible(true);
		}
		
		private int compare(String ip, String str) {
			String[] ips = ip.split("\\."), s = str.split("\\.");
			for(int i=0; i<4; i++) {
				int p = Integer.parseInt(ips[i]), n = Integer.parseInt(s[i]);
				System.out.println("compare:"+p+","+n+"=="+(p>n));
				if(p>n)
					return 1;
				else if(p<n)
					return -1;
			}
			return 0;
		}
	}
}
