package com.steering.pss.sale.order.craftDesign.server;

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.sale.order.craftDesign.dao.MscChemDao;
import com.steering.pss.sale.order.craftDesign.model.*;
import com.steering.pss.sale.order.craftDesign.tool.CraftTool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 成分标准
 * 
 * @author Administrator
 * 
 */
public class MscChem {

	/**
	 * 查询成分索引号
	 * 
	 * @param con
	 * @param msc
	 * @param modelCode
	 * @param mscValig
	 * @return
	 * @throws SQLException
	 */
	public List<String> getCicByMscAndModel(Connection con, String msc,
			String modelCode, String mscValig) throws SQLException {
		MscChemDao chemDaoImp = new MscChemDao();
		List<String> cics = null;
		if (mscValig.equals("C")) {
			cics = chemDaoImp.getExamineCic(con, msc, modelCode);
		} else {
			cics = chemDaoImp.getValidCic(con, msc, modelCode);
		}
		return cics;

	}

	/**
	 * 验证成分标准
	 * 
	 * @param con
	 * @param msc
	 *            冶金规范码
	 * @param design
	 * @param flag
	 *            (0:交付标准;1:特殊要求;2:内控标准)
	 * @return
	 * @throws SQLException
	 */
	public StdEntity checkChem(Connection con, CraftEntity design, ComBaseSpecEntity spec, String flag,
			List<String> cics) throws SQLException {
		StdEntity stdEntity = new StdEntity();
		if (cics == null || cics.size() == 0) {
			stdEntity.setMessage("");
			stdEntity.setFlag(true);
			return stdEntity;
		}
		MscChemDao chemDaoImp = new MscChemDao();
		String message = "";
		String designKey = design.getDesignKey();
		String dimater = spec.getDimater();
		String height = spec.getHeight();
		String specStyle = spec.getMscStyle();
		String specCode = spec.getSpecCode();
		String specName = spec.getSpecName();
		String useCode = design.getUseCode();
		String useDesc = design.getUseDesc();
		for (String cic : cics) {
			// 通过外径、壁厚过滤成分主记录
//			if(flag.equals("2")){
//				ComMscStdCicEntity mscStdCic = chemDaoImp.getMscCicByCic(con, cic);
//				if (specStyle.equals("A")) {
//					if(!CraftTool.checkStr(dimater, mscStdCic.getMinDSign(), mscStdCic.getMinD())
//							|| !CraftTool.checkStr(dimater, mscStdCic.getMaxDSign(), mscStdCic.getMaxD())
//							|| !CraftTool.checkStr(height, mscStdCic.getMinDSign(), mscStdCic.getMinD())
//							|| !CraftTool.checkStr(height, mscStdCic.getMaxDSign(), mscStdCic.getMaxD())){
//						message = "<钢管产品> 没有维护符合合同外径(" + dimater + ")/壁厚(" + height
//								+ ")的成分标准索引码";
//						continue;
//					}
//				} else if (specStyle.equals("B")) {
//					if(!CraftTool.checkStr(dimater, mscStdCic.getMinDSign(), mscStdCic.getMinD())
//							|| !CraftTool.checkStr(dimater, mscStdCic.getMaxDSign(), mscStdCic.getMaxD())){
//						message = "<管坯产品>没有维护符合合同外径(" + dimater + ")的成分标准索引码";
//						continue;
//					}
//				}
//			}
			
			List<CraftOrdDesignStdCicEntity> chems = chemDaoImp.getChemByCic(
					con, cic);
			if (chems == null) {
				message = "成分索引号(" + cic + ")不存在成分标准";
				continue;
			}
			List<String> chemsSize = MscChem.getChemSize(chems);
			List<CraftOrdDesignStdCicEntity> chemAs = null;
			// 过滤限制规格/接箍规格
			if (specStyle.equals("A")) {
				// 钢管
				// 径壁比
				String dh = String.valueOf(Double.parseDouble(dimater)
						/ Double.parseDouble(height));
				// 壁径比
				String hd = String.valueOf(Double.parseDouble(height)
						/ Double.parseDouble(dimater));
				// 内径
				String in = String.valueOf(Double.parseDouble(dimater) - 2
						* Double.parseDouble(height));
				chemAs = MscChem.fiterChemByA(chems, dimater, height, dh, hd,
						in);
				// 管坯
			} else if (specStyle.equals("B")) {
				chemAs = MscChem.fiterChemByB(chems, dimater);
			} else {
				// 钢锭 其它
				chemAs = MscChem.fiterChemByCAndD(chems, specCode);
			}
			// 验证成分标准
			message = MscChem.checkChem(chemAs, specStyle, dimater, height,
					specName, designKey, con, flag);
			if (message.length() > 0) {
				message = "成分索引号(" + cic + ")" + message;
				continue;
			}
			// 过滤没有任何限制条件的元素记录，并且这个元素又存在满足约束的记录
			chemAs = MscChem.fiterChemN(chemAs, specStyle);
			List<String> chemsSizeA = MscChem.getChemSize(chemAs);
			String chemCodeStr = "";
			for (String chemCode : chemsSize) {
				if (!chemsSizeA.contains(chemCode)) {
					chemCodeStr += "," + chemCode;
				}
			}
//			if (chemCodeStr.length() > 0) {
//				message = "成分索引号(" + cic + ")维护化学元素" + chemsSize.size() + "项,"
//						+ "但满足合同要求" + chemsSizeA.size() + "项" + chemCodeStr
//						+ "不满足外径(" + dimater + ")/壁厚(" + height + ")或者规格+("
//						+ specName + ")要求!";
//				continue;
//			}
			
			for (CraftOrdDesignStdCicEntity chem : chemAs) {
				chem.setDesginKey(designKey);
				// 国标与客户标准默认给个Ｙ值
				chem.setMscPline("Y");
				chem.setProcessCode("Y");
				// 是否特殊要求(0否;1是,2内控)
				chem.setSpeclFl(flag);
				if (flag.equals("1")) {
					chem.setUseCode(useCode);
					chem.setUseDesc(useDesc);
				}
				// chemDaoImp.addChem(con, chem);
			}
			// if (flag.equals("0")) {
			// chemDaoImp.updateDesignStd(con, cic, designKey);
			// }
			// 查询熔炼成分套数／成品成分套数
			String[] strArray = chemDaoImp.getCntByCic(con, cic);
			message = "";
			stdEntity.setFlag(true);
			stdEntity.setMessage(message);
			stdEntity.setObjM(chemAs);
			stdEntity.setObjKey(cic);
			stdEntity.setSmeltingCnt(strArray[0]);
			stdEntity.setProducCnt(strArray[1]);
			stdEntity.setRate(strArray[2]);
			return stdEntity;
		}
		stdEntity.setFlag(false);
		stdEntity.setMessage(message);
		return stdEntity;
	}

