package com.steering.jobface.qcm.task;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import CoreFS.SC01.CoreConstantData;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.JudgeHelper;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.model.qcm.ComBaseChemEntity;
import com.steering.model.qcm.CraftOrdDesignStdBiasCEntity;
import com.steering.model.qcm.CraftOrdDesignStdCicEntity;
import com.steering.model.qcm.QcmJhyElementsEntity;

public class ChemJudgeHelper extends DBCommon{
	public static Object[] Judge(QcmJhyElementsEntity jhyElementsEntity, ArrayList<CraftOrdDesignStdCicEntity> craftDesingStdCicNs,
			ArrayList<CraftOrdDesignStdCicEntity> craftDesignStdCicJf, boolean isTubeChem){
		Object[] results = new Object[]{"", null};
		if (craftDesingStdCicNs.size() == 0) {
			results[0] = "没有找到内控标准数据！";
			return results;
		}
		
		List<ComBaseChemEntity> baseChems = getElementRounds();//圆整位数
		HashMap<String, String> rounds = new HashMap<String, String>();
		for(ComBaseChemEntity baseChem : baseChems){
			rounds.put(baseChem.getChemName(), baseChem.getRoundingDigits());
		}
		
		//最终检化验结果（包含复合元素）
		HashMap<String, String> jhyResults = new HashMap<String, String>();
		HashMap<String, String[]> chemResults = new HashMap<String, String[]>();
		results[1] = chemResults;
		
		//先算公式和复合元素
		for (CraftOrdDesignStdCicEntity craftDesingStdCicN : craftDesingStdCicNs) {
			
			//替代元素
			String express = "";
			if(!craftDesingStdCicN.getRepName().equals("")
					&& !craftDesingStdCicN.getRepVal().equals("")
					&& !StringTool.isNumeric(craftDesingStdCicN.getRepVal())){
				express = FillJhyElemetValue(craftDesingStdCicN.getRepVal(), jhyElementsEntity, craftDesingStdCicN, false);
				String value = chemCaculat(express);
				value = roundByStd(value, craftDesingStdCicN.getStdmin(), craftDesingStdCicN.getStdmax(), rounds.get(craftDesingStdCicN.getChemName()));
				craftDesingStdCicN.setRepVal(value);
			}
			
			//限制元素
//			if(!craftDesingStdCicN.getEleMin().equals("")){
//				express = FillJhyElemetValue(craftDesingStdCicN.getEleMin(), jhyElementsEntity, craftDesingStdCicN, false);
//				craftDesingStdCicN.setEleMin(chemCaculat(express, round));
//			}
//			if(!craftDesingStdCicN.getEleMax().equals("")){
//				express = FillJhyElemetValue(craftDesingStdCicN.getEleMax(), jhyElementsEntity, craftDesingStdCicN, false);
//				craftDesingStdCicN.setEleMax(chemCaculat(express, round));
//			}
			
			if (craftDesingStdCicN.getComplexType().equals("1")) {
				//标准元素
				if(!craftDesingStdCicN.getStdmin().equals("")){
					express = FillJhyElemetValue(craftDesingStdCicN.getStdmin(), jhyElementsEntity, craftDesingStdCicN, false);
					craftDesingStdCicN.setStdmin(chemCaculat(express, rounds.get(craftDesingStdCicN.getChemName())));
				}
				if(!craftDesingStdCicN.getStdmax().equals("")){
					express = FillJhyElemetValue(craftDesingStdCicN.getStdmax(), jhyElementsEntity, craftDesingStdCicN, false);
					craftDesingStdCicN.setStdmax(chemCaculat(express, rounds.get(craftDesingStdCicN.getChemName())));
				}
			}

			if (craftDesingStdCicN.getChemType().equals("A")) {
				String fieldName = craftDesingStdCicN.getChemName();
				if(fieldName.equals("As")){
					fieldName = "Asn";
				}
				String value = EntityTool.getValue(jhyElementsEntity, fieldName);
				//化学检验值不修约
				//value = roundByStd(value, craftDesingStdCicN.getStdmin(), craftDesingStdCicN.getStdmax(), rounds.get(craftDesingStdCicN.getChemName()));
				jhyResults.put(craftDesingStdCicN.getChemName(), value);
			} else {
				express = craftDesingStdCicN.getChemFormula();
				express = FillJhyElemetValue(express, jhyElementsEntity, craftDesingStdCicN, true);
				String value = chemCaculat(express);
				if(value.equals("") || !StringTool.isNumeric(value)){
					
				}else{
					BigDecimal b = new BigDecimal(value);
					value = b.setScale(8, BigDecimal.ROUND_HALF_EVEN).toString();
				}
				value = roundByStd(value, craftDesingStdCicN.getStdmin(), craftDesingStdCicN.getStdmax(), rounds.get(craftDesingStdCicN.getChemName()));
				jhyResults.put(craftDesingStdCicN.getChemName(), value);
			}
		}
		
		//处理成品成分偏差
		if(isTubeChem){
			ArrayList<CraftOrdDesignStdBiasCEntity> biasChems = getBiasChem(craftDesingStdCicNs.get(0).getDesginKey());
			for (CraftOrdDesignStdCicEntity craftChem : craftDesingStdCicNs) {
				if(craftChem.getSpeclFl().equals("2")) continue;
				for(CraftOrdDesignStdBiasCEntity biasChem : biasChems){
					if(biasChem.getChemCode().equals(craftChem.getChemCode())){
						if(!craftChem.getStdminSign().equals("") &&
								checkStr(craftChem.getStdmin(), biasChem.getMinSign(), biasChem.getMinVal())
								&& checkStr(craftChem.getStdmin(), biasChem.getMaxSign(), biasChem.getMaxVal())){
							double stdMin = Double.parseDouble(craftChem.getStdmin()) * 10000;
							double biasMin = biasChem.getStdMinVal().equals("") ? 0.0 : Math.abs(Double.parseDouble(biasChem.getStdMinVal())) * 10000;
							craftChem.setStdmin(String.valueOf((stdMin - biasMin)/10000));
						}
						
						if(!craftChem.getStdmaxSign().equals("") &&
								checkStr(craftChem.getStdmax(), biasChem.getMinSign(), biasChem.getMinVal())
								&& checkStr(craftChem.getStdmax(), biasChem.getMaxSign(), biasChem.getMaxVal())){
							double stdMax = Double.parseDouble(craftChem.getStdmax()) * 10000;
							double biasMax = biasChem.getStdMaxVal().equals("") ? 0.0 : Math.abs(Double.parseDouble(biasChem.getStdMaxVal())) * 10000;
							craftChem.setStdmax(String.valueOf((stdMax + biasMax) / 10000));
						}
					}
				}
			}
		}
		
		//比较标准和检验结果
		for(ComBaseChemEntity baseChem : baseChems){
			for (CraftOrdDesignStdCicEntity craftDesingStdCicN : craftDesingStdCicNs) {
				//为了排序所以已基础元素作为主循环。
				if(!craftDesingStdCicN.getChemName().equals(baseChem.getChemName())) continue;
				
				//处理成品成分
				if(isTubeChem && jhyElementsEntity.getSampleId().startsWith("F")){
					String tmpValue = jhyResults.get(craftDesingStdCicN.getChemName());
					if(tmpValue.equals("")){
						continue;
					}
				}
				
				// 如果内控不需要判定则就不比较
				if (craftDesingStdCicN.getIsjudge().equals("0")
						&& craftDesingStdCicN.getIsquote().equals("0")){
					continue;
				}else if(craftDesingStdCicN.getIscheck().equals("0") &&
						craftDesingStdCicN.getIsjudge().equals("0")) { //不检、不判，只报出是针对质保书的。
					continue;
				}
				
				String express = "";
				String value = "";
				
				//验证限制元素
				if (!craftDesingStdCicN.getEleMinSign().equals("")) {
					express = craftDesingStdCicN.getEleMinSign() + craftDesingStdCicN.getEleMin();
					value = jhyResults.get(craftDesingStdCicN.getEleName());
					if(!Boolean.parseBoolean(JudgeHelper.eval(value + express))){
						continue;
					}
				}
				if (!craftDesingStdCicN.getEleMaxSign().equals("")) {
					express = craftDesingStdCicN.getEleMaxSign() + craftDesingStdCicN.getEleMax();
					value = jhyResults.get(craftDesingStdCicN.getEleName());
					if(!Boolean.parseBoolean(JudgeHelper.eval(value + express))){
						continue;
					}
				}
				
				//比较标准
				String[] nkExpresses = new String[] {"", "", "", "1", "0"};
				chemResults.put(craftDesingStdCicN.getChemName(), nkExpresses);
				
				if(craftDesingStdCicN.getIsjudge().equals("1")){
					value = jhyResults.get(craftDesingStdCicN.getChemName());
					nkExpresses[0] = value;
					if(value.equals("")){
//						if(craftDesingStdCicN.getChemName().equals("Als")){
//							results[0] =  "缺项";
//							return results;
//						}
						nkExpresses[3] = "2";
						results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
								"没有报出值";
					}else{
						String evalValue = value;
						if(value.startsWith("-")){
							evalValue = value.replace("-", "");
							if(StringTool.isNumeric(evalValue)){
								DecimalFormat df = new DecimalFormat("0.0000000");
								evalValue = df.format(Double.parseDouble(evalValue) - 0.000001);
							}
						}
						if(!StringTool.isNumeric(evalValue)){
							nkExpresses[3] = "3";
							results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
									"的实际值计算异常";
						}else{
							if (!craftDesingStdCicN.getStdminSign().equals("")) {
								express = craftDesingStdCicN.getStdminSign() + craftDesingStdCicN.getStdmin();
								nkExpresses[1] = express;
								if(!StringTool.isNumeric(craftDesingStdCicN.getStdmin())){
									nkExpresses[3] = "3";
									results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
											"的标准下限值计算异常";
								}else{
									if(!Boolean.parseBoolean(JudgeHelper.eval(evalValue + express))){
										nkExpresses[3] = "0";
										nkExpresses[4] = "1";
										results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
												"低(" + value + "," + craftDesingStdCicN.getStdmin() + ")";
									}
								}
							}
							if (!craftDesingStdCicN.getStdmaxSign().equals("")) {
								express = craftDesingStdCicN.getStdmaxSign() + craftDesingStdCicN.getStdmax();
								nkExpresses[2] = express;
								if(!StringTool.isNumeric(craftDesingStdCicN.getStdmax())){
									nkExpresses[3] = "3";
									results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
											"的标准上限值计算异常";
								}else{
									if(!Boolean.parseBoolean(JudgeHelper.eval(evalValue + express))){
										nkExpresses[3] = "0";
										nkExpresses[4] = "2";
										results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
												"高(" + value + "," + craftDesingStdCicN.getStdmax() + ")";
									}
								}
							}
						}
					}
				}else if(craftDesingStdCicN.getIsquote().equals("1")){
					value = jhyResults.get(craftDesingStdCicN.getChemName());
					nkExpresses[0] = value;
					express = craftDesingStdCicN.getStdminSign() + craftDesingStdCicN.getStdmin();
					nkExpresses[1] = express;
					express = craftDesingStdCicN.getStdmaxSign() + craftDesingStdCicN.getStdmax();
					nkExpresses[2] = express;
					if(value.equals("")){
						nkExpresses[3] = "2";
						results[0] = results[0].toString() + craftDesingStdCicN.getChemName() + 
								"没有报出值";
					}
				}
				
			}
		}
		
		return results;
	}

//	private static ArrayList<String> GetExpressValue(CraftOrdDesignStdCicEntity stdCic,
//			QcmJhyElementsEntity jhyElementsEntity, String round) {
//		ArrayList<String> expresss = new ArrayList<String>();
//		double value = 0.0;
//		String strValue = "";
//		if (!stdCic.getStdmin().equals("")) {
//			String express = "";
//			express = stdCic.getStdmin();
//			express = FillJhyElemetValue(express, jhyElementsEntity);
//			strValue = JudgeHelper.eval(express);
//			if(StringTool.isNumeric(strValue)){
//				value = Math.abs(Double.parseDouble(strValue));
//				value = RoundGBT81702008.round3_2(value, Integer.parseInt(round));
//				strValue = String.valueOf(value);
//			}
//			express = stdCic.getStdminSign() + strValue;
//			expresss.add(express);
//		} else if (!stdCic.getStdmax().equals("")) {
//			String express = "";
//			express = stdCic.getStdmax();
//			express = FillJhyElemetValue(express, jhyElementsEntity);
//			strValue = JudgeHelper.eval(express);
//			if(StringTool.isNumeric(strValue)){
//				value = Math.abs(Double.parseDouble(strValue));
//				value = RoundGBT81702008.round3_2(value, Integer.parseInt(round));
//				strValue = String.valueOf(value);
//			}
//			express = stdCic.getStdmaxSign() + strValue;
//			expresss.add(express);
//		}
//
//		return expresss;
//	}
//
//	private static String GetChemFormulaValue(CraftOrdDesignStdCicEntity stdCic, 
//			QcmJhyElementsEntity jhyElementsEntity, String round) {
//		String chemFormula = stdCic.getChemFormula();
//		chemFormula = FillJhyElemetValue(chemFormula, jhyElementsEntity);
//		String strValue = JudgeHelper.eval(chemFormula);
//		if(!StringTool.isNumeric(strValue)){
//			return strValue;
//		}
//		double value = Math.abs(Double.parseDouble(strValue));
//		return String.valueOf(RoundGBT81702008.round3_2(value, Integer.parseInt(round)));
//	}
	
