package com.connor.jingdiao.handlers;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.connor.jingdiao.util.SqlUtil;
import com.connor.jingdiao.util.TCUtil;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class CodeApplyOperation extends AbstractAIFOperation {
	
//	private TCSession session;
	private ArrayList<TCComponent> revs;
	private ArrayList<String[]> options;
	private StringBuilder msg;
	private HashMap<String, String> classmap;
	
	public CodeApplyOperation(TCSession session, ArrayList<TCComponent> revs, ArrayList<String[]> options, StringBuilder msg) {
//		this.session = session;
		this.revs = revs;
		this.options = options;
		this.msg = msg;
		this.classmap = new HashMap<>();
	}
	
	@Override
	public void executeOperation() throws Exception {
		AIFDesktop desktop = AIFUtility.getActiveDesktop();
		try {
			HashMap<String[], String[]> opmap = new HashMap<>();
			for(String s : options.get(0)) {
				String[] ss = s.split("@@");
				opmap.put(ss[0].split("@"), ss[1].split("\\+"));
			}
			for(String s : options.get(3)) {
				String[] ss = s.split("=");
				classmap.put(ss[0], ss[1]);
			}
			String[] sqlOptions = options.get(1);
			Connection conn1 = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
					"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
			sqlOptions = options.get(2);
//			Connection conn2 = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
//					"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
//			Class.forName("oracle.jdbc.driver.OracleDriver");
			Connection conn2 = DriverManager.getConnection("jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
			conn2.setAutoCommit(false);
//			StringBuilder msg = new StringBuilder("");
			for(TCComponent comp : revs) {
				try {
					TCComponentItemRevision rev = null;
					TCComponentBOMLine bom = null;
					if(comp instanceof TCComponentItemRevision) {
						rev = (TCComponentItemRevision) comp;
					}else {
						bom = (TCComponentBOMLine) comp;
						rev = bom.getItemRevision();
					}
					String[] ops = null;
				OPTS:for(String[] ss : opmap.keySet()) {
						for(String s : ss) {
							String[] ps = s.split("=");
							String[] pss = ps[1].split(";");
							if(!TCUtil.contains(pss, getProp(rev, ps[0]))) {
								continue OPTS;
							}
						}
						ops = opmap.get(ss);
					}
					if(ops==null) {
						continue;
					}
					StringBuilder sb = new StringBuilder("");
					int lshc = 0;
					for(String op : ops) {
						if(op.equals(".")) {
							sb.append(op);
						}else if(op.contains(".")) {
							sb.append(getProp(rev, bom, op));
						}else if(op.startsWith("LSH")) {
							sb.append("LSH");
							lshc = Integer.parseInt(op.substring(3));
						}else if(op.startsWith("#")) {
							throw new Exception(op.substring(1));
						}else {
							sb.append(op);
						}
					}
					String code = sb.toString();
					if(lshc>0) {
						String lsh = "%" + String.format("%02d", lshc) + "d";
						ArrayList<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn1, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+sb+"'");
						if(results.size()>0) {
							int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
							if((no+"").length() > lshc)
								throw new Exception(rev+" 的物料编码的流水号已满，请调整相关的属性项值后再次进行申请！\n");
							SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" + code + "'");
							code = code.replace("LSH", String.format(lsh, no));
						}else {
							String id = sb.substring(0, sb.indexOf("LSH")).replaceAll("\\.", "");
							String sql = "select max(ECMS_CODE) as ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='" +id+ "' group by ECMS_PRE";
							System.out.println("ECMS_SERIAL:"+sql);
							results = SqlUtil.getDBInfo(conn2, sql);
							if(results.size()>0) {
								int no = Integer.parseInt(results.get(0).get("ECMS_NEXTCODE").toString()) + 1;
								if((no+"").length() > lshc)
									throw new Exception(rev+" 的物料编码的流水号已满，请调整相关的属性项值后再次进行申请！\n");
								SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',"+no+")");
								code = code.replace("LSH", String.format(lsh, no));
							}else {
								int no = 1;
								SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',1)");
								code = code.replace("LSH", String.format(lsh, no));
							}
						}
					}else {
						List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn1, 
								"select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+code+"'");
						if (results.size() == 0) {
							SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',0)");
						}else {
							throw new Exception(rev+" 的物料编码 "+code+" 已存在，请检查相关属性值\n");
						}
					}
					rev.setProperty("j6_wlbm", code);
				} catch (Exception e) {
					e.printStackTrace();
					msg.append(comp).append(" ： ").append(e.getMessage()).append("\n");
				}
			}
			if(msg.length()==0)
				MessageBox.post(desktop, "物料编码申请完成！", "提示", MessageBox.INFORMATION);
			else
				MessageBox.post(desktop, "以下对象申请物料编码遇到问题：\n"+msg, "提示", MessageBox.WARNING);
		} catch (Exception e) {
			e.printStackTrace();
			MessageBox.post(desktop, "错误："+e.getMessage(), "ERROR", MessageBox.ERROR);
		}
	}
	
	private String getProp(TCComponentItemRevision rev, TCComponentBOMLine bom, String op) throws Exception {
		String value = "";
		String[] split = op.split(";");
		String[] ss = split[0].split("\\.");
		if(ss[0].equals("rev")) {
			if(ss[1].contains("@Jd_Code_Product_Class")) {
				String v = ss[1].substring(0, ss[1].indexOf("@"));
				value = classmap.get(getProp(rev, v));
			}else
				value = getProp(rev, ss[1]);
		}else if(ss[0].equals("part")) {
			AIFComponentContext[] zjtz = TCUtil.getPseudoFolder(rev, "TC_Is_Represented_By").getChildren();
			if(zjtz.length>0) {
				AIFComponentContext[] ljtz = ((TCComponent)zjtz[0].getComponent()).whereReferencedByTypeRelation(null, new String[] { "J6_ASSOCIATED_REL" });
				if(ljtz.length>0) {
					AIFComponentContext[] ljwl = TCUtil.getPseudoFolder((TCComponent)ljtz[0].getComponent(), "representation_for").getChildren();
					if(ljwl.length>0) {
						value = getProp((TCComponent)ljwl[0].getComponent(), ss[1]);
					}
				}
			}
		}else if(ss[0].equals("parent")) {
			if(bom==null)
				throw new Exception("所选对象不是BOM行，不支持parent属性");
			TCComponentBOMLine parent = bom.parent();
			if(parent==null)
				throw new Exception("未找到父级BOM");
			value = getProp(parent.getItemRevision(), ss[1]);
		}
		if(value.isEmpty()) {
			if(ss[0].equals("part"))
				throw new Exception("获取零件物料编码失败");
			else
				throw new Exception(ss[1]+" 属性为空");
		}
		if(split.length==1)
			return value;
		if(split[1].startsWith("LEN")) {
			value = "" + Integer.parseInt(value) / Integer.parseInt(split[1].substring(3));
			if(value.length() > 4)
				throw new Exception("“线束线缆长度”信息填写错误，请重新编写");
			while(value.length() < 4) {
				value = "0" + value;
			}
            //lidy20240711先判断长度，长度超出则截取，不足则补0
			//20240715客户又要求还原回去
//            int length = value.length();
//            if(length > 5)
//                throw new Exception("“线束线缆长度”信息填写错误，请重新编写");
//            String divisor = split[1].substring(3);
//            int len = 5 - divisor.length() + 1;
//            System.out.println("LEN：" + split[1] + "=" + value + "=" + length + "=" + divisor + "=" + len);
//            if(length > len)
//                value = "" + Integer.parseInt(value) / Integer.parseInt(divisor);
//            System.out.println("value1：" + value);
//            while(value.length() < len) {
//                value = "0" + value;
//            }
            System.out.println("value2：" + value);
			value = value.substring(0, 2) + "." + value.substring(2);
		}else if(split[1].contains(">")) {
			String[] sp = split[1].split(">");
			int n = Integer.parseInt(sp[0])-1;
			value = value.substring(n, n+Integer.parseInt(sp[1]));
		}else {
			int len = Integer.parseInt(split[1]);
			while(value.length()<len) {
				value = "0"+value;
			}
		}
		return value;
	}
	
	private String getProp(TCComponent comp, String prop) throws Exception {
		try {
			return comp.getStringProperty(prop);
		}catch(Exception e) {
			return comp.getProperty(prop);
		}
	}
}