package com.steering.pss.judge.Bll;

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.*;
import com.steering.pss.qcm.model.GenericEntity;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BllImportMeltingData extends DBCommon{
	
	public CoreReturnObject SaveLgJudge(String stoveNo){
		Connection con = null;
		Statement st = null;
		CoreReturnObject cro = new CoreReturnObject();
		try{
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			st = con.createStatement();
			//获取检验数据
			SqlBuilder b = new SqlBuilder("QcmJhyElementsDAL.queryByStoveNo");
			b.Fill(new String[]{ "A", stoveNo });
			QcmJhyElementsEntity jhy = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), con, QcmJhyElementsEntity.class);
			
			//判断是否在系统中判定过
			b = new SqlBuilder("QcmZgJugdeApplyDAL.GetLoadJudgeStoveNoByStoveNo");
			b.Fill(new String[]{ stoveNo });
			ArrayList<QcmZgJugdeApplyEntity> zgApplys = EntityTool.getEntitysBySqlNoClsCon(
					b.toString(), con, QcmZgJugdeApplyEntity.class);
			if(zgApplys.size() > 0){
				b = new SqlBuilder("QcmGpJugdeApplyDAL.getCntByStoveNo");
				b.Fill(new String[]{ stoveNo });
				GenericEntity gpApply = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), con, GenericEntity.class);
				if(gpApply.getCount().equals("0")){
					for(QcmZgJugdeApplyEntity zgApply : zgApplys){
						jhy.setJudgeStoveNo(zgApply.getLoadJudgeStoveNo());
						SaveLgJudge(zgApply, jhy, b, con, st);
					}
				}
			}
			
			con.commit();
			return cro;
		}catch(Exception ex){
			try {
				con.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}finally{
			if(st != null){
				try {
					st.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public CoreReturnObject ImportMelting(ArrayList<String> jsons){
		Connection con = null;
		Statement st = null;
		CoreReturnObject cro = new CoreReturnObject();
		try{
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			st = con.createStatement();
			StringBuffer s = new StringBuffer();
			SqlBuilder b = null;
			for(String json : jsons){
				QcmJhyElementsEntity jhy = EntityTool.getEntityByGson(json, QcmJhyElementsEntity.class);
				jhy.setAssayno(jhy.getStoveNo() + "_" + jhy.getSampleNo() + "_S");
				jhy.setJudgeFlag("20");
				jhy.setLgJudgeFlag("20");
				jhy.setAssaytype("A");
				jhy.setPlineCode("C001");
				jhy.setAlt(jhy.getAl());

				b = new SqlBuilder("QcmJhyElementsDAL.queryJhyElements");
				b.Fill(new String[]{ jhy.getStoveNo() });
				QcmJhyElementsEntity qcmJhyElementsEntity = EntityTool.getEntityBySqlNoClsCon(
						b.toString(), con, QcmJhyElementsEntity.class);
				if(qcmJhyElementsEntity != null){
					s.append("熔炼炉号"+jhy.getStoveNo()+"已存在！无法导入!");
					continue;
				}
				//删除检化验表
				b = new SqlBuilder("QcmJhyElementsDAL.deleteJhyElements");
				b.Fill(new String[]{ jhy.getStoveNo() });
				st.executeUpdate(b.toString());
//				if(jhy.getStoveNo().equals("1605630")){
//					String s = "";
//					s = "";
//				}
				//新增成分检验表
				String iJhyChem = CoreXmlSqlParsersFactory.getSql("QcmJhyElementsDAL.insertQcmJhyElements");
				iJhyChem = EntityTool.fillSqlByEntity(iJhyChem, jhy);
				st.executeUpdate(iJhyChem);
				
				
			}

			con.commit();
			cro.setV_errMsg(s.toString());
			return cro;
		}catch(Exception ex){
			try {
				con.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errMsg(ex.getMessage());
			return cro;
		}finally{
			if(st != null){
				try {
					st.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private void SaveLgJudge(QcmZgJugdeApplyEntity apply, QcmJhyElementsEntity jhy,
			SqlBuilder b, Connection con, Statement st)
			throws Exception{
		String sMaxChemId = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeDAL.GetMaxPk");
		GenericEntity maxChemId = EntityTool.getEntityBySqlNoClsCon(
				sMaxChemId, con, GenericEntity.class);
		
		//作废成分判定主表
		b = new SqlBuilder("SteelMakingAdvanceJudgeDAL.updateLgChemJudgeValid");
		b.Fill(new String[]{ jhy.getJudgeStoveNo(), "0" });
		st.executeUpdate(b.toString());
		//新增成分判定表主表
		String iChemJudge = CoreXmlSqlParsersFactory.getSql("QcmLgChemjudgeDAL.Insert");
		iChemJudge = EntityTool.fillSqlByEntity(iChemJudge, jhy);
		QcmLgChemjudgeEntity chemJudge = new QcmLgChemjudgeEntity();
		chemJudge.setChemJudgeId(maxChemId.getMaxValue());
		chemJudge.setCreateName(jhy.getCreateName());
		chemJudge.setProcessCdoe("B");
		chemJudge.setJudgeresultChem("40740101");
		chemJudge.setOrderisunchain("0");
		chemJudge.setValidflag("1");
		chemJudge.setJudgeSeq("1");
		iChemJudge = EntityTool.fillSqlByEntity(iChemJudge, chemJudge);
		st.executeUpdate(iChemJudge);
		
		//新增成分判定从表
//		b = new SqlBuilder("QcmZgJugdeApplyDAL.GetByLoadJudgeStoveNo");
//		b.Fill(new String[]{ jhy.getJudgeStoveNo(), "D" });
//		QcmZgJugdeApplyEntity apply = EntityTool.getEntityBySqlNoClsCon(
//				b.toString(), con, QcmZgJugdeApplyEntity.class);
//		if(apply == null){
//			throw new Exception("判定炉号"+ jhy.getJudgeStoveNo() + "不是轧管上料炉号！");
//		}
//		//获取炼钢索引码
//		b = new SqlBuilder("CraftOrdDesignStdCic.getLgCicByOrdLnDlyPk");
//		b.Fill(new String[]{ apply.getOrdLnDlyPk(), apply.getCraftSeq(), apply.getIndexSeq(), apply.getGradecode() });
//		CraftOrdDesignStdCicEntity lgCic = EntityTool.getEntityBySqlNoClsCon(
//				b.toString(), con, CraftOrdDesignStdCicEntity.class);
//		if(lgCic == null){
//			throw new Exception("判定炉号"+ jhy.getJudgeStoveNo() + "找不到炼钢索引码！");
//		}
		List<ComBaseChemEntity> baseChems = ChemJudgeHelper.getElementRounds();//圆整位数
		HashMap<String, String> rounds = new HashMap<String, String>();
		for(ComBaseChemEntity baseChem : baseChems){
			rounds.put(baseChem.getChemName(), baseChem.getRoundingDigits());
		}
		String ordLnPk = "";
		if(apply.getIsAllScrap().equals("4")){
			b = new SqlBuilder("JdgSlmOrderLineDelivery.getOrdLnPkByDlyPk");
			b.Fill(new String[]{ apply.getOrdLnDlyPk() });
			PlnSaleordEntity plnSaleord = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, PlnSaleordEntity.class);
			ordLnPk = plnSaleord.getOrdLnPk();
		}else{
			b = new SqlBuilder("JdgPlnSaleOrd.getOrdLnPkByDlyPk");
			b.Fill(new String[]{ apply.getOrdLnDlyPk() });
			PlnSaleordEntity plnSaleord = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, PlnSaleordEntity.class);
			ordLnPk = plnSaleord.getOrdLnPk();
		}
		b = new SqlBuilder("CraftOrdDesignStdCic.queryMeltingCraftChemByOrdLnPk");
		b.Fill(new String[]{ ordLnPk, apply.getCraftSeq(), apply.getIndexSeq(),
				"A", apply.getCic() });
		ArrayList<CraftOrdDesignStdCicEntity> stdCics = EntityTool.getEntitysBySqlNoClsCon(
				b.toString(), con, CraftOrdDesignStdCicEntity.class);
		Class<QcmJhyElementsEntity> jhyChemClass = QcmJhyElementsEntity.class;
		int chemSeq = 0;
		for(Method method : jhyChemClass.getMethods()){
			if(!method.getName().startsWith("get")) continue;
			String name = method.getName().replaceAll("get", "");
			if(name.equals("Asn")){
				name = "As";
			}
			String value = method.invoke(jhy, (Object[]) null) == null ? "" : method.invoke(jhy, (Object[])null).toString();
			boolean isChem = false;
			for(CraftOrdDesignStdCicEntity stdCic : stdCics){
				if(name.equals(stdCic.getChemName())){
					isChem = true;
					value = ChemJudgeHelper.roundByStd(value, stdCic.getStdmin(), stdCic.getStdmax(), rounds.get(name));
					break;
				}
			}
			if(isChem){
				chemSeq++;
				String iChemResult = CoreXmlSqlParsersFactory.getSql("JdgQcmLgChemResult.insert");
				QcmLgChemResultEntity chemResult = new QcmLgChemResultEntity();
				chemResult.setChemJudgeId(maxChemId.getMaxValue());
				chemResult.setJudgeSeq("1");
				chemResult.setChemSeq(String.valueOf(chemSeq));
				chemResult.setChemName(name);
				chemResult.setChemValue(value);
				chemResult.setQualified("1");
				chemResult.setUnqualifiedType("0");
				iChemResult = EntityTool.fillSqlByEntity(iChemResult, chemResult);
				st.executeUpdate(iChemResult);
			}
		}
		
		//作废炼钢判定表
		b = new SqlBuilder("QcmLgJudgeDAL.updateLgJudgeValid");
		b.Fill(new String[]{ jhy.getJudgeStoveNo(), "B", "0" });
		st.executeUpdate(b.toString());
		//新增炼钢判定表
		String iLgJudge = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.Insert");
		iLgJudge = EntityTool.fillSqlByEntity(iLgJudge, jhy);
		String sMatLgJudgeId = CoreXmlSqlParsersFactory.getSql("QcmLgJudgeDAL.GetMaxPk");
		GenericEntity maxLgJudgeId = EntityTool.getEntityBySqlNoClsCon(
				sMatLgJudgeId, con, GenericEntity.class);
		QcmLgJudgeEntity lgJudge = new QcmLgJudgeEntity();
		lgJudge.setJudgeId(maxLgJudgeId.getMaxValue());
		lgJudge.setChemJudgeId(maxChemId.getMaxValue());
		lgJudge.setJudgeresult("40740701");
		lgJudge.setJudgeresultChem("40740101");
		lgJudge.setProcessCdoe("B");
		iLgJudge = EntityTool.fillSqlByEntity(iLgJudge, lgJudge);
		st.executeUpdate(iLgJudge);
	}
}