	private static String chemCaculat(String express){
		String strValue = JudgeHelper.eval(express);
		if(!StringTool.isNumeric(strValue)){
			return strValue;
		}
		
		return strValue;
	}
	
	private static String chemCaculat(String express, String round){
		String strValue = JudgeHelper.eval(express);
		if(!StringTool.isNumeric(strValue)){
			return strValue;
		}
		double value = Math.abs(Double.parseDouble(strValue));
		return RoundGBT81702008.round3_2String(value, Integer.parseInt(round));
	}

	private static String FillJhyElemetValue(String express, QcmJhyElementsEntity jhyElementsEntity,
			CraftOrdDesignStdCicEntity craftDesingStdCicN, boolean isMultiChem) {
		// 复合元素处理
		Method[] ms = QcmJhyElementsEntity.class.getMethods();
		Arrays.sort(ms, new MyComprator());
		for (Method m : ms) {
			if(!m.getName().startsWith("get")) continue;
			String methodName = m.getName().substring(3);
			String replaceName = methodName;
			if(methodName.equals("Asn")){
				replaceName = "As";
			}
			String value = EntityTool.getValue(jhyElementsEntity, methodName);
			
			if(value.startsWith("-")){
				//对于B元素，如果报出值为-0.0005则当0处理
				if(replaceName.equals("B") && value.equals("-0.0005")){
					value = "0";
				}else{
					value = value.replace("-", "");
					if(StringTool.isNumeric(value)){
						value = String.valueOf(Double.parseDouble(value) - 0.00000001);
					}
				}
			}
			if (express.contains(replaceName)) {
				if(isMultiChem){
					if(craftDesingStdCicN.getRepName().equals(replaceName)
							&& !craftDesingStdCicN.getRepVal().equals("")){
						String repExpress = "";
						boolean repResult = true;
						if(!craftDesingStdCicN.getRepMinSign().equals("")){
							repExpress = craftDesingStdCicN.getRepMinSign() + craftDesingStdCicN.getRepMin();
							if(!Boolean.parseBoolean(JudgeHelper.eval(value + repExpress))){
								repResult = false;
							}
						}
						if(!craftDesingStdCicN.getRepMaxSign().equals("")){
							repExpress = craftDesingStdCicN.getRepMaxSign() + craftDesingStdCicN.getRepMax();
							if(!Boolean.parseBoolean(JudgeHelper.eval(value + repExpress))){
								repResult = false;
							}
						}
						if("C031".equals(craftDesingStdCicN.getChemCode()) && methodName.equals("B") && "A".equals(jhyElementsEntity.getAssaytype())){
							//19-10-26 CEpcm熔炼成分判断B含量小于0.005时不处理
						}
						else if(repResult){
							value = craftDesingStdCicN.getRepVal();
						}
					}
				}
				if(!value.equals("")){
					express = express.replaceAll(replaceName, value);
				}
			}
		}

		return express;
	}
	
