package com.steering.pss.plnsaleord.lenthCal;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import CoreFS.SA08.CoreXmlSqlParsersFactory;

import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.CoreUnitConvert;
import com.steering.pss.plnsaleord.lenthCal.model.LenZgCalEntiy;
import com.steering.pss.plnsaleord.ordAmCal.model.InZgOrdCalEntity;
import com.steering.pss.plnsaleord.order.baseMethod.CoreTolerOfNk;
import com.steering.pss.plnsaleord.order.model.CoreTolerOfNkParam;
import com.steering.pss.plnsaleord.order.model.PlnOrdInfo;

/**
 * @author tjg 2017-04-23
 */
public class PlnZglenthCal {

	/**
	 * 外径壁厚变化率
	 * 
	 * @param diameter
	 *            成品外径
	 * @param height
	 *            成品壁厚
	 * @param diameterZg
	 *            轧制外径
	 * @param heightZg
	 *            轧制壁厚
	 * @param buringDbk
	 *            镦拔扩产线烧损率（%）
	 * @return
	 */
	public static double getDhChangeRate(double diameter, double height,
			double diameterZg, double heightZg, double buringDbk) {
		double rate = 1;
		rate = height * (diameter - height)
				/ (heightZg * (diameterZg - heightZg)) / (1 - buringDbk / 100);
		return rate;
	}

	/***
	 * 轧管转移长度推算 （m）
	 * 
	 * @param len
	 *            成品长度（m）
	 * @param rate
	 *            外径壁厚变化率
	 * @param lenDc
	 *            镦粗影响长（mm）
	 * @param dbkCut
	 *            镦拔扩镦拔扩切头尾（mm）
	 * @param inspectLen
	 *            探伤盲区切长（mm）
	 * @param checkJVal
	 *            接箍J值（mm）
	 * @param addlenZgRule
	 *            轧管加长原则（mm）
	 * @return
	 */
	public static double lenthZgCal(double len, double rate, double lenDc,
			double dbkCut, double inspectLen, double checkJVal,
			double addlenZgRule) {
		double lenZg = 0;
		lenZg = rate
				* (len + (lenDc + addlenZgRule + dbkCut + inspectLen - checkJVal) / 1000);
		// lenZg = new BigDecimal(lenZg).setScale(2, RoundingMode.HALF_UP)
		// .doubleValue();
		return new BigDecimal(lenZg).setScale(3, RoundingMode.HALF_UP)
				.doubleValue();
	}

	/***
	 * 镦拔扩原料上限长度推算 （m）
	 * 
	 * @param lenMax
	 *            成品上长度（m）
	 * @param lenMin
	 *            成品下长度（m）
	 * @param rate
	 *            镦拔扩变化率
	 * @param lenDc
	 *            镦粗影响长（mm）
	 * @param dbkCut
	 *            镦拔扩镦拔扩切头尾（mm）
	 * @param checkJVal
	 *            接箍J值（mm）
	 * @param lenSpoe
	 *            加严率
	 * @return
	 */
	public static double lenthDbkCalMax(double lenMax, double lenMin,
			double rate, double lenDc, double dbkCut, double checkJVal,
			double lenSpoe) {
		double lenZg = 0;
		double lenPcMax = lenMax - checkJVal / 1000;
		double lenPcMin = lenMin - checkJVal / 1000;
		lenZg = rate
				* (lenPcMax - 0.5 * lenSpoe / 100 * (lenPcMax - lenPcMin) + (lenDc + dbkCut) / 1000);
		// lenZg = new BigDecimal(lenZg).setScale(2, RoundingMode.HALF_UP)
		// .doubleValue();
		return lenZg;
	}

	/***
	 * 镦拔扩原料下限长度推算 （m）
	 * 
	 * @param lenMax
	 *            成品上长度（m）
	 * @param lenMin
	 *            成品下长度（m）
	 * @param rate
	 *            镦拔扩变化率
	 * @param lenDc
	 *            镦粗影响长（mm）
	 * @param dbkCut
	 *            镦拔扩镦拔扩切头尾（mm）
	 * @param checkJVal
	 *            接箍J值（mm）
	 * @param lenSpoe
	 *            加严率
	 * @return
	 */
	public static double lenthDbkCalMin(double lenMax, double lenMin,
			double rate, double lenDc, double dbkCut, double checkJVal,
			double lenSpoe) {
		double lenZg = 0;
		double lenPcMax = lenMax - checkJVal / 1000;
		double lenPcMin = lenMin - checkJVal / 1000;
		lenZg = rate
				* (lenPcMin + 0.5 * lenSpoe / 100 * (lenPcMax - lenPcMin) + (lenDc + dbkCut) / 1000);
		// lenZg = new BigDecimal(lenZg).setScale(2, RoundingMode.HALF_UP)
		// .doubleValue();
		return lenZg;
	}

