package com.steering.pss.judge.Bll;

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

import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.data.ComBaseInfo;
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.plnsaleord.GpOptimize.model.PlnReqinfGpEntity;
import com.steering.pss.plnsaleord.stove.ComPlanFurnace;
import com.steering.pss.qcm.model.GenericEntity;
import com.steering.pss.sale.order.orderchange.CrmOrderProduceService;
import com.steering.pss.ydm.entity.YdmGpInlistEntity;
import com.steering.pss.plnsaleord.stove.entity.MatGpMEntity;
import com.steering.pss.ydm.pipemanage.FrmGpIqInList;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

import net.sf.json.JSONObject;

public class BllSteelMakingColligateJudge extends DBCommon{

//	public CoreReturnObject Query(ArrayList<Object> parms){
//		SqlBuilder b = new SqlBuilder("QcmGpJugdeApplyDAL.QueryP");
//		b.Fill(parms.toArray());
//
//	}

//	/**
//     * 判定
//     * @param gpJudgeApplyJson
//     * @param lgJudgeJson
//     * @param chemResultCode
//     * @return
//     */
//    public CoreReturnObject JudgeSteelMaking(String judgeStoveNo,
//    		String judgeApplayCode, String faceResult, String phyResult, String proPlanId,
//    		String judgeType, String judgeApplaySqe){
//    	QcmLgJudgeEntity lgJudge = EntityTool.getEntityByJSONStr(lgJudgeJson, QcmLgJudgeEntity.class);
//    	return JudgeSteelMaking(lgJudge, stoveNo, judgeStoveNo, plineCode, judgeResult,
//    			judgeResultDesc, judgeApplayCode, faceResult,
//    			phyResult, proPlanId, judgeType, judgeApplaySqe);
//    }

	public CoreReturnObject refreshDB(String judgeApplayCode, String judgeApplaySqe,String judgeStoveNo,
											 String user,String judgeMemo){
		Connection con = null;
		Statement st = null;
		CoreReturnObject cro = new CoreReturnObject();
		SqlBuilder b;
		String phyResult = "";
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			st = con.createStatement();
			//通过主键查询申请判定表记录
			b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
			b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
			QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), con, QcmGpJudgeApplyEntity.class);
			if(gpJudgeApply.getSteelStandrad().contains("PIC"))
			{
				String lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNo();
				if(!gpJudgeApply.getJudgeStoveNoLg().equals("")){
					lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNoLg();
				}
				b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryJhyDbCnt");
				b.Fill(new String[]{ lgJudgeStoveNo });
				GenericEntity craftDbCnt = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), con, GenericEntity.class);
				if(craftDbCnt.getCount().equals("0")){
					cro.setV_errMsg("技术标准有低倍要求，但没有找到低倍实绩信息，不允许判定！");
					return cro;
				}
			}
			phyResult = judgePhyDb(gpJudgeApply, user, judgeMemo, con);
			if(!"40740201".equals(phyResult)){
				cro.setV_errMsg("理化判定，不合格！");
				return cro;
			}
			//查询理化
			b = new SqlBuilder("QcmLgPhyjudgeDAL.queryByJudgeStoveNo");
			b.Fill(new String[]{ judgeStoveNo, "B" });
			QcmZgPhyjudgeEntity zgPhyJudge = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), con, QcmZgPhyjudgeEntity.class);
			String phyResultId = "";
			if(zgPhyJudge != null){
				phyResultId = zgPhyJudge.getPhyResultId();
			}
			//修改理化判定结果
			b = new SqlBuilder("QcmGpJugdeApplyDAL.updatePhyResultCode");
			b.Fill(new String[]{ phyResult,judgeApplayCode, judgeApplaySqe, judgeStoveNo });
			st.executeUpdate(b.toString());
			//修改理化结果id
			b = new SqlBuilder("QcmGpJugdeApplyDAL.updatePhyResultId");
			b.Fill(new String[]{ phyResultId,judgeApplayCode, judgeApplaySqe, judgeStoveNo });
			st.executeUpdate(b.toString());
			con.commit();
		}catch(Exception ex){
			try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}finally{
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

    /**
     * 判定
     */
    public CoreReturnObject JudgeSteelMaking(String judgeApplayCode, String judgeApplaySqe,
    		String judgeStoveNo, String user, String judgeOrder, String judgeGroup,
    		String judgeMemo, String judgeMemo2, String judgeType){
    	Connection con = null;
    	Statement st = null;
        CoreReturnObject cro = new CoreReturnObject();
        SqlBuilder b;
        String judgeResult = "";
        String faceResult = "40740601";
        String specResult = "40740301";
        String detectResult = "40740401";
        String phyResult = "";
        Date now = new Date();
        try{
        	con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
        	con.setAutoCommit(false);
        	st = con.createStatement();
            GenericEntity maxPk = null;

            //通过主键查询申请判定表记录
            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
            QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
            if("40740701".equals(gpJudgeApply.getJudgeResultCode())||"40740702".equals(gpJudgeApply.getJudgeResultCode())
            		||"40740706".equals(gpJudgeApply.getJudgeResultCode()))
            {
            	cro.setV_errMsg("该记录已经判定，不允许重复判定！");
            	return cro;
            }
            //查询成分判定记录
            List<QcmLgChemjudgeEntity> lgChemJudges = EntityTool.getEntitysBySqlNoClsCon(
            		new SqlBuilder("QcmLgJudgeDAL.getChemJudge").Fill(
            				new String[]{ gpJudgeApply.getJudgeStoveNo(), "B" }).toString(),
            		con, QcmLgChemjudgeEntity.class);
            if(lgChemJudges.size() == 0){
            	cro.setV_errMsg("没有找到成分判定记录，请先进行成分判定！");
            	return cro;
            }

            if(gpJudgeApply.getInstancyFlag().equals("0")) {
				// 判断库存支数
				int gpSum = 0;
				b = new SqlBuilder("QcmGpJugdeApplyDAL.getCntByApplyCode");
				b.Fill(new String[]{judgeApplayCode, judgeApplaySqe});
				ResultSet gpCount = st.executeQuery(b.toString());
				if (gpCount.next()) {
					gpSum = gpCount.getInt(1);
				}
				gpCount.close();
				b = new SqlBuilder("JdgMatGpM.queryCount");
				b.Fill(new String[]{judgeApplayCode + judgeApplaySqe});
				ResultSet gpMatCount = st.executeQuery(b.toString());
				if (gpMatCount.next()) {
					if (gpMatCount.getInt(1) < gpSum) {
						gpMatCount.close();
						cro.setV_errMsg("库存与判定支数不一致，不能判定！");
						return cro;
					}
				}
				gpMatCount.close();
			}

            //---------------------------验证锁定
            checkJudgeLock(b, gpJudgeApply, con);

            QcmLgJudgeEntity lgJudge = new QcmLgJudgeEntity();
            lgJudge.setCreateName(user);
            String chemResult = "40740101";
            String assayNos = "";
            for(QcmLgChemjudgeEntity lgChemJudge : lgChemJudges){
            	if(lgChemJudge.getJudgeresultChem().equals("40740102")){
            		chemResult = "40740102";
            	}
            	if(assayNos.equals("")){
            		assayNos = lgChemJudge.getAssayno();
            	}else{
            		assayNos += "," + lgChemJudge.getAssayno();
            	}
            }

        	lgJudge.setAssayno(assayNos);
        	lgJudge.setJudgeresultChem(chemResult);
        	lgJudge.setMemoChem(lgChemJudges.get(0).getMemo());
        	lgJudge.setChemJudgeId(lgChemJudges.get(0).getChemJudgeId());

            // 判定理化低倍数据
        	if(gpJudgeApply.getSteelStandrad().contains("PIC"))
        	{
        		String lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNo();
        		if(!gpJudgeApply.getJudgeStoveNoLg().equals("")){
        			lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNoLg();
        		}
        		b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryJhyDbCnt");
                b.Fill(new String[]{ lgJudgeStoveNo });
                GenericEntity craftDbCnt = EntityTool.getEntityBySqlNoClsCon(
                		b.toString(), con, GenericEntity.class);
                if(craftDbCnt.getCount().equals("0")){
                	cro.setV_errMsg("技术标准有低倍要求，但没有找到低倍实绩信息，不允许判定！");
                	return cro;
                }
        	}
        	phyResult = judgePhyDb(gpJudgeApply, lgJudge.getCreateName(), lgJudge.getMemo(), con);

//            if(gpJudgeApply.getDetectResultPath().equals("")){
//            	detectResult = "";
//            }
            if(gpJudgeApply.getFaceResultPath().equals("")){
            	faceResult = "";
            	detectResult = ""; //暂时和表面一样。
            }
            //所有项目合格综合才合格
            if(chemResult.equals("40740101")
            		&& (phyResult.equals("40740201") || phyResult.equals(""))
            		&& (detectResult.equals("40740401") || detectResult.equals(""))
            		&& (faceResult.equals("40740601") || faceResult.equals(""))){
            	judgeResult = "40740701";
            }else{
            	judgeResult = "40740704";
            }

            //判定不合格，如果有处置结果就根据处置结果得出最终判定结果
            b = new SqlBuilder("QcmGpPassApplyDAL.queryByGpJudgeApplyByType");
        	b.Fill(new String[]{ gpJudgeApply.getJugdeApplyCode(), gpJudgeApply.getJugdeApplySqe(),
        			gpJudgeApply.getJudgeStoveNo() });
        	QcmGpPassApplyEntity gpPassApply = EntityTool.getEntityBySqlNoClsCon(
        			b.toString(), con, QcmGpPassApplyEntity.class);
            if(judgeResult.equals("40740704")){
            	if(gpPassApply != null && gpPassApply.getType().equals("0")){
            		if(gpPassApply.getAuditResult2().equals("407502")
            				|| gpPassApply.getAuditResult2().equals("407503")){
            			judgeResult = "40740701";
            		}else if(gpPassApply.getAuditResult2().equals("407504")){
            			cro.setV_errMsg("放行处置结果为降级/改判，请操作撤销判定！");
                    	return cro;
            		}else if(gpPassApply.getAuditResult2().equals("407505")){
            			cro.setV_errMsg("放行处置结果为报废，请操作撤销判定！");
                    	return cro;
            		}else if(gpPassApply.getAuditResult2().equals("407506")){
            			cro.setV_errMsg("放行处置结果为返工，请操作撤销判定！");
                    	return cro;
            		}
            	}
            }

            //查询理化
            b = new SqlBuilder("QcmLgPhyjudgeDAL.queryByJudgeStoveNo");
            b.Fill(new String[]{ judgeStoveNo, "B" });
            QcmZgPhyjudgeEntity zgPhyJudge = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmZgPhyjudgeEntity.class);
            String phyJudgeId = "";
            String phyResultId = "";
            if(zgPhyJudge != null){
            	phyJudgeId = zgPhyJudge.getPhyJudgeId();
            	phyResultId = zgPhyJudge.getPhyResultId();
            }

            lgJudge.setMemo(judgeMemo);
            lgJudge.setStoveNo(gpJudgeApply.getStoveNo());
            lgJudge.setJudgeStoveNo(judgeStoveNo);
            lgJudge.setPlineCode(gpJudgeApply.getPlineCode());
            lgJudge.setProcessCdoe("B");
            lgJudge.setProcessDesc("铸造");
            lgJudge.setJudgeresultPhy(phyResult);
            lgJudge.setJudgeresultFace(faceResult);
            lgJudge.setJudgeresultSpec(specResult);
            lgJudge.setJudgeresult(judgeResult);
            lgJudge.setPhyResultId(phyResultId);
            lgJudge.setOldGradecode(gpJudgeApply.getOldGradecode());
            lgJudge.setOldGradename(gpJudgeApply.getOldGradename());
            lgJudge.setOldCic(gpJudgeApply.getOldCic());
            lgJudge.setJugdeApplyCode(judgeApplayCode);
            lgJudge.setJugdeApplySqe(judgeApplaySqe);
            b = new SqlBuilder("QcmLgJudgeDAL.updateLgJudgeValid");
            b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "B", "0",judgeApplayCode, judgeApplaySqe });
            st.executeUpdate(b.toString());

