package com.steering.pss.qcm;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

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

import com.steering.comm.converter.CoreConverter;
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.JudgeHelper;
import com.steering.pss.qcm.model.ComBaseSplineEntity;
import com.steering.pss.qcm.model.ComMscPhySampleEntity;
import com.steering.pss.qcm.model.ComMscPhySpline2Entity;
import com.steering.pss.qcm.model.SlmOrderLineEntity;
import com.steering.pss.sale.order.model.ComMscBlEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;

public class CorePhySample extends DBCommon {

    public CoreReturnObject Query(String phycode, String stdCode, String steelCode, String produccode) {
        SqlBuilder b = new SqlBuilder("CorePhySample.QUERY");
        b.Fill(new String[]{ phycode, stdCode, steelCode, produccode});
        return this.getData(b.toString());
    }
    
    public CoreReturnObject GetStdTest(String pic){
    	String sql = CoreXmlSqlParsersFactory.getSql("CorePhySample.GetStdTest");
    	sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
    	return this.getData(sql);
    }
    
    public CoreReturnObject GetSIC(String phyCodeMin, String itemCodeC, String itemCodeF, String itemCodeW, String pic) {
        SqlBuilder sqlBuilder = new SqlBuilder("CorePhySample.GetSIC");
    	sqlBuilder.Build("ITEM_CODE_C", itemCodeC, SqlBuilder.IsNull);
    	sqlBuilder.Build("ITEM_CODE_F", itemCodeF, SqlBuilder.IsNull);
    	sqlBuilder.Build("ITEM_CODE_W", itemCodeW, SqlBuilder.IsNull);
    	sqlBuilder.Fill("PIC", pic);
    	sqlBuilder.Fill("PHY_CODE_MIN", phyCodeMin);
        return this.getData(sqlBuilder.GetSql()); // 获取SIC
    }
    
    public CoreReturnObject Link(ArrayList<String> sampleJsons, ArrayList<String> splineJsons,
    		String pic, String phyCodeMin, String itemCodeF, String itemCodeC, String itemCodeW,
    		String stdCodeTest, String[] eics) {
    	
    	ArrayList<String> sqllist = new ArrayList<String>();
		SqlBuilder sqlBuilder = new SqlBuilder("CorePhySample.DELETE");
		sqlBuilder.Build("ITEM_CODE_F", itemCodeF, SqlBuilder.IsNull);
		sqlBuilder.Build("ITEM_CODE_C", itemCodeC, SqlBuilder.IsNull);
		sqlBuilder.Build("ITEM_CODE_W", itemCodeW, SqlBuilder.IsNull);
		sqlBuilder.Fill("PIC", pic);
		sqlBuilder.Fill("PHY_CODE_MIN", phyCodeMin);
		String sqlDelSample = sqlBuilder.GetSql();
		sqllist.add(sqlDelSample);
    	
    	for(String sampleJson : sampleJsons){
    		ComMscPhySampleEntity sampleEntity = EntityTool.getEntityByGson(sampleJson, ComMscPhySampleEntity.class);
    		String sql = CoreXmlSqlParsersFactory.getSql("CorePhySample.Link");
    		sql = EntityTool.fillSqlByEntity(sql, sampleEntity);
    		sqllist.add(sql);
    		
    		sql = CoreXmlSqlParsersFactory.getSql("CorePhySample.UpdateStdCodeTest");
    		sql = EntityTool.fillSqlByEntity(sql, sampleEntity);
    		sqllist.add(sql);
    	}
    	
    	//删除
		sqlBuilder = new SqlBuilder("CorePhySample.DeleteSpline");
		sqlBuilder.AppendLn("A.ITEM_CODE_F = {0}", !itemCodeF.equals(""));
		sqlBuilder.AppendLn("A.ITEM_CODE_F IS NULL", itemCodeF.equals(""));
		sqlBuilder.AppendLn("AND A.ITEM_CODE_C = {1}", !itemCodeC.equals(""));
		sqlBuilder.AppendLn("AND A.ITEM_CODE_C IS NULL", itemCodeC.equals(""));
		sqlBuilder.AppendLn("AND A.ITEM_CODE_W = {2}", !itemCodeW.equals(""));
		sqlBuilder.AppendLn("AND A.ITEM_CODE_W IS NULL", itemCodeW.equals(""));
		sqlBuilder.AppendLn("AND A.PHY_CODE_MIN = {3}");
		sqlBuilder.AppendLn("AND A.STD_CODE_TEST = {4}");
		sqlBuilder.AppendLn(CoreConverter.toSqlConditionString("A.EIC", eics));
		sqlBuilder.Fill(new String[]{itemCodeF, itemCodeC, itemCodeW, phyCodeMin, stdCodeTest});
		sqllist.add(sqlBuilder.GetSql());
		
    	
    	for(String splineJson : splineJsons){
    		ComMscPhySpline2Entity splineEntity = EntityTool.getEntityByGson(splineJson, ComMscPhySpline2Entity.class);
    		String sql = CoreXmlSqlParsersFactory.getSql("CorePhySample.InsertSpline");
    		sql = EntityTool.fillSqlByEntity(sql, splineEntity);
    		sqllist.add(sql);
    	}
        
       return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    }
    