	public static void mergeChemResult(HashMap<String, String[]> judgeJhyResults, HashMap<String, String[]> mergeResults){
    	for(String key : judgeJhyResults.keySet()){
    		if(mergeResults.containsKey(key)){
    			String[] results = mergeResults.get(key);
    			String value1 = "";
    			String value2 = "";
    			//比较下限
    			if(mergeResults.get(key)[1].equals("")){
    				results[1] = judgeJhyResults.get(key)[1];
    			}else{
    				if(!judgeJhyResults.get(key)[1].equals("")){
    					value1 = judgeJhyResults.get(key)[1].replace(">", "").replace("=", "");
    					value2 = mergeResults.get(key)[1].replace(">", "").replace("=", "");
    					if(Double.parseDouble(value1) > Double.parseDouble(value2)){
    						results[1] = judgeJhyResults.get(key)[1];
    					}
    				}
    			}
    			
    			//比较上限
    			if(mergeResults.get(key)[2].equals("")){
    				results[1] = judgeJhyResults.get(key)[2];
    			}else{
    				if(!judgeJhyResults.get(key)[2].equals("")){
    					value1 = judgeJhyResults.get(key)[2].replace("<", "").replace("=", "");
    					value2 = mergeResults.get(key)[2].replace("<", "").replace("=", "");
    					if(Double.parseDouble(value1) < Double.parseDouble(value2)){
    						results[2] = judgeJhyResults.get(key)[2];
    					}
    				}
    			}
    			
    			//处理结果
    			if(judgeJhyResults.get(key)[3].equals("0")
    					&& !results[3].equals("0")){
    				results[3] = judgeJhyResults.get(key)[3];
    			}else if(judgeJhyResults.get(key)[3].equals("2")
    					&& results[3].equals("1")){
    				results[3] = judgeJhyResults.get(key)[3];
    			}
    		}else{
    			mergeResults.put(key, judgeJhyResults.get(key));
    		}
    	}
    }
	
