package com.steering.pss.judge.Bll;

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 CoreFS.SA06.CoreReturnObject;
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.comm.tools.StringTool;
import com.steering.pss.judge.comm.ChemJudgeHelper;
import com.steering.pss.judge.model.*;
import com.steering.pss.qcm.model.GenericEntity;

public class BllSteelMakingChemJudge extends DBCommon{
	private int _judgeSeq = 0;
	/**
     * 炼钢成分判定
     * @return
     */
    public CoreReturnObject judge(String judgeStoveNo, String plineCode,
    		String lkFlag, String user, String memo){
		Connection con = null;
		Statement st = null;
		CoreReturnObject cro = new CoreReturnObject();
		SqlBuilder b;
		try{
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			st = con.createStatement();
			String[] zgProPlanIds;
			String stoveNo = "";
			
			b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo2");
            b.Fill(new String[]{ judgeStoveNo });
            QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
            
            if(gpJudgeApply != null && (gpJudgeApply.getPlineCode().equals("C063")
            		|| gpJudgeApply.getPlineCode().equals("C064") || gpJudgeApply.getLkFlag().equals("1")
            		|| gpJudgeApply.getGptype().equals("2") ||
            		!gpJudgeApply.getOldCic().equals("") && !gpJudgeApply.getOldGradecode().equals(""))){
            	stoveNo = gpJudgeApply.getStoveNo();
            	b = new SqlBuilder("QcmGpJugdeApplyDAL.getApplyPlnIdByJudgeStoveNo");
                b.Fill(new String[]{ judgeStoveNo });
                ArrayList<QcmGpJudgeApplyEntity> gpProPlanIds = EntityTool.getEntitysBySqlNoClsCon(
                		b.toString(), con, QcmGpJudgeApplyEntity.class);
				zgProPlanIds = GetApplyZgPlanId(gpProPlanIds,judgeStoveNo,stoveNo, con);
            }else{
				b = new SqlBuilder("QcmGpJugdeApplyDAL.getStlPlnIdByJudgeStoveNo");
				b.Fill(new String[]{ judgeStoveNo });
				 ArrayList<StlIncisionEntity> stlEntitys = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), con, StlIncisionEntity.class);
				stoveNo = stlEntitys.get(0).getStoveNo();
				zgProPlanIds = GetStlZgPlanId(stlEntitys, con);
				//增加余材获取成分
				if(zgProPlanIds.length<=0){
					b = new SqlBuilder("QcmGpJugdeApplyDAL.getStlPlnIdByStoveNo");
					b.Fill(new String[]{ judgeStoveNo,stoveNo });
					 stlEntitys = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, StlIncisionEntity.class);
					stoveNo = stlEntitys.get(0).getStoveNo();
					zgProPlanIds = GetStlZgPlanId(stlEntitys, con);
				}
				//增加余材获取成分
				if(zgProPlanIds.length<=0){
					b = new SqlBuilder("QcmGpJugdeApplyDAL.getApplyPlnIdByStoveNoApplyNo");
					b.Fill(new String[]{ "","",judgeStoveNo,stoveNo });
					ArrayList<QcmGpJudgeApplyEntity> applyEntitys = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, QcmGpJudgeApplyEntity.class);
					stoveNo = applyEntitys.get(0).getStoveNo();
					zgProPlanIds = GetApplyZgPlanId(applyEntitys,judgeStoveNo,stoveNo, con);
				}
			}
			
			//判定成分
			b = new SqlBuilder("PlnSteelforOrdDAL.getCicByJudgeStoveNo");
			b.Fill(new String[]{ judgeStoveNo });
			CraftOrdDesignMscPlPrcEntity plnCic = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
			String[] cics = new String[1];
			if(plnCic != null){
				cics = plnCic.getCic().split(",");
			}else if(gpJudgeApply != null){
				cics[0] = gpJudgeApply.getCic();
			}

			b = new SqlBuilder("JdgPlnOrderZgS.queryCraftCicByZgProPlanIdNoFirst");
			b.Fill(new Object[]{ zgProPlanIds, cics.length, cics });
			ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
					b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
			
			//增加余材获取成分
			if(craftPrcs.size()<=0){
				b = new SqlBuilder("PlnSteelforOrdDAL.getCicByProPlanId");
				b.Fill(new Object[]{ zgProPlanIds });
				plnCic = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
				cics = new String[1];
				if(plnCic != null){
					cics = plnCic.getCic().split(",");
				}else if(gpJudgeApply != null){
					cics[0] = gpJudgeApply.getCic();
				}
				b = new SqlBuilder("JdgPlnOrderZgS.queryCraftCicByZgProPlanId");
				b.Fill(new Object[]{ zgProPlanIds, cics.length, cics });
				craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
				if(craftPrcs.size()<=0){
					b = new SqlBuilder("JdgPlnOrderZgS.queryCraftCicByZgProPlanIdNew");
					b.Fill(new Object[]{ zgProPlanIds});
					craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
							b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
				}
			}

			//修改判定记录状态
			b = new SqlBuilder("SteelMakingAdvanceJudgeDAL.updateLgChemJudgeValid");
			b.Fill(new String[]{ judgeStoveNo, "0" });
			st.executeUpdate(b.toString());
			b = new SqlBuilder("SteelMakingAdvanceJudgeDAL.updateLgChemJudgeExceptionValid");
			b.Fill(new String[]{ judgeStoveNo, "0" });
			st.executeUpdate(b.toString());
			
			//成分判定记录表
			GenericEntity maxChemJudgeId = EntityTool.getEntityBySqlNoClsCon(CoreXmlSqlParsersFactory.getSql(
					"QcmLgChemJudgeDAL.getMaxChemJudgeId"), con, GenericEntity.class);
			Long maxJudgeId  = Long.parseLong(maxChemJudgeId.getMaxValue());
			_judgeSeq = 0;
			String oldGradecode = "";
			String oldGradename = "";
			String oldCic = "";
			String chemResult601 = judge(stoveNo, judgeStoveNo, plineCode, zgProPlanIds, 
					"601", craftPrcs, user, maxJudgeId, oldGradecode, oldGradename, oldCic, st, con);
			
			String chemResult602 = judge(stoveNo, judgeStoveNo, plineCode, zgProPlanIds,
					"602", craftPrcs, user, maxJudgeId, oldGradecode, oldGradename, oldCic, st, con);
			String chemResult603 = judge(stoveNo, judgeStoveNo, plineCode, zgProPlanIds,
					"603", craftPrcs, user, maxJudgeId, oldGradecode, oldGradename, oldCic, st, con);
			
			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";
			}
			
			//根据成分判定ID修改汇总成分结果、取样类型。
			b = new SqlBuilder("QcmLgChemJudgeDAL.setSampleType");
			b.Fill(new String[]{ String.valueOf(maxJudgeId), chemResult });
			st.executeUpdate(b.toString());
			
			//修改成分化验表
			b = new SqlBuilder("QcmJhyElementsDAL.updateJudgeFlag");
			b.Fill(new String[]{ "20", stoveNo });
			st.executeUpdate(b.toString());
			
            if(plineCode.equals("C063") || plineCode.equals("C064") || lkFlag.equals("利库")
            		|| gpJudgeApply != null && (gpJudgeApply.getGptype().equals("2") 
            		|| !gpJudgeApply.getOldCic().equals("") && !gpJudgeApply.getOldGradecode().equals(""))){
            	b = new SqlBuilder("QcmGpJugdeApplyDAL.udpateGpJudgeApplyCxFlagChem");
    			b.Fill(new String[]{ judgeStoveNo, "20", chemResult });
    			st.executeUpdate(b.toString());
            }else{
            	//管坯申请判定表也更新
            	b = new SqlBuilder("QcmGpJugdeApplyDAL.udpateGpJudgeApplyCxFlagChem");
    			b.Fill(new String[]{ judgeStoveNo, "20", chemResult });
    			st.executeUpdate(b.toString());
            	//回写切割实绩表
    			b = new SqlBuilder("StlIncisionDAL.setChemJudge");
    			b.Fill(new String[]{ String.valueOf(maxJudgeId), "20", chemResult, judgeStoveNo });
    			st.executeUpdate(b.toString());
            }
			
			con.commit();
			return cro;
		}catch(Exception ex){
			try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}finally{
			if(st != null){
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
    }
    
    /**
     * 成分判定
     * @param stoveNo
     * @param judgeStoveNo
     * @param plineCode
     * @param sampleNo
     * @param craftPrcs
     * @param user
     * @param maxJudgeId
     * @param st
     * @param con
     * @return
     * @throws SQLException
     */
    private String judge(String stoveNo, String judgeStoveNo, String plineCode, String[] zgProPlanIds,
    		String sampleNo, ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs,
			String user, Long maxJudgeId, String oldGradecode, String oldGradename, String oldCic,
			Statement st, Connection con)
			throws SQLException{
		SqlBuilder b;
		ArrayList<String> chemResults = new ArrayList<String>();
		b = new SqlBuilder("QcmJhyElementsDAL.queryAllByStoveNo");
		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 "";
		}
		//if(craftPrcs.size() == 0) return "40740101";
		
		String proPlanId = "";
		for(String strProPlanId : zgProPlanIds){
			if(proPlanId.equals("")){
				proPlanId = strProPlanId;
			}else{
				proPlanId += "," + strProPlanId;
			}
		}
		
		for(QcmJhyElementsEntity jhyElement : jhyElements){
			_judgeSeq++;
			chemResults.clear();
			//判定炉号涉及到的合同都需要判定
			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){
				
				/*//取基础成分信息改成取工艺评审信息
				String designKey="";
				b = new SqlBuilder("JdgPlnOrderZgS.queryCraftNoByZgProPlanId");
				b.Fill(new Object[]{ zgProPlanIds });
				ResultSet rs = st.executeQuery(b.toString());
                while(rs.next()){
                	designKey=rs.getString("DESGIN_KEY");
                }
				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryApplyChemByDesignAndCic");
				b.Fill(new String[]{ designKey,craftCics.get(0).getCic() });
				craftCics = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), con, CraftOrdDesignStdCicEntity.class);*/
                
                
				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryApplyChemByJudgeStoveNo");
				b.Fill(new String[]{ judgeStoveNo });
				ArrayList<CraftOrdDesignStdCicEntity> craftCics = EntityTool.getEntitysBySqlNoClsCon(
						b.toString(), con, CraftOrdDesignStdCicEntity.class);
				//引用坯料标准判定  2024/11/13 XYL
				if(craftCics.size() == 0){
					b = new SqlBuilder("QcmGpJugdeApplyDAL.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){
					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{
					chemResults.add("40740101");
				}
				cics = craftCics.get(0).getCic();
			}else{
				for(CraftOrdDesignMscPlPrcEntity craftPrc : craftPrcs){
					b = new SqlBuilder("QcmLgChemJudgeDAL.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){
						HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
						ChemJudgeHelper.mergeChemResult(judgeJhyResults, nkJhyResults);
					}
					if(!results[0].toString().equals("")){
						chemResults.add("40740102");
						if(!results[0].toString().equals("")){
							if(memo.equals("")){
								memo = craftCics.get(0).getCic() + "：" + results[0].toString();
							}else{
								memo += "\r\n" + craftCics.get(0).getCic() + "：" + results[0].toString();
							}
						}
					}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("CraftOrdDesignStdCic.getCraftJfChem");
					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(user);
			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);
			String sql = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeDAL.Insert");
			sql = EntityTool.fillSqlByEntity(sql, lgChemJudge);
			st.executeUpdate(sql);
			
			//写入成分判定异常表
			//。。。。
			if (chemResults.contains("40740102"))
	        {
	            QcmLgChemjudgeExceptionEntity lgChemJudgeException = new QcmLgChemjudgeExceptionEntity();
	            lgChemJudgeException.setCreateName(user);
	            lgChemJudgeException.setJudgeStoveNo(judgeStoveNo);
	            lgChemJudgeException.setOrderisunchain("1");
	            lgChemJudgeException.setOrdLnPk("1");
	            if(!proPlanId.equals("")){
	            	lgChemJudgeException.setPlanProorder(proPlanId);
	            }else{
	            	lgChemJudgeException.setPlanProorder("1");
	            }
	            lgChemJudgeException.setProcessCdoe("B");
	            lgChemJudgeException.setProcessDesc("铸造");
	            lgChemJudgeException.setAssayno(jhyElement.getAssayno());

	            for(QcmJhyElementsEntity jhyElement2 : jhyElements)
	            {
	            	b = new SqlBuilder("QcmJhyElementsDAL.queryByPk");
	            	b.Fill(new String[]{ jhyElement2.getAssayno() });
	            	QcmJhyElementsEntity jhyElementNew = EntityTool.getEntityBySqlNoClsCon(
	            			b.toString(), con, QcmJhyElementsEntity.class);
	            	b = new SqlBuilder("QcmLgChemJudgeDAL.getCraftNkChem");
	            	b.Fill(new String[]{ designKeys, mscPlines, "A", cics });
	            	ArrayList<CraftOrdDesignStdCicEntity> craftNkChems = EntityTool.getEntitysBySqlNoClsCon(
	            			b.toString(), con, CraftOrdDesignStdCicEntity.class);
	            	b = new SqlBuilder("QcmLgChemJudgeDAL.getCraftJfChem");
	            	b.Fill(new String[]{ designKeys });
	            	ArrayList<CraftOrdDesignStdCicEntity> craftJfChems = EntityTool.getEntitysBySqlNoClsCon(
	            			b.toString(), con, CraftOrdDesignStdCicEntity.class);
	                Object[] results2 = ChemJudgeHelper.Judge(jhyElementNew, craftNkChems, craftJfChems, false);
	                if (Boolean.parseBoolean(results2[0].toString()))
	                {
	                	lgChemJudgeException.setJudgeresultChem("40740103");
	                }
	                else
	                {
	                	lgChemJudgeException.setJudgeresultChem("40740104");
	                	break;
	                }
	            }
	            
	            //写入炼钢成分异常表
				String sqlZgChemJudgeException = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeExceptionDAL.Insert");
				sqlZgChemJudgeException = StringTool.ReplaceAll(sqlZgChemJudgeException, "#CHEM_JUDGE_ID#", String.valueOf(maxJudgeId));
				sqlZgChemJudgeException = StringTool.ReplaceAll(sqlZgChemJudgeException, "#JUDGE_SEQ#", String.valueOf(_judgeSeq));
				sqlZgChemJudgeException = EntityTool.fillSqlByEntity(sqlZgChemJudgeException, lgChemJudgeException);
				st.executeUpdate(sqlZgChemJudgeException);
	        }

			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("QcmLgChemJudgeDAL.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);
			}
		}
	}
    
//    private void mergeChemResult(HashMap<String, String[]> judgeJhyResults, HashMap<String, String[]> mergeResults){
//    	for(String key : judgeJhyResults.keySet()){
//    		if(mergeResults.containsKey(key)){
//    			String[] results = mergeResults.get(key);
//    			String value1 = "";
//    			String value2 = "";
//    			//比较下限
//    			if(mergeResults.get(key)[1].equals("")){
//    				results[1] = judgeJhyResults.get(key)[1];
//    			}else{
//    				if(!judgeJhyResults.get(key)[1].equals("")){
//    					value1 = judgeJhyResults.get(key)[1].replace(">", "").replace("=", "");
//    					value2 = mergeResults.get(key)[1].replace(">", "").replace("=", "");
//    					if(Double.parseDouble(value1) > Double.parseDouble(value2)){
//    						results[1] = judgeJhyResults.get(key)[1];
//    					}
//    				}
//    			}
//    			
//    			//比较上限
//    			if(mergeResults.get(key)[2].equals("")){
//    				results[1] = judgeJhyResults.get(key)[2];
//    			}else{
//    				if(!judgeJhyResults.get(key)[2].equals("")){
//    					value1 = judgeJhyResults.get(key)[2].replace("<", "").replace("=", "");
//    					value2 = mergeResults.get(key)[2].replace("<", "").replace("=", "");
//    					if(Double.parseDouble(value1) < Double.parseDouble(value2)){
//    						results[2] = judgeJhyResults.get(key)[2];
//    					}
//    				}
//    			}
//    		}else{
//    			mergeResults.put(key, judgeJhyResults.get(key));
//    		}
//    	}
//    }
    
//    /**
//     * 炼钢成分判定
//     * @param listJSONJhyElement
//     * @param jsonLgChemJudge
//     * @param steelMakingJSON
//     * @param chemResultCode
//     * @return
//     */
//    public CoreReturnObject judge(String jhyElementJson, String jsonLgChemJudge,
//    		String stoveNo, String judgeStoveNo, String proPlanId, String cic,
//    		String judgeApplayCode, String chemResultCode, String judgeType){
//    	ArrayList<QcmJhyElementsEntity> jhyElements = EntityTool.getEntitysByGson(jhyElementJson,
//    			new TypeToken<ArrayList<QcmJhyElementsEntity>>(){}.getType());
////    	for(String jhyElementJson : listJSONJhyElement){
////    		jhyElements.add(EntityTool.getEntityByJSONStr(jhyElementJson, QcmJhyElementsEntity.class));
////    	}
//    	QcmLgChemjudgeEntity lgChemJudge = EntityTool.getEntityByJSONStr(
//    			jsonLgChemJudge, QcmLgChemjudgeEntity.class);
//    	return judge(jhyElements, lgChemJudge, stoveNo, judgeStoveNo, proPlanId, 
//    			cic, judgeApplayCode, chemResultCode, judgeType);
//	}
    
    /**
	 * 获取轧管计划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("JdgPlnOrderZgS.queryByGpreqId");
	                    b.Fill(new String[]{ proPlanId });
	                    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();
				}
    		}
    	}
	}
	
	/**
     * 获取轧管计划ID
     * @param con
     * @return
     * @throws SQLException 
     */
    public static 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("JdgPlnOrderZgS.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("QcmGpJugdeApplyDAL.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("JdgPlnOrderZgS.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();
				}
    		}
    	}
    }
    
    /**
	 * 删除检化验成分实绩
	 * @param stoveNo
	 * @return
	 */
	public CoreReturnObject deleteJhyElements(String stoveNo){
		Connection jhyCon = null;
		//Connection jhyCon = this.getDao(CoreConstantData.sysbeanstr).getConnection();
		CoreReturnObject cro = new CoreReturnObject();
		try{
			//修改检化验状态
			SqlBuilder b = new SqlBuilder("JdgSteerChemAuditResult.updateCxFlag");
			b.Fill(new String[]{ "-1", stoveNo });
			jhyCon = this.getDao("JhyDao").getConnection();
			jhyCon.setAutoCommit(false);
			Statement st = jhyCon.createStatement();
			st.executeUpdate(b.toString());
			st.close();
			
			//删除QCM检化验实绩表
			ArrayList<String> sqllist = new ArrayList<String>();
			b = new SqlBuilder("QcmJhyElementsDAL.deleteJhyElements");
			b.Fill(new String[]{ stoveNo });
			sqllist.add(b.toString());
			//更新切割实绩表
			b = new SqlBuilder("StlIncisionDAL.updateChemJudgeByStoveNo");
			b.Fill(new String[]{ "", "00", "", stoveNo });
			sqllist.add(b.toString());
			//作废判定记录
			b = new SqlBuilder("QcmLgChemJudgeDAL.updateValidflag");
			b.Fill(new String[]{ stoveNo, "B", "0" });
			sqllist.add(b.toString());
			b = new SqlBuilder("QcmLgChemjudgeExceptionDAL.updateValidflag");
			b.Fill(new String[]{ stoveNo, "B", "0" });
			sqllist.add(b.toString());
			
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			jhyCon.commit();
			return cro;
		}catch(Exception ex){
			try {
				jhyCon.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}
		finally{
			try {
				jhyCon.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 更新备注
	 * @param judgeStoveNo
	 * @param memo
	 * @return
	 */
	public CoreReturnObject updateMemo(String judgeStoveNo, String memo){
		SqlBuilder b = new SqlBuilder("QcmLgChemJudgeDAL.updateMemo");
		b.Fill(new String[]{ judgeStoveNo, "B", memo });
		return this.setData(b.toString());
	}
	
	
//	public CoreReturnObject AddChemData(){
//		CoreReturnObject cro = new CoreReturnObject();
//		Connection con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
//		try{
//			con.setAutoCommit(false);
//			Statement st = con.createStatement();
//			SqlBuilder b = new SqlBuilder("QcmLgChemJudgeDAL.getLgChemJudgeByNoChemId");
//			ArrayList<QcmLgChemjudgeEntity> chemJudges = EntityTool.getEntitysBySqlNoClsCon(
//					b.toString(), con, QcmLgChemjudgeEntity.class);
//			for(QcmLgChemjudgeEntity chemJudge : chemJudges){
//				String[] zgProPlanIds;
//				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo2");
//	            b.Fill(new String[]{ chemJudge.getJudgeStoveNo() });
//	            QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
//	            		b.toString(), con, QcmGpJudgeApplyEntity.class);
//	            if(gpJudgeApply != null && (gpJudgeApply.getPlineCode().equals("C063")
//	            		|| gpJudgeApply.getPlineCode().equals("C064") || gpJudgeApply.getLkFlag().equals("1")
//	            		|| gpJudgeApply.getGptype().equals("2") ||
//	            		!gpJudgeApply.getOldCic().equals("") && !gpJudgeApply.getOldGradecode().equals(""))){
//	            	b = new SqlBuilder("QcmGpJugdeApplyDAL.getApplyPlnIdByJudgeStoveNo");
//	                b.Fill(new String[]{ chemJudge.getJudgeStoveNo() });
//	                ArrayList<QcmGpJudgeApplyEntity> gpProPlanIds = EntityTool.getEntitysBySqlNoClsCon(
//	                		b.toString(), con, QcmGpJudgeApplyEntity.class);
//					zgProPlanIds = GetApplyZgPlanId(gpProPlanIds, con);
//	            }else{
//					b = new SqlBuilder("QcmGpJugdeApplyDAL.getStlPlnIdByJudgeStoveNo");
//					b.Fill(new String[]{ chemJudge.getJudgeStoveNo() });
//					 ArrayList<StlIncisionEntity> stlEntitys = EntityTool.getEntitysBySqlNoClsCon(
//							b.toString(), con, StlIncisionEntity.class);
//					zgProPlanIds = GetStlZgPlanId(stlEntitys, con);
//				}
//				
//				//判定成分
//				b = new SqlBuilder("QcmLgChemJudgeDAL.getJhyElementByAssayNo");
//				b.Fill(new String[]{ chemJudge.getAssayno() });
//				QcmJhyElementsEntity jhyElement = EntityTool.getEntityBySqlNoClsCon(
//						b.toString(), con, QcmJhyElementsEntity.class);
//				if(jhyElement == null){
//					System.out.println("没找到检化验实绩信息！");
//					continue;
//				}
//				
//				
//				
//				HashMap<String, String[]> jhyResults = new HashMap<String, String[]>();
//				if(zgProPlanIds.length == 0){
//					b = new SqlBuilder("QcmGpJugdeApplyDAL.queryApplyChemByJudgeStoveNo");
//					b.Fill(new String[]{ chemJudge.getJudgeStoveNo() });
//					ArrayList<CraftOrdDesignStdCicEntity> craftCics = EntityTool.getEntitysBySqlNoClsCon(
//							b.toString(), con, CraftOrdDesignStdCicEntity.class);
//					Object[] results = ChemJudgeHelper.Judge(jhyElement, craftCics, null);
//					//添加成分元素
//					if(results[1] != null){
//						HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
//						ChemJudgeHelper.mergeChemResult(judgeJhyResults, jhyResults);
//					}
//				}else{
//					b = new SqlBuilder("JdgPlnOrderZgS.queryCraftCicByZgProPlanId");
//					b.Fill(new Object[]{ zgProPlanIds });
//					
//					ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
//							b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
//					if(craftPrcs.size() == 0){
//						System.out.println("没有找到内控标准信息，判定失败！");
//						continue;
//					}
//					for(CraftOrdDesignMscPlPrcEntity craftPrc : craftPrcs){
//						b = new SqlBuilder("CraftOrdDesignStdCic.queryCraftChem");
//						b.Fill(new String[]{ craftPrc.getDesginKey(), craftPrc.getMscPline(),
//								craftPrc.getCic(), "A" });
//						ArrayList<CraftOrdDesignStdCicEntity> craftCics = EntityTool.getEntitysBySqlNoClsCon(
//								b.toString(), con, CraftOrdDesignStdCicEntity.class);
//						Object[] results = ChemJudgeHelper.Judge(jhyElement, craftCics, null);
//						//添加成分元素
//						if(results[1] != null){
//							HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
//							ChemJudgeHelper.mergeChemResult(judgeJhyResults, jhyResults);
//						}
//					}
//				}
//				
//				
//				//保存成分判定明细（包含复合元素）
//				b = new SqlBuilder("QcmLgChemJudgeDAL.deleteChemResult");
//				b.Fill(new String[]{ chemJudge.getChemJudgeId(), chemJudge.getJudgeSeq() });
//				st.addBatch(b.toString());
//				int chemSeq = 0;
//				for(String key : jhyResults.keySet()){
//					chemSeq++;
//					b = new SqlBuilder("QcmLgChemJudgeDAL.insertLgChemResult");
//					b.Fill(new String[]{ chemJudge.getChemJudgeId(), chemJudge.getJudgeSeq(),
//							String.valueOf(chemSeq), key, jhyResults.get(key)[0],
//							jhyResults.get(key)[1], jhyResults.get(key)[2], jhyResults.get(key)[3] });
//					st.addBatch(b.toString());
//				}
//			}
//			
//			st.executeBatch();
//			con.commit();
//			return cro;
//		}catch(Exception ex){
//			try {
//				con.rollback();
//			} catch (SQLException e) {
//				e.printStackTrace();
//			}
//			cro.setV_errMsg(ex.getMessage());
//			return cro;
//		}finally{
//			try {
//				con.close();
//			} catch (SQLException e) {
//				e.printStackTrace();
//			}
//		}
//	}
}
