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.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.connor.jingdiao.util.SqlUtil;
import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class DrawingNoApplyDialog extends AbstractAIFDialog {
	private static final long serialVersionUID = 1L;
	private TCSession session;
	private JCheckBox createChx;
	private JButton exportBtn;
	private JButton closeBtn;
	private JTable impTable;
	private DefaultTableModel impModel;
	private ArrayList<TCComponentItemRevision> list;
	private HashMap<String, Integer> map;
	private Map<String, String[]> ruleOpsMap;
//	public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception {
	public DrawingNoApplyDialog(TCSession session, ArrayList<String[]> options, 
			InterfaceAIFComponent[] targets,Map<String, String[]> ruleOpsMap) throws Exception {
		super(AIFUtility.getActiveDesktop());
		this.session = session;
		list = new ArrayList<>();
		map = new HashMap<>();
		setTitle("图号申请");
		this.ruleOpsMap = ruleOpsMap;
		System.out.println(ruleOpsMap.toString());
		createChx = new JCheckBox("生成物料");
		createChx.setSelected(true);
		exportBtn = new JButton("申请");
		closeBtn = new JButton("关闭");
		JPanel btnPanel = new JPanel(new FlowLayout());
		btnPanel.add(createChx);
		btnPanel.add(exportBtn);
		btnPanel.add(closeBtn);
		JPanel topPanel = new JPanel(new BorderLayout());
		topPanel.add(BorderLayout.SOUTH, btnPanel);

		ArrayList<String[]> props = new ArrayList<>();
//		String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
		String[] tables = options.get(0);
		String[] tableHeader = new String[tables.length + 1];
		tableHeader[0] = "序号";
		for (int i = 0; i < tables.length; i++) {
			String[] split = tables[i].split("=");
			props.add(split[1].split("\\."));
			tableHeader[i + 1] = split[0];
			map.put(split[1], i + 1);
		}
		impModel = new DefaultTableModel(tableHeader, 0);
		impTable = new JTable() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		impTable.getTableHeader().setReorderingAllowed(false);
		impTable.setFillsViewportHeight(true);
//		impTable.setEnabled(false);
		impTable.setEnabled(true);
//		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		impTable.setModel(impModel);
		for (int i = 1; i < impModel.getColumnCount(); i++)
			impTable.getColumnModel().getColumn(i).setPreferredWidth(150);
		int r = 1;
		TCAccessControlService acs = session.getTCAccessControlService();
		TCComponent[] user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
		StringBuilder msg = new StringBuilder("");
		StringBuilder msg2 = new StringBuilder("");
		for (InterfaceAIFComponent t : targets) {
			TCComponentItemRevision rev = (TCComponentItemRevision) t;
			if (!rev.getProperty("j6_drawingno").isEmpty()) {
				msg.append(rev).append("、");
				continue;
			}
			if(!acs.checkAccessorsPrivilege(user, rev, "WRITE")) {
				msg2.append(rev).append("、");
				continue;
			}
			TCComponentItem item = rev.getItem();
			int size = props.size() + 1;
			Object[] data = new Object[size];
			data[0] = r++;
			for (int i = 1; i < size; i++) {
				String[] ss = props.get(i-1);
				if (ss[0].equals("item")) {
					data[i] = item.getStringProperty(ss[1]);
				} else {
					data[i] = rev.getStringProperty(ss[1]);
				}
			}
			
			impModel.addRow(data);
			list.add(rev);
		}
		if (targets.length > list.size()) {
			StringBuilder m = new StringBuilder("所选对象：\n");
			if(msg.length()>0) {
				m.append(msg.deleteCharAt(msg.length() - 1)).append(" 已有图号，无法再次申请！\n");
			}
			if(msg2.length()>0) {
				m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" 无编辑权限，无法申请图号！");
			}
			MessageBox.post(AIFUtility.getActiveDesktop(), m.toString(), "警告", MessageBox.WARNING);
		}
		if (list.size() == 0) {
			return;
		}
		JScrollPane tablePanel = new JScrollPane(impTable);

		addActionListener(options);

		setLayout(new BorderLayout());
		add(BorderLayout.NORTH, topPanel);
		add(BorderLayout.CENTER, tablePanel);
		pack();
		setSize(new Dimension(1400, 700));
		setDefaultLookAndFeelDecorated(true);
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
//		setAlwaysOnTop(true);
		setVisible(true);
	}

	private void addActionListener(ArrayList<String[]> options) {
		exportBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				new Thread() {
					public void run() {
						try {
							createChx.setEnabled(false);
							exportBtn.setEnabled(false);
							closeBtn.setEnabled(false);
							String[] sqlOptions = options.get(2);
							Connection conn = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
									"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
							if (conn == null) {
								throw new Exception("无法获取数据库连接信息");
							}
							StringBuilder msg = new StringBuilder("");
							
							for (int i = 0; i < list.size(); i++) {
								TCComponentItemRevision rev = list.get(i);
								String itemtype = rev.getItem().getType();
								HashMap<String[], String> opm = new HashMap<>();
								if(ruleOpsMap.containsKey(itemtype)) {
									String[] ops = ruleOpsMap.get(itemtype);
									for (int tt = 0; tt < ops.length; tt++) {
										String[] ss = ops[tt].split("@@");
										opm.put(ss[0].split("@"), ss[1]);
									}
								}
								String dno = "";
								boolean norule = true;
								OPM: for (String[] ss : opm.keySet()) {
									boolean check = false;
									for (int j = 0; j < ss.length; j++) {
										String[] s2 = ss[j].split("=");
										String[] ss2 = s2[1].split(";");
										boolean c = true;
										for(String s : ss2) {
											System.out.println(i+"::"+s+"=="+impTable.getValueAt(i, map.get(s2[0]))+"<<"+s2[0]);
											if(s.equals(impTable.getValueAt(i, map.get(s2[0])))){
												c = false;
												break;
											}
										}
										System.out.println(c);
										if(c)
											check = true;
									}
									System.out.println("check:"+check);
									if(check)
										continue;
									norule = false;
									StringBuilder id = new StringBuilder("");
									String rul = opm.get(ss);
									String[] rule = rul.split("\\+");
									for(String s : rule) {
										if(s.startsWith(".")) {
											id.append(s);
										}else if(s.startsWith("LSH")) {
											String lsh = "%" + String.format("%02d", Integer.parseInt(s.substring(3))) + "d";
											List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
											if (results.size() == 0) {
												SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
												id.append(String.format(lsh, 1));
											} else {
												int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
												SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
												id.append(String.format(lsh, no));
											}
										}else if(s.startsWith("#rev.")) {
											String value = rev.getStringProperty(s.substring(5));
											if(value.isEmpty()) {
												msg.append(rev).append(" 的部分图号相关属性为空，请检查\n");
												break OPM;
											}
											id.append(value);
										}else if(map.containsKey(s)) {
											String value = impTable.getValueAt(i, map.get(s)).toString();
											if(value.isEmpty()) {
												msg.append(rev).append(" 的部分图号相关属性为空，请检查\n");
												break OPM;
											}
											id.append(value);
										}else if(s.contains(".")) {//.startsWith("J6_ASSOCIATED_REL.j6_drawingno")
											String[] sp = s.split("\\.");
											AIFComponentContext[] parent = rev.whereReferencedByTypeRelation(null, new String[] { sp[0] });
											if(parent==null || parent.length==0) {
												msg.append(rev).append(" 与零件未关联，请关联后再申请图号\n");
												break OPM;
											}
											String p = parent[0].getComponent().getProperty(sp[1]);
											if(p.isEmpty()) {
												if(sp[1].equals("j6_drawingno")) {
													msg.append(rev).append(" 上级图纸无图号，请先申请上级图号后再申请本图图号\n");
													break OPM;
												}else {
													msg.append(rev).append(" 上级对象属性为空，请检查\n");
													break OPM;
												}
											}
											id.append(p);
										}else {
											id.append(s);
										}
									}
									if(!rul.contains("LSH")) {
										List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, 
												"select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
										if (results.size() == 0) {
											SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',0)");
										}else {
											msg.append(rev).append(" 的图号 ").append(id).append(" 已存在，请检查相关属性值\n");
											break;
										}
									}
									dno = id.toString();
									rev.setProperty("j6_drawingno", dno);
									impTable.setValueAt(dno, i, map.get("rev.j6_drawingno"));
									break;
								}
								if(norule) {
									msg.append(rev).append(" 无满足条件的规则，无法申请图号 ");
								}
								norule = true;
								
								if(dno.isEmpty())
									continue;
								if(!createChx.isSelected())
									continue;
								TCComponentItem item = rev.getItem();
								TCComponentForm form = TCUtil.getItemRevisionMasterForm(rev);
								String type = "", dtype = item.getType(), ptype = rev.getProperty("j6_processtype");
								String t = dtype+";"+ptype+"=";
								for(String ss : options.get(3)) {
									if(ss.startsWith(t)) {
										type = ss.substring(ss.indexOf("=")+1);
										break;
									}
								}
								if(type.isEmpty())
									continue;
								AIFComponentContext[] rfs = rev.getChildren("representation_for")[0].getComponent().getChildren();
								if(rfs!=null && rfs.length>0) {
									int choose = JOptionPane.showOptionDialog(DrawingNoApplyDialog.this, rev+" 下已存在物料，是否继续创建?", "提示", 
											JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"是","否"}, "结束操作");
									if(choose==1)
										continue;
								}
								TCComponentItemType typec = (TCComponentItemType)session.getTypeComponent(type);
								TCComponentItem pitem = typec.create(typec.getNewID(), null, type, item.getProperty("object_name"), "", null);
								TCComponentItemRevision prev = pitem.getLatestItemRevision();
								TCComponentForm pform = TCUtil.getItemRevisionMasterForm(prev);
								t = dtype+";"+type+"@@";
								for(String s : options.get(4)) {
									if(!s.startsWith(t))
										continue;
									String[] ss = s.substring(s.indexOf("@@")+2).split(";");
									for(String s1 : ss) {
										String[] ps = s1.split("=");
										setProp(ps, pitem, prev, pform, item, rev, form);
									}
									break;
								}
								rev.add("representation_for", prev);
							}
							if(msg.length()>0)
								MessageBox.post(DrawingNoApplyDialog.this, "以下对象图号申请遇到问题，请检查：\n" + msg, "提示", MessageBox.WARNING);
							else
								MessageBox.post(DrawingNoApplyDialog.this, "图号申请完成！", "提示", MessageBox.INFORMATION);
						} catch (Exception e1) {
							e1.printStackTrace();
							MessageBox.post(DrawingNoApplyDialog.this, "错误：" + e1.getMessage(), "ERROR", MessageBox.ERROR);
						}
						createChx.setEnabled(true);
						exportBtn.setEnabled(true);
						closeBtn.setEnabled(true);
					}
				}.start();
			}
		});
		closeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
	}
	
	private void setProp(String[] ps, TCComponentItem pitem, TCComponentItemRevision prev, TCComponentForm pform, 
			TCComponentItem item, TCComponentItemRevision rev, TCComponentForm form) throws Exception {
		String[] p1 = ps[0].split("\\."), p2 = ps[1].split("\\.");
		Object val = "";
		if(p2.length<2) {
			val = p2[0];
		}else if(p2[0].equals("item")) {
		    val = MethodUtil.getTCPropertyValue(item, p2[1]);
			//val = item.getProperty(p2[1]);
		}else if(p2[0].equals("rev")) {
		    val = MethodUtil.getTCPropertyValue(rev, p2[1]);
			//val = rev.getProperty(p2[1]);
		}else if(p2[0].equals("revmaster")) {
		    val = MethodUtil.getTCPropertyValue(form, p2[1]);
			//val = form.getProperty(p2[1]);
		}
		System.out.println("val:"+val);
		if(p1[0].equals("item")) {
		    MethodUtil.setTCPropertyValue(pitem, p1[1], val);
		}else if(p1[0].equals("rev")) {
		    MethodUtil.setTCPropertyValue(prev, p1[1], val);
		}else if(p1[0].equals("revmaster")) {
		    MethodUtil.setTCPropertyValue(pform, p1[1], val);
		}
	}
}