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.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.connor.jingdiao.util.SqlTIUtil;
import com.connor.jingdiao.util.SqlUtil;
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.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class WlbmApplyDialog extends AbstractAIFDialog {

	private JButton exportBtn;
	private JButton closeBtn;
	private JTable impTable;
	private DefaultTableModel impModel;
	private ArrayList<TCComponentItemRevision> list;
	private HashMap<String, Integer> map;
	private HashMap<String, String> productClassMap;
	public WlbmApplyDialog(TCSession session, String tables[], String[] options, 
			String[] sqlOptions, InterfaceAIFComponent[] targets,String[] sqlOptionsTI,String[] productClass) throws Exception {
		super(AIFUtility.getActiveDesktop());
//		this.session = session;
		list = new ArrayList<>();
		map = new HashMap<>();
		productClassMap = new HashMap<String, String>();
		setTitle("物料编码申请");

		exportBtn = new JButton("申请");
		closeBtn = new JButton("关闭");
		JPanel btnPanel = new JPanel(new FlowLayout());
		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[] tableHeader = new String[tables.length + 1];
		tableHeader[0] = "序号";
		
		for(int i=0;i<productClass.length;i++) {
			String[] split = productClass[i].split("=");
			productClassMap.put(split[0], split[1]);
		}
		
		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);
		}
		System.out.println("MAP==>"+map.toString());
		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_wlbm").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);
				System.out.println("prop==>"+ss[1]);
				if (ss[0].equals("item")) {
					data[i] = item.getProperty(ss[1]);
				} else {
					data[i] = rev.getProperty(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, sqlOptions,sqlOptionsTI);

		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(String[] options, String[] sqlOptions, String[] sqlOptionsTI) {
		exportBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					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("无法获取数据库连接信息");
					}
					Connection connTI = SqlTIUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
							"jdbc:oracle:thin:@" + sqlOptionsTI[0] + ":1521:" + sqlOptionsTI[3], sqlOptionsTI[1], sqlOptionsTI[2]);
					if (connTI == null) {
						throw new Exception("无法获取TI数据库连接信息");
					}
					StringBuilder msg = new StringBuilder("");
					HashMap<String[], String> opm = new HashMap<>();
					for (int i = 0; i < options.length; i++) {
						String[] ss = options[i].split("@@");
						opm.put(ss[0].split("@"), ss[1]);
					}
					for (int i = 0; i < list.size(); i++) {
						TCComponentItemRevision rev = list.get(i);
						//加工方式为零件的Part 找bom上级
						String processType = rev.getProperty("j6_processtype");
						String itemType = rev.getItem().getType();
						if(itemType.equals("Part")&&processType.equals("零件")) {
							
							TCComponent[] procs = rev.whereUsed(TCComponentItemRevision.WHERE_USED_ALL);
							for(TCComponent component : procs) {
								if(component instanceof TCComponentItemRevision) {
									TCComponentItemRevision zjRevision = (TCComponentItemRevision) component;
									String zjType = zjRevision.getProperty("j6_processtype");
									if(zjRevision.getType().contains("Part") && zjType.equals("组件")) {
										
										String pDon = zjRevision.getProperty("j6_wlbm");
										if(pDon.isEmpty()) {
											msg.append(rev).append(" 上级图纸无物料编码，请先申请上级物料编码后再申请本物料编码\n");
											break;
										}
										if(pDon.endsWith("00")) {
											String id = pDon.substring(0, pDon.length()-2);
											StringBuffer code = new StringBuffer("");
											List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
											if (results.size() == 0) {
												
												List<HashMap<String, Object>> resultsTi = SqlTIUtil.getDBInfo(connTI, "select ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='"+id+"'");
												
												if(resultsTi.size()==0) {
													SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
													code.append(String.format("%02d", 1));
												}else {
													int no = (Integer) results.get(0).get("ECMS_NEXTCODE") + 1;
													SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
													code.append(String.format("%02d", no));
												}
											} else {
												int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
												SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
												code.append(String.format("%02d", no));
											}
											
											rev.setProperty("j6_wlbm", code.toString());
											impTable.setValueAt(code, i, map.get("rev.j6_wlbm"));
											break;
										}
									}
								}
							}
							continue;
						}
						
						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;
								}else {
									check = false;
								}
							}
							System.out.println("check:"+check);
							if(check) {
								continue;
							}
							norule = false;
							StringBuilder id = new StringBuilder("");
							String rul = opm.get(ss);
							System.out.println("rule==>"+rul);
							String[] rule = rul.split("\\+");
							for(String s : rule) {
								System.out.println(s);
								if(s.startsWith(".")) {
									System.out.println("startWish . "+s);
									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) {
										
										List<HashMap<String, Object>> resultsTi = SqlTIUtil.getDBInfo(connTI, "select ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='"+id+"'");
										
										if(resultsTi.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("ECMS_NEXTCODE") + 1;
											SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
											id.append(String.format(lsh, no));
										}
									} 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 prop = s.substring(5);
									String value = rev.getStringProperty(prop);
									if(value.isEmpty()) {
										msg.append(rev).append(" 的部分物料编码相关属性为空，请检查\n");
										break OPM;
									}else if(prop.equals("j6_productseries")){
										if(productClassMap.containsKey(value)) {
											value = productClassMap.get(value);
										}else {
											msg.append("产品分类码 ").append(value).append(" 在首选项 Jd_Code_Product_Class 中未找到配置，请检查\n");
										}
									}
									id.append(value);
								}else if(s.startsWith("rev.")) {
									System.out.println("rev==>"+s);
									String prop = s.substring(4);
									String value = "";
									value = rev.getStringProperty(prop);
									System.out.println(value);
									if(s.contains("j6_topicno")) {
										value = value.substring(0,3);
									}
									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;
								}
							}
							String dno = id.toString();
							rev.setProperty("j6_wlbm", dno);
							if(map.containsKey("rev.j6_wlbm")) {
								impTable.setValueAt(dno, i, map.get("rev.j6_wlbm"));
							}
							break;
						}
						if(norule) {
							msg.append(rev).append(" 无满足条件的规则，无法申请物料编码 ");
						}
						norule = true;
					}
					if(msg.length()>0)
						MessageBox.post(WlbmApplyDialog.this, "以下对象物料编码申请遇到问题，请检查：\n" + msg, "提示", MessageBox.WARNING);
					else
						MessageBox.post(WlbmApplyDialog.this, "物料编码申请完成！", "提示", MessageBox.INFORMATION);
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post(WlbmApplyDialog.this, "错误：" + e1.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					SqlUtil.freeAll();
					SqlTIUtil.freeAll();
				}
			}
		});
		closeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
	}
	
}