	//比较器，x坐标从小到大排序；x相同时，按照y从小到大排序
	static class MyComprator implements Comparator<Method> {
	    public int compare(Method t1, Method t2) {
	        if(t1.getName().length() < t2.getName().length()){
	        	return 1;
	        }else if(t1.getName().length() > t2.getName().length()){
	        	return -1;
	        }else{
	        	return 0;
	        }
	    }
	}
	
	/**
	 * 获取元素修约位数
	 * @return
	 */
	private static List<ComBaseChemEntity> getElementRounds(){
		DBCommon db = new DBCommon();
		Connection con = db.getDao(CoreConstantData.sysbeanstr).getConnection();
		SqlBuilder b = new SqlBuilder("ChemJudgeHelper.queryRound");
		List<ComBaseChemEntity> baseChems = EntityTool.getEntitysBySql(
				b.toString(), con, ComBaseChemEntity.class);
		
		return baseChems;
	}
	
	private static ArrayList<CraftOrdDesignStdBiasCEntity> getBiasChem(String designKey){
		DBCommon db = new DBCommon();
		Connection con = db.getDao(CoreConstantData.sysbeanstr).getConnection();
		SqlBuilder b = new SqlBuilder("ChemJudgeHelper.getBiasChem");
		b.Fill(new String[]{ designKey });
		ArrayList<CraftOrdDesignStdBiasCEntity> biasChems = EntityTool.getEntitysBySql(
				b.toString(), con, CraftOrdDesignStdBiasCEntity.class);
		
		return biasChems;
	}
	
