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

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

import CoreFS.SA06.CoreReturnObject;

import com.steering.pss.judge.comm.JudgeHelper;
import com.steering.pss.qcm.CoreWaterStand;
import com.steering.pss.sale.order.craftDesign.dao.MscWaterDao;
import com.steering.pss.sale.order.craftDesign.model.ComBaseSpecEntity;
import com.steering.pss.sale.order.craftDesign.model.ComBaseWaterRatioEntity;
import com.steering.pss.sale.order.craftDesign.model.ComMscStdWaterEntity;
import com.steering.pss.sale.order.craftDesign.model.CraftEntity;
import com.steering.pss.sale.order.craftDesign.model.CraftOrdDesignStdWicEntity;
import com.steering.pss.sale.order.craftDesign.model.StdEntity;
import com.steering.pss.sale.order.craftDesign.tool.CraftTool;

public class MscWater {
	// 验证水压流程:
	// 1、根据冶金规范码查询水压索引号(冶金规范码类型通过审批,则查询通过审批的水压索引号,没通过则查询有效的水压索引号)
	// 2、过滤水压索引号(外径、壁厚)
	// 2、根据水压索引号查询水压标准
	// 3、查询水压系数
	// 4、只要一个水压索引号通过,则水压通过验证
	//
	private static String message = "";

	/**
	 * 查询水压索引号
	 * 
	 * @param con
	 * @param msc
	 * @param modelCode
	 * @param mscValig
	 * @param dimater
	 * @param height
	 * @return
	 * @throws SQLException
	 */
	public List<String> getWicByMscAndModel(Connection con, String msc,
			String modelCode, String mscValig, String dimater, String height)
			throws SQLException {
		MscWaterDao mscWaterDao = new MscWaterDao();
		List<ComMscStdWaterEntity> waterM = null;
		if (mscValig.equals("C")) {
			waterM = mscWaterDao.getExamineWic(con, msc, modelCode, "C");
		} else {
			waterM = mscWaterDao.getExamineWic(con, msc, modelCode, "");
		}
		List<String> wics = MscWater.fiterWaterIndex(dimater, height, waterM);
		return wics;
	}