/*            String sqlMaxPk = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.GetMaxPk");
            maxPk = EntityTool.getEntityBySqlNoClsCon(sqlMaxPk, con, GenericEntity.class);
            lgJudge.setJudgeId(maxPk.getMaxValue());
            String sqlInsert = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.Insert");
            sqlInsert = EntityTool.fillSqlByEntity(sqlInsert, lgJudge);
            st.executeUpdate(sqlInsert);*/


            //修改申请判定表的结转年月
            b = new SqlBuilder("QcmGpPassApplyDAL.queryByGpJudgeApplyPkNew");
        	b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
        	ResultSet rsPassApply = st.executeQuery(b.toString());
        	boolean instancy = false;
        	while(rsPassApply.next()){
        		if(rsPassApply.getString("TYPE").equals("1")){
        			instancy = true;
        		}
        	}
        	rsPassApply.close();
        	//紧急放行时写了结转年月，再次判定就不需要写了。
            if(!instancy){
	            b = new SqlBuilder("QcmGpJugdeApplyDAL.setBalYearMonth");
	            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo,
						"120504".equals(gpJudgeApply.getSupplyUnit())? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now) });

	            st.executeUpdate(b.toString());
            }

            //回写管坯申请判定表中的处置方式
            String auditResult = "407501";
            String auditMemo = "";
            String auditResutl2 = "407501";
            String auditMemo2 = "";
            if(gpPassApply != null){
            	auditResult = gpPassApply.getAuditResult();
            	auditMemo = gpPassApply.getAuditMemo();
            	auditResutl2 = gpPassApply.getAuditResult2();
            	auditMemo2 = gpPassApply.getAuditMemo2();
            }
            b = new SqlBuilder("QcmGpJugdeApplyDAL.setAuditResult");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo,
            		auditResult, auditMemo });
            st.executeUpdate(b.toString());
            b = new SqlBuilder("QcmGpJugdeApplyDAL.setAuditResult2");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo,
            		auditResutl2, auditMemo2 });
            st.executeUpdate(b.toString());

            //修改放行单中的判定状态。
            b = new SqlBuilder("QcmGpPassApplyDAL.updateJudgeResult");
            b.Fill(new String[]{ judgeStoveNo, judgeResult });
            st.executeUpdate(b.toString());

            //回写炼钢、锻造生产物料主表  更新条件应该是 末工序就是成品否者就是在制品。
            String matStatus = "";
            if(gpJudgeApply.getIsendgx().equals("1")){
            	matStatus = "80150202";
            }else{
            	matStatus = "80150102";
            }

            //判定不合格所属权不变。
            if(judgeResult.equals("40740701") || judgeResult.equals("40740702")){
            	if(gpJudgeApply.getSupplyUnitCode().equals("120504")){
            		b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMBelong");
                    b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "002023005", "产品制造部" });
                    st.executeUpdate(b.toString());
                    b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistoryBelong");
                    b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "002023005", "产品制造部" });
                    st.executeUpdate(b.toString());
            	}else{
            		b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMBelong");
                    b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "002001001", "生产计划部" });
                    st.executeUpdate(b.toString());
                    b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistoryBelong");
                    b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "002001001", "生产计划部" });
                    st.executeUpdate(b.toString());
            	}

            }
            //*********************更新材料表
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpM");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, judgeResult, lgJudge.getCreateName(),
            		"1", "1", matStatus, gpJudgeApply.getFaceResultCode(),
            		user, chemResult, lgChemJudges.get(0).getCreateTime(), lgChemJudges.get(0).getCreateName(),
            		phyResult, user, lgChemJudges.get(0).getChemJudgeId(), phyJudgeId, phyResultId });
            st.executeUpdate(b.toString());

            //更新材料历史表
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistory");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, judgeResult, lgJudge.getCreateName(),
            		"1", "1", matStatus, gpJudgeApply.getFaceResultCode(),
            		user, chemResult, lgChemJudges.get(0).getCreateTime(), lgChemJudges.get(0).getCreateName(),
            		phyResult, user, lgChemJudges.get(0).getChemJudgeId(), phyJudgeId, phyResultId });
            st.executeUpdate(b.toString());

            if(judgeResult.equals("40740701") || judgeResult.equals("40740702")){
//            	if(!plnZyCMsg.equals("")){
//            		con.rollback();
//            		cro.setV_errMsg(plnZyCMsg);
//            		return cro;
//            	}

            	//增加商品坯写入质保书数据
            	b = new SqlBuilder("QcmGpPassApplyDAL.queryPlanByOrdNo");
             	b.Fill(new String[]{ gpJudgeApply.getProPlanId()});
             	ResultSet psPlan = st.executeQuery(b.toString());
             	String productSort = "";
             	if(psPlan.next()){
             		productSort=psPlan.getString("produce_sort");
             	}
             	psPlan.close();
            	if("商品坯".equals(productSort)){
            		List<ComBaseChemEntity> baseChems = ChemJudgeHelper.getElementRounds();//圆整位数
            		HashMap<String, String> rounds = new HashMap<String, String>();
            		for(ComBaseChemEntity baseChem : baseChems) {
            			rounds.put(baseChem.getChemName(), baseChem.getRoundingDigits());
            		}

            		b = new SqlBuilder("JdgQcmZcChemColresult.getLgZbsByJudgestoveNo");
            		b.Fill(new String[]{ judgeStoveNo});
            		ArrayList<QcmZbsChemResultEntity> parms = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, QcmZbsChemResultEntity.class);
            		HashMap<String, Integer> mapRound = new HashMap<String, Integer>();
            		for(QcmZbsChemResultEntity parm : parms){
            			parm.setProcessCode("A");
            			int round = getChemRound(parm, rounds);
        				if(!mapRound.containsKey(parm.getChemName())){
        					mapRound.put(parm.getChemName(), round);
        				}
            		}
            		b = new SqlBuilder("JdgQcmZbsChemResult.getMaxChemZbsId");
                 	b.Fill(new String[]{ gpJudgeApply.getProPlanId()});
                 	psPlan = st.executeQuery(b.toString());
                 	String ZbsId = "";
                 	if(psPlan.next()){
                 		ZbsId=psPlan.getString("ZBS_ID");
                 	}
                 	Date nowTime = new Date();
            		SimpleDateFormat dfT = new SimpleDateFormat("yyyyMMdd");
            		String strNowTime = dfT.format(nowTime);
                 	if(ZbsId==null||"".equals(ZbsId)){
                 		ZbsId="GP"+strNowTime+"00001";
                 	}else{
                 		int seq = Integer.parseInt(ZbsId.substring(ZbsId.length() - 5,
                 				ZbsId.length()))+1;
                 		ZbsId="GP"+strNowTime+StringTool.formatDecimal(seq, "00000");
                 	}
            		b = new SqlBuilder("JdgQcmZbsChemResult.deleteByJudgeStoveNo");
                    b.Fill(new String[]{ judgeStoveNo});
                    st.executeUpdate(b.toString());

            		//保存
            		List<String> alSampleNos = new ArrayList<String>();
            		for(QcmZbsChemResultEntity parm : parms){
            			if(parm.getProcessCode().equals("A")){
            				parm.setChemType("0");
            			}else{
            				parm.setChemType("1");
            			}
            			String insert = CoreXmlSqlParsersFactory.getSql("JdgQcmZbsChemResult.insert");
            			parm.setZbsId(ZbsId);
            			parm.setRound(String.valueOf(mapRound.get(parm.getChemName())));
            			parm.setJudgeStoveNo(judgeStoveNo);
            			//特殊处理Al和Alt元素
            			if((parm.getChemName().equals("Al") || parm.getChemName().equals("Alt"))){
            				if(alSampleNos.contains(parm.getSampleNo())){
            					continue;
            				}else{
            					if(parm.getChemName().equals("Alt")){
            						parm.setChemName("Al");
            					}
            					alSampleNos.add(parm.getSampleNo());
            				}
            			}

            			insert = EntityTool.fillSqlByEntity(insert, parm);
            			st.executeUpdate(insert);
            		}
            	}
            	//紧急放行的判定不能写入库表， 紧急放行审核通过时写了
            	if(!instancy){
/*            		b = new SqlBuilder("JdgYdmGpInlist.queryPropertyInListCount");
            		b.Fill(new String[]{ judgeStoveNo });
            		ResultSet rsInListCnt = st.executeQuery(b.toString());
            		if(rsInListCnt.next()){
            			if(rsInListCnt.getInt(1) == 0){
            				//新增入库表
            				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
                    		b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
                    		List<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
                    				b.toString(), con, QcmGpJudgeApplyEntity.class);
                    		FrmGpIqInList gpIqInList = new FrmGpIqInList();
                    		for(QcmGpJudgeApplyEntity gpJudgeApplySub : gpJudgeApplys){
                    			String gpJudgeApplyJson = EntityTool.getGsonByEntity(gpJudgeApplySub);
                                ArrayList<String> gpJudgeApplyJsons = new ArrayList<String>();
                                gpJudgeApplyJsons.add(gpJudgeApplyJson);
                                gpIqInList.insertGpInList(con, gpJudgeApplyJsons, lgJudge.getCreateName());
                    		}
            			}
            		}
            		rsInListCnt.close();
            		*/
            		//取消判断入库表是否有数据 2020-12-15
            		//新增入库表
                    //通过主键查询申请判定表记录
                    b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
                    b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
                    QcmGpJudgeApplyEntity gpJudgeApplynew = EntityTool.getEntityBySqlNoClsCon(
                    		b.toString(), con, QcmGpJudgeApplyEntity.class);
                    if("40740701".equals(gpJudgeApplynew.getJudgeResultCode())||"40740702".equals(gpJudgeApplynew.getJudgeResultCode())
                    		||"40740706".equals(gpJudgeApplynew.getJudgeResultCode()))
                    {
                    	cro.setV_errMsg("该记录已经判定，不允许重复判定！");
                    	return cro;
                    }

    				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
            		b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
            		List<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
            				b.toString(), con, QcmGpJudgeApplyEntity.class);
            		FrmGpIqInList gpIqInList = new FrmGpIqInList();
            		for(QcmGpJudgeApplyEntity gpJudgeApplySub : gpJudgeApplys){
            			String gpJudgeApplyJson = EntityTool.getGsonByEntity(gpJudgeApplySub);
                        ArrayList<String> gpJudgeApplyJsons = new ArrayList<String>();
                        gpJudgeApplyJsons.add(gpJudgeApplyJson);
                        // 入库记录
                        gpIqInList.insertGpInList(con, gpJudgeApplyJsons, lgJudge.getCreateName());
                        
                      //wj 2025115 add
                        //上传判定量到产销
	                    b = new SqlBuilder("QcmGpJugdeApplyDAL.queryMatGpApplyByJudgeStoveNo");
	                    b.Fill(new String[]{ judgeApplayCode,judgeApplayCode });
	                    MatGpMEntity MatGpMApply1 = EntityTool.getEntityBySqlNoClsCon(
	                    b.toString(), con, MatGpMEntity.class);
	                    
                        MatGpMEntity MatGpMApply = new MatGpMEntity();
                        MatGpMApply.setProOrderNo(MatGpMApply1.getProOrderNo());
                        MatGpMApply.setGradename(gpJudgeApplySub.getGradename());
                        MatGpMApply.setDimater(gpJudgeApplySub.getActDimater());
                        MatGpMApply.setActWeight(gpJudgeApplySub.getActTheoryWeight());
                        sendGpReqInf(MatGpMApply);
            		}
            		
            		
            		//生成
                	ArrayList<String> parm = new ArrayList<String>();
                	parm.add(judgeApplayCode);
                	parm.add(judgeApplaySqe);
                	parm.add(judgeStoveNo);
                	ArrayList<ArrayList<String>> parms = new ArrayList<ArrayList<String>>();
                	parms.add(parm);
                	ComPlanFurnace.addPlnZyC(parms, lgJudge.getCreateName(), con);
                	
            	}
            	
				//crm同步
				//通过主键查询申请判定表记录
            	if(!instancy){
            		b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
    				b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
    				QcmGpJudgeApplyEntity crmJudgeApplyEntity = EntityTool.getEntityBySqlNoClsCon(
    						b.toString(), con, QcmGpJudgeApplyEntity.class);
    				String proOrderNo = crmJudgeApplyEntity.getProOrderNo();
    				String[] parts = proOrderNo.split("/");
    				if (parts.length == 3){
    					String orderNo = parts[0];
    					String orderSeq = parts[1];
    					String deliveryNo = parts[2];
    					b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNoToCrm");
    					b.Fill(new String[]{ orderNo, orderSeq, deliveryNo });
    					PlnSaleordEntity plnSaleordEntity = EntityTool.getEntityBySqlNoClsCon(
    							b.toString(), con, PlnSaleordEntity.class);
    					if(plnSaleordEntity !=null && !plnSaleordEntity.getOrdLnPk().equals("")){
    						crmJudgeApplyEntity.setOrdLnDlyPk(plnSaleordEntity.getOrdLnPk());
    						CrmOrderProduceService crmOrderProduceService = new CrmOrderProduceService();
    						crmOrderProduceService.insertJudgeLGCrmOrderProduce(con,crmJudgeApplyEntity,true);
    					}
    				}
            	}
            	
                
            }
          //回写管坯申请判定表
            b = new SqlBuilder("QcmGpJugdeApplyDAL.setJudgeResult");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo, judgeResult,
            		lgJudge.getCreateName(), faceResult, phyResult, detectResult,
            		chemResult, "20", judgeMemo2, judgeOrder, judgeGroup, specResult });
            st.executeUpdate(b.toString());
            String sqlMaxPk = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.GetMaxPk");
            maxPk = EntityTool.getEntityBySqlNoClsCon(sqlMaxPk, con, GenericEntity.class);
            lgJudge.setJudgeId(maxPk.getMaxValue());
            String sqlInsert = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.Insert");
            sqlInsert = EntityTool.fillSqlByEntity(sqlInsert, lgJudge);
            st.executeUpdate(sqlInsert);

            //防止同时撤销申请判定
            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
            QcmGpJudgeApplyEntity gpJudgeApplynew = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
            if(gpJudgeApplynew==null)
            {
            	con.rollback();
            	return cro;
            }
            
            
           
            //tzh 测试先注释 9.5
            
