package com.steering.pss.judge.Bll;

import java.sql.Connection;
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.pss.judge.comm.ChemJudgeHelper;
import com.steering.pss.judge.model.CraftOrdDesignStdCicEntity;
import com.steering.pss.judge.model.QcmBcChemResultEntity;
import com.steering.pss.judge.model.QcmBcChemjudgeEntity;
import com.steering.pss.judge.model.QcmJhyElementsEntity;
import com.steering.pss.judge.model.QcmZcCheckconsignEntity;
import com.steering.pss.judge.model.QcmZgJugdeApplyEntity;
import com.steering.pss.qcm.model.GenericEntity;

public class BllRolledTubeChemJudge extends DBCommon{
	
	/**
     * 轧管成分判定
     * @return
	 * @throws SQLException 
     */
    public static String[] judge(QcmZcCheckconsignEntity zcCheckconsign, String ordLnPk,
    		List<QcmJhyElementsEntity> jhyElements, ArrayList<CraftOrdDesignStdCicEntity> craftCics, 
    		String user, String memo, Connection con, Statement st) throws SQLException{
		SqlBuilder b;
		
		//成分判定记录表
		GenericEntity maxChemJudgeId = EntityTool.getEntityBySqlNoClsCon(CoreXmlSqlParsersFactory.getSql(
				"JdgQcmBcChemJudgeDAL.getMaxChemJudgeId"), con, GenericEntity.class);
		Long maxJudgeId  = Long.parseLong(maxChemJudgeId.getMaxValue());
		
		String judgeResult = judge(zcCheckconsign, ordLnPk, jhyElements, craftCics, user, maxJudgeId, st, con);
		
		
		//根据成分判定ID修改汇总成分结果、取样类型。
		b = new SqlBuilder("JdgQcmBcChemJudgeDAL.setSampleType");
		b.Fill(new String[]{ String.valueOf(maxJudgeId), judgeResult });
		st.executeUpdate(b.toString());
		
		//修改成分化验表
		b = new SqlBuilder("QcmJhyElementsDAL.updateJudgeFlagByBatchNo");
		b.Fill(new String[]{ zcCheckconsign.getCheckNo(), zcCheckconsign.getJudgeStoveNo(),
				zcCheckconsign.getBatchNo(), zcCheckconsign.getProcessCode(), "20" });
		st.executeUpdate(b.toString());
		
//    	b = new SqlBuilder("JdgQcmZcCheckconsign.updateChemResult");
//		b.Fill(new String[]{ zcCheckconsign.getCheckNo(), zcCheckconsign.getJudgeStoveNo(),
//				zcCheckconsign.getBatchNo(), zcCheckconsign.getProcessCode(), judgeResult });
//		st.executeUpdate(b.toString());
		
		return new String[]{String.valueOf(maxJudgeId), judgeResult};
    }
    
