package com.steering.pss.sale.order.qualityDesign.server.iserver;

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.model.ComMscEntity;
import com.steering.pss.sale.order.model.DesignStdWicEntity;
import com.steering.pss.sale.order.model.DesignWaterRatioEntity;
import com.steering.pss.sale.order.model.MscStdWaterEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import com.steering.pss.sale.order.qualityDesign.Dao.factory.FactoryDao;
import com.steering.pss.sale.order.qualityDesign.Dao.imp.MscDaoImp;
import com.steering.pss.sale.order.qualityDesign.Dao.imp.MscWaterDaoImp;
import com.steering.pss.sale.order.qualityDesign.ReturnsModel.DesignEntity;
import com.steering.pss.sale.order.qualityDesign.server.imp.MscWaterImp;

public class IMscWater implements MscWaterImp {

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

	/**
	 * 验证水压标准
	 * 
	 * @param con
	 *            连接字符串
	 * @param design
	 *            质量设计类
	 * @return boolean
	 * @throws SQLException
	 */
	public String[] checkWater(Connection con, String msc, DesignEntity design,
			String flag) throws SQLException {
		message = "";
		String[] results = new String[]{"", ""};
		MscWaterDaoImp mscWaterDaoImp = FactoryDao.getMscWaterDaoImp();
		MscDaoImp mscDaoImp = FactoryDao.getMscDaoImp();
		String designKey = design.getDesignKey();
		String useCode = design.getUserCode();
		String useDesc = design.getUserDesc();
		String modelCode = design.getModelCode();
		ComMscEntity comMscEntity = mscDaoImp.getMsc(con, msc);
		// 如果冶金规范码已经通过审批，即状态等于C，则认为标准通过验证
		List<MscStdWaterEntity> waterM = new ArrayList<MscStdWaterEntity>();
		if (comMscEntity.getValidflag().equals("C")) {
			waterM = mscWaterDaoImp.getExamineWic(con, msc, modelCode);
		} else {
			waterM = mscWaterDaoImp.getValidWic(con, msc, modelCode);
		}
		List<String> wics = IMscWater.fiterWaterIndex(design, waterM);
		// 找不到水压索引号
		if (wics == null || wics.size() == 0) {
			return new String[]{ message, ""};
		}
		for (String wic : wics) {
			// 查询水压标准
			List<DesignStdWicEntity> waters = mscWaterDaoImp.getWaterByWic(con,
					wic);
			if (waters == null || waters.size() == 0) {
				message = "水压标准存在水压索引号,但找不到水压标准";
				continue;
			}
			//一个水索引码只能维护一套水压值
			if(waters.size() > 1){
				message = "水压标准索引号" + wic + "只能维护一套水压标准值";
				continue;
			}
			// 验证水压系数
			boolean flagA = true;
			for (DesignStdWicEntity water : waters) {
				if (water.getFormula().contains("f")) {
					// 查询水压系数
					String[] ratio = IMscWater.checkWaterRatio(con, design, flag);
					if (ratio == null) {
						//如果MSC0没有找到水压，而又有MSCN，那么MSCN必须维护水压标准。
						if(flag.equals("0") && !design.getMsc().equals(design.getOrderLineMsc())){
							List<MscStdWaterEntity> tmpWater = mscWaterDaoImp.getValidWic(con, design.getOrderLineMsc(), modelCode);
							List<String> tmpWics = IMscWater.fiterWaterIndex(design, tmpWater);
							if(tmpWics == null){
								flagA = false;
								results[1] = "MSC(n)";
								message = "请维护" + design.getOrderLineMsc() + "的水压标准！（"+ design.getMsc() +"中的水压索引号:" + 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]);
					}
				}
				
				if(!water.getFormula().equals("")){
					String waterYS = mscWaterDaoImp.getWaterYS(con, designKey);
					String waterTS = mscWaterDaoImp.getWaterTS(con, designKey);
					String formula = water.getFormula();
					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;
						}
					}
					
					water.setPressure(String.valueOf(mpa));
					water.setPressureY(String.valueOf(psi));
				}
			}
			if (!flagA) {
				continue;
			}