	/**
	 * 验证水压标准
	 * 
	 * @param con
	 *            连接字符串
	 * @param design
	 *            质量设计类
	 * @return boolean
	 * @throws SQLException
	 */
	public StdEntity checkWater(Connection con, CraftEntity design, String flag,
			List<String> wics, List<String> mscnWics) throws SQLException {
		message = "";
		MscWaterDao mscWaterDao = new MscWaterDao();
		String designKey = design.getDesignKey();
		String useCode = design.getUseCode();
		String useDesc = design.getUseDesc();
		StdEntity stdEntity = new StdEntity();
		for (String wic : wics) {
			
			// 查询水压标准
			List<CraftOrdDesignStdWicEntity> waters = mscWaterDao
					.getWaterByWic(con, wic);
			if (waters == null || waters.size() == 0) {
				message = "水压标准存在水压索引号,但找不到水压标准";
				continue;
			}
			//一个水索引码只能维护一套水压值
			if(waters.size() > 1){
				message = "水压标准索引号" + wic + "只能维护一套水压标准值";
				continue;
			}
			// 验证水压系数
			boolean flagA = true;
			for (CraftOrdDesignStdWicEntity water : waters) {
				if (water.getFormula().contains("f")) {
					// 查询水压系数
					String[] ratio = MscWater.checkWaterRatio(con, design, flag, wic);
					if (ratio == null) {
						//如果MSC0没有找到水压，而又有MSCN，那么MSCN必须维护水压标准。
						if(flag.equals("0") && !design.getMsc0().equals(design.getMscOr())){
							if(mscnWics == null){
								flagA = false;
								stdEntity.setListItem("MSC(n)");
								message = "请维护" + design.getMscOr() + "的水压标准！（"+ design.getMsc0() +"中的水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
										+ message + "）";
								break;
							}else{
								break;
							}
						}else{
							flagA = false;
							message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
									+ message;
							break;
						}
					} else {
						water.setRatioStd(ratio[0]);
						water.setMaxPress(ratio[1]);
					}
				}
				//比较内控与交付的保压时间2020-4-14
				if(flag.equals("2")){
					String time = mscWaterDao
							.getTimeByDesignKey(con, designKey);
					if(time!=null){
						double Value0 = Double.parseDouble(time);
						double Value2 = Double.parseDouble(water.getSaveTime());
						if(Value0>Value2){
							flagA = false;
							message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
									+ "内控保压时间不能小于交付保压时间";
							break;
						}
					}	
				}
				String formula = water.getFormula();
				if(!formula.equals("")){
					String waterYS = mscWaterDao.getWaterYS(con, designKey);
					String waterTS = mscWaterDao.getWaterTS(con, designKey);
					
					if(formula.contains("YS") && waterYS.equals("")){
						flagA = false;
						message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
								+ "理化标准中找不到最小屈服强度值，无法计算此公式";
						break;
					}else if(formula.contains("TS") && waterTS.equals("")){
						flagA = false;
						message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
								+ "理化标准中找不到最小抗拉强度值，无法计算此公式";
						break;
					}
					formula = formula.replaceAll("f", water.getRatioStd());
					formula = formula.replaceAll("YS", waterYS);
					formula = formula.replaceAll("TS", waterTS);
					formula = formula.replaceAll("t", design.getHeight());
					formula = formula.replaceAll("D", design.getDimater());
					String value = JudgeHelper.eval(formula);
					double dValue = Double.parseDouble(value);
					CoreWaterStand waterStand = new CoreWaterStand();
					CoreReturnObject cro = waterStand.waterRound(dValue, water.getRoundRule());
					double mpa = ((double[])cro.getResult())[0];
					double psi = ((double[])cro.getResult())[1];
					
					//最大试验压力
					if(!water.getMaxPress().equals("")){
						double maxPress = Double.parseDouble(water.getMaxPress());
						CoreReturnObject cro2 = waterStand.waterRound(maxPress, water.getRoundRule());
						double psi2 = ((double[])cro2.getResult())[1];
						if(mpa > maxPress){
							mpa = maxPress;
							psi = psi2;
						}
					}

					if(water.getOutputStyle().equals("")){
						flagA = false;
						message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
								+ "请选择工艺文件输出方式";
						break;
					}
					if(water.getZbsOutputStyle().equals("")){
						flagA = false;
						message = "水压索引号:" + wic + "水压序号:" + water.getIndexSeq()
								+ "请选择质保书输出方式";
						break;
					}
					water.setPressureY(String.valueOf(psi));
					water.setPressure(String.valueOf(mpa));
					water.setPressureBar(String.valueOf(mpa * 10));//1bar = 10MPa
//					if(water.getOutputStyle().equals("410702")){
//						water.setPressureY(String.valueOf(psi));
//					}else if(water.getOutputStyle().equals("410701")){
//						water.setPressure(String.valueOf(mpa));
//					}else{
//						water.setPressure(String.valueOf(mpa));
//						water.setPressureY(String.valueOf(psi));
//					}
				}
			}
			if (!flagA) {
				continue;
			}

			for (CraftOrdDesignStdWicEntity water : waters) {
				// 国标与其它标准是没有制程号与工序号的．只是默认给个值
				water.setMscPline("Y");
				water.setProcessCode("Y");
				// 是否特殊要求(0否;1是)
				water.setSpeclFl(flag);
				water.setDesginKey(designKey);
				if (flag.equals("1")) {
					water.setUseCode(useCode);
					water.setUseDesc(useDesc);
				}
				// mscWaterDao.saveWater(con, water, designKey);
			}
			// if (flag.equals("0")) {
			// mscWaterDao.updateDesignStd(con, wic, designKey);
			// }
			stdEntity.setFlag(true);
			stdEntity.setMessage("水压标准通过验证!");
			stdEntity.setObjKey(wic);
			stdEntity.setObjM(waters);
			return stdEntity;
		}
		stdEntity.setFlag(false);
		stdEntity.setMessage(message);
		return stdEntity;
	}

