package com.steering.pss.judge.Bll;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
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.pss.judge.model.ComBaseInfoEntity;
import com.steering.pss.judge.model.QcmBcJudgeEntity;
import com.steering.pss.judge.model.QcmZgJugdeApplyEntity;
import com.steering.pss.plnsaleord.stove.PlanFurnProduction;
import com.steering.pss.qcm.model.GenericEntity;
import com.steering.pss.ydm.pipemanage.FrmBcIqInList;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

public class BllDbkSpecJudge extends DBCommon{
	
	/**
	 * 镦拔扩申请判定时调用的判定方法
	 * @param applyCode
	 * @param judgeStoveNo
	 * @param batchNo
	 * @return
	 */
	public CoreReturnObject judge(String applyCode, String judgeStoveNo, String batchNo){
		Connection con = null;
		Statement st = null;
		CoreReturnObject cro = new CoreReturnObject();
		cro.setResult("1");
		SqlBuilder b;
		Date now = new Date();
		try{
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			st = con.createStatement();
			b = new SqlBuilder("QcmZgJugdeApplyDAL.QueryByBatchNo");
			b.Fill(new String[]{ applyCode, judgeStoveNo, batchNo });
			QcmZgJugdeApplyEntity apply = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), con, QcmZgJugdeApplyEntity.class);
			//有理化要求不能自动判合格。
			if(apply.getSteelStandrad().contains("PIC")){
				return cro;
			}
			
			apply.setJudgeResultCode("40740701");
			apply.setJudgeResult(getComBaseName("40740701", con));
			
			QcmBcJudgeEntity bcJudge = new QcmBcJudgeEntity();
			bcJudge.setAssayno("");
            bcJudge.setChemResult("");
            bcJudge.setChemJudgeId("");
            if(!apply.getSpecResultPath().equals("")){
            	apply.setSpecResultCode("40740301");
        		bcJudge.setSpecResult(apply.getSpecResultCode());
        	}
            if(!apply.getFaceResultPath().equals("")){
            	apply.setFaceResultCode("40740601");
        		bcJudge.setFaceResult(apply.getFaceResultCode());
        	}
            if(!apply.getDetectResultPath().equals("")){
            	apply.setDetectResultCode("40740401");
        		bcJudge.setDetectResult(apply.getDetectResultCode());
        	}
            bcJudge.setJudgeResult("40740701");
            //写入半成品综合判定表
        	bcJudge.setCreateName("SYSTEM");
        	bcJudge.setJudgeStoveNo(judgeStoveNo);
        	bcJudge.setBatchNo(batchNo);
        	bcJudge.setProcessCdoe(apply.getProcessCode());
        	bcJudge.setPlineCode(apply.getPlineCode());
        	bcJudge.setJugdeApplyCode(apply.getJugdeApplyCode());
        	bcJudge.setActCount(apply.getActCount());
        	bcJudge.setActWeight(apply.getActWeight());
        	bcJudge.setActTheoryWeight(apply.getActTheoryWeight());
        	//新增前作废有效的综合判定记录
        	b = new SqlBuilder("JdgQcmBcJudge.updateValid");
        	b.Fill(new String[]{ judgeStoveNo, batchNo, apply.getProcessCode(),
        			apply.getJugdeApplyCode(), "0" });
        	st.executeUpdate(b.toString());
        	//新增判定记录
        	String sqlMaxPk = CoreXmlSqlParsersFactory.getSql("JdgQcmBcJudge.GetMaxPk");
        	GenericEntity maxPk = null;
            maxPk = EntityTool.getEntityBySqlNoClsCon(sqlMaxPk, con, GenericEntity.class);
            bcJudge.setJudgeId(maxPk.getMaxValue());
            String sqlInsert = CoreXmlSqlParsersFactory.getSql("JdgQcmBcJudge.Insert");
            sqlInsert = EntityTool.fillSqlByEntity(sqlInsert, bcJudge);
            st.executeUpdate(sqlInsert);
            