    /**
     * 成分判定
     * @param stoveNo
     * @param judgeStoveNo
     * @param plineCode
     * @param proPlanId
     * @param sampleNo
     * @param craftPrcs
     * @param user
     * @param maxJudgeId
     * @param st
     * @param con
     * @return
     * @throws SQLException
     */
    private static String judge(QcmZcCheckconsignEntity zcCheckconsign, String ordLnPk,
    		List<QcmJhyElementsEntity> jhyElements, ArrayList<CraftOrdDesignStdCicEntity> craftCics,
    		String user, Long maxJudgeId,
    		Statement st, Connection con) throws SQLException{
		SqlBuilder b;
		ArrayList<String> pChemResults = new ArrayList<String>();
		ArrayList<String> jfChemResults = new ArrayList<String>();
		
		int judgeSeq = 0;
		for(QcmJhyElementsEntity jhyElement : jhyElements){
			judgeSeq++;
			ArrayList<String> cChemResults = new ArrayList<String>();
			//判定炉号涉及到的合同都需要判定
			String memo = "";
			HashMap<String, String[]> jhyResults = new HashMap<String, String[]>();

			//判定内控
			Object[] results = ChemJudgeHelper.Judge(jhyElement, craftCics, null, true);
			//添加成分元素
			if(results[1] != null){
				@SuppressWarnings("unchecked")
				HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
				ChemJudgeHelper.mergeChemResult(judgeJhyResults, jhyResults);
			}
			if(!results[0].toString().equals("")){
				cChemResults.add("40740102");
				pChemResults.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{
				cChemResults.add("40740101");
				pChemResults.add("40740101");
			}
			
			ArrayList<QcmBcChemResultEntity> bcChemResults = FillBcChemResultEntity(
					jhyResults, String.valueOf(maxJudgeId), String.valueOf(judgeSeq));
			
			//*****************判定交付标准*******************
			//2020-07-23 增加氧氮氢相关，熔炼判定取内控，成品判定取交付
			if("A".equals(zcCheckconsign.getProcessCode())){
				b = new SqlBuilder("CraftOrdDesignStdCic.getCraftJfChemByOrdLnPkMaking");
				b.Fill(new String[]{ ordLnPk, zcCheckconsign.getCraftSeq(), zcCheckconsign.getCic() });
			}
			else{
				b = new SqlBuilder("CraftOrdDesignStdCic.getCraftJfChemByOrdLnPk");
				b.Fill(new String[]{ ordLnPk, zcCheckconsign.getCraftSeq(),
						zcCheckconsign.getIndexSeq(), zcCheckconsign.getProcessCode(), zcCheckconsign.getCic() });
			}
			
			ArrayList<CraftOrdDesignStdCicEntity> craftJfCics = EntityTool.getEntitysBySqlNoClsCon(
					b.toString(), con, CraftOrdDesignStdCicEntity.class);
			results = ChemJudgeHelper.Judge(jhyElement, craftJfCics, null, true);
			//添加成分元素
			if(results[1] != null){
				@SuppressWarnings("unchecked")
				HashMap<String, String[]> judgeJhyResults = (HashMap<String, String[]>)results[1];
				FillBcChemResultEntity(judgeJhyResults, String.valueOf(maxJudgeId), 
						String.valueOf(judgeSeq), bcChemResults);
			}
			String jfChemResult = "";
			if(!results[0].toString().equals("")){
				jfChemResults.add("40740104");
				jfChemResult = "40740104";
			}else{
				jfChemResults.add("40740103");
				jfChemResult = "40740103";
			}
			
			
			QcmBcChemjudgeEntity bcChemJudge = new QcmBcChemjudgeEntity();
			if(cChemResults.contains("40740102")){
				bcChemJudge.setJudgeresultChem("40740102");
			}else{
				bcChemJudge.setJudgeresultChem("40740101");
			}
			bcChemJudge.setJfChemResult(jfChemResult);
			bcChemJudge.setChemJudgeId(String.valueOf(maxJudgeId));
			bcChemJudge.setLotNo(zcCheckconsign.getLotNo());
			bcChemJudge.setStoveNo(zcCheckconsign.getStoveNo());
			bcChemJudge.setJudgeStoveNo(zcCheckconsign.getJudgeStoveNo());
			bcChemJudge.setBatchNo(zcCheckconsign.getBatchNo());
			bcChemJudge.setPlineCode(zcCheckconsign.getPlineCode());
			bcChemJudge.setProcessCdoe(zcCheckconsign.getProcessCode());
			bcChemJudge.setOrderisunchain("0");
			bcChemJudge.setAssayno(jhyElement.getAssayno());
			bcChemJudge.setCreateName(user);
			bcChemJudge.setOrdLnDlyPk(zcCheckconsign.getOrdLnDlyPk());
			bcChemJudge.setCraftSeq(zcCheckconsign.getCraftSeq());
			bcChemJudge.setMscPline(zcCheckconsign.getIndexSeq());
			bcChemJudge.setCic(zcCheckconsign.getCic());
			bcChemJudge.setMemo(memo);
			bcChemJudge.setSampleId(zcCheckconsign.getCheckNo());
			bcChemJudge.setSampleNo(jhyElement.getSampleNo());
			bcChemJudge.setJudgeSeq(String.valueOf(judgeSeq));
			bcChemJudge.setJudgegradecode(zcCheckconsign.getGradecode());
			bcChemJudge.setJudgesteelcode(zcCheckconsign.getSteelcode());
			bcChemJudge.setCraftSource(zcCheckconsign.getCraftSource());
			//作废已存判的样管
			b = new SqlBuilder("JdgQcmBcChemJudgeDAL.setValidflag");
			b.Fill(new String[]{ zcCheckconsign.getJudgeStoveNo(), zcCheckconsign.getBatchNo(),
					bcChemJudge.getSampleNo(), bcChemJudge.getSampleId(),
					bcChemJudge.getProcessCdoe(), "0" });
			st.executeUpdate(b.toString());
			String sql = CoreXmlSqlParsersFactory.getSql("JdgQcmBcChemJudgeDAL.insert");
			sql = EntityTool.fillSqlByEntity(sql, bcChemJudge);
			st.executeUpdate(sql);
			
			//保存成分判定明细（包含复合元素）
			for(QcmBcChemResultEntity bcChemResult : bcChemResults){
				String insertBcChemResult = CoreXmlSqlParsersFactory.getSql("JdgQcmBcChemResult.insert");
				insertBcChemResult = EntityTool.fillSqlByEntity(insertBcChemResult, bcChemResult);
				st.executeUpdate(insertBcChemResult);
			}
		}
		
		if(jfChemResults.contains("40740104")){
			return "40740104";
		}else{
			if(pChemResults.contains("40740102")){
				return "40740102";
			}else{
				return "40740101";
			}
		}
	}
    
    /**
     * 填充半成品成分内控明细
     * @param jhyResults
     * @param chemJudgeId
     * @param judgeSeq
     * @return
     */
    private static ArrayList<QcmBcChemResultEntity> FillBcChemResultEntity(
    		HashMap<String, String[]> jhyResults, String chemJudgeId, String judgeSeq){
    	int chemSeq = 0;
    	ArrayList<QcmBcChemResultEntity> bcChemResults = new ArrayList<QcmBcChemResultEntity>();
		for(String key : jhyResults.keySet()){
			chemSeq++;
			QcmBcChemResultEntity bcChemResult = new QcmBcChemResultEntity();
			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.setNkQualified(jhyResults.get(key)[3]);
			bcChemResult.setUnqualifiedType(jhyResults.get(key)[4]);
			bcChemResults.add(bcChemResult);
		}
		
		return bcChemResults;
    }
    
    /**
     * 填充半成品交付明细
     * @param jhyResults
     * @param chemJudgeId
     * @param judgeSeq
     * @param bcChemResults
     */
    private static void FillBcChemResultEntity(
    		HashMap<String, String[]> jhyResults, String chemJudgeId, String judgeSeq,
    		ArrayList<QcmBcChemResultEntity> bcChemResults){
    	for(String key : jhyResults.keySet()){
    		boolean exists = false;
    		for(QcmBcChemResultEntity bcChemResult : bcChemResults){
    			if(bcChemResult.getChemName().equals(key)){
    				exists = true;
    				bcChemResult.setJfMin(jhyResults.get(key)[1]);
    				bcChemResult.setJfMax(jhyResults.get(key)[2]);
    				bcChemResult.setJfQualified(jhyResults.get(key)[3]);
    				break;
    			}
    		}
    		if(!exists){
    			QcmBcChemResultEntity bcChemResult = new QcmBcChemResultEntity();
    			bcChemResult.setChemJudgeId(chemJudgeId);
    			bcChemResult.setJudgeSeq(judgeSeq);
    			bcChemResult.setChemSeq(String.valueOf(bcChemResults.size() + 1));
    			bcChemResult.setChemName(key);
    			bcChemResult.setChemValue(jhyResults.get(key)[0]);
    			bcChemResult.setJfMin(jhyResults.get(key)[1]);
    			bcChemResult.setJfMax(jhyResults.get(key)[2]);
    			bcChemResult.setJfQualified(jhyResults.get(key)[3]);
    			bcChemResult.setUnqualifiedType(jhyResults.get(key)[4]);
    			bcChemResults.add(bcChemResult);
    		}
		}
    }
    
    /**
	 * 删除检化验成分实绩
	 * @param stoveNo
	 * @return
	 */
	public CoreReturnObject deleteJhyElements(String judgeApplyCode, String judgeStoveNo,
			String batchNo, String processCode){
		//Connection jhyCon = null;
		Connection jhyCon = this.getDao("JhyDao").getConnection();
		CoreReturnObject cro = new CoreReturnObject();
		try{
			//修改检化验状态
			SqlBuilder b = new SqlBuilder("QcmZgJugdeApplyDAL.QueryByBatchNo");
			b.Fill(new String[]{ judgeApplyCode, judgeStoveNo, batchNo });
			Connection con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			QcmZgJugdeApplyEntity apply = EntityTool.getEntityBySql(
					b.toString(), con, QcmZgJugdeApplyEntity.class);
			
			b = new SqlBuilder("JdgPipeCheckConsignDetail.setChemFlag");
			b.Fill(new String[]{ judgeStoveNo, batchNo, apply.getPlineCode(), "3" });
			//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.deleteJhyElementsByBatchNo");
			b.Fill(new String[]{ judgeStoveNo, batchNo, processCode });
			sqllist.add(b.toString());
			//更新轧管排产表
			b = new SqlBuilder("QcmZgJugdeApplyDAL.udpateChemResult");
			b.Fill(new String[]{ judgeApplyCode, judgeStoveNo, batchNo, processCode, "" });
			sqllist.add(b.toString());
			//作废判定记录
			b = new SqlBuilder("JdgQcmBcChemJudgeDAL.setValidflag");
			b.Fill(new String[]{ judgeStoveNo, batchNo, processCode, "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 batchNo, 
			String processCode, String memo){
		SqlBuilder b = new SqlBuilder("JdgQcmBcChemJudgeDAL.updateMemo");
		b.Fill(new String[]{ judgeStoveNo, batchNo, processCode, memo });
		return this.setData(b.toString());
	}
}