	// 钢锭与特殊规格过滤接箍规格，管坯过滤外径，钢管过滤外径，壁厚，同时也要考虑替代元素

	/**
	 * 查询维护成分元素项
	 * 
	 * @param chems
	 * @return
	 */
	public static List<String> getChemSize(
			List<CraftOrdDesignStdCicEntity> chems) {
		List<String> list = new ArrayList<String>();
		if (chems == null || chems.size() == 0) {
			return null;
		}
		for (CraftOrdDesignStdCicEntity chem : chems) {
			if (!list.contains(chem.getChemCode())) {
				list.add(chem.getChemCode());
			}
		}
		return list;
	}

	/**
	 * 过滤钢管规格
	 * 
	 * @param chems
	 *            成分集合
	 * @param dimater
	 *            外径
	 * @param height
	 *            壁厚
	 * @param DHProportion
	 *            径壁比
	 * @param HDProportion
	 *            壁径比
	 * @param innerProportion
	 *            内径
	 * @return
	 */
	public static List<CraftOrdDesignStdCicEntity> fiterChemByA(
			List<CraftOrdDesignStdCicEntity> chems, String dimater,
			String height, String DHProportion, String HDProportion,
			String innerProportion) {
		if (chems == null || chems.size() == 0) {
			return null;
		}
		List<CraftOrdDesignStdCicEntity> list = new ArrayList<CraftOrdDesignStdCicEntity>();

		// 过滤外径壁厚
		for (int i = 0; i < chems.size(); i++) {
			CraftOrdDesignStdCicEntity chem = chems.get(i);
			if (chem.getSizeCode().equals("") && chem.getSizeCode2().equals("")) {
				list.add(chem);
				continue;
			}
			// 外径 :400301 壁厚:400302 径壁比:400303 壁径比 400304 内径 400305 长度 400306
			if (chem.getSizeCode2().equals("400301")) {
				if ((!CraftTool.checkStr(dimater, chem.getSizeMinSign2(),
						chem.getSizeMin2()))
						|| (!CraftTool.checkStr(dimater,
								chem.getSizeMaxSign2(), chem.getSizeMax2()))) {
					continue;
				}
			}
			if (chem.getSizeCode2().equals("400302")) {
				if ((!CraftTool.checkStr(height, chem.getSizeMinSign2(),
						chem.getSizeMin2()))
						|| (!CraftTool.checkStr(height, chem.getSizeMaxSign2(),
								chem.getSizeMax2()))) {
					continue;
				}
			}
			if (chem.getSizeCode2().equals("400303")) {
				if ((!CraftTool.checkStr(DHProportion, chem.getSizeMinSign2(),
						chem.getSizeMin2()))
						|| (!CraftTool.checkStr(DHProportion,
								chem.getSizeMaxSign2(), chem.getSizeMax2()))) {
					continue;
				}
			}
			if (chem.getSizeCode2().equals("400304")) {
				if ((!CraftTool.checkStr(HDProportion, chem.getSizeMinSign2(),
						chem.getSizeMin2()))
						|| (!CraftTool.checkStr(HDProportion,
								chem.getSizeMaxSign2(), chem.getSizeMax2()))) {
					continue;
				}
			}
			if (chem.getSizeCode2().equals("400305")) {
				if ((!CraftTool.checkStr(innerProportion,
						chem.getSizeMinSign2(), chem.getSizeMin2()))
						|| (!CraftTool.checkStr(innerProportion,
								chem.getSizeMaxSign2(), chem.getSizeMax2()))) {
					continue;
				}
			}

			if (chem.getSizeCode().equals("400301")) {
				if ((!CraftTool.checkStr(dimater, chem.getSizeMinSign(),
						chem.getSizeMin()))
						|| (!CraftTool.checkStr(dimater, chem.getSizeMaxSign(),
								chem.getSizeMax()))) {
					continue;
				}
			}
			if (chem.getSizeCode().equals("400302")) {
				if ((!CraftTool.checkStr(height, chem.getSizeMinSign(),
						chem.getSizeMin()))
						|| (!CraftTool.checkStr(height, chem.getSizeMaxSign(),
								chem.getSizeMax()))) {
					continue;
				}
			}
			if (chem.getSizeCode().equals("400303")) {
				if ((!CraftTool.checkStr(DHProportion, chem.getSizeMinSign(),
						chem.getSizeMin()))
						|| (!CraftTool.checkStr(DHProportion,
								chem.getSizeMaxSign(), chem.getSizeMax()))) {
					continue;
				}
			}
			if (chem.getSizeCode().equals("400304")) {
				if ((!CraftTool.checkStr(HDProportion, chem.getSizeMinSign(),
						chem.getSizeMin()))
						|| (!CraftTool.checkStr(HDProportion,
								chem.getSizeMaxSign(), chem.getSizeMax()))) {
					continue;
				}
			}
			if (chem.getSizeCode().equals("400305")) {
				if ((!CraftTool.checkStr(innerProportion,
						chem.getSizeMinSign(), chem.getSizeMin()))
						|| (!CraftTool.checkStr(innerProportion,
								chem.getSizeMaxSign(), chem.getSizeMax()))) {
					continue;
				}
			}
			list.add(chem);
		}
		return list;
	}