	/**
	 * 轧管加长原则 （mm）
	 * 
	 * @param lenMax
	 *            成品长度上限（m）
	 * @param lenMin
	 *            成品长度下限（m）
	 * @param modelDesc
	 *            扣型描述
	 * @return mm
	 */
	public static double addLenZgRule(double lenMax, double lenMin,
			String modelDesc) {
		double addlen = 0;
		if ((modelDesc.contains("PE") || modelDesc.contains("BE"))
				&& (lenMax - lenMin) < 0.3) {
			addlen = 0.3 / (int) (14.5 / lenMax);
		}
		return addlen * 1000;
	}

	/**
	 * 单倍成品长度上限轧管加长原则 （mm）
	 * 
	 * @param lenMax
	 *            成品长度上限（m）
	 * @param lenMin
	 *            成品长度下限（m）
	 * @param modelDesc
	 *            扣型描述
	 * @return mm
	 */
	public static double addLenZgRuleMaxS(double lenMax, double lenMin,
			String modelDesc) {
		double addlen = 0;
		if ((modelDesc.contains("PE") || modelDesc.contains("BE"))
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) <= 0.15
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) >= 0.05) {
			addlen = 0.1;
		}
		if ((modelDesc.contains("PE") || modelDesc.contains("BE"))
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) < 0.05) {
			addlen = 0.23;
		}
		double d = addlen * 1000;
		return d;
	}

	/**
	 * 单倍成品长度上限轧管加长原则 （mm）
	 *
	 * @param
	 *
	 *
	 * @return mm
	 */
	public static double addLenZgRuleMax(Connection con,PlnOrdInfo ordInfo,int cutJg) throws SQLException {
		double addLenMax = 0.0;
		String sql = CoreXmlSqlParsersFactory.getSql("CorePlnProcessOrd.addLenZgRuleMax");
		sql = EntityTool.fillSqlByEntity(sql,ordInfo);
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			addLenMax = Double.parseDouble(rs.getString("LEN_LONGER_MAX"));
		}
		rs.close();
		ps.close();
		return addLenMax;
	}


	/**
	 * 单倍成品长度下限轧管加长原则 （mm）
	 * 
	 * @param lenMax
	 *            成品长度上限（m）
	 * @param lenMin
	 *            成品长度下限（m）
	 * @param modelDesc
	 *            扣型描述
	 * @return mm
	 */
	public static double addLenZgRuleMinS(double lenMax, double lenMin,
			String modelDesc) {
		double addlen = 0;
		if ((modelDesc.contains("PE") || modelDesc.contains("BE"))
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) <= 0.15
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) >= 0.05) {
			addlen = 0.02;
		}
		if ((modelDesc.contains("PE") || modelDesc.contains("BE"))
				&& (new BigDecimal(lenMax - lenMin).setScale(2,
						RoundingMode.HALF_UP).doubleValue()) < 0.05) {
			addlen = 0.15;
		}
		double d = addlen * 1000;
		return d;
	}

	/**
	 * 单倍成品长度上限轧管加长原则 （mm）
	 *
	 * @param
	 *
	 * @param
	 *
	 * @param
	 *
	 * @return mm
	 */
	public static double addLenZgRuleMin(Connection con,PlnOrdInfo ordInfo,int cutJg) throws SQLException {
		double addLenMin = 0.0;
		String sql = CoreXmlSqlParsersFactory.getSql("CorePlnProcessOrd.addLenZgRuleMin");
		sql = EntityTool.fillSqlByEntity(sql,ordInfo);
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			addLenMin = Double.parseDouble(rs.getString("LEN_LONGER_MIN"));
		}
		rs.close();
		ps.close();
		return addLenMin;
	}

	/**
	 * 轧管转移长度上限（m）
	 * 
	 * @param lanCalEntity
	 * @return
	 */
	public static double lenZgCalMax(LenZgCalEntiy lanCalEntity) {
		double lenZg = 0;
		double rate = getDhChangeRate(lanCalEntity.getDiameter(), lanCalEntity
				.getHeight(), lanCalEntity.getDiameterZg(), lanCalEntity
				.getHeightZg(), lanCalEntity.getBuringDbk());
		double addLenRule = addLenZgRuleMaxS(lanCalEntity.getLenMax(),
				lanCalEntity.getLenMin(), lanCalEntity.getModelDesc());
		lenZg = lenthZgCal(lanCalEntity.getLenMax(), rate, lanCalEntity
				.getLenDc(), lanCalEntity.getDbkCut(), lanCalEntity
				.getInspectLen(), lanCalEntity.getCheckJVal(), addLenRule);
		return lenZg;
	}

	/**
	 * 轧管转移长度下限（m）
	 * 
	 * @param lanCalEntity
	 * @return
	 */
	public static double lenZgCalMin(LenZgCalEntiy lanCalEntity) {
		double lenZg = 0;
		double rate = getDhChangeRate(lanCalEntity.getDiameter(), lanCalEntity
				.getHeight(), lanCalEntity.getDiameterZg(), lanCalEntity
				.getHeightZg(), lanCalEntity.getBuringDbk());
		double addLenRule = addLenZgRuleMinS(lanCalEntity.getLenMax(),
				lanCalEntity.getLenMin(), lanCalEntity.getModelDesc());
		lenZg = lenthZgCal(lanCalEntity.getLenMin(), rate, lanCalEntity
				.getLenDc(), lanCalEntity.getDbkCut(), lanCalEntity
				.getInspectLen(), lanCalEntity.getCheckJVal(), addLenRule);
		return lenZg;
	}

	/**
	 * 获取轧管加长原则，转移长度上下限，加工分切,控制外径壁厚 ，管单重（下发）
	 * 
	 * @param conn
	 * @param ordInfo
	 * @return
	 */
	public static PlnOrdInfo calcPlnInfo(Connection conn, PlnOrdInfo ordInfo) {
		PreparedStatement psta = null;
		LenCalculateInObject lenCalIn = new LenCalculateInObject();
		ResultSet rs = null;
		String sql = "";
		double lengZgMax = 0;
		double lengZgMin = 0;
		int cutJg = 1;// 加工分切数
		double x = 1;
		double outdiameterIn = 0;// 墩拔扩原料外径
		double wallthickIn = 0;// 墩拔扩原料壁厚
		double outdiameterDbk = 0;// 墩拔扩外径
		double wallthickDbk = 0;// 墩拔扩壁厚
		double buringRateDbk = 0;// 墩拔扩烧损率
		String dbkpline = "";// 墩拔扩产线
		double addDbk = 0;// 镦拔扩切头尾加长（mm）
		double addDc = 0;// 镦粗加长（mm）
		double lengthCpMax = 0;// 成品长度上限
		double lengthCpMin = 0;// 成品长度下限
		double buringRateZg = 0;// 轧管烧损率
		String sic = "";// 内控公差索引码
		String wholeBacklog = "";// 制程编号
		String wholeBacklogDesc = "";// 制程描述
		double toleranceZone = 0;// 机组公差能力带
		String dbkcutHead = "";
		String dbkcutEnd = "";
		double totlengthM = 0;
		try {
//			if (ordInfo.getTotlengthUnit().trim().equals("英尺")) {
//				totlengthM = CoreUnitConvert
//						.FootoMi(ordInfo.getTotlength());
//			} else if (ordInfo.getTotlengthUnit().trim().equals("米")) {
//				totlengthM = ordInfo.getTotlength();
//			} else {
//				totlengthM = 0;
//			}
//			if (lengthCpMax > totlengthM && totlengthM != 0) {
//				cutJg = (int) (totlengthM / lengZgMax);
//			} else {
//				cutJg = (int) (lengthCpMax / lengZgMax);
//			}
//			if (cutJg == 0) {
//				cutJg = 1;
//			}


			// 轧管加长原则(mm)
//			double addlenZgRuleMax = addLenZgRuleMax(conn,ordInfo,cutJg);// 轧管加长原则上限(mm)
//			double addlenZgRuleMin = addLenZgRuleMin(conn,ordInfo,cutJg);// 轧管加长原则下限(mm)
			double addlenZgRuleMax = 0.0;// 轧管加长原则上限(mm)
			double addlenZgRuleMin = 0.0;// 轧管加长原则下限(mm)
			// 查询轧管产线成品长度上下限
			sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcessOrd.queryBasePlineD");
			psta = conn.prepareStatement(sql);
			psta.setString(1, ordInfo.getPlineD());
			rs = psta.executeQuery();
			if (rs.next()) {
				lengthCpMax = rs.getDouble("LENGTH_MAX");
				lengthCpMin = rs.getDouble("LENGTH_MIN");
				toleranceZone = rs.getDouble("TOLERANCE_ZONE");
			}
			rs.close();
			psta.close();

			// 查询原料管规格
			sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcessOrd.queryDesginBom");
			psta = conn.prepareStatement(sql);
			psta.setString(1, ordInfo.getBom());
			rs = psta.executeQuery();
			if (rs.next()) {
				outdiameterIn = rs.getDouble("DIMATER");
				wallthickIn = rs.getDouble("HEIGHT");
				outdiameterDbk = rs.getDouble("DIMATERDBK");
				wallthickDbk = rs.getDouble("HEIGHTDBK");
				wholeBacklog = rs.getString("WHOLE_BACKLOG");
				wholeBacklogDesc = rs.getString("WHOLE_BACKLOG_DESC");

				String[] dbkAdd = addLenDbk(conn, rs
						.getString("E_IN_MATERIAL_NO"), rs
						.getString("E_OUT_MATERIAL_NO"),
						ordInfo.getDesginKey(), ordInfo.getIndexSeq());
				dbkpline = dbkAdd[2];
				String sqldbk = CoreXmlSqlParsersFactory
						.getSql("CorePlnProcessOrd.queryBasePlineD");
				PreparedStatement ps = conn.prepareStatement(sqldbk);
				ps.setObject(1, dbkpline);
				ResultSet result = ps.executeQuery();
				if (result.next()) {
					buringRateDbk = Double.parseDouble(result.getString("BURNOUT_RATE"));
				}
				result.close();
				ps.close();
				// 轧管烧损率
				ps = conn.prepareStatement(sqldbk);
				ps.setObject(1, ordInfo.getPlineD());
				result = ps.executeQuery();
				if (result.next()) {
					buringRateZg = result.getDouble("BURNOUT_RATE");
				}
				result.close();
				ps.close();
				// 经过镦拔扩并且是镦粗的判断基础数据
				if (wholeBacklog != null && wholeBacklog != ""
						&& wholeBacklog.contains("E")) {
					if (wholeBacklogDesc.contains("镦粗")) {
						if (dbkAdd[1] == null || dbkAdd[1].equals("")) {
							dbkAdd[1] = "0";
							ordInfo.setErrCode(-1);
							ordInfo.setErrMessage("镦粗加长为空,请维护产出物料及产线能力基础数据！");
							return ordInfo;
						}
						addDc = Double.parseDouble(dbkAdd[1]);
						if (dbkAdd[3] == null || dbkAdd[3].equals("")) {
							dbkAdd[3] = "0";
						}
						if (dbkAdd[4] == null || dbkAdd[4].equals("")) {
							dbkAdd[4] = "0";
						}
						ordInfo.setLenCutendCbk(dbkAdd[3]);
						ordInfo.setLenCutheadDbk(dbkAdd[4]);
						ordInfo.setAddDbkLen(Double.parseDouble(dbkAdd[0]));
						ordInfo.setAddDcLen(addDc);
//						ordInfo.setLenScope(0);
					} else {
						if (ordInfo.getLenCutheadDbk() == null
								|| ordInfo.getLenCutheadDbk().equals("")) {
							ordInfo.setErrCode(-1);
							ordInfo.setErrMessage("镦拔扩切头为空,请维护！");
							return ordInfo;
						}
						if (ordInfo.getLenCutendCbk() == null
								|| ordInfo.getLenCutendCbk().equals("")) {
							ordInfo.setErrCode(-1);
							ordInfo.setErrMessage("镦拔扩切尾为空,请维护！");
							return ordInfo;
						}
						// addDbk = Double.parseDouble(ordInfo.getAddDbkLen());
						// addDc = Double.parseDouble(dbkAdd[1]);
						// dbkcutHead =ordInfo.getLenCutheadDbk();
						// dbkcutEnd = ordInfo.getLenCutendCbk();
						// ordInfo.setAddDbkLen(addDbk);
						if (ordInfo.getAddDcLen() == 0) {
							ordInfo.setAddDcLen(addDc);
						}
						// ordInfo.setAddDcLen(addDc);
					}
				}

			}
			rs.close();
			psta.close();
			double outAimXz = 0;// 选择外径
			double wallThXz = 0;// 选择壁厚
			if (ordInfo.getProduceSort().equals("接箍短节")) {
				outAimXz = ordInfo.getOutdiameter();
				wallThXz = ordInfo.getWallthick();
			} else {
				if (wholeBacklog != null && wholeBacklog != ""
						&& wholeBacklog.contains("E")) {
					outAimXz = outdiameterDbk;
					wallThXz = wallthickDbk;
				} else {
					outAimXz = outdiameterIn;
					wallThXz = wallthickIn;
				}

				InZgOrdCalEntity ordEntity = new InZgOrdCalEntity();
				CoreTolerOfNkParam nkParam = new CoreTolerOfNkParam();
				CoreTolerOfNk tolerOfNk = new CoreTolerOfNk();
				// 轧管内控壁厚公差
				nkParam.setBias_code("404019");
				nkParam.setOutdiameter(outAimXz);
				nkParam.setWallthick(wallThXz);
				nkParam.setSic(sic);
				nkParam.setLengthmax(ordInfo.getLengthmax());
				nkParam.setLengthmin(ordInfo.getLengthmin());
				nkParam = tolerOfNk.queryTolerance(nkParam, ordInfo
						.getDesginKey(), ordInfo.getIndexSeq(), "1");
				if (nkParam != null) {
					if (nkParam.getWallUpper() == 0
							&& nkParam.getWallLower() == 0) {
						ordEntity.setWallUpper(0);
						ordEntity.setWallLower(0);
					} else {
						ordEntity.setWallUpper(nkParam.getWallUpper());
						ordEntity.setWallLower(nkParam.getWallLower());
					}
				}
				if (ordInfo.getShrtStove() != null
						&& !ordInfo.getShrtStove().equals("")
						&& !ordInfo.getShrtStove().equals("/")) {
					ordEntity.setShrtstove(true);
				}
				// 轧管内外径公差
				nkParam.setBias_code("404012");
				nkParam.setOutdiameter(outAimXz);
				nkParam.setWallthick(wallThXz);
				nkParam.setSic(sic);
				nkParam.setLengthmax(ordInfo.getLengthmax());
				nkParam.setLengthmin(ordInfo.getLengthmin());
				nkParam = tolerOfNk.queryToleranceAim(nkParam, ordInfo
						.getDesginKey(), ordInfo.getIndexSeq(), "1");
				if (nkParam != null) {
					if (nkParam.getAimUpper() == 0
							&& nkParam.getAimLower() == 0) {
						ordEntity.setAimUpper(0);
						ordEntity.setAimLower(0);
					} else {
						ordEntity.setAimUpper(nkParam.getAimUpper());
						ordEntity.setAimLower(nkParam.getAimLower());
					}
				}
				// 计算控制壁厚外径，及控制外径壁厚管单重
				lenCalIn.setOrderUnit(ordInfo.getOrderUnit());
				lenCalIn.setWeighType(ordInfo.getWeighType());
				lenCalIn.setAimLower(ordEntity.getAimLower());
				lenCalIn.setAimUpper(ordEntity.getAimUpper());
				lenCalIn.setWallLower(ordEntity.getWallLower());
				lenCalIn.setWallUpper(ordEntity.getWallUpper());
				lenCalIn.setWallthick(wallThXz);
				lenCalIn.setOutdiameter(outAimXz);
				lenCalIn.setToleranceZone(toleranceZone);
				LenCalculateOutObject lenCalOut =new LenCalculateOutObject();
				if(wholeBacklog.contains("D")){
				lenCalOut = PlnControlOutWallTick
						.outWallTick(lenCalIn);}
				if (!lenCalOut.getisOutput()) {
					ordInfo.setErrCode(-1);
					ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
							+ lenCalOut.getReason());
					return ordInfo;
				}
				ordInfo.setAimwallthick(Double.parseDouble(lenCalOut
						.getAimwallthick()));
				ordInfo.setAimoutdiameter(lenCalOut.getAimoutdiameter());
				ordInfo.setFinisWj(lenCalOut.getMiGtWt());
			}
			double lengZgMax1 = 0;
			double lengZgMin1 = 0;
			if (wholeBacklog != null && wholeBacklog != ""
					&& wholeBacklog.contains("E")) {
				if (wholeBacklogDesc.contains("镦粗")) {
					x = 1;
				} else {
					x = ordInfo.getRatioDbk();
				}
				// （成品排产长度上限-0.5*加严率*（成品排产长度上限-成品排产长度下限）+
				// （镦拔扩切头尾+镦粗加长）/1000）*本行的变径率===》镦拔扩原料长度上限
				double lenDbkMax = lenthDbkCalMax(ordInfo.getLengthmax(),
						ordInfo.getLengthmin(), x, ordInfo.getAddDcLen(),
						ordInfo.getAddDbkLen(), ordInfo.getCheckJVal(), ordInfo
								.getLenScope());
				double lenDbkMin = lenthDbkCalMin(ordInfo.getLengthmax(),
						ordInfo.getLengthmin(), x, ordInfo.getAddDcLen(),
						ordInfo.getAddDbkLen(), ordInfo.getCheckJVal(), ordInfo
								.getLenScope());
				if (ordInfo.getTotlengthUnit().trim().equals("英尺")) {
					totlengthM = CoreUnitConvert
							.FootoMi(ordInfo.getTotlength());
				} else if (ordInfo.getTotlengthUnit().trim().equals("米")) {
					totlengthM = ordInfo.getTotlength();
				} else {
					totlengthM = 0;
				}
				if (lengthCpMax > totlengthM && totlengthM != 0) {
					cutJg = (int) (totlengthM / lengZgMax);
				} else {
					if(lengZgMax >0)
					{
						cutJg = (int) (lengthCpMax / lengZgMax);
					}else
					{
						cutJg =0;
					}

				}
				if (cutJg == 0) {
					cutJg = 1;
				}

				addlenZgRuleMax = addLenZgRuleMax(conn,ordInfo,cutJg);
				addlenZgRuleMin = addLenZgRuleMin(conn,ordInfo,cutJg);
				lengZgMax = lenDbkMax
						+ (addlenZgRuleMax + ordInfo.getAddInspect()) / 1000;
				// lenthZgCal(ordInfo.getLengthmax(), x, ordInfo
				// .getAddDcLen(), ordInfo.getAddDbkLen(), ordInfo
				// .getAddInspect(), ordInfo.getCheckJVal(),
				// addlenZgRuleMax);
				// lengZgMin = lenthZgCal(ordInfo.getLengthmin(), x, ordInfo
				// .getAddDcLen(), ordInfo.getAddDbkLen(), ordInfo
				// .getAddInspect(), ordInfo.getCheckJVal(),
				// addlenZgRuleMin);
				lengZgMin = lenDbkMin
						+ (addlenZgRuleMax + ordInfo.getAddInspect()) / 1000;
				//double totlengthM = 0;


				lengZgMax1 = lenDbkMax + ordInfo.getAddInspect() / 1000;
				lengZgMin1 = lenDbkMin + ordInfo.getAddInspect() / 1000;

				ordInfo.setCutJg(cutJg);
			} else {
				if (wallthickIn != 0 && outdiameterIn != 0) {
					// 外径壁厚 变化率
					x = 1;
					// getDhChangeRate(ordInfo.getOutdiameter(), ordInfo
					// .getWallthick(), outdiameterIn, wallthickIn,
					// buringRateZg);
				}
				lengZgMax = lenthZgCal(ordInfo.getLengthmax(), x, 0, 0, ordInfo
						.getAddInspect(), ordInfo.getCheckJVal(),
						addlenZgRuleMax);
				lengZgMin = lenthZgCal(ordInfo.getLengthmin(), x, 0, 0, ordInfo
						.getAddInspect(), ordInfo.getCheckJVal(),
						addlenZgRuleMin);
				//double totlengthM = 0;
				if (ordInfo.getTotlengthUnit().trim().equals("英尺")) {
					totlengthM = CoreUnitConvert
							.FootoMi(ordInfo.getTotlength());
				} else if (ordInfo.getTotlengthUnit().trim().equals("米")) {
					totlengthM = ordInfo.getTotlength();
				} else {
					totlengthM = 0;
				}
				if (lengthCpMax > totlengthM && totlengthM != 0) {
					cutJg = (int) (totlengthM / lengZgMax);
				} else {
					cutJg = (int) (lengthCpMax / lengZgMax);
				}
				if (cutJg == 0) {
					cutJg = 1;
				}
				ordInfo.setCutJg(cutJg);

//				// 轧管转移长度上限AA
//				lengZgMax1 = lenthZgCal(ordInfo.getLengthmax(), x, 0, 0,
//						ordInfo.getAddInspect(), ordInfo.getCheckJVal(), 0);
//				// 轧管转移长度下限AA
//				lengZgMin1 = lenthZgCal(ordInfo.getLengthmin(), x, 0, 0,
//						ordInfo.getAddInspect(), ordInfo.getCheckJVal(), 0);
				addlenZgRuleMax = addLenZgRuleMax(conn,ordInfo,cutJg);
				addlenZgRuleMin = addLenZgRuleMin(conn,ordInfo,cutJg);
				if(ordInfo.getModelDesc().equals("PE")||ordInfo.getModelDesc().equals("BE"))
				{
					lengZgMax1 = ordInfo.getLengthmax() ;
					lengZgMin1 = ordInfo.getLengthmin() ;
				}else
				{
					lengZgMax1 = lenthZgCal(ordInfo.getLengthmax(), x, 0, 0,
						ordInfo.getAddInspect(), ordInfo.getCheckJVal(), 0);
					lengZgMin1 = lenthZgCal(ordInfo.getLengthmin(), x, 0, 0, ordInfo.getAddInspect(), ordInfo.getCheckJVal(), 0);
				}

			}

//			double lengMax = lengZgMax1 * cutJg + (cutJg - 1) * 0.02 + x
//					* addlenZgRuleMax / 1000;
			double lengMax = lengZgMax1 * cutJg +addlenZgRuleMax/1000;
			//double lengMax = ordInfo.getLengthmax() +addlenZgRuleMax/1000;
			// 判断转移长度最大值与产线长度上限最大值
//			do {
//				if (lengMax > lengthCpMax) {
//					cutJg = cutJg - 1;
//					if (cutJg <= 0) {
//						cutJg = 1;
//						lengMax = lengZgMax1 * cutJg + (cutJg - 1) * 0.02 + x
//								* addlenZgRuleMax / 1000;
//						break;
//					}
//					lengMax = lengZgMax1 * cutJg + (cutJg - 1) * 0.02 + x
//							* (addlenZgRuleMax / 1000);
//				}
//			} while (lengMax > lengthCpMax);

//			double lengMin = lengZgMin1 * cutJg + (cutJg - 1) * 0.02 + x
//					* (addlenZgRuleMin / 1000);
			double lengMin = lengZgMin1 * cutJg + addlenZgRuleMin/1000;
			if (wholeBacklog != null && wholeBacklog != ""
					&& wholeBacklog.contains("D")) {
				if(lengMax<lengthCpMin)
				{
					ordInfo.setErrMessage("轧管转移长度上限超出产线范围,转移长度范围:" + lengMin
							+ "~" + lengMax + ",产线范围:" + lengthCpMin + "~"
							+ lengthCpMax + "");
					return ordInfo;
				}
				// 如果轧管转移长度上限大于产线长度上限，则取产线长度上限为轧管转移长度上限
				if (lengMax > lengthCpMax) {
					lengMax = lengthCpMax;
				}


				// 如果轧管转移长度下限小于产线长度下限，则取产线长度下限为轧管转移长度下限
				if (lengMin < lengthCpMin) {
					lengMin = lengthCpMin;
				}
				// 如果轧管转移长度下限大于产线长度上限，则轧管转移长度上下限超出产线范围，无法生产
				if (lengMin > lengthCpMax) {
					ordInfo.setErrCode(-1);
					ordInfo.setErrMessage("轧管转移长度上下限超出产线范围,转移长度范围:" + lengMin
							+ "~" + lengMax + ",产线范围:" + lengthCpMin + "~"
							+ lengthCpMax + "");
					return ordInfo;
				}
			}
			ordInfo.setAddlenZgRuleMax(addlenZgRuleMax);
			ordInfo.setAddlenZgRuleMin(addlenZgRuleMin);
			if(ordInfo.getAbc()  != null)
			{
				if(ordInfo.getAbc().equals("A"))
				{
					ordInfo.setLenMax(lengZgMax1);
					ordInfo.setLenMin(lengZgMin1);
				}else
				{
					ordInfo.setLenMax(new BigDecimal(lengMax).setScale(3,
							RoundingMode.HALF_UP).doubleValue());
					ordInfo.setLenMin(new BigDecimal(lengMin).setScale(3,
							RoundingMode.HALF_UP).doubleValue());
				}
			}else
			{
				ordInfo.setLenMax(new BigDecimal(lengMax).setScale(3,
						RoundingMode.HALF_UP).doubleValue());
				ordInfo.setLenMin(new BigDecimal(lengMin).setScale(3,
						RoundingMode.HALF_UP).doubleValue());
			}


			ordInfo.setProCut(cutJg);
			ordInfo.setBuringRateDbk(buringRateDbk);
			// ordInfo.setAddDcLen(addDc);
			// ordInfo.setAddDbkLen(addDbk);
		} catch (SQLException e) {
			ordInfo.setErrCode(-1);
			ordInfo.setErrMessage(e.getMessage());
		}
		return ordInfo;
	}

	/**
	 * 拔扩加长（mm）
	 * 
	 * @param conn
	 * @param
	 * @param desginKey
	 * @param mscPline
	 * @return
	 * @throws SQLException
	 */
	public static String[] addLenDbk(Connection conn, String eInMaterialNo,
			String eOutMaterialNo, String desginKey, String mscPline)
			throws SQLException {
		// String sql = CoreXmlSqlParsersFactory
		// .getSql("CorePlnProcessOrd.queryDesginBom");
		// PreparedStatement ps = conn.prepareStatement(sql);
		String[] dbkAdd = new String[5];
		double cutHeadEnd = 0;// 拔扩加长(mm)
		String addLenDc = "";// 镦粗加长（mm）
		String plineCode = "";
		// ps.setObject(1, bom);
		// ResultSet rs = ps.executeQuery();
		// if (rs.next()) {
		// String eInMaterialNo = "";
		// String eOutMaterialNo = "";
		// if (rs.getString("E_IN_MATERIAL_NO") != null) {
		// eInMaterialNo = rs.getString("E_IN_MATERIAL_NO");
		// }
		// if (rs.getString("E_OUT_MATERIAL_NO") != null) {
		// eOutMaterialNo = rs.getString("E_OUT_MATERIAL_NO");
		// }
		String cutHead = "";
		String cutEnd = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnProcessOrd.queryBaseMaterialEPl");
		PreparedStatement psta = conn.prepareStatement(sql);
		psta.setObject(1, eInMaterialNo);
		psta.setObject(2, eOutMaterialNo);
		psta.setObject(3, desginKey);
		psta.setObject(4, mscPline);
		ResultSet result = psta.executeQuery();
		if (result.next()) {
			if (result.getString("CROP_END") != null
					&& result.getString("CROP_HEAD") != null) {
				cutHeadEnd = result.getDouble("CROP_END")
						+ result.getDouble("CROP_HEAD");
			}
			cutEnd = result.getString("CROP_END");
			cutHead = result.getString("CROP_HEAD");
			addLenDc = result.getString("UPSETTING_LENGTH");
			plineCode = result.getString("PLINE_CODE");
		}
		result.close();
		psta.close();
		// }
		// rs.close();
		// ps.close();
		dbkAdd[0] = String.valueOf(cutHeadEnd);
		dbkAdd[1] = addLenDc;
		dbkAdd[2] = plineCode;
		dbkAdd[3] = cutEnd;
		dbkAdd[4] = cutHead;
		return dbkAdd;
	}
}