    public CoreReturnObject setEic(String ordLnPk, String phyCodeMin, String itemCodeF,
    		String itemCodeC, String itemCodeW, String setEic){
    	ArrayList<String> sqllist = new ArrayList<String>();
    	SqlBuilder sqlBuilder = new SqlBuilder("CorePhySample.deleteSetEic");
    	sqlBuilder.Fill(new String[]{ordLnPk, phyCodeMin, itemCodeF,itemCodeC, itemCodeW});
    	sqllist.add(sqlBuilder.toString());
    	sqlBuilder = new SqlBuilder("CorePhySample.insertSetEic");
    	sqlBuilder.Fill(new String[]{ordLnPk, setEic, phyCodeMin, itemCodeF, itemCodeC, itemCodeW});
    	sqllist.add(sqlBuilder.toString());
    	return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    }
    
    public String QuerySplineSql(String phyCodeMin, String itemCodeF,String itemCodeC,
    		String stdCodeTest, String ordLnPk, String dimater, String height){
    	String stdCode = "";
    	String steel = "";
    	String product = "";
    	String model = "";
    	
    	if(ordLnPk.startsWith("BL")){
    		ComMscBlEntity mscBl = EntityTool.getEntityBySql(new SqlBuilder(
        			"CorePhySample.getMsCBlByPk").Fill(new String[]{ordLnPk}).toString(),
        			this.getDao(CoreConstantData.sysbeanstr).getConnection(),
        			ComMscBlEntity.class);
    		if(mscBl != null){
    			stdCode = mscBl.getStdCode();
        		steel = mscBl.getSteelcode();
        		product = mscBl.getProduccode();
        		model = mscBl.getModelCode();
    		}
    		
    	}else{
    		SlmOrderLineEntity orderLine = EntityTool.getEntityBySql(new SqlBuilder(
        			"CorePhySample.getOrderLineByPk").Fill(new String[]{ordLnPk}).toString(),
        			this.getDao(CoreConstantData.sysbeanstr).getConnection(),
        			SlmOrderLineEntity.class);
    		if(orderLine != null){
    			stdCode = orderLine.getStdCode();
        		steel = orderLine.getSteelcode();
        		product = orderLine.getProduccode();
        		model = orderLine.getModelCode();
    		}
    	}
    	
    	SqlBuilder sqlBuilder = new SqlBuilder("CorePhySample.QuerySpline");
    	sqlBuilder.Fill(new String[]{phyCodeMin, itemCodeF, itemCodeC, stdCodeTest, stdCode,
    			dimater, height, product, steel, model});
    	return sqlBuilder.toString();
    }
    
