package com.steering.pss.judge.DAL;

import java.sql.Connection;
import java.util.ArrayList;
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.comm.tools.TransctionTool;
import com.steering.pss.judge.comm.ChemJudgeHelper;
import com.steering.pss.judge.model.ChemJudgeEntity;
import com.steering.pss.judge.model.CraftOrdDesignStdCicEntity;
import com.steering.pss.judge.model.QcmJhyElementsEntity;
import com.steering.pss.judge.model.QcmLgChemjudgeEntity;
import com.steering.pss.judge.model.QcmLgChemjudgeExceptionEntity;
import com.steering.pss.qcm.model.GenericEntity;

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

/**
 * 数据库表QCM_LG_CHEMJUDGE所对应的Java类（生成工具：代码生成工具4.0   访问地址：http://172.16.2.128/tool/）
 * @author tgcx-test   date 2016-09-07
 */
public class QcmLgChemjudgeDAL extends DBCommon{

 /**
     * 通用查询
     */
    public CoreReturnObject Query(String furnaceNo, String processCode){
    	SqlBuilder b = new SqlBuilder("QcmLgChemjudgeDAL.Query");
    	b.Fill(new String[]{ furnaceNo, processCode});
        
    	return this.getData(b.toString());
    }
    
    /**
     * 查询炼钢判定记录
     * @param stoveNo
     * @param judgeStoveNo
     * @param judgeTimeB
     * @param judgeTimeE
     * @return
     */
    public CoreReturnObject QuerySteelMaking(String stoveNo, String judgeStoveNo,
    		String judgeTimeB, String judgeTimeE){
    	SqlBuilder b = new SqlBuilder("QcmLgChemjudgeDAL.QuerySteelMaking");
    	b.AppendLn("AND T.STOVE_NO LIKE '%' || {1} || '%'", !stoveNo.equals(""));
        b.AppendLn("AND T.JUDGE_STOVE_NO LIKE '%' || {2} || '%'", !judgeStoveNo.equals(""));
        b.AppendLn("AND T.CREATE_TIME >= TO_DATE({3}, 'YYYY-MM-DD HH24:MI:SS')", !judgeTimeB.equals(""));
        b.AppendLn("AND T.CREATE_TIME <= TO_DATE({4}, 'YYYY-MM-DD HH24:MI:SS')", !judgeTimeE.equals(""));
        b.AppendLn("ORDER BY T.JUDGE_STOVE_NO, T.CHEM_JUDGE_ID DESC");
        b.Fill(new String[]{ "A", stoveNo, judgeStoveNo, judgeTimeB, judgeTimeE });
        
        return this.getData(b.toString());
    }

    /**
     * 通过主键查询
     */
    public CoreReturnObject QueryByPk(String chemJudgeId){
        String sqlQuery = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeDAL.QueryByPk");
        return this.getData(sqlQuery);
    }
    