	/**
	 * 过滤钢锭或者其它规格
	 * 
	 * @param chems
	 * @param specCode
	 * @return
	 */
	public static List<CraftOrdDesignStdCicEntity> fiterChemByCAndD(
			List<CraftOrdDesignStdCicEntity> chems, String specCode) {
		List<CraftOrdDesignStdCicEntity> list = new ArrayList<CraftOrdDesignStdCicEntity>();
		for (CraftOrdDesignStdCicEntity chem : chems) {
			if (chem.getSpecJg().equals("")
					|| chem.getSpecJg().equals(specCode)) {
				list.add(chem);
			}
		}
		return list;
	}

	/**
	 * 过滤管坯规格
	 * 
	 * @param chems
	 * @param dimater
	 * @return
	 */
	public static List<CraftOrdDesignStdCicEntity> fiterChemByB(
			List<CraftOrdDesignStdCicEntity> chems, String dimater) {
		List<CraftOrdDesignStdCicEntity> list = new ArrayList<CraftOrdDesignStdCicEntity>();
		for (CraftOrdDesignStdCicEntity chem : chems) {
			if (chem.getSizeCode().equals("") && chem.getSizeCode2().equals("")) {
				list.add(chem);
				continue;
			}
			if (!chem.getSizeCode().equals("400301")
					|| !chem.getSizeCode2().equals("400301")) {
				continue;
			} else {
				if (chem.getSizeCode2().equals("400301")) {
					if ((!CraftTool.checkStr(dimater, chem.getSizeMinSign2(),
							chem.getSizeMin2()))
							|| (!CraftTool.checkStr(dimater,
									chem.getSizeMaxSign2(), chem.getSizeMax2()))) {
						continue;
					}
				}
				if (chem.getSizeCode().equals("400301")) {
					if ((!CraftTool.checkStr(dimater, chem.getSizeMinSign(),
							chem.getSizeMin()))
							|| (!CraftTool.checkStr(dimater,
									chem.getSizeMaxSign(), chem.getSizeMax()))) {
						continue;
					}
				}
				list.add(chem);
			}
		}
		return list;
	}