            //回写申请判定表
            b = new SqlBuilder("QcmZgJugdeApplyDAL.setJudgeResult");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo, apply.getProcessCode(),
            		apply.getJudgeResultCode(), "SYSTEM", "", "", apply.getFaceResultCode(),
            		apply.getDetectResultCode(), apply.getSpecResultCode(),
            		apply.getWpressureResultCode(), apply.getProcessResultCode(),
            		"20", "", bcJudge.getJudgeId(), "", "", "" });
            st.executeUpdate(b.toString());
            b = new SqlBuilder("QcmZgJugdeApplyDAL.setJudgeTime", apply.getJugdeApplyCode(),
					judgeStoveNo, batchNo, apply.getProcessCode(), apply.getJudgeResultCode());
			st.executeUpdate(b.toString());

            b = new SqlBuilder("QcmZgJugdeApplyDAL.setBalYearMonth");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,apply.getProcessCode(),
					"120504".equals(apply.getSupplyUnit())? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now)});
            st.executeUpdate(b.toString());
            
            b = new SqlBuilder("JdgMatBcQcmTrack.setJudgeResult");
            b.Fill(new String[]{ judgeStoveNo, batchNo, apply.getProcessCode(), apply.getJugdeApplyCode(),
            		bcJudge.getJudgeId(),
            		apply.getSteelStandrad(), bcJudge.getJudgeResult(), "SYSTEM", "",
            		"", "", "", "", "", "", "", "", "", apply.getFaceResultPath(), "",
            		apply.getSpecResultPath(), "", apply.getDetectResultPath(),
            		apply.getDetectResultPath1(), apply.getWpressureResultPath(), "",
            		apply.getProcessResultPath(), "", "", "", "", "", "", "", ""});
            st.executeUpdate(b.toString());
            
            //回写炼钢、锻造生产物料主表  更新条件应该是 末工序就是成品否者就是在制品。
            String matStatus = "";
            if(apply.getTarget().equals("A")){
            	matStatus = "80150202";
            }else{
            	matStatus = "80150102";
            }
            
            //判定不合格所属权不变。
            if(bcJudge.getJudgeResult().equals("40740701") || bcJudge.getJudgeResult().equals("40740702")){
//            	if(apply.getBelongCodeJugde().equals("")){
//            		con.rollback();
//            		cro.setV_errMsg("判定所属权为空，不能判定！");
//                	return cro;
//            	}
            	b = new SqlBuilder("JdgMatBcM.updateBelong");
                b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,  apply.getBelongCodeJugde(), apply.getBelongNameJugde() });
                st.executeUpdate(b.toString());
                b = new SqlBuilder("JdgMatBcBackup.updateBelong");
                b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo, apply.getBelongCodeJugde(), apply.getBelongNameJugde() });
                st.executeUpdate(b.toString());
            }
            //*********************更新材料表
            String chemJudgeTime = "";
            String chemJudgeName = "";
            String phyJudgeTime = "";
            String phyJudgeName = "";
            b = new SqlBuilder("JdgMatBcM.updateJudgeResult");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,
            		apply.getFaceResultCode(), "", "", apply.getSpecResultCode(), "", "",
            		apply.getChemResultCode(), chemJudgeTime, chemJudgeName,
            		apply.getPhyResultCode(), phyJudgeTime, phyJudgeName, apply.getWpressureResultCode(), 
            		apply.getJudgeResultCode(),apply.getJudgeMaker(), bcJudge.getJudgeId(), apply.getDetectResultCode(),
            		apply.getDetectResultCode1(), apply.getTestingGrade(), apply.getTestingType(),
            		apply.getTestingGrade1(), apply.getTestingType1() });
            st.executeUpdate(b.toString());
            //更新材料历史表
            b = new SqlBuilder("JdgMatBcBackup.updateJudgeResult");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,
            		apply.getFaceResultCode(), "", "", apply.getSpecResultCode(), "", "",
            		apply.getChemResultCode(), chemJudgeTime, chemJudgeName,
            		apply.getPhyResultCode(), phyJudgeTime, phyJudgeName, apply.getWpressureResultCode(), 
            		apply.getJudgeResultCode(), apply.getJudgeMaker(), bcJudge.getJudgeId(), apply.getDetectResultCode(),
            		apply.getDetectResultCode1(), apply.getTestingGrade(), apply.getTestingType(),
            		apply.getTestingGrade1(), apply.getTestingType1() });
            st.executeUpdate(b.toString());
            //更新材料状态、入库标志
            b = new SqlBuilder("JdgMatBcM.updateInstockMatStatus");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,
            		matStatus, "1" });
            st.executeUpdate(b.toString());
            //更新材料状态、入库标志
            b = new SqlBuilder("JdgMatBcBackup.updateInstockMatStatus");
            b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo,
            		matStatus, "1" });
            st.executeUpdate(b.toString());
        	
            if(bcJudge.getJudgeResult().equals("40740701") || bcJudge.getJudgeResult().equals("40740702")){
            	//紧急放行的判定不能写入库表， 紧急放行审核通过时写了
            	//新增入库表
        		b = new SqlBuilder("QcmZgJugdeApplyDAL.QueryByBatchNo");
                b.Fill(new String[]{ apply.getJugdeApplyCode(), judgeStoveNo, batchNo });
                ArrayList<com.steering.pss.ydm.entity.QcmZgJugdeApplyEntity> zgJudges = EntityTool.getEntitysBySqlNoClsCon(
                		b.toString(), con, com.steering.pss.ydm.entity.QcmZgJugdeApplyEntity.class);
        		FrmBcIqInList bcIqInList = new FrmBcIqInList();
        		bcIqInList.insertBcInList(con, zgJudges, "SYSTEM");
        		
        		//调用生成下工序生产计划。
            	if(apply.getProcessCode().equals("E")){
            		PlanFurnProduction.addPlnZyCD(apply.getJugdeApplyCode(), judgeStoveNo, "SYSTEM", con, batchNo);
            	}
            	else if(apply.getProcessCode().equals("F"))
            	{
            		PlanFurnProduction.addPlnZyCF(apply.getJugdeApplyCode(), judgeStoveNo, "SYSTEM", con, batchNo);
            	}
            }
			
			con.commit();
			return cro;
		}catch(Exception ex){
			try {
				con.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if(ex instanceof SQLException){
				cro.setV_errMsg("程序处理失败！");
			}else{
				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 applyCode
	 * @param judgeStoveNo
	 * @param batchNo
	 */
	public CoreReturnObject cancelJudge(String applyCode, String judgeStoveNo, String batchNo){
		BllRolledTubeColligateJudge colligateJudge = new BllRolledTubeColligateJudge();
		SqlBuilder b = new SqlBuilder("QcmZgJugdeApplyDAL.QueryByBatchNo");
		b.Fill(new String[]{ applyCode, judgeStoveNo, batchNo });
		QcmZgJugdeApplyEntity apply = EntityTool.getEntityBySql(
				b.toString(), this.getDao(CoreConstantData.sysbeanstr).getConnection(),
				QcmZgJugdeApplyEntity.class);
		return colligateJudge.deleteJudge(applyCode, judgeStoveNo, batchNo, apply.getProcessCode(), "SYSTEM");
	}
	
	/**
     * 获取基础信息
     * @param baseCode
     * @param con
     * @return
     */
    private String getComBaseName(String baseCode, Connection con){
    	SqlBuilder b = new SqlBuilder("JdgComBaseInfo.QueryBaseName");
    	b.Fill(new String[]{ baseCode });
    	
    	ComBaseInfoEntity baseInfo = EntityTool.getEntityBySqlNoClsCon(
    			b.toString(), con, ComBaseInfoEntity.class);
    	return baseInfo.getBasename();
    }
}