	/**
	 * 通过外径、壁厚过滤水压索引号
	 * @param waters
	 * @return
	 */
	public static List<String> fiterWaterIndex(String dimater, String height,
			List<ComMscStdWaterEntity> waters) {
		List<String> list = new ArrayList<String>();
		if (waters == null || waters.size() == 0) {
			return null;
		}
		// 过滤外径、壁厚
		for (ComMscStdWaterEntity water : waters) {
			if (CraftTool.checkStr(water.getMinD(), "<=", dimater)
					&& CraftTool.checkStr(water.getMaxD(), ">=", dimater)
					&& CraftTool.checkStr(water.getMinH(), "<=", height)
					&& CraftTool.checkStr(water.getMaxH(), ">=", height)) {
				list.add(water.getWic());
			}
		}

		return list;
	}

	/**
	 * 查詢水压系数和最大水压压力
	 * 
	 * @param design
	 * @return
	 * @throws SQLException
	 */
	public static String[] checkWaterRatio(Connection con, CraftEntity design, 
			String flag, String wic)
			throws SQLException {
		String[] str = new String[2];
		MscWaterDao mscWaterDaoImp = new MscWaterDao();
		// 查询水压系数
		List<ComBaseWaterRatioEntity> waterRatios = mscWaterDaoImp
				.getWaterPress(con, design.getModelCode(), design.getStdCode(),
						design.getSteelCode(), design.getStdStyle(), wic);
		// 过滤外径
		List<ComBaseWaterRatioEntity> waterRatiosA = MscWater.fiterWaterRatio(
				waterRatios, design.getDimater());
		// 查詢適用所有标准类别的水压系数
		if (waterRatiosA == null || waterRatiosA.size() == 0) {
			List<ComBaseWaterRatioEntity> waterRatioNexts = mscWaterDaoImp
					.getWaterPressOther(con, design.getModelCode(),
							design.getStdCode(), design.getSteelCode());
			List<ComBaseWaterRatioEntity> waterRatiosNextA = MscWater
					.fiterWaterRatio(waterRatioNexts, design.getDimater());
			// 如果过滤完，如果没有值，则查询引用水压标准
			if (waterRatiosNextA == null || waterRatiosNextA.size() == 0) {
				String[] id = mscWaterDaoImp.getQuoteWaterStd(con,
						design.getStdCode(), design.getStdStyle());
				if (id == null) {
//					//当有MSCn的时候MSC0不卡水压系数
//					if(flag.equals("0") && !design.getMsc0().equals(design.getMscOr())){
//						str[0] = "100";
//						str[1] = "250";
//						return str;
//					}
					
					message = " 外径:" + design.getDimater() + "扣型:"
							+ design.getModelDesc() + " 钢级:"
							+ design.getSteelName() + "标准类别:"
							+ design.getStdStyleDesc() + "找不到水压系数,并且找不到引用水压标准!";
					return null;
				} else {
					// 如果找到引用水压标准主键，则用引用水压标准找水压系数
					List<ComBaseWaterRatioEntity> waterRatiosN = mscWaterDaoImp
							.getWaterPress(con, design.getModelCode(), id[0],
									design.getSteelCode(), id[1], wic);
					List<ComBaseWaterRatioEntity> waterRatiosAN = MscWater
							.fiterWaterRatio(waterRatiosN, design.getDimater());
					if (waterRatiosAN != null && waterRatiosAN.size() == 1) {
						str[0] = waterRatiosAN.get(0).getRatioStd();
						str[1] = waterRatiosAN.get(0).getMaxPress();
						return str;
					} else {
						//获取设定水压系数
						String ratioId = mscWaterDaoImp.getSetRatioId(con, design.getOrdLnPk());
						if(!ratioId.equals("") && waterRatiosAN != null){
							for(ComBaseWaterRatioEntity waterRatioAN : waterRatiosAN){
								if(waterRatioAN.getRatioId().equals(ratioId)){
									str[0] = waterRatioAN.getRatioStd();
									str[1] = waterRatioAN.getMaxPress();
									return str;
								}
							}
						}
						
//						//当有MSCn的时候MSC0不卡水压系数
//						if(flag.equals("0") && !design.getMsc0().equals(design.getMscOr())){
//							str[0] = "100";
//							str[1] = "250";
//							return str;
//						}
						message = " 外径:" + design.getDimater() + "扣型:"
								+ design.getModelDesc() + " 钢级:"
								+ design.getSteelName() + "标准类别:"
								+ design.getStdStyleDesc() + "找到引用水压标准" + id[0]
								+ ",但引用水压标准找不到水压系数,或者找到多个水压系数!";
						return null;
					}
				}
			} else if (waterRatiosNextA.size() == 1) {
				// 如果值有一条，则正确
				str[0] = waterRatiosNextA.get(0).getRatioStd();
				str[1] = waterRatiosNextA.get(0).getMaxPress();
				return str;
			} else {
				//获取设定水压系数
				String ratioId = mscWaterDaoImp.getSetRatioId(con, design.getOrdLnPk());
				if(!ratioId.equals("") && waterRatiosNextA != null){
					for(ComBaseWaterRatioEntity waterRatioNextA : waterRatiosNextA){
						if(waterRatioNextA.getRatioId().equals(ratioId)){
							str[0] = waterRatioNextA.getRatioStd();
							str[1] = waterRatioNextA.getMaxPress();
							return str;
						}
					}
				}
				
//				//当有MSCn的时候MSC0不卡水压系数
//				if(flag.equals("0") && !design.getMsc0().equals(design.getMscOr())){
//					str[0] = "100";
//					str[1] = "250";
//					return str;
//				}
				// 如果值有多条，错误
				message = " 外径:" + design.getDimater() + "扣型:"
						+ design.getModelDesc() + " 钢级:"
						+ design.getSteelName() + "找到多个水压系数!";
				return null;
			}

		} else if (waterRatiosA.size() == 1) {
			// 如果值有一条，则正确
			str[0] = waterRatiosA.get(0).getRatioStd();
			str[1] = waterRatiosA.get(0).getMaxPress();
			return str;
		} else {
			//获取设定水压系数
			String ratioId = mscWaterDaoImp.getSetRatioId(con, design.getOrdLnPk());
			if(!ratioId.equals("") && waterRatiosA != null){
				for(ComBaseWaterRatioEntity waterRatioA : waterRatiosA){
					if(waterRatioA.getRatioId().equals(ratioId)){
						str[0] = waterRatioA.getRatioStd();
						str[1] = waterRatioA.getMaxPress();
						return str;
					}
				}
			}
//			//当有MSCn的时候MSC0不卡水压系数
//			if(flag.equals("0") && !design.getMsc0().equals(design.getMscOr())){
//				str[0] = "100";
//				str[1] = "250";
//				return str;
//			}
			// 如果值有多条，错误
			message = " 外径:" + design.getDimater() + "扣型:"
					+ design.getModelDesc() + " 钢级:" + design.getSteelName()
					+ "标准类别:" + design.getStdStyleDesc() + "找到多个水压系数!";
			return null;
		}

	}

	/**
	 * 过滤水压系数
	 *
	 * @return
	 */
	public static List<ComBaseWaterRatioEntity> fiterWaterRatio(
			List<ComBaseWaterRatioEntity> waterRatios, String dimater) {
		if (waterRatios == null || waterRatios.size() == 0) {
			return null;
		}
		for (int i = 0; i < waterRatios.size(); i++) {
			ComBaseWaterRatioEntity waterRatio = waterRatios.get(i);
			if (!CraftTool.checkStr(dimater, waterRatio.getSizeMinSign(),
					waterRatio.getSizeMin())
					|| !CraftTool.checkStr(dimater,
							waterRatio.getSizeMaxSign(),
							waterRatio.getSizeMax())) {
				waterRatios.remove(waterRatio);
				--i;
			}
		}

		return waterRatios;
	}
}