//          //tzh 24.9.5 加入判定量回传产线
//            //通过主键查询判定对应的库存数据
//            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryMatGpApplyByJudgeStoveNo");
//            b.Fill(new String[]{ judgeApplayCode,judgeApplayCode });
//            MatGpMEntity MatGpMApply = EntityTool.getEntityBySqlNoClsCon(
//            b.toString(), con, MatGpMEntity.class);
//           // System.out.print(b.toString());
//            sendGpReqInf(MatGpMApply);
            
            
            con.commit();
            return cro;
        }catch(Exception ex){
        	try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
            cro.setV_errMsg(ex.getMessage());
            return cro;
        }finally{
        	try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        	try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        }
    }
    
    //tzh 24.9.5 add
    public String sendGpReqInf(MatGpMEntity MatGpMApply) {
		String Result = "";
		try {
			JSONObject jsonObj = new JSONObject();
//			jsonObj.put("plan_no", gpReqEntity.getGpreqId());
//			jsonObj.put("wall_thickness", "");
//			jsonObj.put("product_category_code", gpReqEntity.getDiameterGp());
//			jsonObj.put("product_category", "");
//			jsonObj.put("outer_diam", "");
//			jsonObj.put("length", gpReqEntity.getLenGpSingle());
//			jsonObj.put("ruler_length", gpReqEntity.getLengthGp());
//			jsonObj.put("gtecstan_no", "");
//			jsonObj.put("xtecstan_no", "");
//			jsonObj.put("plan_type", gpReqEntity.getRecType());
//			jsonObj.put("length_range", "");
//			jsonObj.put("controls_thickness", "");
//			jsonObj.put("pass", "");
//			jsonObj.put("brand", gpReqEntity.getGradename());
//			jsonObj.put("head_tail_length", gpReqEntity.getCutLoseLen());
//			jsonObj.put("contract_lengt", gpReqEntity.getLengthZz());
//			jsonObj.put("contracted_quantity", "");
//			jsonObj.put("quantity_purchased", gpReqEntity.getGpWeight());
//			jsonObj.put("delivery_status", "");
//			jsonObj.put("section", gpReqEntity.getDiameterGp());//TZH 新增断面/坯料直径
//			jsonObj.put("contract_buyer", gpReqEntity.getBuyplanWtLong());
//			jsonObj.put("delivery_data", "");
//			jsonObj.put("product_contract_nonumber", gpReqEntity.getOrderNo());
//			jsonObj.put("product_contract_no_num", gpReqEntity.getOrderSeq());
//			jsonObj.put("flag", "I"); //TZH 新增状态
		
			//TZH 24.11.4  按产销的要求发送合同号去掉/和之后的东西
			//zhoujl 2025-6-20 调整为/替换成01 SH20250604024/001==》SH20250604024_0001
			String matNo = "";
			String xx = MatGpMApply.getProOrderNo().replace("/", "01");
			/*int i = xx.indexOf('/');	
			if (i!=-1)
			{
				xx=xx.substring(0,i);
			}*/
			Connection con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			String sql = "select mat_no\r\n" + 
					"  from cx_mat_info t\r\n" + 
					" where t.order_item_num = '"+xx+"'\r\n" + 
					"   and rownum = 1";
			PreparedStatement psta = con.prepareStatement(sql);
			ResultSet rs = psta.executeQuery();
			if(rs.next()) {
				matNo = rs.getString(1);
			}
			//TZH 24.11.6 SG_GRADE 的值换成Gradename
			jsonObj.put("contractno", xx);//采购合同号
			jsonObj.put("sg_grade", MatGpMApply.getGradename());//钢级
			jsonObj.put("outer_diam", MatGpMApply.getDimater());//直径
			jsonObj.put("decide_amount", MatGpMApply.getActWeight());//重量
			jsonObj.put("form_name", "坯料验收结果");//重量
			jsonObj.put("form_code","MESTHPO04");//重量
			jsonObj.put("matNo",matNo);//材料号
			//   MatGpMApply.getJudgeResultCode().toString(); //判断结果
	           
			DefaultWebServiceRequest request = new DefaultWebServiceRequest();
			request.setMsgBody("["+jsonObj.toString()+"]");
			//request.setMsgBody(jsonObj.toString());
			//System.out.print(request.setMsgBody);
			//System.out.print(request);
			request.setServiceId("MESTHPO04");
//			System.out.print(request.getMsgBody());
//			Object[] values = new Object[2];
			//values[0] = "{\"KEY\":"+jsonObj.toString()+"}";
			
			//tzh 测试暂时注销
			Result  = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx", request,
					"receiveMessage","");	
			
			
			//return Result+values[0].toString().substring(0, 100);
			return Result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
		
	}
    /**
     * 判定
     */
    public CoreReturnObject refreshZbsInfo(String judgeApplayCode, String judgeApplaySqe,
    		String judgeStoveNo){
    	Connection con = null;
    	Statement st = null;
        CoreReturnObject cro = new CoreReturnObject();
        SqlBuilder b;
        String phyResult = "";
        try{
        	con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
        	con.setAutoCommit(false);
        	st = con.createStatement();
            GenericEntity maxPk = null;
            
            //通过主键查询申请判定表记录
            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
            QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
            
            if(gpJudgeApply.getJudgeResult()!=null){
            	
            	//增加商品坯写入质保书数据
            	b = new SqlBuilder("QcmGpPassApplyDAL.queryPlanByOrdNo");
             	b.Fill(new String[]{ gpJudgeApply.getProPlanId()});
             	ResultSet psPlan = st.executeQuery(b.toString());
             	String productSort = "";
             	if(psPlan.next()){
             		productSort=psPlan.getString("produce_sort");
             	}
             	psPlan.close();
//            	if("商品坯".equals(productSort)){
            		List<ComBaseChemEntity> baseChems = ChemJudgeHelper.getElementRounds();//圆整位数
            		HashMap<String, String> rounds = new HashMap<String, String>();
            		for(ComBaseChemEntity baseChem : baseChems) {
            			rounds.put(baseChem.getChemName(), baseChem.getRoundingDigits());
            		}
            		
            		b = new SqlBuilder("JdgQcmZcChemColresult.getLgZbsByJudgestoveNo");
            		b.Fill(new String[]{ judgeStoveNo});
            		ArrayList<QcmZbsChemResultEntity> parms = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, QcmZbsChemResultEntity.class);
            		HashMap<String, Integer> mapRound = new HashMap<String, Integer>();
            		for(QcmZbsChemResultEntity parm : parms){
            			parm.setProcessCode("A");
            			int round = getChemRound(parm, rounds);
        				if(!mapRound.containsKey(parm.getChemName())){
        					mapRound.put(parm.getChemName(), round);
        				}
            		}
            		b = new SqlBuilder("JdgQcmZbsChemResult.getMaxChemZbsId");
                 	b.Fill(new String[]{ gpJudgeApply.getProPlanId()});
                 	psPlan = st.executeQuery(b.toString());
                 	String ZbsId = "";
                 	if(psPlan.next()){
                 		ZbsId=psPlan.getString("ZBS_ID");
                 	}
                 	Date nowTime = new Date();
            		SimpleDateFormat dfT = new SimpleDateFormat("yyyyMMdd");
            		String strNowTime = dfT.format(nowTime);
                 	if(ZbsId==null||"".equals(ZbsId)){
                 		ZbsId="GP"+strNowTime+"00001";
                 	}else{
                 		int seq = Integer.parseInt(ZbsId.substring(ZbsId.length() - 5,
                 				ZbsId.length()))+1;
                 		ZbsId="GP"+strNowTime+StringTool.formatDecimal(seq, "00000");
                 	}
            		b = new SqlBuilder("JdgQcmZbsChemResult.deleteByJudgeStoveNo");
                    b.Fill(new String[]{ judgeStoveNo});
                    st.executeUpdate(b.toString());
            		
            		//保存
            		List<String> alSampleNos = new ArrayList<String>();
            		for(QcmZbsChemResultEntity parm : parms){
            			if(parm.getProcessCode().equals("A")){
            				parm.setChemType("0");
            			}else{
            				parm.setChemType("1");
            			}
            			String insert = CoreXmlSqlParsersFactory.getSql("JdgQcmZbsChemResult.insert");
            			parm.setZbsId(ZbsId);
            			parm.setRound(String.valueOf(mapRound.get(parm.getChemName())));
            			parm.setJudgeStoveNo(judgeStoveNo);
            			//特殊处理Al和Alt元素
            			if((parm.getChemName().equals("Al") || parm.getChemName().equals("Alt"))){
            				if(alSampleNos.contains(parm.getSampleNo())){
            					continue;
            				}else{
            					if(parm.getChemName().equals("Alt")){
            						parm.setChemName("Al");
            					}
            					alSampleNos.add(parm.getSampleNo());
            				}
            			}
            			
            			insert = EntityTool.fillSqlByEntity(insert, parm);
            			st.executeUpdate(insert);
            		}
//            	}
            }
            
            con.commit();
            return cro;
        }catch(Exception ex){
        	try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
            cro.setV_errMsg(ex.getMessage());
            return cro;
        }finally{
        	try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        	try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        }
    }
    
	private static int getChemRound(QcmZbsChemResultEntity parm, HashMap<String, String> rounds){
		int round = 0;
		if(parm.getJfMin().equals("") && parm.getJfMax().equals("") && parm.getNkMin().equals("")
				&& parm.getNkMax().equals("")){
			round = Integer.parseInt(rounds.get(parm.getChemName()));
		}else{
			String[] jfMinValues = parm.getJfMin().replaceAll("<", "").replaceAll("=", "").replaceAll(">", "").split("\\.");
			int jfMinRound = 0;
			if(jfMinValues.length > 1){
				jfMinRound = jfMinValues[1].length();
			}
			String[] jfMaxValues = parm.getJfMax().replaceAll("<", "").replaceAll("=", "").replaceAll(">", "").split("\\.");
			int jfMaxRound = 0;
			if(jfMaxValues.length > 1){
				jfMaxRound = jfMaxValues[1].length();
			}
			String[] nkMinValues = parm.getNkMin().replaceAll("<", "").replaceAll("=", "").replaceAll(">", "").split("\\.");
			int nkMinRound = 0;
			if(nkMinValues.length > 1){
				nkMinRound = nkMinValues[1].length();
			}
			String[] nkMaxValues = parm.getNkMax().replaceAll("<", "").replaceAll("=", "").replaceAll(">", "").split("\\.");
			int nkMaxRound = 0;
			if(nkMaxValues.length > 1){
				nkMaxRound = nkMaxValues[1].length();
			}
			
			ArrayList<Integer> stdRounds = new ArrayList<Integer>();
			stdRounds.add(jfMinRound);
			stdRounds.add(jfMaxRound);
			stdRounds.add(nkMinRound);
			stdRounds.add(nkMaxRound);
			if(Collections.max(stdRounds) == 0){
				String strRound = rounds.get(parm.getChemName());
				if(strRound != null && StringTool.isNumeric(strRound))
				round = Integer.parseInt(strRound);
			}else{
				round = Collections.max(stdRounds);
			}
		}
		
		return round;
	}
    
    private void checkJudgeLock(SqlBuilder b, QcmGpJudgeApplyEntity gpApply, Connection con) throws Exception{
    	b = new SqlBuilder("JdgQcmJudgeLock.getLockInfo");
    	b.Fill(new String[]{ gpApply.getJudgeStoveNo(), "", "A", "A" });
    	QcmJudgeLockEntity lockEntity = EntityTool.getEntityBySqlNoClsCon(
    			b.toString(), con, QcmJudgeLockEntity.class);
    	if(lockEntity != null){
    		throw new Exception("炉号：" + gpApply.getJudgeStoveNo() + "已被锁定，暂时无法操作！\r\n锁定人："
    				+ lockEntity.getLockName() +" 锁定原因：" + lockEntity.getLockReason());
    	}
    }
    
    /**
     * 获取轧管计划ID
     * @param gpJudgeApply
     * @param con
     * @return
     * @throws SQLException 
     */
    public static String[] GetZgPlanId(QcmGpJudgeApplyEntity gpJudgeApply, Connection con) throws SQLException
    {
    	Statement st = null;
    	try{
    		st = con.createStatement();
    		String zgProPlanId = "";
            String zgGxPlanNo = "";
            if (gpJudgeApply.getProPlanIdNext() != "" && gpJudgeApply.getProPlanIdNext().startsWith("ZG"))
            {
                zgProPlanId = gpJudgeApply.getProPlanIdNext();
                zgGxPlanNo = 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());
                if(rs.next()){
                	zgProPlanId = rs.getString("PRO_PLAN_ID");
                	zgGxPlanNo = rs.getString("GX_PLAN_NO");
                }
            }
            return new String[] { zgProPlanId, zgGxPlanNo };
    	}finally{
    		if(st != null){
    			try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
    
    /**
     * 判定理化低倍数据
     * @param gpJudgeApply
     * @param user
     * @param memo
     * @param con
     * @return
     * @throws SQLException 
     */
    private String judgePhyDb(QcmGpJudgeApplyEntity gpJudgeApply,
    		String user, String memo, Connection con) throws SQLException{
    	Statement st = null;
    	try{
    		st = con.createStatement();
    		SqlBuilder b = new SqlBuilder("QcmGpJugdeApplyDAL.getApplyPlnIdByJudgeStoveNo");
            b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo() });
            ArrayList<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
            String[] zgProPlanIds = BllSteelMakingChemJudge.GetApplyZgPlanId(gpJudgeApplys,gpJudgeApply.getJudgeStoveNo(),gpJudgeApply.getStoveNo(), con);
            
            String proPlanId = "";
    		for(String strProPlanId : zgProPlanIds){
    			if(proPlanId.equals("")){
    				proPlanId = strProPlanId;
    			}else{
    				proPlanId += "," + strProPlanId;
    			}
    		}
    		
    		//判定成分
    		String designKeys = "";
			String mscPlines = "";
			String pics = "";
			b = new SqlBuilder("JdgPlnOrderZgS.queryCraftPicByZgProPlanId");
			b.Fill(new Object[]{ zgProPlanIds });
			ArrayList<CraftOrdDesignMscPlPrcEntity> craftPrcs = EntityTool.getEntitysBySqlNoClsCon(
					b.toString(), con, CraftOrdDesignMscPlPrcEntity.class);
			for(CraftOrdDesignMscPlPrcEntity craftPrc : craftPrcs){
				if(pics.equals("")){
					pics = craftPrc.getCic();
					designKeys = craftPrc.getDesginKey();
					mscPlines = craftPrc.getMscPline();
				}else{
					pics += "," + craftPrc.getCic();
					designKeys += "," + craftPrc.getDesginKey();
					mscPlines += "," + craftPrc.getMscPline();
				}
			}
            
			//对于锻坯，获取低倍时炉号使用炼钢的判定炉号。
			String lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNo();
			if(!gpJudgeApply.getJudgeStoveNoLg().equals("")){
				lgJudgeStoveNo = gpJudgeApply.getJudgeStoveNoLg();
			}
    		b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryJhyDbCnt");
            b.Fill(new String[]{ lgJudgeStoveNo });
            GenericEntity craftDbCnt = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, GenericEntity.class);
            ArrayList<String> failSamples = new ArrayList<String>();
            if(!craftDbCnt.getCount().equals("0")){
            	//删除之前的理化低倍判定记录
            	b = new SqlBuilder("QcmLgPhyjudgeDAL.updateLgPhyJudgeValid");
            	b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "B", "0" });
            	st.executeUpdate(b.toString());
            	b = new SqlBuilder("QcmLgPhyjudgeDAL.updateLgPhyResultValid");
            	b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "B", "0" });
            	st.executeUpdate(b.toString());
            	
            	String jhyLgPhyResultsSql = getPhyDbSql(lgJudgeStoveNo);
            	List<QcmJhyLgPhyresultEntity> jhyLgPhyResults = EntityTool.getEntitysBySqlNoClsCon(
            			jhyLgPhyResultsSql, con, QcmJhyLgPhyresultEntity.class);
            	
            	for(QcmJhyLgPhyresultEntity jhyLgPhyResult : jhyLgPhyResults){
            		if(StringTool.isNumeric(jhyLgPhyResult.getValue1())){
            			if(Double.valueOf(jhyLgPhyResult.getValue1()) > 2){
            				if(!failSamples.contains(jhyLgPhyResult.getSampleNo())){
            					failSamples.add(jhyLgPhyResult.getSampleNo());
            				}
            			}
            		}else if(jhyLgPhyResult.getValue1().equals("有")){
            			if(!failSamples.contains(jhyLgPhyResult.getSampleNo())){
        					failSamples.add(jhyLgPhyResult.getSampleNo());
        				}
            		}
            	}
	        	
	        	//写入理化判定结果集表
                String sampleNo = "";
                String sqlMaxPk = CoreXmlSqlParsersFactory.getSql("QcmLgPhyjudgeDAL.getMaxPhyJudgeId");
	    	    GenericEntity zgPhyJudgeId = EntityTool.getEntityBySqlNoClsCon(sqlMaxPk, con, GenericEntity.class);
	    	    String maxJudgeId = zgPhyJudgeId.getMaxValue();
                int i = 0;
                int judgeSeq = 0;
                for(QcmJhyLgPhyresultEntity jhyLgPhyResult : jhyLgPhyResults){
                	if(jhyLgPhyResult.getSampleId().equals("")) continue;
                	if(!sampleNo.equals(jhyLgPhyResult.getSampleNo())){
                		i = 0;
                		judgeSeq++;
                	}
                	i++;
                	
                	if(!sampleNo.equals(jhyLgPhyResult.getSampleNo())){
                		sampleNo = jhyLgPhyResult.getSampleNo();
	    	        	QcmZgPhyjudgeEntity zgPhyjudge = new QcmZgPhyjudgeEntity();
	    	        	zgPhyjudge.setPhyJudgeId(maxJudgeId);
	    	        	zgPhyjudge.setPhyResultId(maxJudgeId);
	                    zgPhyjudge.setStoveNo(gpJudgeApply.getStoveNo());
	                    zgPhyjudge.setJudgeStoveNo(gpJudgeApply.getJudgeStoveNo());
	                    zgPhyjudge.setPlineCode(gpJudgeApply.getPlineCode());
	                    zgPhyjudge.setProcessCdoe("B");
	                    zgPhyjudge.setProcessDesc("铸造");
	                    if(failSamples.contains(sampleNo)){
	                    	zgPhyjudge.setJudgeresultPhy("40740204");
	                    }else{
	                    	zgPhyjudge.setJudgeresultPhy("40740201");
	                    }
	                    
	                    zgPhyjudge.setJudgegradecode(gpJudgeApply.getGradecode());
	                    zgPhyjudge.setMemo(memo);
	                    zgPhyjudge.setCreateName(user);
	                    zgPhyjudge.setDesignKey(designKeys);
	                    zgPhyjudge.setMscPline(mscPlines);
	                    zgPhyjudge.setPic(pics);
	                    zgPhyjudge.setSampleNo(sampleNo);
	                    zgPhyjudge.setJudgeSeq(String.valueOf(judgeSeq));
	                    zgPhyjudge.setProPlanId(proPlanId);
	                    String sqlInsert = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.insertLgPhyJudge");
	    	        	sqlInsert = EntityTool.fillSqlByEntity(sqlInsert, zgPhyjudge);
	    	        	st.executeUpdate(sqlInsert);
                	}
                	
                	String sqlZgPhyResultInsert = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.insertLgPhyResult");
                	QcmZgPhyresultEntity zgPhyResult = new QcmZgPhyresultEntity();
                	zgPhyResult.setPhyResultId(maxJudgeId);
                	zgPhyResult.setPhyResultSeq(String.valueOf(judgeSeq));
                	zgPhyResult.setStoveNo(gpJudgeApply.getStoveNo());
                	zgPhyResult.setJudgeStoveNo(gpJudgeApply.getJudgeStoveNo());
                	zgPhyResult.setPhyCode(jhyLgPhyResult.getPhyCode());
                	zgPhyResult.setPhyName(jhyLgPhyResult.getPhyName());
                	zgPhyResult.setValue1(jhyLgPhyResult.getValue1());
                	zgPhyResult.setSampleId(jhyLgPhyResult.getSampleId());
                	zgPhyResult.setXh(String.valueOf(i));
                	zgPhyResult.setIndexSeq(String.valueOf(i));
                	zgPhyResult.setCreateName(user);
                	zgPhyResult.setQualified("1");
                	if(StringTool.isNumeric(jhyLgPhyResult.getValue1())){
            			if(Double.valueOf(jhyLgPhyResult.getValue1()) > 2){
            				zgPhyResult.setQualified("0");
            			}
            		}else if(jhyLgPhyResult.getValue1().equals("有")){
            			zgPhyResult.setQualified("0");
            		}
                	zgPhyResult.setNkRange("<=2");
                	sqlZgPhyResultInsert = EntityTool.fillSqlByEntity(sqlZgPhyResultInsert, zgPhyResult);
                	st.executeUpdate(sqlZgPhyResultInsert);
                }
            }else{
            	return "";
            }
            
            st.close();
            
            if(failSamples.size() == 0){
            	return "40740201";
            }else{
            	return "40740204";
            }
    	}finally{
    		if(st != null){
    			try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
    
//    private boolean insertZgPhyResult(){
//    	
//    }
    
    public CoreReturnObject cancelJudge(){
    	return null;
		//      ComPlanFurnace plan = new ComPlanFurnace();
		//    	ArrayList<String> parm = new ArrayList<String>();
		//    	parm.add(judgeApplayCode);
		//    	parm.add(judgeApplaySqe);
		//    	parm.add(judgeStoveNo);
		//    	ArrayList<ArrayList<String>> parms = new ArrayList<ArrayList<String>>();
		//    	parms.add(parm);
		//    	plan.deletePlnSteelOrdC(parms, lgJudge.getCreateName());
    	
    	//删除入库表
//    	FrmGpIqInList gpIqInList = new FrmGpIqInList();
//        String gpJudgeApplyJson = EntityTool.getGsonByEntity(gpJudgeApply);
//        ArrayList<String> gpJudgeApplyJsons = new ArrayList<String>();
//        gpJudgeApplyJsons.add(gpJudgeApplyJson);
//        gpIqInList.cancelInsertGpInList(con, qcmEntity);
    }
    
    /**
     * 申请放行
     * @param gpJudgeApplyPkJson
     * @param user
     * @return
     */
    public CoreReturnObject passApply(ArrayList<String> gpJudgeApplyPkJsons, String user,
    		String unit, String memo){
    	Connection con = null;
    	Statement st = null;
    	CoreReturnObject cro = new CoreReturnObject();
    	try{
        	SqlBuilder b;
        	con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
        	con.setAutoCommit(false);
        	st = con.createStatement();
        	for(String  gpJudgeApplyPkJson : gpJudgeApplyPkJsons){
        		QcmGpJudgeApplyEntity gpJudgeApplyPk = EntityTool.getEntityByJSONStr(
        				gpJudgeApplyPkJson, QcmGpJudgeApplyEntity.class);
        		b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getJudgeStoveNo() });
        		QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
        				b.toString(), con, QcmGpJudgeApplyEntity.class);
        		if(!gpJudgeApply.getJudgeResultCode().equals("40740704")){
        			cro.setV_errMsg("只有判定不合格的记录，才能申请质量放行！");
        			return cro;
        		}
        		ResultSet rs = st.executeQuery(CoreXmlSqlParsersFactory.getSql("QcmGpPassApplyDAL.GetMaxPk"));
        		String passApplyNo = "";
        		if(rs.next()){
        			passApplyNo = rs.getString(1);
        			rs.close();
        		}
        		
        		b = new SqlBuilder("QcmGpPassApplyDAL.GetGpApplyCnt");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getMultipleNum(), gpJudgeApplyPk.getJudgeStoveNo() });
        		ResultSet rsGpApplyCnt = st.executeQuery(b.toString());
        		int gpApplyCnt = 0;
        		if(rsGpApplyCnt.next())
        		{
        			gpApplyCnt = rsGpApplyCnt.getInt(1);
        		}
        		if(gpApplyCnt > 0) //如果有放行申请单，则不重复生成。
        		{
        			continue;
        		}
        		
        		//*****************处理判定结果***********************
        		String judgeResult = "";
                String faceResult = "40740601";
                String detectResult = "40740401";
                String phyResult = "";

        		//理化低倍判定
                //phyResult = judgePhyDb(gpJudgeApply, user, memo, con);
        		
        		//查询成分判定记录