	/**
	 * 验证过滤后的成分数据
	 * 
	 * @param chems
	 * @return
	 * @throws SQLException 
	 */
	public static String checkChem(List<CraftOrdDesignStdCicEntity> chems,
			String specStyle, String dimater, String height, String specName,
			String designKey, Connection con, String flag) throws SQLException {
		if (chems == null || chems.size() == 0) {
			if (specStyle.equals("A")) {
				return "<钢管产品> 没有维护符合合同外径(" + dimater + ")/壁厚(" + height
						+ ")的成分标准";
			} else if (specStyle.equals("B")) {
				return "<管坯产品>没有维护符合合同外径(" + dimater + ")的成分标准";
			} else {
				return "<钢锭/其它产品>没有维护符合合同接箍规格(" + specName + ")的成分标准";
			}
		}
		// 有替代/限制元素
		List<CraftOrdDesignStdCicEntity> listRep = new ArrayList<CraftOrdDesignStdCicEntity>();
		List<String> strRep = new ArrayList<String>();
		// 没有任何限制规格/限制元素/替代元素
		List<CraftOrdDesignStdCicEntity> listNo = new ArrayList<CraftOrdDesignStdCicEntity>();
		List<String> strNo = new ArrayList<String>();
		// 只有限制规格
		List<CraftOrdDesignStdCicEntity> listSize = new ArrayList<CraftOrdDesignStdCicEntity>();
		List<String> strSize = new ArrayList<String>();
		
		//排序元素
		CraftOrdDesignStdCicEntity[] chemAry = null;
		if(flag.equals("1")){
			//验证处理MSCn的复合元素（MSCN必须拿MSC0的单一元素一起验证)
			MscChemDao chemDao = new MscChemDao();
			List<CraftOrdDesignStdCicEntity> msc0Chems = chemDao.getCraftMsc0Chem(con, designKey);
			List<CraftOrdDesignStdCicEntity> jfChems = new ArrayList<CraftOrdDesignStdCicEntity>();
			for(CraftOrdDesignStdCicEntity chem : chems){
				jfChems.add(chem);
			}
			for(CraftOrdDesignStdCicEntity msc0chem : msc0Chems){
				boolean exits = false;
				for(CraftOrdDesignStdCicEntity chem : jfChems){
					if(chem.getChemCode().equals(msc0chem.getChemCode())){
						exits = true;
					}
				}
				if(!exits){
					jfChems.add(msc0chem);
				}
			}
			chemAry = new CraftOrdDesignStdCicEntity[jfChems.size()];
			chemAry = jfChems.toArray(chemAry);
			Arrays.sort(chemAry, new MyComprator());
		}else{
			chemAry = new CraftOrdDesignStdCicEntity[chems.size()];
			chemAry = chems.toArray(chemAry);
			Arrays.sort(chemAry, new MyComprator());
		}
		
		
		for (CraftOrdDesignStdCicEntity chem : chems) {
			// 如果成分标准包含替代元素,限制元素
			if (!chem.getRepCode().equals("") || !chem.getEleCode().equals("")) {
				listRep.add(chem);
				strRep.add(chem.getChemName());
			} else {
				// 有限制规格
				if (specStyle.equals("A") || specStyle.equals("B")) {
					// 钢管/管坯
					if (!chem.getSizeCode().equals("")
							|| !chem.getSizeCode2().equals("")) {
						listSize.add(chem);
						strSize.add(chem.getChemName());
					} else {
						listNo.add(chem);
						strNo.add(chem.getChemName());
					}
				} else {
					// 钢锭/其它
					if (!chem.getSpecJg().equals("")) {
						listSize.add(chem);
						strSize.add(chem.getChemName());
					} else {
						listNo.add(chem);
						strNo.add(chem.getChemName());
					}
				}
			}
			
			//验证复合元素必须包含单一元素
			if(chem.getChemType().equals("B")){
				String formula = chem.getChemFormula();
				for(CraftOrdDesignStdCicEntity sortChem : chemAry){
					if(sortChem.getChemType().equals("B")) continue;
					if(formula.contains(sortChem.getChemName())){
						formula = formula.replaceAll(sortChem.getChemName(), "1");
					}else if(sortChem.getChemName().equals("Alt")){
						formula = formula.replaceAll("Al", "1");
					}else if(sortChem.getChemName().equals("Al")){
						formula = formula.replaceAll("Alt", "1");
					}
					formula = formula.replaceAll("f", "1");
				}
				String evalResult = JudgeHelper.eval(formula);
				if(!StringTool.isNumeric(evalResult)){
					return "复合元素"+ chem.getChemName() +"缺少必要的单一元素项!";
				}
			}
		}
		
		
		// 判断成分标准是否符合要求
		// 1.没有任何限制元素的集合，有相同元素，返回提示
		String message = "";
		message = MscChem.getCommon(strNo);
		if (message.length() > 0) {
			return "存在多条相同成分元素(" + message + ")并且没有任何限制条件的成分标准!";
		}
		message = MscChem.getCommon(strSize);
		if (message.length() > 0) {
			if (specStyle.equals("A")) {
				return "<钢管产品>满足合同外径(" + dimater + "),壁厚(" + height
						+ ")并且没有替代/限制元素的成分标准,存在相同的元素:" + message;
			} else if (specStyle.equals("B")) {
				return "<管坯产品>满足合同外径(" + dimater + ")并且没有替代/限制元素的成分标准,存在相同的元素:"
						+ message;
			} else {
				return "<钢锭/其它产品>满足接箍规格(" + specName
						+ "并且没有替代/限制元素的 成分标准,存在相同的元素:" + message;
			}
		}
		if (strNo != null && strNo.size() > 0) {
			for (int i = 0; i < strRep.size(); i++) {
				if (strNo.contains(strRep.get(i))
						|| strSize.contains(strRep.get(i))) {
					return "化学元素:" + strRep.get(i) + "有替代/限制元素约束,所有满足外径("
							+ dimater + "),壁厚" + height + ")的此类化学元素必须有替代/限制元素!";
				}
			}
		}
		return "";

	}