	/**
	 * 通过标准上下限修约
	 * @param value
	 * @param stdMin
	 * @param stdMax
	 * @return
	 */
	public static String roundByStd(String value, String stdMin, String stdMax, String strRound){
		if(value.equals("") || !StringTool.isNumeric(value)){
			return value;
		}
		int round = 0;
		int minLen = 0;
		int maxLen = 0;
		if(StringTool.isNumeric(stdMin)){
			if(stdMin.contains(".")){
				minLen = stdMin.split("\\.")[1].length();
			}
		}
		if(StringTool.isNumeric(stdMax)){
			if(stdMax.contains(".")){
				maxLen = stdMax.split("\\.")[1].length();
			}
		}
		
		ArrayList<Integer> stdRounds = new ArrayList<Integer>();
		stdRounds.add(minLen);
		stdRounds.add(maxLen);
		if(Collections.max(stdRounds) == 0){
			if(strRound != null && StringTool.isNumeric(strRound)){
				round = Integer.parseInt(strRound);
			}
		}else{
			round = Collections.max(stdRounds);
		}
		value = RoundGBT81702008.round3_2String(Double.parseDouble(value), round);
		
		return value;
	}
	
	/**
	 * 验证字符串 如：1<2
	 * 
	 * @param strA
	 *            数字字符串
	 * @param sign
	 *            符号
	 * @param strB
	 *            数字字符串
	 * @return true Or false
	 */
	public static boolean checkStr(String strA, String sign, String strB) {
		if (strA.length() == 0 || strB.length() == 0) {
			return true;
		}
		double a = Double.parseDouble(strA);
		double b = Double.parseDouble(strB);
		if (sign.equals("=")) {
			if (a == b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals(">")) {
			if (a > b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals(">=")) {
			if (a >= b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals("<")) {
			if (a < b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals("<=")) {
			if (a <= b) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}