			for (DesignStdWicEntity water : waters) {
				// 是否特殊要求(0否;1是)
				water.setSpeclFl(flag);
				if (flag.equals("1")) {
					water.setUseCode(useCode);
					water.setUseDesc(useDesc);
				}
				mscWaterDaoImp.saveWater(con, water, designKey);
			}
			if (flag.equals("0")) {
				mscWaterDaoImp.updateDesignStd(con, wic, designKey);
			}

			message = "";
			break;
		}
		
		results[0] = message;
		return results;
	}

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

		return list;
	}

	/**
	 * 查詢水压系数和最大水压压力
	 * 
	 * @param design
	 * @return
	 * @throws SQLException
	 */
	public static String[] checkWaterRatio(Connection con, DesignEntity design, String flag)
			throws SQLException {
		String[] str = new String[2];
		MscWaterDaoImp mscWaterDaoImp = FactoryDao.getMscWaterDaoImp();
		// 查询水压系数
		List<DesignWaterRatioEntity> waterRatios = mscWaterDaoImp
				.getWaterPress(con, design.getModelCode(), design.getStdCode(),
						design.getSteelCode(), design.getStdStyle());
		// 过滤外径
		List<DesignWaterRatioEntity> waterRatiosA = IMscWater.fiterWaterRatio(
				waterRatios, design.getDimater());
		// 查詢適用所有标准类别的水压系数
		if (waterRatiosA == null || waterRatiosA.size() == 0) {
			List<DesignWaterRatioEntity> waterRatioNexts = mscWaterDaoImp
					.getWaterPressOther(con, design.getModelCode(),
							design.getStdCode(), design.getSteelCode());
			List<DesignWaterRatioEntity> waterRatiosNextA = IMscWater
					.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.getMsc().equals(design.getOrderLineMsc())){
//						str[0] = "100";//10000
//						str[1] = "250";
//						return str;
//					}
					message = " 外径:" + design.getDimater() + "扣型:"
							+ design.getModelDesc() + " 钢级:"
							+ design.getSteelName() + "标准类别:"
							+ design.getStdStyleDesc() + "找不到水压系数,并且找不到引用水压标准!";
					return null;
				} else {
					// 如果找到引用水压标准主键，则用引用水压标准找水压系数
					List<DesignWaterRatioEntity> waterRatiosN = mscWaterDaoImp
							.getWaterPress(con, design.getModelCode(), id[0],
									design.getSteelCode(), id[1]);
					List<DesignWaterRatioEntity> waterRatiosAN = IMscWater
							.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(DesignWaterRatioEntity waterRatioAN : waterRatiosAN){
								if(waterRatioAN.getRatioId().equals(ratioId)){
									str[0] = waterRatioAN.getRatioStd();
									str[1] = waterRatioAN.getMaxPress();
									return str;
								}
							}
						}
						
						//当有MSCn的时候MSC0不卡水压系数
//						if(flag.equals("0") && !design.getMsc().equals(design.getOrderLineMsc())){
//							str[0] = "100";//10000
//							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(DesignWaterRatioEntity waterRatioNextA : waterRatiosNextA){
						if(waterRatioNextA.getRatioId().equals(ratioId)){
							str[0] = waterRatioNextA.getRatioStd();
							str[1] = waterRatioNextA.getMaxPress();
							return str;
						}
					}
				}
				// 如果值有多条，错误
				//当有MSCn的时候MSC0不卡水压系数
//				if(flag.equals("0") && !design.getMsc().equals(design.getOrderLineMsc())){
//					str[0] = "100";//10000
//					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(DesignWaterRatioEntity waterRatioA : waterRatiosA){
					if(waterRatioA.getRatioId().equals(ratioId)){
						str[0] = waterRatioA.getRatioStd();
						str[1] = waterRatioA.getMaxPress();
						return str;
					}
				}
			}
			
			//当有MSCn的时候MSC0不卡水压系数
//			if(flag.equals("0") && !design.getMsc().equals(design.getOrderLineMsc())){
//				str[0] = "100";//10000
//				str[1] = "250";
//				return str;
//			}
			// 如果值有多条，错误
			message = " 外径:" + design.getDimater() + "扣型:"
					+ design.getModelDesc() + " 钢级:" + design.getSteelName()
					+ "标准类别:" + design.getStdStyleDesc() + "找到多个水压系数!";
			return null;
		}

	}

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

		return waterRatios;
	}
}