//                QcmLgChemjudgeEntity lgChemJudge = EntityTool.getEntityBySqlNoClsCon(
//                		new SqlBuilder("QcmLgJudgeDAL.getChemJudge").Fill(
//                				new String[]{ gpJudgeApply.getJudgeStoveNo(), "B" }).toString(),
//                		con, QcmLgChemjudgeEntity.class);
                
                //如果存在有效的放行单，作废掉。 （紧急放行后可以操作质量放行。）
                b = new SqlBuilder("QcmGpPassApplyDAL.updateValidflagByJudgeStoveNo");
	            b.Fill(new String[]{ gpJudgeApplyPk.getJudgeStoveNo(), "0", user,
	            		gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe()});
	            st.executeUpdate(b.toString());
        		
        		b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getJudgeStoveNo() });
        		List<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
        				b.toString(), con, QcmGpJudgeApplyEntity.class);
        		for(QcmGpJudgeApplyEntity gpJudgeApplySub : gpJudgeApplys){
        			b = new SqlBuilder("QcmGpPassApplyDAL.GetMaxSeq");
        			b.Fill(new String[]{ passApplyNo });
        			ResultSet rsMaxSeq = st.executeQuery(b.toString());
        			String passApplySeq = "";
        			if(rsMaxSeq.next()){
        				passApplySeq = rsMaxSeq.getString(1);
        			}
        			String sql = CoreXmlSqlParsersFactory.getSql("JdgQcmGpPassApply.insert");
        			//gpJudgeApplySub.setChemResultCode(lgChemJudge.getJudgeresultChem());
        			//gpJudgeApplySub.setPhyResultCode(phyResult);
        			//gpJudgeApplySub.setFaceResultCode(faceResult);
        			//gpJudgeApplySub.setDetectResultCode(detectResult);
        			//gpJudgeApplySub.setJudgeResultCode(judgeResult);
        			gpJudgeApplySub.setMemo(memo);
            		sql = EntityTool.fillSqlByEntity(sql, gpJudgeApplySub);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_NAME#", user);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_NO#", passApplyNo);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_SEQ#", passApplySeq);
            		sql = StringTool.ReplaceAll(sql, "#UNIT_CODE#", unit);
            		sql = StringTool.ReplaceAll(sql, "#TYPE#", "0");
            		st.executeUpdate(sql);
        		}
        	}
        	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();
				}
    		}
    		try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    	}
    }
    
    public CoreReturnObject urgentPassApply(ArrayList<String> gpJudgeApplyPkJsons, String user,
    		String unit, String memo){
    	Connection con = null;
    	Statement st = null;
    	CoreReturnObject cro = new CoreReturnObject();
    	try{
        	SqlBuilder b;
        	con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
        	con.setAutoCommit(false);
        	st = con.createStatement();
        	for(String  gpJudgeApplyPkJson : gpJudgeApplyPkJsons){
        		QcmGpJudgeApplyEntity gpJudgeApplyPk = EntityTool.getEntityByJSONStr(
        				gpJudgeApplyPkJson, QcmGpJudgeApplyEntity.class);
        		b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getJudgeStoveNo() });
        		QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
        				b.toString(), con, QcmGpJudgeApplyEntity.class);
        		if(!gpJudgeApply.getJudgeResultCode().equals("")){
        			cro.setV_errMsg("已判定的记录不能申请紧急放行！");
        			return cro;
        		}
        		
        		ResultSet rs = st.executeQuery(CoreXmlSqlParsersFactory.getSql("QcmGpPassApplyDAL.GetMaxPk"));
        		String passApplyNo = "";
        		if(rs.next()){
        			passApplyNo = rs.getString(1);
        			rs.close();
        		}
        		b = new SqlBuilder("QcmGpPassApplyDAL.GetGpApplyCnt");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getMultipleNum(), gpJudgeApplyPk.getJudgeStoveNo() });
        		ResultSet rsGpApplyCnt = st.executeQuery(b.toString());
        		int gpApplyCnt = 0;
        		if(rsGpApplyCnt.next())
        		{
        			gpApplyCnt = rsGpApplyCnt.getInt(1);
        			rsGpApplyCnt.close();
        		}
        		if(gpApplyCnt > 0) //如果有放行申请单，则不重复生成。
        		{
        			continue;
        		}
        		
        		
        		b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
        		b.Fill(new String[]{ gpJudgeApplyPk.getJugdeApplyCode(), gpJudgeApplyPk.getJugdeApplySqe(),
        				gpJudgeApplyPk.getJudgeStoveNo() });
        		List<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
        				b.toString(), con, QcmGpJudgeApplyEntity.class);
        		for(QcmGpJudgeApplyEntity gpJudgeApplySub : gpJudgeApplys){
        			b = new SqlBuilder("QcmGpPassApplyDAL.GetMaxSeq");
        			b.Fill(new String[]{ passApplyNo });
        			ResultSet rsMaxSeq = st.executeQuery(b.toString());
        			String passApplySeq = "";
        			if(rsMaxSeq.next()){
        				passApplySeq = rsMaxSeq.getString(1);
        				rsMaxSeq.close();
        			}
        			String sql = CoreXmlSqlParsersFactory.getSql("JdgQcmGpPassApply.insert");
        			gpJudgeApplySub.setChemResultCode("");
        			gpJudgeApplySub.setPhyResultCode("");
        			gpJudgeApplySub.setFaceResultCode("");
        			gpJudgeApplySub.setDetectResultCode("");
        			gpJudgeApplySub.setJudgeResultCode("");
        			gpJudgeApplySub.setMemo(memo);
            		sql = EntityTool.fillSqlByEntity(sql, gpJudgeApplySub);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_NAME#", user);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_NO#", passApplyNo);
            		sql = StringTool.ReplaceAll(sql, "#PASS_APPLY_SEQ#", passApplySeq);
            		sql = StringTool.ReplaceAll(sql, "#UNIT_CODE#", unit);
            		sql = StringTool.ReplaceAll(sql, "#TYPE#", "1");
            		st.executeUpdate(sql);

        		}
        	}
        	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();
				}
    		}
    		try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    	}
    }
    
    public String getPhyDbSql(String judgeStoveNo){
//		SqlBuilder b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryCraftDbCnt");
//		b.Fill(new String[]{ designKey, mscPline, "B", pic });
//		GenericEntity count = EntityTool.getEntityBySqlNoClsCon(
//				b.toString(), con, GenericEntity.class);
//		String phyCodeMin = "";
//		if(!count.getCount().equals("0")){
//			b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryCraftProcessC");
//			b.Fill(new String[]{ designKey, mscPline, "B" });
//			GenericEntity value = EntityTool.getEntityBySqlNoClsCon(
//					b.toString(), con, GenericEntity.class);
//			
//			
//			if(value.getValue().equals("B002")){//连铸
//				phyCodeMin = "C0010";
//			}else{//模铸
//				phyCodeMin = "C0025";
//			}
//		}
//		
//		b = new SqlBuilder("QcmJhyPhyDbResultDAL.query");
//		b.Fill(new String[]{ judgeStoveNo, phyCodeMin });
		
    	SqlBuilder b = new SqlBuilder("QcmJhyPhyDbResultDAL.queryQcmJhyDbResult");
    	b.Fill(new String[]{ judgeStoveNo });
		return b.toString();
	}
    
    /**
     * 撤销判定
     * @param judgeApplayCode
     * @param judgeApplaySqe
     * @param judgeStoveNo
     * @param user
     * @return
     */
    public CoreReturnObject deleteJudge(String judgeApplayCode, String judgeApplaySqe,
    		String judgeStoveNo, String user){
    	Connection con = null;
    	Statement st = null;
    	Connection jhyCon = null;
    	Statement jhySt = null;
    	CoreReturnObject cro = new CoreReturnObject();
    	try{
        	SqlBuilder b;
        	con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
        	con.setAutoCommit(false);
        	st = con.createStatement();
        	
        	b = new SqlBuilder("JdgPlnZyZgM.queryIsLoadNew");
        	b.Fill(new String[]{ judgeStoveNo,judgeApplayCode+judgeApplaySqe });
        	ResultSet rsIsLoad = st.executeQuery(b.toString());
        	if(rsIsLoad.next()){
        		if(rsIsLoad.getString("IS_LOAD")!=null){
        			if(rsIsLoad.getString("IS_LOAD").equals("1")){
        				rsIsLoad.close();
            			cro.setV_errMsg("此炉号已轧管上料，不能撤销判定！");
            			return cro;
        			}
        		}
        		/*if(rsIsLoad.getString("IS_LOAD").equals("1")){
        			rsIsLoad.close();
        			cro.setV_errMsg("此炉号已轧管上料，不能撤销判定！");
        			return cro;
        		}*/
        	}
        	rsIsLoad.close();
        	
        	//是否结转
        	b = new SqlBuilder("QcmGpJugdeApplyDAL.QueryOver");
            b.Fill(new String[]{ judgeApplayCode,judgeApplaySqe,judgeStoveNo });
            ResultSet rsIsOver = st.executeQuery(b.toString());
            if(rsIsOver.next()){
                if(rsIsOver.getString("IS_CARRY_VOER").equals("1")){
                    rsIsOver.close();
                    cro.setV_errMsg("此炉号已月末结转，不能撤销判定！");
                    return cro;
                }
            }
            rsIsOver.close();
            
        	//是否委外了
        	b = new SqlBuilder("JdgMatGpM.queryOutSourcingCount");
        	b.Fill(new String[]{ judgeStoveNo });
        	ResultSet rsOutSourcingCnt = st.executeQuery(b.toString());
        	if(rsOutSourcingCnt.next()){
        		if(rsOutSourcingCnt.getInt(1) > 0){
        			rsOutSourcingCnt.close();
        			cro.setV_errMsg("此炉号已委外加工，不能撤销判定！");
        			return cro;
        		}
        	}
        	rsOutSourcingCnt.close();
        	
        	//通过主键查询申请判定表记录
            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
            b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
            QcmGpJudgeApplyEntity gpJudgeApply = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpJudgeApplyEntity.class);
        	
        	//是否轧管利库
        	b = new SqlBuilder("JdgMatGpM.queryLkFData");
        	b.Fill(new String[]{ judgeStoveNo,judgeApplayCode+judgeApplaySqe });
        	ResultSet rsLkData = st.executeQuery(b.toString());
        	if(rsLkData.next()){
        		if(rsLkData.getString("LK_FLAG").equals("1")){
        			b = new SqlBuilder("PlnOrderZg.queryByPk");
        			b.Fill(new String[]{ rsLkData.getString("PRO_PLAN_ID_ZG"), rsLkData.getString("GX_PLAN_NO_ZG") });
        			ResultSet rsPlnZgS = st.executeQuery(b.toString());
        			if(rsPlnZgS.next()){
        				cro.setV_errMsg("此炉号已轧管利库，不能撤销判定！\r\n（如需撤销判定，请联系轧制产线" + rsPlnZgS.getString("PLINE_NAME") + "的计划员）");
        			}
        			rsPlnZgS.close();
        			
        			rsLkData.close();
        			return cro;
        		}
        	}
        	rsLkData.close();


        	// 判断库存支数/长度
			int gpSum = 0;
			int gpLem = 0;
        	b = new SqlBuilder("QcmGpJugdeApplyDAL.getCntByApplyCode");
			b.Fill(new String[]{ judgeApplayCode,judgeApplaySqe });
			ResultSet gpCount = st.executeQuery(b.toString());
			if(gpCount.next()){
				gpSum = gpCount.getInt(1);
				gpLem = gpCount.getInt(2);
			}
			gpCount.close();
			b = new SqlBuilder("JdgMatGpM.queryCount");
			b.Fill(new String[]{ judgeApplayCode+judgeApplaySqe });
			ResultSet gpMatCount = st.executeQuery(b.toString());
			if(gpMatCount.next()){
				if(gpMatCount.getInt(1) < gpSum){
					gpMatCount.close();
					cro.setV_errMsg("库存与判定支数不一致，不能撤销判定！");
					return cro;
				}
			}
			gpMatCount.close();
			b = new SqlBuilder("JdgMatGpM.queryLen");
			b.Fill(new String[]{ judgeApplayCode+judgeApplaySqe, String.valueOf(gpLem)});
			ResultSet gpMatLen = st.executeQuery(b.toString());
			if(gpMatLen.next()){
				if(gpMatLen.getInt(1) != gpLem){
					gpMatLen.close();
					cro.setV_errMsg("库存与判定长度不一致，不能撤销判定！");
					return cro;
				}
			}
			gpMatLen.close();

        	
        	b = new SqlBuilder("QcmGpPassApplyDAL.queryByGpJudgeApplyPk");
        	b.Fill(new String[]{ gpJudgeApply.getJugdeApplyCode(), gpJudgeApply.getJugdeApplySqe(),
        			gpJudgeApply.getJudgeStoveNo() });
        	QcmGpPassApplyEntity passApply = EntityTool.getEntityBySqlNoClsCon(
            		b.toString(), con, QcmGpPassApplyEntity.class);
        	if(passApply != null && passApply.getAuditResult2().equals("")){
        		cro.setV_errMsg("此炉号有放行单正在审核，不能撤销判定！");
    			return cro;
        	}
        	
            
            //更新申请判定表
//            b = new SqlBuilder("QcmGpPassApplyDAL.queryByGpJudgeApplyPk");
//        	b.Fill(new String[]{ gpJudgeApply.getJugdeApplyCode(), gpJudgeApply.getJugdeApplySqe(),
//        			gpJudgeApply.getJudgeStoveNo() });
            
            //如果有处置方式，撤销判定只修改状态。
            if(gpJudgeApply.getAuditResult2().equals("407504") || gpJudgeApply.getAuditResult2().equals("407505")
            		|| gpJudgeApply.getAuditResult2().equals("407506")){
            	b = new SqlBuilder("QcmGpJugdeApplyDAL.setValidflag");
            	b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo, "00" });
            	st.executeUpdate(b.toString());
            }else{
            	b = new SqlBuilder("QcmGpJugdeApplyDAL.setJudgeResult");
            	if(gpJudgeApply.getPlineCode().equals("C063") || gpJudgeApply.getPlineCode().equals("C064")){
					b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo, "",
							"", "", "", "", gpJudgeApply.getChemResultCode(), "00", "", "", "", "" });
				}else{
					b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo, "",
							"", "", "", "", "", "00", "", "", "", "" });
				}
                st.executeUpdate(b.toString());
                
                //更新申请放行记录
                b = new SqlBuilder("QcmGpPassApplyDAL.updateValidflagByJudgeStoveNo");
                b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "0", user,
                		judgeApplayCode, judgeApplaySqe});
                st.executeUpdate(b.toString());
            }
            
            
            //删除之前的理化低倍判定记录
        	b = new SqlBuilder("QcmLgPhyjudgeDAL.updateLgPhyJudgeValid");
        	b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "B", "0" });
        	st.executeUpdate(b.toString());
        	b = new SqlBuilder("QcmLgPhyjudgeDAL.updateLgPhyResultValid");
        	b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "B", "0" });
        	st.executeUpdate(b.toString());
        	
        	//把检化验低倍标志改为-1
        	jhyCon = this.getDao("JhyDao").getConnection();
        	jhyCon.setAutoCommit(false);
        	jhySt = jhyCon.createStatement();
        	b = new SqlBuilder("QcmJhyPhyDbResultDAL.updateJhyDbCxFlag");
        	b.Fill(new String[]{ gpJudgeApply.getJudgeStoveNo(), "-1" });
        	jhySt.executeUpdate(b.toString());
        	jhySt.close();
            
            //更新判定记录表
            b = new SqlBuilder("QcmLgJudgeDAL.updateLgJudgeValid");
            b.Fill(new String[]{ judgeStoveNo, "B", "0" ,judgeApplayCode, judgeApplaySqe});
            st.executeUpdate(b.toString());
            
            //删除炉计划
        	ArrayList<String> parm = new ArrayList<String>();
        	parm.add(judgeApplayCode);
        	parm.add(judgeApplaySqe);
        	parm.add(judgeStoveNo);
        	ArrayList<ArrayList<String>> parms = new ArrayList<ArrayList<String>>();
        	parms.add(parm);
            ComPlanFurnace.deletePlnSteelOrdC(parms, user, con);
            
            //删除入库表
        	//重新查询数据库的新数据
        	b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
    		b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
    		List<QcmGpJudgeApplyEntity> gpJudgeApplys = EntityTool.getEntitysBySqlNoClsCon(
    				b.toString(), con, QcmGpJudgeApplyEntity.class);

			// 删除财务中间表
			for (QcmGpJudgeApplyEntity qcmGpAppEntity : gpJudgeApplys) {
				qcmGpAppEntity.setJugdeApplyCodeSqe(qcmGpAppEntity.getJugdeApplyCode()+qcmGpAppEntity.getJugdeApplySqe()+qcmGpAppEntity.getJugdeApplySequeno());
				String getInListSql = CoreXmlSqlParsersFactory.getSql("FrmGpIqInList.getGpInList");
				getInListSql = EntityTool.fillSqlByEntity(getInListSql, qcmGpAppEntity);
				YdmGpInlistEntity ydmGpInlistEntity = EntityTool.getEntityBySqlNoClsCon(getInListSql, con, YdmGpInlistEntity.class);
				if(ydmGpInlistEntity != null){
					con.rollback();
					cro.setV_errMsg("炉号："+ydmGpInlistEntity.getJudgeStoveNo()+"已被财务系统接收，不能撤销判定！请联系财务系统相关人员！");
					return cro;
				}
				String delGpInListSql = CoreXmlSqlParsersFactory.getSql("FrmGpIqInList.delGpInList");
				delGpInListSql = EntityTool.fillSqlByEntity(delGpInListSql, qcmGpAppEntity);
				st.executeUpdate(delGpInListSql);
				
				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryMatGpApplyByJudgeStoveNo");
                b.Fill(new String[]{ judgeApplayCode,judgeApplayCode });
                MatGpMEntity MatGpMApply1 = EntityTool.getEntityBySqlNoClsCon(
                b.toString(), con, MatGpMEntity.class);
                
	            MatGpMEntity MatGpMApply = new MatGpMEntity();
	            MatGpMApply.setProOrderNo(MatGpMApply1.getProOrderNo());
                MatGpMApply.setGradename(qcmGpAppEntity.getGradename());
                MatGpMApply.setDimater(qcmGpAppEntity.getActDimater());
                MatGpMApply.setActWeight(Double.toString((Double.parseDouble(qcmGpAppEntity.getActTheoryWeight()) * -1)));
	            sendGpReqInf(MatGpMApply);
			}
    		FrmGpIqInList gpIqInList = new FrmGpIqInList();
    		for(QcmGpJudgeApplyEntity gpJudgeApplySub : gpJudgeApplys){
    			String gpJudgeApplyJson = EntityTool.getGsonByEntity(gpJudgeApplySub);
                ArrayList<String> gpJudgeApplyJsons = new ArrayList<String>();
                gpJudgeApplyJsons.add(gpJudgeApplyJson);
                gpIqInList.cancelInsertGpInList(con, gpJudgeApplyJsons);
    		}
    		
    		//更新管坯材料表
            String belongCode = "";
            String belongName = "";
            if(gpJudgeApply.getPlineCode().equals("C002")){
            	belongCode = "002001020004";
            	belongName = "1#炼钢";
            }else if(gpJudgeApply.getPlineCode().equals("C004")){
            	belongCode = "002001020006";
            	belongName = "2#炼钢";
            }else if(gpJudgeApply.getPlineCode().equals("C005")){
            	belongCode = "002001020008";
            	belongName = "2#炼快锻";
            }else if(gpJudgeApply.getPlineCode().equals("C007")){
            	belongCode = "002001020009";
            	belongName = "3#炼钢";
            }else if(gpJudgeApply.getPlineCode().equals("C063") || gpJudgeApply.getPlineCode().equals("C064")){
            	if(gpJudgeApply.getSupplyUnitCode().equals("120504")){
            		belongCode = "002023005";
                	belongName = "产品制造部";
            	}else{
            		belongCode = "002001001";
                	belongName = "生产计划部";
            	}	
            }
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpM");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "", "", "", 
            		"", "80150101", "", "", "", "", "", "", "", "", "", "" });
            st.executeUpdate(b.toString());
            
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistory");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "", "", "", 
            		"", "80150101", "", "", "", "", "", "", "", "", "", "" });
            st.executeUpdate(b.toString());
            
            //*********************更新材料表紧急放行标志
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMInstancy");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "0" });
            st.executeUpdate(b.toString());
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMBelong");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, belongCode, belongName });
            st.executeUpdate(b.toString());
            
            //更新材料历史表紧急放行标志
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistoryInstancy");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, "0" });
            st.executeUpdate(b.toString());
            b = new SqlBuilder("QcmLgJudgeDAL.updateMatGpMHistoryBelong");
            b.Fill(new String[]{ judgeApplayCode + judgeApplaySqe, belongCode, belongName });
            st.executeUpdate(b.toString());

			//crm同步
			//通过主键查询申请判定表记录
			b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNo");
			b.Fill(new String[]{ judgeApplayCode, judgeApplaySqe, judgeStoveNo });
			QcmGpJudgeApplyEntity crmJudgeApplyEntity = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), con, QcmGpJudgeApplyEntity.class);
			String proOrderNo = crmJudgeApplyEntity.getProOrderNo();
			String[] parts = proOrderNo.split("/");
			if (parts.length == 3){
				String orderNo = parts[0];
				String orderSeq = parts[1];
				String deliveryNo = parts[2];
				b = new SqlBuilder("QcmGpJugdeApplyDAL.queryGpApplyByJudgeStoveNoToCrm");
				b.Fill(new String[]{ orderNo, orderSeq, deliveryNo });
				PlnSaleordEntity plnSaleordEntity = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), con, PlnSaleordEntity.class);
				if(plnSaleordEntity !=null && !plnSaleordEntity.getOrdLnPk().equals("")){
					crmJudgeApplyEntity.setOrdLnDlyPk(plnSaleordEntity.getOrdLnPk());
					CrmOrderProduceService crmOrderProduceService = new CrmOrderProduceService();
					crmOrderProduceService.insertJudgeLGCrmOrderProduce(con,crmJudgeApplyEntity,false);
				}
			}
			
			//tzh 24.11.28 add 新增负的判定量给产销
			  //tzh 24.9.5 加入判定量回传产线
            //通过主键查询判定对应的库存数据
