package com.steering.jobface.qcm.task;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;

import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.model.qcm.*;

import org.apache.log4j.Logger;

public class SteelMakingAdvanceJudgeTask extends TimerTask {
	private static class SteelMakingAdvanceJudgeTaskClass{
		private static final SteelMakingAdvanceJudgeTask instance = new SteelMakingAdvanceJudgeTask();
	}
	
	private SteelMakingAdvanceJudgeTask(){};
	
	public static SteelMakingAdvanceJudgeTask getInstance(){
		return SteelMakingAdvanceJudgeTaskClass.instance;
	}
	private final Logger logger = Logger.getLogger(MainTask.class);
	private Long _maxJudgeId = 0L;
	private int _judgeSeq = 0;
	public void run(){
		synchronized (this) {
			Connection qcmCon = null;
			Statement st = null;
			try{
				qcmCon = new DBCommon().getDao(CoreConstantData.sysbeanstr).getConnection();
				qcmCon.setAutoCommit(false);
				st = qcmCon.createStatement();
				//获取检化验数据 熔炼炉号判定
				SqlBuilder b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getJhyElementStoveNo");
				List<QcmJhyElementsEntity> jhyElementStoveNos = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), qcmCon, QcmJhyElementsEntity.class);
				b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getMaxChemJudgeId");
				QcmLgChemjudgeEntity maxJudgeIdEntity = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), qcmCon, QcmLgChemjudgeEntity.class);
				_maxJudgeId = Long.parseLong(maxJudgeIdEntity.getChemJudgeId());
				for(QcmJhyElementsEntity jhyElementStoveNo : jhyElementStoveNos){
					try {
						//自炼
						b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getStlJudgeStoveNoByStoveNo");
						b.Fill(new String[]{ jhyElementStoveNo.getStoveNo() });
						ArrayList<StlIncisionEntity> stlJudgeStoves = EntityTool.getEntitysBySqlNoClsCon(
								b.toString(), qcmCon, StlIncisionEntity.class);
						for(StlIncisionEntity stlJudgeStove : stlJudgeStoves){
							String judgeStoveNo = stlJudgeStove.getJudgeStoveNo();
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getStlPlnIdByJudgeStoveNo");
							b.Fill(new String[]{ judgeStoveNo });
							ArrayList<StlIncisionEntity> stls = EntityTool.getEntitysBySqlNoClsCon(
									b.toString(), qcmCon, StlIncisionEntity.class);
							String[] zgProPlanIds = GetStlZgPlanId(stls, qcmCon);
							String chemResult = judge(jhyElementStoveNo.getStoveNo(), judgeStoveNo,
									stls.get(0).getPlineCode(), zgProPlanIds, st, qcmCon);
							if(!"40740106".equals(chemResult)){
								//更新切割实绩表
								b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateStlInCision");
								b.Fill(new String[]{ judgeStoveNo, String.valueOf(_maxJudgeId), "20", chemResult });
								//st.addBatch(b.toString());
								st.executeUpdate(b.toString());
								//更新管坯申请判定表的判定状态。
								b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
								b.Fill(new String[]{ judgeStoveNo, "00", chemResult });
								//st.addBatch(b.toString());
								st.executeUpdate(b.toString());
							}
							
						}
						
						//外购
						b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getApplyJudgeStoveNoByStoveNo");
						b.Fill(new String[]{ jhyElementStoveNo.getStoveNo() });
						ArrayList<QcmGpJudgeApplyEntity> applyJudgeStoveNos = EntityTool.getEntitysBySqlNoClsCon(
								b.toString(), qcmCon, QcmGpJudgeApplyEntity.class);
						for(QcmGpJudgeApplyEntity applyJudgeStoveNo : applyJudgeStoveNos){
							String judgeStoveNo = applyJudgeStoveNo.getJudgeStoveNo();
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getApplyPlnIdByJudgeStoveNo");
							b.Fill(new String[]{ judgeStoveNo });
							ArrayList<QcmGpJudgeApplyEntity> gpApplys = EntityTool.getEntitysBySqlNoClsCon(
									b.toString(), qcmCon, QcmGpJudgeApplyEntity.class);
							String[] zgProPlanIds = GetApplyZgPlanId(gpApplys,judgeStoveNo,applyJudgeStoveNo.getStoveNo(), qcmCon);
							String chemResult = judge(jhyElementStoveNo.getStoveNo(), judgeStoveNo,
									gpApplys.get(0).getPlineCode(), zgProPlanIds, st, qcmCon);
							if(!"40740106".equals(chemResult)){
								//更新管坯申请判定表的判定状态。
								b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
								b.Fill(new String[]{ judgeStoveNo, "20", chemResult });
								//st.addBatch(b.toString());
								st.executeUpdate(b.toString());
							}
						}
						//更新检化验表
						b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateQcmJhyElement");
						b.Fill(new String[]{ "20", jhyElementStoveNo.getStoveNo() });
						//st.addBatch(b.toString());
						st.executeUpdate(b.toString());
						
						qcmCon.commit();
					}catch(Exception ex) {
						qcmCon.rollback();
						//更新检化验表
						b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateQcmJhyElement");
						b.Fill(new String[]{ "-1", jhyElementStoveNo.getStoveNo() });
						st.executeUpdate(b.toString());
						qcmCon.commit();
						String msg = "SteelMakingAdvanceJudgeTask异常: StoveNo=" + jhyElementStoveNo.getStoveNo() + ex.getMessage();
						logger.error(msg);
					}
				}
				
				//只有检化验表都判完了，才使用判定炉号驱动判定
				if(jhyElementStoveNos.size() == 0){
					// 切割表判定炉号驱动判定
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getStlJudgeStoveNo");
					List<StlIncisionEntity> stlJudgeStoveNos = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), qcmCon, StlIncisionEntity.class);
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getMaxChemJudgeId");
					maxJudgeIdEntity = EntityTool.getEntityBySqlNoClsCon(
							b.toString(), qcmCon, QcmLgChemjudgeEntity.class);
					_maxJudgeId = Long.parseLong(maxJudgeIdEntity.getChemJudgeId());
					for(StlIncisionEntity stlJudgeStoveNo : stlJudgeStoveNos){
						try {
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getStlPlnIdByJudgeStoveNo");
							b.Fill(new String[]{ stlJudgeStoveNo.getJudgeStoveNo() });
							ArrayList<StlIncisionEntity> stls = EntityTool.getEntitysBySqlNoClsCon(
									b.toString(), qcmCon, StlIncisionEntity.class);
							String[] zgProPlanIds = GetStlZgPlanId(stls, qcmCon);
							String chemResult = judge(stlJudgeStoveNo.getStoveNo(), stlJudgeStoveNo.getJudgeStoveNo(),
									stls.get(0).getPlineCode(), zgProPlanIds, st, qcmCon);
							
							//更新切割实绩表
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateStlInCision");
							b.Fill(new String[]{ stlJudgeStoveNo.getJudgeStoveNo(), String.valueOf(_maxJudgeId), "20", chemResult });
							//st.addBatch(b.toString());
							st.executeUpdate(b.toString());
							//更新管坯申请判定表的判定状态。
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
							b.Fill(new String[]{ stlJudgeStoveNo.getJudgeStoveNo(), "20", chemResult });
							//st.addBatch(b.toString());
							st.executeUpdate(b.toString());
							qcmCon.commit();
						}catch(Exception ex) {
							qcmCon.rollback();
							//更新管坯申请判定表的判定状态。
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
							b.Fill(new String[]{ stlJudgeStoveNo.getJudgeStoveNo(), "-1", "" });
							st.executeUpdate(b.toString());
							qcmCon.commit();
							String msg = "SteelMakingAdvanceJudgeTask异常: StoveNo=" + stlJudgeStoveNo.getStoveNo() + ex.getMessage();
							logger.error(msg);
						}
					}
					
					// 申请判定表判定炉号驱动判定
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getApplyJudgeStoveNo");
					List<QcmGpJudgeApplyEntity> applyJudgeStoveNos = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), qcmCon, QcmGpJudgeApplyEntity.class);
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getMaxChemJudgeId");
					maxJudgeIdEntity = EntityTool.getEntityBySqlNoClsCon(
							b.toString(), qcmCon, QcmLgChemjudgeEntity.class);
					_maxJudgeId = Long.parseLong(maxJudgeIdEntity.getChemJudgeId());
					for(QcmGpJudgeApplyEntity applyJudgeStoveNo : applyJudgeStoveNos){
						try {
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getApplyPlnIdByJudgeStoveNo");
							b.Fill(new String[]{ applyJudgeStoveNo.getJudgeStoveNo() });
							ArrayList<QcmGpJudgeApplyEntity> gpApplys = EntityTool.getEntitysBySqlNoClsCon(
									b.toString(), qcmCon, QcmGpJudgeApplyEntity.class);
							String[] zgProPlanIds = GetApplyZgPlanId(gpApplys,applyJudgeStoveNo.getJudgeStoveNo(),applyJudgeStoveNo.getStoveNo(), qcmCon);
							String chemResult = judge(applyJudgeStoveNo.getStoveNo(), applyJudgeStoveNo.getJudgeStoveNo(),
									gpApplys.get(0).getPlineCode(), zgProPlanIds, st, qcmCon);
							
							//更新管坯申请判定表的判定状态。
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
							b.Fill(new String[]{ applyJudgeStoveNo.getJudgeStoveNo(), "20", chemResult });
							//st.addBatch(b.toString());
							st.executeUpdate(b.toString());
							qcmCon.commit();
						}catch(Exception ex) {
							qcmCon.rollback();
							//更新管坯申请判定表的判定状态。
							b = new SqlBuilder("SteelMakingAdvanceJudgeTask.udpateGpJudgeApplyCxFlag");
							b.Fill(new String[]{ applyJudgeStoveNo.getJudgeStoveNo(), "-1", "" });
							//st.addBatch(b.toString());
							st.executeUpdate(b.toString());
							qcmCon.commit();
							String msg = "SteelMakingAdvanceJudgeTask异常: StoveNo=" + applyJudgeStoveNo.getStoveNo() + ex.getMessage();
							logger.error(msg);
						}
					}
				}
			}catch(Exception ex){
				try {
					qcmCon.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				logger.error("SteelMakingAdvanceJudgeTask异常: " + ex.getMessage());
			}finally{
				if(st != null){
					try {
						st.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if(qcmCon != null){
					try {
						qcmCon.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	/**
	 * 炼钢预判(自炼成分)
	 * @param stoveNo
	 * @param judgeStoveNo
	 * @throws SQLException 
	 */
	private String judge(String stoveNo, String judgeStoveNo, String plineCode, String[] zgProPlanIds,
			Statement st, Connection qcmCon) throws SQLException{
		SqlBuilder b;
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getGpApplyByJudgeStoveNo");
		b.Fill(new String[]{ judgeStoveNo });
		QcmGpJudgeApplyEntity gpApply = EntityTool.getEntityBySqlNoClsCon(
				b.toString(), qcmCon, QcmGpJudgeApplyEntity.class);
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getCicByJudgeStoveNo");
		b.Fill(new String[]{ judgeStoveNo });
		CraftOrdDesignMscPlPrcEntity plnCic = EntityTool.getEntityBySqlNoClsCon(b.toString(), qcmCon, CraftOrdDesignMscPlPrcEntity.class);
		String[] cics = new String[1];
		if(plnCic != null){
			cics = plnCic.getCic().split(",");
		}else if(gpApply != null&&gpApply.getCic()!=null&&!gpApply.getCic().equals("")){
			cics[0] = gpApply.getCic();
		}else{
			return "";
		}
		//获取工艺信息		
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryCraftCicByZgProPlanId");
		b.Fill(new Object[]{ zgProPlanIds, cics.length, cics });
		ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
				b.toString(), qcmCon, CraftOrdDesignMscPlPrcEntity.class);
		
		//修改判定记录状态
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateLgChemJudgeValid");
		b.Fill(new String[]{ judgeStoveNo, "0" });
		//st.addBatch(b.toString());
		st.executeUpdate(b.toString());
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.updateLgChemJudgeExceptionValid");
		b.Fill(new String[]{ judgeStoveNo, "0" });
		//st.addBatch(b.toString());
		st.executeUpdate(b.toString());
		
		_maxJudgeId++;
		_judgeSeq = 0;
		
		String oldGradecode = "";
		String oldGradename = "";
		String oldCic = "";
		if(gpApply != null){
			oldGradecode = gpApply.getOldGradecode();
			oldGradename = gpApply.getOldGradename();
			oldCic = gpApply.getOldCic();
		}
		String chemResult601 = judge(stoveNo, judgeStoveNo, plineCode,
				"601", craftPrcs, _maxJudgeId, zgProPlanIds, oldGradecode, oldGradename, oldCic, st, qcmCon);
		String chemResult602 = judge(stoveNo, judgeStoveNo, plineCode,
				"602", craftPrcs, _maxJudgeId, zgProPlanIds, oldGradecode, oldGradename, oldCic, st, qcmCon);
		String chemResult603 = judge(stoveNo, judgeStoveNo, plineCode,
				"603", craftPrcs, _maxJudgeId, zgProPlanIds, oldGradecode, oldGradename, oldCic, st, qcmCon);
		
		String chemResult = "40740102";
		if(chemResult601.equals("") && chemResult602.equals("") && chemResult603.equals("")){
			chemResult = "40740102";
		}else if((chemResult601.equals("40740101") || chemResult601.equals("")) 
				&& (chemResult602.equals("40740101") || chemResult602.equals(""))
				&& (chemResult603.equals("40740101") || chemResult603.equals(""))){
			chemResult = "40740101";
		}else if(chemResult601.equals("40740106")){//增加40740106，代表缺项
			chemResult = "40740106";
		}
		
		//根据成分判定ID修改汇总成分结果、取样类型。
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.setSampleType");
		b.Fill(new String[]{ String.valueOf(_maxJudgeId), chemResult });
		//st.addBatch(b.toString());
		st.executeUpdate(b.toString());
		
		return chemResult;
	}
	
	/**
	 * 获取轧管计划ID
	 * @param con
	 * @return
	 * @throws SQLException
	 */
	private String[] GetStlZgPlanId(ArrayList<StlIncisionEntity> stls, Connection con) throws SQLException{
		Statement st = null;
    	try{
    		st = con.createStatement();
    		ArrayList<String> zgProPlanIds = new ArrayList<String>();
    		for(StlIncisionEntity stl : stls){
    			String[] aryProPlanIds = stl.getProPlanId().split(",");
    			String[] aryGxPlanNos = stl.getGxPlanNo().split(",");
        		for(int i = 0; i < aryProPlanIds.length; i++){
        			String proPlanId = aryProPlanIds[i];
        			String gxPlanNo = aryGxPlanNos[i];
        			if(proPlanId.startsWith("ZG")){
        				zgProPlanIds.add(proPlanId + gxPlanNo);
        			}else{
        				SqlBuilder b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryByGpreqId");
                        b.Fill(new String[]{ proPlanId });
                        ResultSet rs = st.executeQuery(b.toString());
                        while(rs.next()){
                        	if(!zgProPlanIds.contains(rs.getString("PRO_PLAN_ID"))){
                        		zgProPlanIds.add(rs.getString("PRO_PLAN_ID"));
                        	}
                        }
        			}
        		}
    		}
            
            String[] aryZgProPlanId = new String[zgProPlanIds.size()];
            return zgProPlanIds.toArray(aryZgProPlanId);
    	}finally{
    		if(st != null){
    			try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
    		}
    	}
	}
	
	/**
     * 获取轧管计划ID
     * @param con
     * @return
     * @throws SQLException 
     */
    private String[] GetApplyZgPlanId(ArrayList<QcmGpJudgeApplyEntity> gpJudgeApplys,String judgeStoveNo
    		,String stoveNo, Connection con)
    		throws SQLException{
    	Statement st = null;
    	try{
    		st = con.createStatement();
    		ArrayList<String> zgProPlanIds = new ArrayList<String>();
    		for(QcmGpJudgeApplyEntity gpJudgeApply : gpJudgeApplys){
    			if (gpJudgeApply.getProPlanIdNext() != "" && gpJudgeApply.getProPlanIdNext().startsWith("ZG"))
                {
                	zgProPlanIds.add(gpJudgeApply.getProPlanIdNext() + gpJudgeApply.getGxPlanNoNext());
                }
                else
                {
                    String zzProPlanId = "";
                    if (gpJudgeApply.getProPlanIdNext() != "")
                    {
                        zzProPlanId = gpJudgeApply.getProPlanIdNext();
                    }
                    else
                    {
                        zzProPlanId = gpJudgeApply.getProPlanId();
                    }
                    SqlBuilder b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryByGpreqId");
                    b.Fill(new String[]{ zzProPlanId });
                    ResultSet rs = st.executeQuery(b.toString());
                    while(rs.next()){
                    	zgProPlanIds.add(rs.getString("PRO_PLAN_ID"));
                    }
                }
    		}
            //增加余材获取成分
            if (zgProPlanIds.size() <= 0)
            {
            	SqlBuilder b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getApplyPlnIdByStoveNoApplyNo");
                b.Fill(new String[]{ "","",judgeStoveNo,stoveNo});
                gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
                		b.toString(), con, QcmGpJudgeApplyEntity.class);
                
                for(QcmGpJudgeApplyEntity gpJudgeApply : gpJudgeApplys)
                {
                    String proPlanIdNext = gpJudgeApply.getProPlanIdNext();
                    String gxPlanNoNext = gpJudgeApply.getGxPlanNoNext();
                    String proPlanId = gpJudgeApply.getProPlanId();
                    if (gpJudgeApply.getProPlanIdNext() != "" && gpJudgeApply.getProPlanIdNext().startsWith("ZG"))
                    {
                    	zgProPlanIds.add(gpJudgeApply.getProPlanIdNext() + gpJudgeApply.getGxPlanNoNext());
    	            }
                    else
                    {
                    	String zzProPlanId = "";
                        if (proPlanIdNext != "")
                        {
                            zzProPlanId = proPlanIdNext;
                        }
                        else
                        {
                            zzProPlanId = proPlanId;
                        }
                        
                        b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryByGpreqId");
    	                b.Fill(new String[]{ zzProPlanId });
    	                ResultSet rs = st.executeQuery(b.toString());
    	                while(rs.next()){
    	                	zgProPlanIds.add(rs.getString("PRO_PLAN_ID"));
    	                }
                    }
                }
            }
    		
    		
            String[] aryZgProPlanId = new String[zgProPlanIds.size()];
            return zgProPlanIds.toArray(aryZgProPlanId);
    	}finally{
    		if(st != null){
    			try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	
	private String judge(String stoveNo, String judgeStoveNo, String plineCode, String sampleNo,
			ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs, Long maxJudgeId, String[] proPlanIds,
			String oldGradecode, String oldGradename, String oldCic, Statement st, Connection con)
			throws SQLException{
		SqlBuilder b;
		ArrayList<String> chemResults = new ArrayList<String>();
		b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getJhyElements");
		b.Fill(new String[]{ stoveNo, sampleNo });
		List<QcmJhyElementsEntity> jhyElements = EntityTool.getEntitysBySqlNoClsCon(
				b.toString(), con, QcmJhyElementsEntity.class);
		if(jhyElements.size() == 0){
//			if(sampleNo.equals("601")){
//				return "40740102";
//			}else{
//				return "40740101";
//			}
			return "";
		}
		
		String proPlanId = "";
		for(String strProPlanId : proPlanIds){
			if(proPlanId.equals("")){
				proPlanId = strProPlanId;
			}else{
				proPlanId += "," + strProPlanId;
			}
		}
		
		for(QcmJhyElementsEntity jhyElement : jhyElements){
			_judgeSeq++;
			//判定炉号涉及到的合同都需要判定
			String designKeys = "";
			String mscPlines = "";
			String cics = "";
			String memo = "";
			HashMap<String, String[]> nkJhyResults = new HashMap<String, String[]>();
			HashMap<String, String[]> jfJhyResults = new HashMap<String, String[]>();
			//对于外购管和利库如果通过铸造订单找不到轧管订单，就去管坯需求表中找。
			if(craftPrcs.size() == 0){
				b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryApplyChemByJudgeStoveNo");
				b.Fill(new String[]{ judgeStoveNo });
				ArrayList<CraftOrdDesignStdCicEntity> craftCics = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), con, CraftOrdDesignStdCicEntity.class);
				//引用坯料标准判定  2025/4/18 ZJL
				if(craftCics.size() == 0){
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryBaseChemByJudgeStoveNo");
					b.Fill(new String[]{ judgeStoveNo });
					craftCics = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, CraftOrdDesignStdCicEntity.class);
				}
				if(craftCics.size() == 0){
					return "40740102";
				}
				Object[] results = ChemJudgeHelper.Judge(jhyElement, craftCics, null, false);
				//添加成分元素
				if(results[1] != null){
					@SuppressWarnings("unchecked")
					HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
					ChemJudgeHelper.mergeChemResult(judgeJhyResults, nkJhyResults);
				}
				if(!results[0].toString().equals("")){
					chemResults.add("40740102");
					if(memo.equals("")){
						memo = craftCics.get(0).getCic() + "：" + results[0].toString();
					}else{
						memo += "\r\n" + craftCics.get(0).getCic() + "：" + results[0].toString();
					}
				}else{
					if(results[0].toString().equals("缺项")){//增加酸溶铝缺项
						chemResults.add("40740106");
					}else{
						chemResults.add("40740101");
					}
				}
				cics = craftCics.get(0).getCic();
			}else{
				for(CraftOrdDesignMscPlPrcEntity craftPrc : craftPrcs){
					/*b = new SqlBuilder("SteelMakingAdvanceJudgeTask.queryCraftChem");
					b.Fill(new String[]{ craftPrc.getDesginKey(), craftPrc.getMscPline(),
							craftPrc.getCic(), "A" });*/
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getCraftNkChem");
					b.Fill(new String[]{ craftPrc.getDesginKey(), craftPrc.getMscPline(),
							"A" ,craftPrc.getCic()});
					
					ArrayList<CraftOrdDesignStdCicEntity> craftCics = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, CraftOrdDesignStdCicEntity.class);
					Object[] results = ChemJudgeHelper.Judge(jhyElement, craftCics, null, false);
					//添加成分元素
					if(results[1] != null){
						@SuppressWarnings("unchecked")
						HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
						ChemJudgeHelper.mergeChemResult(judgeJhyResults, nkJhyResults);
					}
					if(!results[0].toString().equals("")){
						chemResults.add("40740102");
						if(memo.equals("")){
							memo = craftCics.get(0).getCic() + "：" + results[0].toString();
						}else{
							memo += "\r\n" + craftCics.get(0).getCic() + "：" + results[0].toString();
						}
					}else{
						if(results[0].toString().equals("缺项")){//增加酸溶铝缺项
							chemResults.add("40740106");
						}else{
							chemResults.add("40740101");
						}
					}
					if(cics.equals("")){
						cics = craftPrc.getCic();
						designKeys = craftPrc.getDesginKey();
						mscPlines = craftPrc.getMscPline();
					}else{
						cics += "," + craftPrc.getCic();
						designKeys += "," + craftPrc.getDesginKey();
						mscPlines += "," + craftPrc.getMscPline();
					}

					/*//交付
					b = new SqlBuilder("BcChemJudgeTask.getCraftJfChem");
					b.Fill(new String[]{ craftPrc.getDesginKey() });*/
					//交付
					b = new SqlBuilder("SteelMakingAdvanceJudgeTask.getCraftNewJfChem");
					b.Fill(new String[]{ craftPrc.getDesginKey(),craftPrc.getCic() });
					
					ArrayList<CraftOrdDesignStdCicEntity> jfCics = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, CraftOrdDesignStdCicEntity.class);
					Object[] jfResults = ChemJudgeHelper.Judge(jhyElement, jfCics, null, false);
					//添加成分元素
					if(jfResults[1] != null){
						HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)jfResults[1];
						ChemJudgeHelper.mergeChemResult(judgeJhyResults, jfJhyResults);
					}
					if(!jfResults[0].toString().equals("")){
						if(memo.equals("")){
							memo = "交付标准：" + jfResults[0].toString();
						}else{
							memo += "\r\n" + "交付标准：" + jfResults[0].toString();
						}
					}
				}
			}
			
			QcmLgChemjudgeEntity lgChemJudge = new QcmLgChemjudgeEntity();
			if(chemResults.contains("40740102")){
				lgChemJudge.setJudgeresultChem("40740102");
			}else{
				lgChemJudge.setJudgeresultChem("40740101");
			}
			
			lgChemJudge.setChemJudgeId(String.valueOf(maxJudgeId));
			lgChemJudge.setStoveNo(stoveNo);
			lgChemJudge.setJudgeStoveNo(judgeStoveNo);
			lgChemJudge.setPlineCode(plineCode);
			lgChemJudge.setProcessCdoe("B");
			lgChemJudge.setProcessDesc("铸造");
			lgChemJudge.setOrderisunchain("0");
			lgChemJudge.setAssayno(jhyElement.getAssayno());
			lgChemJudge.setCreateName("SYSTEM");
			lgChemJudge.setDesignKey(designKeys);
			lgChemJudge.setMscPline(mscPlines);
			lgChemJudge.setCic(cics);
			lgChemJudge.setMemo(memo);
			lgChemJudge.setSampleNo(jhyElement.getSampleNo());
			lgChemJudge.setJudgeSeq(String.valueOf(_judgeSeq));
			lgChemJudge.setProPlanId(proPlanId);
			lgChemJudge.setOldGradecode(oldGradecode);
			lgChemJudge.setOldGradename(oldGradename);
			lgChemJudge.setOldCic(oldCic);
			
			lgChemJudge.setOldGradecode(oldGradecode);
			String sql = CoreXmlSqlParsersFactory.getSql("SteelMakingAdvanceJudgeTask.InsertLgChemJudge");
			sql = EntityTool.fillSqlByEntity(sql, lgChemJudge);
			st.executeUpdate(sql);

			ArrayList<QcmLgChemResultEntity> lgChemResults = FillLgChemResultNk(
					nkJhyResults, String.valueOf(maxJudgeId), String.valueOf(_judgeSeq));
			//填充交付标准
			FillLgChemResultJf(jfJhyResults, String.valueOf(maxJudgeId),
					String.valueOf(_judgeSeq), lgChemResults);

			//保存成分判定明细（包含复合元素）
			for(QcmLgChemResultEntity lgChemResult : lgChemResults){
				String insertBcChemResult = CoreXmlSqlParsersFactory.getSql("SteelMakingAdvanceJudgeTask.insertLgChemResult");
				insertBcChemResult = EntityTool.fillSqlByEntity(insertBcChemResult, lgChemResult);
				st.executeUpdate(insertBcChemResult);
			}
		}
		
		if(chemResults.contains("40740102")){
			return "40740102";
		}else{
			return "40740101";
		}
	}

	/**
	 * 填充成分内控明细
	 * @param jhyResults
	 * @param chemJudgeId
	 * @param judgeSeq
	 * @return
	 */
	private static ArrayList<QcmLgChemResultEntity> FillLgChemResultNk(
			HashMap<String, String[]> jhyResults, String chemJudgeId, String judgeSeq){
		int chemSeq = 0;
		ArrayList<QcmLgChemResultEntity> lgChemResults = new ArrayList<QcmLgChemResultEntity>();
		for(String key : jhyResults.keySet()){
			chemSeq++;
			QcmLgChemResultEntity bcChemResult = new QcmLgChemResultEntity();
			bcChemResult.setChemJudgeId(chemJudgeId);
			bcChemResult.setJudgeSeq(judgeSeq);
			bcChemResult.setChemSeq(String.valueOf(chemSeq));
			bcChemResult.setChemName(key);
			bcChemResult.setChemValue(jhyResults.get(key)[0]);
			bcChemResult.setNkMin(jhyResults.get(key)[1]);
			bcChemResult.setNkMax(jhyResults.get(key)[2]);
			bcChemResult.setQualified(jhyResults.get(key)[3]);
			bcChemResult.setUnqualifiedType(jhyResults.get(key)[4]);
			lgChemResults.add(bcChemResult);
		}

		return lgChemResults;
	}

	/**
	 * 填充成分交付明细
	 * @param jhyResults
	 * @param chemJudgeId
	 * @param judgeSeq
	 */
	private static void FillLgChemResultJf(HashMap<String, String[]> jhyResults,
										   String chemJudgeId, String judgeSeq, ArrayList<QcmLgChemResultEntity> lgChemResults){
		for(String key : jhyResults.keySet()){
			boolean exists = false;
			for(QcmLgChemResultEntity lgChemResult : lgChemResults){
				if(lgChemResult.getChemName().equals(key)){
					exists = true;
					lgChemResult.setJfMin(jhyResults.get(key)[1]);
					lgChemResult.setJfMax(jhyResults.get(key)[2]);
					lgChemResult.setJfQualified(jhyResults.get(key)[3]);
					break;
				}
			}
			if(!exists && !key.equals("CEⅡw") && !key.equals("CEpcm")){
				QcmLgChemResultEntity lgChemResult = new QcmLgChemResultEntity();
				lgChemResult.setChemJudgeId(chemJudgeId);
				lgChemResult.setJudgeSeq(judgeSeq);
				lgChemResult.setChemSeq(String.valueOf(lgChemResults.size() + 1));
				lgChemResult.setChemName(key);
				lgChemResult.setChemValue(jhyResults.get(key)[0]);
				lgChemResult.setJfMin(jhyResults.get(key)[1]);
				lgChemResult.setJfMax(jhyResults.get(key)[2]);
				lgChemResult.setJfQualified(jhyResults.get(key)[3]);
				lgChemResult.setUnqualifiedType(jhyResults.get(key)[4]);
				lgChemResults.add(lgChemResult);
			}
		}
	}
}