	/**
	 * 取出List相同的元素
	 * 
	 * @param list
	 * @return
	 */
	public static String getCommon(List<String> list) {
		if (list == null || list.size() == 0) {
			return "";
		}
		for (int i = 0; i < list.size(); i++) {
			for (int j = i + 1; j < list.size(); j++) {
				if (list.get(i).equals(list.get(j))) {
					return list.get(j);
				}
			}
		}
		return "";
	}

	/**
	 * 过滤成分标准
	 * 
	 * @param chems
	 *            成分标准集合
	 * @return
	 */
	public static List<CraftOrdDesignStdCicEntity> fiterChemN(
			List<CraftOrdDesignStdCicEntity> chems, String specStyle) {
		List<CraftOrdDesignStdCicEntity> list = new ArrayList<CraftOrdDesignStdCicEntity>();
		for (CraftOrdDesignStdCicEntity chem : chems) {
			if (!chem.getSizeCode().equals("")
					|| !chem.getSizeCode2().equals("")
					|| !chem.getSpecJg().equals("")) {
				for (int i = 0; i < list.size(); i++) {
					CraftOrdDesignStdCicEntity chemi = list.get(i);
					if (chemi.getRepCode().equals("")
							&& chemi.getEleCode().equals("")
							&& chemi.getChemCode().equals(chem.getChemCode())) {
						if (specStyle.equals("A") || specStyle.equals("B")) {
							if (chemi.getSizeCode().equals("")
									&& chemi.getSizeCode2().equals("")) {
								list.remove(i);
							}
						} else {
							if (chemi.getSpecJg().equals("")) {
								list.remove(i);
							}
						}

					}
				}
			}
			list.add(chem);
		}
		return list;
	}
	