//            b = new SqlBuilder("QcmGpJugdeApplyDAL.queryMatGpApplyByJudgeStoveNo2");
//            b.Fill(new String[]{ judgeApplayCode,judgeApplayCode });
//            MatGpMEntity MatGpMApply = EntityTool.getEntityBySqlNoClsCon(
//            b.toString(), con, MatGpMEntity.class);
//           // System.out.print(b.toString());
//            sendGpReqInf(MatGpMApply);

        	return cro;
    	}catch(Exception ex){
    		try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    		try {
				jhyCon.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    		cro.setV_errMsg(ex.getMessage());
    		return cro;
    	}
    	finally{
    		if(jhyCon != null){
    			try {
    				jhyCon.commit();
    			} catch (SQLException e2) {
    				e2.printStackTrace();
    			}
    		}
    		if(con != null){
    			try {
    				con.commit();
    			} catch (SQLException e2) {
    				e2.printStackTrace();
    			}
    		}
        	
    		if(st != null)
    		{
    			try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
    		}
    		if(con != null){
    			try {
    				con.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		
    		if(jhySt != null){
    			try {
    				jhySt.close();
    			} catch (SQLException e1) {
    				e1.printStackTrace();
    			}
    		}
    		
    		if(jhyCon != null){
    			try {
    				jhyCon.close();
    			} catch (SQLException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    	}
    }
    
    /**
     * 更新备注
     * @param parms
     * @return
     */
    public CoreReturnObject UpdateMemo(ArrayList<String[]> parms){
    	ArrayList<String> sqllist = new ArrayList<String>();
    	SqlBuilder b;
    	for(String[] parm : parms){
    		b = new SqlBuilder("QcmLgJudgeDAL.updateMemo");
    		b.Fill(new String[]{ parm[2], "B", parm[3] });
    		sqllist.add(b.toString());
    		
    		b = new SqlBuilder("QcmGpJugdeApplyDAL.udpateJudgeMemo");
    		b.Fill(new String[]{ parm[0], parm[1], parm[2], parm[4] });
    		sqllist.add(b.toString());
    		
    	}
    	
    	return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    }

	/**
	 * 更新自动判定标识
	 * @return
	 */
	public CoreReturnObject setAutoJudge(String judgeApplyCode, String judgeStoveNo){
		SqlBuilder b = new SqlBuilder("QcmGpJugdeApplyDAL.setAutoJudge");
		b.Fill(new String[]{ judgeApplyCode, judgeStoveNo });


		return this.setData(b.toString());
	}
}