    /**
     * 炼钢成分判定
     * @param jhyElements
     * @param lgChemJudge
     * @param steelMaking
     * @param chemResultCode
     * @param judgeType 判定类型 0炼钢 1连铸 2轧管
     * @return
     */
    public CoreReturnObject judge(ArrayList<QcmJhyElementsEntity> jhyElements, 
    		QcmLgChemjudgeEntity lgChemJudge, String stoveNo, String judgeStoveNo, 
    		String proPlanId, String cic, String judgeApplayCode, String chemResultCode,
    		String judgeType){
    	String processCode = "";
    	String processDesc = "";
    	if(judgeType.startsWith("1")){
    		processCode = "A";
    		processDesc = "炼钢";
    	}else if(judgeType.startsWith("2")){
    		processCode = "B";
    		processDesc = "铸造";
    	}
//    	String stoveNo = "";
//    	String judgeStoveNo = "";
//    	String proOrderNo = "";
//    	String processCode = "";
//    	String processDesc = "";
//    	String cic = "";
//    	if(judgeType.startsWith("1")){
//    		stoveNo = steelForOrd.getStoveNo();
//    		judgeStoveNo = steelForOrd.getJudgeStoveNo();
//    		proOrderNo = steelForOrd.getProPlanId();
//    		processCode = "A";
//    		processDesc = "炼钢";
//    		cic = steelForOrd.getCic();
//    	}else{
//    		stoveNo = gpJudgeApply.getStoveNo();
//    		judgeStoveNo = steelForOrd.getJudgeStoveNo();
//    		proOrderNo = gpJudgeApply.getProOrderNo();
//    		processCode = "B";
//    		processDesc = "铸造";
//    	}
    	TransctionTool transction = new TransctionTool();
		Connection con = transction.getCon();
		SqlBuilder b;
		try{
			for(QcmJhyElementsEntity jhyElement : jhyElements){
				//修改成分化验表
				String sqlSetJudgeFlag = CoreXmlSqlParsersFactory.getSql("QcmJhyElementsDAL.updateJudgeFlag");
				sqlSetJudgeFlag = StringTool.ReplaceAll(sqlSetJudgeFlag, "#ASSAYNO#", jhyElement.getAssayno());
				if(!transction.ExcuteTransction(sqlSetJudgeFlag)){
					return transction.getReturnObject();
				}
			}
			
			//成分判定记录表
			GenericEntity maxChemJudgeId = EntityTool.getEntityBySqlNoClsCon(CoreXmlSqlParsersFactory.getSql(
					"QcmLgChemJudgeDAL.getMaxChemJudgeId"), con, GenericEntity.class);
			lgChemJudge.setChemJudgeId(maxChemJudgeId.getMaxValue());
			String sql = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeDAL.Insert");
			sql = EntityTool.fillSqlByEntity(sql, lgChemJudge);
			if(!transction.ExcuteTransction(sql)){
				return transction.getReturnObject();
			}
			
			//写入成分判定异常表
			//。。。。
			if (chemResultCode.equals("40740102"))
            {
				b = new SqlBuilder("SteelMakingAdvanceJudgeDAL.queryCraftDesignKey");
				b.Fill(new String[]{ proPlanId });
				ChemJudgeEntity chemJudge = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), con, ChemJudgeEntity.class);
				
				String assayNos = "";
				for(QcmJhyElementsEntity jhyElement : jhyElements){
					if(assayNos.equals("")){
						assayNos = jhyElement.getAssayno();
					}else{
						assayNos += "," + jhyElement.getAssayno();
					}
				}
				
                QcmLgChemjudgeExceptionEntity lgChemJudgeException = new QcmLgChemjudgeExceptionEntity();
                lgChemJudgeException.setCreateName(lgChemJudge.getCreateName());
                lgChemJudgeException.setJudgeStoveNo(judgeStoveNo);
                lgChemJudgeException.setOrderisunchain("1");
                lgChemJudgeException.setOrdLnPk("1");
                lgChemJudgeException.setPlanProorder(proPlanId);
                lgChemJudgeException.setProcessCdoe(processCode);
                lgChemJudgeException.setProcessDesc(processDesc);
                lgChemJudgeException.setAssayno(assayNos);

                for(QcmJhyElementsEntity jhyElement : jhyElements)
                {
                	b = new SqlBuilder("QcmJhyElementsDAL.queryByPk");
                	b.Fill(new String[]{ jhyElement.getAssayno() });
                	QcmJhyElementsEntity jhyElementNew = EntityTool.getEntityBySqlNoClsCon(
                			b.toString(), con, QcmJhyElementsEntity.class);
                	b = new SqlBuilder("QcmLgChemJudgeDAL.getCraftNkChem");
                	b.Fill(new String[]{ chemJudge.getDesginKey(), cic, chemJudge.getMscPline(), processCode });
                	ArrayList<CraftOrdDesignStdCicEntity> craftNkChems = EntityTool.getEntitysBySqlNoClsCon(
                			b.toString(), con, CraftOrdDesignStdCicEntity.class);
                	b = new SqlBuilder("QcmLgChemJudgeDAL.getCraftJfChem");
                	b.Fill(new String[]{ chemJudge.getDesginKey(), cic, chemJudge.getMscPline() });
                	ArrayList<CraftOrdDesignStdCicEntity> craftJfChems = EntityTool.getEntitysBySqlNoClsCon(
                			b.toString(), con, CraftOrdDesignStdCicEntity.class);
                    Object[] results = ChemJudgeHelper.Judge(jhyElementNew, craftNkChems, craftJfChems, false);
                    if (Boolean.parseBoolean(results[0].toString()))
                    {
                    	lgChemJudgeException.setJudgeresultChem("40740103");
                    }
                    else
                    {
                    	lgChemJudgeException.setJudgeresultChem("40740104");
                    	break;
                    }
                }
                
                //写入炼钢成分异常表
				String sqlZgChemJudgeException = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeExceptionDAL.Insert");
				sqlZgChemJudgeException = StringTool.ReplaceAll(sqlZgChemJudgeException, "#CHEM_JUDGE_ID#", lgChemJudge.getChemJudgeId());
				sqlZgChemJudgeException = EntityTool.fillSqlByEntity(sqlZgChemJudgeException, lgChemJudgeException);
				if(!transction.ExcuteTransction(sqlZgChemJudgeException)){
					return transction.getReturnObject();
				}
            }
			
			//回写切割实绩表
			if(judgeType.startsWith("1")){
				b = new SqlBuilder("StlIncisionDAL.setChemJudge");
				b.Fill(new String[]{ lgChemJudge.getChemJudgeId(), "20", lgChemJudge.getJudgeresultChem(), judgeStoveNo });
				if(!transction.ExcuteTransction(b.toString())){
					return transction.getReturnObject();
				}
			}else{//回写连铸申请判定表
				SqlBuilder setChemResultCode = new SqlBuilder("QcmGpJugdeApplyDAL.setChemResultCode");
				setChemResultCode.Fill(new String[]{ chemResultCode, judgeApplayCode });
				if(!transction.ExcuteTransction(setChemResultCode.toString())){
					return transction.getReturnObject();
				}
			}
			
		}catch(Exception ex){
			CoreReturnObject cro = transction.rollBack();
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}
		return transction.commit();
    }
    
    /**
     * 炼钢成分判定
     * @param listJSONJhyElement
     * @param jsonLgChemJudge
     * @param steelMakingJSON
     * @param chemResultCode
     * @return
     */
    public CoreReturnObject judge(ArrayList<String> listJSONJhyElement, String jsonLgChemJudge,
    		String stoveNo, String judgeStoveNo, String proPlanId, String cic,
    		String judgeApplayCode, String chemResultCode, String judgeType){
    	ArrayList<QcmJhyElementsEntity> jhyElements = new ArrayList<QcmJhyElementsEntity>();
    	for(String jhyElementJson : listJSONJhyElement){
    		jhyElements.add(EntityTool.getEntityByJSONStr(jhyElementJson, QcmJhyElementsEntity.class));
    	}
    	QcmLgChemjudgeEntity lgChemJudge = EntityTool.getEntityByJSONStr(
    			jsonLgChemJudge, QcmLgChemjudgeEntity.class);
    	return judge(jhyElements, lgChemJudge, stoveNo, judgeStoveNo, proPlanId, 
    			cic, judgeApplayCode, chemResultCode, judgeType);
	}
}