	//比较器，x坐标从小到大排序；x相同时，按照y从小到大排序
	static class MyComprator implements Comparator<CraftOrdDesignStdCicEntity> {
	    public int compare(CraftOrdDesignStdCicEntity t1, CraftOrdDesignStdCicEntity t2) {
	        if(t1.getChemName().length() < t2.getChemName().length()){
	        	return 1;
	        }else if(t1.getChemName().length() > t2.getChemName().length()){
	        	return -1;
	        }else{
	        	return 0;
	        }
	    }
	}
	
	public static String checkChemRate(String designKey, Connection con){
		//验证成分取样频率, 如果理化没有按检验批取样的试样组，那么成分不能选择检验批取样频率
		SqlBuilder b = new SqlBuilder("Msc0Dao.getCraftOrdDesignStd");
		b.Fill(new String[]{ designKey });
		CraftOrdDesignStdEntity designStd = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, CraftOrdDesignStdEntity.class);
		b = new SqlBuilder("MscPhyDao.getCraftPicSmp");
		b.Fill(new String[]{ designKey });
		ArrayList<CraftOrdDesignStdPicSmpEntity> craftPicSmps = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, CraftOrdDesignStdPicSmpEntity.class);
		ArrayList<String> allMscPlines = new ArrayList<String>();
		ArrayList<String> jypMscPlines = new ArrayList<String>();
		for(CraftOrdDesignStdPicSmpEntity craftPicSmp : craftPicSmps){
			if(!allMscPlines.contains(craftPicSmp.getMscPline())){
				allMscPlines.add(craftPicSmp.getMscPline());
			}
			if(craftPicSmp.getRate().equals("408602")){
				jypMscPlines.add(craftPicSmp.getMscPline());
			}
		}
		
		String rate = designStd.getRateN().equals("") ? designStd.getRate() : designStd.getRateN();
		if(rate.equals("408602")){
			if(craftPicSmps.size() == 0){
				return "没有找到取样频率为检验批的取样要求，成分标准取样频率不能选择检验批！";	
			}
			for(String mscPline : allMscPlines){
				boolean exists = false;
				for(String jypMscPline : jypMscPlines){
					if(jypMscPline.equals(mscPline)){
						exists = true;
					}
				}
				if(!exists){
					return "制程" + mscPline + "没有找到取样频率为检验批的取样要求，成分标准取样频率不能选择检验批！";
				}
			}
		}
		
		return "";
	}
}