    /**
     * 通过规格过滤
     * @param baseSplines
     * @param dimater
     * @param height
     * @return
     */
    public static Object[] FilterSplineBySpec(List<ComBaseSplineEntity> baseSplines,
    		String dimater, String height){
    	ArrayList<String> eics = new ArrayList<String>();
    	ArrayList<ComBaseSplineEntity> splines = new ArrayList<ComBaseSplineEntity>();
    	for(ComBaseSplineEntity spline : baseSplines){
			String formula = spline.getFormula();
			if(!formula.equals("")){
				formula = formula.replaceAll("t", height).replaceAll("D", dimater);
				if(StringTool.isDouble(JudgeHelper.eval(formula))){
					double dFormula = Double.parseDouble(JudgeHelper.eval(formula));
					BigDecimal d = new BigDecimal(dFormula);
					dFormula = d.setScale(2, RoundingMode.HALF_UP).doubleValue();//4舍5入
					formula = String.valueOf(dFormula);
				}else{
					formula = "-1";
				}
			}
			
			if(spline.getSplineNo().equals("CJ25")){
				String st = "";
				st += st;//(((t-D/2+((D/2)^2-756.25)^0.5-1)<5)?0:1)+((7.5>(t-D/2+((D/2)^2-25)^0.5-1)>=5)?0:1)
			}
			
			if(!spline.getMinDSign().equals("")){
				if(!QualityDesignTool.checkStr(dimater, spline.getMinDSign(), spline.getMinD())){
					continue;
				}
			}
			if(!spline.getMaxDSign().equals("")){
				if(!QualityDesignTool.checkStr(dimater, spline.getMaxDSign(), spline.getMaxD())){
					continue;
				}
			}
			if(!spline.getMinHSign().equals("")){
				if(!QualityDesignTool.checkStr(height, spline.getMinHSign(), spline.getMinH())){
					continue;
				}
			}
			if(!spline.getMaxHSign().equals("")){
				if(!QualityDesignTool.checkStr(height, spline.getMaxHSign(), spline.getMaxH())){
					continue;
				}
			}
			
			if(!spline.getMinFSign().equals("")){
				if(!QualityDesignTool.checkStr(formula, spline.getMinFSign(), spline.getMinF())){
					continue;
				}
			}
			if(!spline.getMaxFSign().equals("")){
				if(!QualityDesignTool.checkStr(formula, spline.getMaxFSign(), spline.getMaxF())){
					continue;
				}
			}
			
			if(!eics.contains(spline.getEic())){
				if(spline.getSplineNo().equals("CJ25")){
					String st = "";
					st += st;
				}
				eics.add(spline.getEic());
			}
			
			
			splines.add(spline);
		}
    	
    	Object[] objs = new Object[2];
    	objs[0] = eics;
    	objs[1] = splines;
    	return objs;
    }
    
    /**
     * 查询试样码关系
     */
    public CoreReturnObject QuerySpline(String phyCodeMin, String itemCodeF, String itemCodeC,
    		String stdCodeTest, String ordLnPk, String dimater, String height){
    	String sql = QuerySplineSql(phyCodeMin, itemCodeF, itemCodeC,
    			stdCodeTest, ordLnPk, dimater, height);
    	Connection con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
    	List<ComBaseSplineEntity> baseSplines = EntityTool.getEntitysBySql(
    			sql, con, ComBaseSplineEntity.class);
    	Object[] objs = CorePhySample.FilterSplineBySpec(baseSplines, dimater, height);
    	CoreReturnObject cro = new CoreReturnObject();
    	cro.setResult(objs[0]);
    	return cro;
    }
    
    public CoreReturnObject querySetEic(String ordLnPk, String phyCodeMin, String itemCodeF,
    		String itemCodeC, String itemCodeW){
    	SqlBuilder b = new SqlBuilder("CorePhySample.querySetEic");
    	b.Fill(new String[]{ordLnPk, phyCodeMin, itemCodeF, itemCodeC, itemCodeW});
    	return this.getData(b.toString());
    }
    
    /**
     * 查询试样组与实验标准
     * @param eic
     * @return
     */
    public CoreReturnObject QueryStdRTest(String phyCodeMin){
    	String sql = CoreXmlSqlParsersFactory.getSql("CorePhySample.QueryStdRTest");
    	sql = StringTool.ReplaceAll(sql, "#PHY_CODE_MIN#", phyCodeMin);
    	return this.getData(sql);
    }
    
    /**
     * 查询理化标准数据
     * @param pic
     * @return
     */
    public CoreReturnObject GetPicData(String pic, String designKey, 
    		String mscPline, String processCode){
    	SqlBuilder sqlBuilder = new SqlBuilder("CorePhySample.GetPicData");
    	sqlBuilder.Fill(new String[]{ pic, designKey, mscPline, processCode });

    	return this.getData(sqlBuilder.GetSql());
    }
    
    /**
     * 获取转换的理化
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject getConvertPhy(String ordLnPk){
    	SqlBuilder b = new SqlBuilder("CorePhySample.getConvertPhy");
    	b.Fill(new String[]{ ordLnPk });
    	return this.getData(b.toString());
    }
    
    /**
     * 获取试样码维护科室
     * @return
     */
    public CoreReturnObject getSplineUnit(){
    	SqlBuilder b = new SqlBuilder("CorePhySample.getSplineUnit");
    	return this.getData(b.toString());
    }
}
