package com.steering.pss.plnsaleord.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.CoreUnitConvert;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.ordAmCal.PlnProducCal;
import com.steering.pss.plnsaleord.ordAmCal.model.InOrdParamEntity;
import com.steering.pss.plnsaleord.ordAmCal.model.OutOrdParamEntity;
import com.steering.pss.plnsaleord.order.baseMethod.*;
import com.steering.pss.plnsaleord.order.model.*;
import com.steering.pss.sale.order.CoreOrderInfoUpdate;
import com.steering.pss.sale.order.model.ReportOrderLineDelivery;
import net.sf.json.JSONObject;

import javax.script.ScriptException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 销售合同接收下发
 * 
 * @author xiaohai
 */
public class CorePlnSaleOrder extends DBCommon {


	/**
	 * 查询
	 * 
	 * @param list
	 * @param designOk
	 * @return
	 */
	public CoreReturnObject querySaleOrder(ArrayList<Object> list,
			Boolean designOk) {
		return querySaleOrder(list,designOk,"");
	}

	public CoreReturnObject querySaleOrder(ArrayList<Object> list,
										   Boolean designOk,String supp) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.querySaleOrder");
		if(!list.get(1).equals(""))
		{
			sql = sql + " T.ACCEPT_NO LIKE '%' || '"+list.get(1)+"' || '%'";
		}else
		{
			list.remove(1);
		}
		if (designOk) {
			sql = sql + " AND T2.DESIGN_STS = '通过'";
		}
		/*if (!StringUtils.isEmpty(supp)) {
			sql += " and T.SUPPLY_UNIT_CODE = '"+ supp.split("-")[0] +"'";
		}*/
		if (!StringUtils.isEmpty(supp) && supp.contains("XS")) {
			sql += " and T.ORDERFROM != '备料需求' ";
		}
		if (!StringUtils.isEmpty(supp) && "120501".equals(supp)) {
			sql += " and (T.CONFIRM_XS = '2' OR T.ORDERFROM = '备料需求')";
		}
		cro = this.getData(sql, list.toArray());
		return cro;
	}

	public CoreReturnObject querySaleOrder1(ArrayList<Object> list,
										   Boolean designOk,String supp) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.querySaleOrder1");
		if(!list.get(1).equals(""))
		{
			sql = sql + " T.ACCEPT_NO LIKE '%' || '"+list.get(1)+"' || '%'";
		}else
		{
			list.remove(1);
		}
		list.remove(1);
		list.remove(2);
		list.remove(2);
		list.remove(2);
		list.remove(2);
		list.remove(2);
		list.remove(2);
		if (designOk) {
			sql = sql + " AND T2.DESIGN_STS = '通过'";
		}
		if (!StringUtils.isEmpty(supp)) {
			sql += " and T.SUPPLY_UNIT_CODE = '"+ supp.split("-")[0] +"'";
		}
		if (!StringUtils.isEmpty(supp) && supp.contains("XS")) {
			sql += " and T.ORDERFROM != '备料需求' ";
		}
		if (!StringUtils.isEmpty(supp) && "120501".equals(supp)) {
			sql += " and (T.CONFIRM_XS = '2' OR T.ORDERFROM = '备料需求')";
		}
		cro = this.getData(sql, list.toArray());
		return cro;
	}

		public CoreReturnObject updateConfirmXs(ArrayList<ArrayList<String>> list) {
			return updateConfirmXs(list,null);
		}

		public CoreReturnObject updateConfirmXs(ArrayList<ArrayList<String>> list,ArrayList<Object> parm) {
		CoreReturnObject cro = new CoreReturnObject();
		ArrayList<String> sqllist = new ArrayList<String>();
		ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
		for (int i = 0; i < list.size(); i++) {
			//修改销售确认状态
			sqllist.add("CorePlnSaleOrder.updateConfirmXs");
			parmlist.add(list.get(i).toArray());

			if(parm != null && parm.size() >0){
				// 将量写入进程表
				String jsonStr = parm.get(i).toString();
				JSONObject json = JSONObject.fromObject(jsonStr);
				ReportOrderLineDelivery reportModel = (ReportOrderLineDelivery) JSONObject
						.toBean(json, ReportOrderLineDelivery.class);
				sqllist.add("CoreOrderReport.UpdateProcessOrderApp");
				parmlist.add(new Object[]{reportModel.getOrderQty(),reportModel.getOrderUnit(),reportModel.getOrdLnDlyPk()});
			}
		}
		cro = this.setDataById(sqllist, parmlist);
		return cro;
	}

	/**
	 * 查询交货行工艺
	 * 
	 * @param ordLnPk
	 * @return
	 */
	public CoreReturnObject queryOrdCraftOrdDesign(String ordLnPk) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryOrdCraftOrdDesign");
		sql += " ORDER BY T.CRAFT_SEQ DESC";
		cro = this.getData(sql, new Object[] { ordLnPk });
		return cro;
	}

	/**
	 * 查询合同行部门科室
	 * 
	 * @param ordLnPk
	 * @return
	 */
	public CoreReturnObject queryOrdLineDepartUnit(String ordLnPk) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryOrdLineDepartUnit");
		cro = this.getData(sql, new Object[] { ordLnPk });
		return cro;
	}

	/**
	 * 通过合同号有无重复
	 * 
	 * @param list
	 *            合同号、行号、交货码
	 * @return object
	 */
	public CoreReturnObject querySaleByPrimary(ArrayList<String> list) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnSaleOrder.querySaleByPrimary",
				list.toArray());
		return cro;
	}

	/**
	 * 查询基础维护数据
	 * 
	 * @return
	 */
	public CoreReturnObject queryBaseinfoAll() {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryBaseinfoAll");
		return cro;
	}

	/**
	 * 查询销售合同状态
	 * 
	 * @param str
	 * @return object
	 */
	public CoreReturnObject querySaleStatus(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.querySaleStatus",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询品名基础表
	 * 
	 * @param str
	 *            品名代码
	 */
	public CoreReturnObject queryProducType(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryProducType",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询计重方式
	 * 
	 * @param str
	 *            附加要求编码
	 */
	public CoreReturnObject queryWeighType(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryWeighType",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询交货到站
	 * 
	 * @param str
	 */
	public CoreReturnObject queryTransit(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryTransit",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询交货运输方案
	 * 
	 * @param str
	 * @return
	 */
	public CoreReturnObject queryTranType(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryTranType",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询质量设计制程
	 * 
	 * @param str
	 */
	public CoreReturnObject queryDesginPl(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryDesginPl",
				new Object[] { str, str });
		return cro;
	}

	/**
	 * 销售合同查询制程工序
	 * 
	 * @param list
	 * @return object
	 */
	public CoreReturnObject queryMscplPrc(ArrayList<String> list) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryMscplPrc",
				list.toArray());
		return cro;
	}

	/**
	 * 查询是否Assel
	 * 
	 * @param ordLnPk
	 * @return
	 */
	public CoreReturnObject queryAsselFl(String ordLnPk) {
		return this.getDataBySqlID("CorePlnSaleOrder.queryAsselFl",
				new Object[] { ordLnPk });
	}

	/**
	 * 查询监制基础表
	 * 
	 * @param list
	 *            监制编号,主制程号
	 * @return
	 */
	public CoreReturnObject queryLinePrdcr(ArrayList<Object> list) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryLinePrdcr",
				list.toArray());
		return cro;
	}

	/**
	 * 根据DESGIN_KEY查询接箍码
	 * 
	 * @param str
	 *            查询参数
	 * @return object
	 */
	public CoreReturnObject queryJgCode(String str) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryJgCode",
				new Object[] { str });
		return cro;
	}

	/**
	 * 根据接箍码查询接箍基础信息
	 * 
	 * @param str
	 *            查询参数
	 * @return object
	 */
	public CoreReturnObject queryJgBase(String str) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryJgBase",
				new Object[] { str });
		return cro;
	}

	/**
	 * 根据DESGIN_KEY查询短节备料码
	 * 
	 * @param str
	 *            查询参数
	 * @return object
	 */
	public CoreReturnObject queryBlCode(String str) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryBlCode",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询附加要求信息
	 * 
	 * @param str
	 *            附加要求码
	 * @return
	 */
	public CoreReturnObject queryAddAsk(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryAddAsk",
				new Object[] { str });
		return cro;
	}

	/**
	 * 合同接收
	 * 
	 * @param list
	 * @param listPro
	 * @return
	 */
	public CoreReturnObject updatePretreat(ArrayList<PlnSaleordEntity> list,
			ArrayList<PlnSaleordProcEntity> listPro) {
		CoreReturnObject cro = new CoreReturnObject();

		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.updateSaleOrder");
		String sqlPrc = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.addSaleOrderPrc");

		Connection conn = null;
		PreparedStatement ps = null;
		try {
			String sqlAcp = CoreXmlSqlParsersFactory
					.getSql("CorePlnSaleOrder.getAcceptNum");
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ps = conn.prepareStatement(sqlAcp);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				if (rs.getString("ACCEPTNO") != null) {
					String acceptNo = rs.getString("ACCEPTNO");
					for (int i = 0; i < list.size(); i++) {
						PreparedStatement pst = null;
						String sqlAdd = "";
						String sqlUp = "";
						String region = getOrdRegion(conn, list.get(i)
								.getOrdLnDlyPk());

						list.get(i).setAcceptNo(acceptNo);
						sqlUp = EntityTool.fillSqlByEntity(sql, list.get(i));
						pst = conn.prepareStatement(sqlUp);
						pst.executeUpdate();
						pst.close();

						listPro.get(i).setIfExport(region);
						sqlAdd = EntityTool.fillSqlByEntity(sqlPrc,
								listPro.get(i));
						pst = conn.prepareStatement(sqlAdd);
						pst.executeUpdate();
						pst.close();
					}
				}
			}
			rs.close();
			ps.close();

			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 合同回退
	 * 
	 * @param list
	 * @param
	 * @return
	 */
	public CoreReturnObject cancelAcp(ArrayList<ArrayList<String>> listLog,
			ArrayList<ArrayList<String>> list) {
		CoreReturnObject cro = new CoreReturnObject();
		ArrayList<String> sqllist = new ArrayList<String>();
		ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
		for (int i = 0; i < list.size(); i++) {
			sqllist.add("CorePlnSaleOrder.addCancelAcpLog");
			parmlist.add(listLog.get(i).toArray());

			// 更新销售合同各工序状态
			sqllist.add("CorePlnSaleOrder.updateCancelAcp");
			parmlist.add(list.get(i).toArray());
			// 删除拆分记录
			sqllist.add("CorePlnSaleOrder.deleteCancelAcp");
			parmlist.add(list.get(i).toArray());
		}
		cro = this.setDataById(sqllist, parmlist);
		return cro;
	}

	/**
	 * 查询投料原则，投料率
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public CoreReturnObject queryPutRate(String year, String month) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnSaleOrder.queryPutRate",
				new Object[] { year, month });
		return cro;
	}

	/**
	 * 清楚回退标识
	 * 
	 * @param ordLnDlyPk
	 * @return
	 */
	public CoreReturnObject clearOrdBackI(String ordLnDlyPk) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = null;
			String sql = "UPDATE PLN_SALEORD T SET T.IS_BACKORD = '0' WHERE T.ORD_LN_DLY_PK = ?";
			ps = conn.prepareStatement(sql);
			ps.setObject(1, ordLnDlyPk);
			ps.executeUpdate();
			ps.close();

			conn.commit();
			cro.setResult("操作成功！");
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (Exception sqle) {
			if (conn != null) {
				try {
					conn.rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 区分国内外港澳台
	 * 
	 * @param conn
	 * @param ordLnDlyPk
	 * @return
	 * @throws SQLException
	 */
	public static String getOrdRegion(Connection conn, String ordLnDlyPk)
			throws SQLException {
		String regionAre = "/";// 国内外港澳台
		String finalUser = "";// 客户编号
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.selectOrdFinaLuser");
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setObject(1, ordLnDlyPk);
		ResultSet rs = ps.executeQuery();
		if (!rs.next()) {
			return regionAre;
		}

		if (rs.getString("FINAL_USER") != null
				&& rs.getString("FINAL_USER").length() > 1) {
			finalUser = rs.getString("FINAL_USER");
		} else if (rs.getString("BUYER_ID") != null
				&& rs.getString("BUYER_ID").length() > 1) {
			finalUser = rs.getString("BUYER_ID");
		} else {
			return regionAre;
		}
		rs.close();
		ps.close();

		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.selectCustomerRegion");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, finalUser);
		rs = ps.executeQuery();
		if (!rs.next()) {
			return regionAre;
		}

		if (rs.getString("REGION_NO") != null
				&& rs.getString("REGION_NO").trim().length() > 0) {
			String regionNo = "";// 地区编号
			regionNo = rs.getString("REGION_NO");
			if (regionNo.length() > 2) {
				String strCountryCode = regionNo.substring(0, 3);
				if (strCountryCode.equals("101")) {
					if (regionNo.length() > 4) {
						String strProvinceCode = regionNo.substring(0, 5);
						if (strProvinceCode.equals("10156")) {
							regionAre = "香港";
						} else if (strProvinceCode.equals("10157")) {
							regionAre = "台湾";
						} else if (strProvinceCode.equals("10158")) {
							regionAre = "澳门";
						} else {
							regionAre = "国内";
						}
					} else {
						regionAre = "国内";
					}
				} else {
					regionAre = "国外";
				}
			}
		} else {
			return regionAre;
		}
		rs.close();
		ps.close();

		return regionAre;
	}

	/**
	 * 获取记重方式
	 * 
	 * @param conn
	 * @param addAskNo
	 * @return
	 * @throws SQLException
	 */
	public static String getWeighType(Connection conn, String addAskNo)
			throws SQLException {
		String weighType = "";
		PreparedStatement ps = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryWeighType");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, addAskNo);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getString("ASK_SUB_ITME_VAL_DESC") != null) {
				weighType = rs.getString("ASK_SUB_ITME_VAL_DESC");
			}
		}
		rs.close();
		ps.close();
		return weighType;
	}

	/**
	 * 获取到站信息
	 * 
	 * @param conn
	 * @param ordLnDlyPk
	 * @return
	 * @throws SQLException
	 */
	public static String[] getTransit(Connection conn, String ordLnDlyPk)
			throws SQLException {
		String[] transit = new String[2];
		String stationNo = "";
		String stationName = "";
		PreparedStatement ps = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryTransit");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, ordLnDlyPk);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getString("STATION_NO") != null) {
				stationNo = rs.getString("STATION_NO");
			}
			if (rs.getString("STATION_NM") != null) {
				stationName = rs.getString("STATION_NM");
			}
		}
		transit[0] = stationNo;
		transit[1] = stationName;
		rs.close();
		ps.close();
		return transit;
	}

	/**
	 * 获取运输方式
	 * 
	 * @param conn
	 * @param ordLnDlyPk
	 * @return
	 * @throws SQLException
	 */
	public static String getTranType(Connection conn, String ordLnDlyPk)
			throws SQLException {
		String tranType = "";
		PreparedStatement ps = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryTranType");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, ordLnDlyPk);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getString("TRANSIT_TYP") != null) {
				tranType = rs.getString("TRANSIT_TYP");
			}
		}
		rs.close();
		ps.close();
		return tranType;
	}

	/**
	 * 接收
	 * 
	 * @param list
	 * @param AccpetName
	 * @return
	 */
	public CoreReturnObject doReceive(ArrayList<String> list, String AccpetName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection con = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			List<String> messageErr = new ArrayList<String>();
			CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
			/**
			 * 1. 接收批次号
			 */
			String acceptNo = PlnHelper.getParam(con,
					"CorePlnSaleOrder.getAcceptNum", null, "ACCEPTNO");
			if (acceptNo.equals("")) {
				cro.setResult("接收批次号生成出错！");
				return cro;
			}
			/**
			 * 2.接收验证
			 */
			for (String ordLnDlyPk : list) {
				// [start] 验证合同
				String desginKey = "";// 工艺设计主键
				String producType = "";// 品名类型
				PlnSaleordProcEntity ordProcEntity = new PlnSaleordProcEntity();

				// 2.1查询接收表信息
				PlnSaleordEntity ordEntity = PlnHelper.getEntityData(con,
						new String[] { ordLnDlyPk },
						"CorePlnSaleOrder.getPlnSaleordByPk",
						PlnSaleordEntity.class);
				if (ordEntity == null) {
					messageErr.add("没有接收合同信息!");
					continue;
				}
				ordEntity.getOutsStlPipeFl();
				
				//校验接收合同是否已确认，ORD_LN_PK的值在SLM_ORDER_LINE表中的IF_CONFIRMED是否为1
				String querySql ="SELECT COUNT(1) AS C FROM SLM_ORDER_LINE WHERE ORD_LN_PK=? AND IS_CONFIRMED=1";
				PreparedStatement ps = con.prepareStatement(querySql);
				ps.setObject(1, ordEntity.getOrdLnPk());
				ResultSet rs = ps.executeQuery();
				int count =0;
				while(rs.next()){
					count =rs.getInt("C");
				}
				rs.close();
				ps.close();
				//切换之后打开
				/*if(count==0){
					throw new RuntimeException("合同号【"+ordEntity.getOrderNo()+"】对应的合同行信息未确认，请联系工艺人员在[销售管理-合同管理-合同质量结果管理]界面进行质量信息确认!");
				}*/
				
				// 2.2验证核对是否多条
				ordEntity.setAcceptNo(acceptNo);
				if (!isNotRepeatOrd(con, ordEntity.getOrderNo(),
						ordEntity.getOrderSeq(), ordEntity.getDeliveryNo())) {
					messageErr.add("交货行：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "/"
							+ ordEntity.getDeliveryNo() + "存在多条，请联系合同提报人！");
					continue;
				}
				if (!ordEntity.getPorderstatus().equals("0")) {
					messageErr.add("交货行：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "/"
							+ ordEntity.getDeliveryNo() + "已经接收过了！");
					continue;
				}
				// 2.3查找工艺
				String[] craftInfo = PlnHelper.getArray(con,
						"CorePlnSaleOrder.queryOrdCraftOrdDesign",
						" AND T.VALIDFLAG = '1'",
						new String[] { ordEntity.getOrdLnPk() }, new String[] {
								"CRAFT_SEQ", "DESGIN_KEY", "CRAFT_NAME",
								"CRAFT_NO", "CRAFT_NO_V" });
				if (craftInfo == null || craftInfo.length == 0) {
					messageErr.add("合同行：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "未找到有效的工艺评审！");
					continue;
				}

				ordProcEntity.setCraftSeq(craftInfo[0]);
				desginKey = craftInfo[1];
				ordProcEntity.setCraftFileMan(craftInfo[2]);
				ordProcEntity.setCraftFileNo(craftInfo[3]);
				ordProcEntity.setCraftNoV(craftInfo[4]);
				// 判断单倍尺长是否有成品使用公差
				if (!ordEntity.getSiglLen().trim().equals("")) {
					if (ordEntity.getEndlenSpecstd().trim().equals("")) {
						messageErr
								.add("合同行：" + ordEntity.getOrderNo() + "/"
										+ ordEntity.getOrderSeq()
										+ "是单倍尺长,成品长度公差不能为空！");
						continue;
					}
				}
				// 2.4长度转换
				getLenUnitConvert(ordEntity);

				// 2.5 查询销售分类和品名类型
				String[] producStyle = PlnHelper.getArray(con,
						"CorePlnSaleOrder.queryProducType",
						new String[] { ordEntity.getProduccode() },
						new String[] { "PRODUC_STYLE", "PRODUC_TYPE" });
				if (producStyle != null && producStyle.length > 0) {
					ordEntity.setPrdCls(producStyle[0]);
					producType = producStyle[1];
				}
				if (producType.equals("D")
						&& !(ordEntity.getOrderUnit().trim().equals("个") || ordEntity
								.getOrderUnit().trim().equals("支"))) {
					messageErr.add("成品接箍合同：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "/"
							+ ordEntity.getDeliveryNo() + "交货单位不是“支”，请检查合同！");
					continue;
				}
				// 2.6计重方式
				ordEntity.setWeighType(getWeighType(con,
						ordEntity.getAddAskNo()));
				String[] transit = getTransit(con, ordEntity.getOrdLnDlyPk());
				if (transit != null) {
					ordEntity.setStationNo(transit[0]);
					ordEntity.setStationNm(transit[1]);
				}
				ordEntity.setTransitTyp(getTranType(con,
						ordEntity.getOrdLnDlyPk()));

				// 2.7查询工艺评审制程
				List<CraftOrdDesignMscPlEntityO> mscPlList = PlnHelper
						.getEntityDatas(con, new String[] { desginKey,
								desginKey }, "CorePlnSaleOrder.queryDesginPl",
								CraftOrdDesignMscPlEntityO.class);
				if (mscPlList == null || mscPlList.size() == 0) {
					messageErr.add("合同行：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "未找到制程，请查看工艺评审。");
					continue;
				}
				boolean flag = false;
				String[] message = new String[1];
				for (CraftOrdDesignMscPlEntityO mscPlEntity : mscPlList) {
					String wholeDesc = mscPlEntity.getWholeBacklogDesc();
					String endGxName = wholeDesc.substring(wholeDesc
							.lastIndexOf('-') + 1);
					ordEntity.setEndgxname(endGxName);
					ordProcEntity.setIndexSeq(mscPlEntity.getMscPline());
					ordProcEntity.setProcessSeq(mscPlEntity.getWholeBacklog());
					ordProcEntity.setGradecodeAll(mscPlEntity.getGradename());
					// 查询二级工序
					List<CraftOrdDesignMscPlPrcEntity> mscPrcList = PlnHelper
							.getEntityDatas(con, new String[] { desginKey,
									ordProcEntity.getIndexSeq() },
									"CorePlnSaleOrder.queryMscplPrc",
									CraftOrdDesignMscPlPrcEntity.class);
					if (mscPrcList == null) {
						continue;
					}
					// 根据制程查询全程途经工序
					ordProcEntity.setGroupJgx("/");
					ordProcEntity.setGroupRcl("/");
					ordProcEntity.setBjType("/");
					String wholeBacklog = ordProcEntity.getProcessSeq();
					String endgxCode = wholeBacklog.substring(wholeBacklog
							.length() - 1);
					String gprocessC = ""; // 加工二级工序
					String fprocessC = ""; // 热处理二级工序
					for (CraftOrdDesignMscPlPrcEntity prcEntity : mscPrcList) {
						if (prcEntity.getProcessCode().trim().equals("H")) {
							ordProcEntity.setGroupJgx("200401");
						} else if (prcEntity.getProcessCode().trim()
								.equals("G")) {
							gprocessC = prcEntity.getProcessCodeC();
						} else if (prcEntity.getProcessCode().trim()
								.equals("F")) {
							fprocessC = prcEntity.getProcessCodeC();
							ordProcEntity.setProcDescCRcl(prcEntity
									.getProcessDescC());
						} else if (prcEntity.getProcessCode().trim()
								.equals("E")) {
							ordProcEntity
									.setBjType(prcEntity.getProcessDescC());
						}
					}
					// 轧管去向
					String abc = CoreOrdBase.getAbc(
							mscPlEntity.getWholeBacklog(),
							mscPlEntity.getWholeBacklogDesc());
					ordProcEntity.setAbc(abc);
					ordEntity.setProduceSort(CoreOrdBase.produceSort(endgxCode,
							ordEntity.getPrdCls(), gprocessC, fprocessC));
					int mergeType = getMergeType(con, desginKey,
							ordProcEntity.getProcessSeq());// 组合类型
					ordEntity.setMergetype(String.valueOf(mergeType));
					ordEntity.setPipeProperty(CoreOrdBase
							.pipeProperty(ordEntity.getMaterialNo()));
					ordEntity.setBlGroupNum(desginKey);
					ordEntity.setSpecstandard(desginKey);
					ordEntity.setUpdateName(AccpetName);
					ordProcEntity.setOrdLnDlyPk(ordEntity.getOrdLnDlyPk());
					ordProcEntity.setPlnDivideId("01");
					// 如果短尺率大于0，则短尺随炉，否则不短尺随炉。
					if (!ordEntity.getShrtLenRato().trim().equals("")
							&& Double.parseDouble(ordEntity.getShrtLenRato()) > 0) {
						ordEntity.setShrtStove("短尺随炉");
					}
					// 查询监制要求
					String[] prdcrArr = PlnHelper.getArray(con,
							"CorePlnSaleOrder.queryLinePrdcr",
							new String[] { ordEntity.getPrdcrNo(),
									ordProcEntity.getIndexSeq() },
							new String[] { "MONITORDEMAND", "PRDCR_DESC" });
					if (prdcrArr != null) {
						ordEntity.setMonitordemand(prdcrArr[1]);
					}
					if (ordEntity.getPrdcrNo() != null
							&& !ordEntity.getPrdcrNo().equals("")) {
						if(ordEntity.getMonitordemand() ==null)
						{
							message[0] = "合同：" + ordEntity.getOrderNo() + "/"
									+ ordEntity.getOrderSeq() + "/"
									+ ordEntity.getDeliveryNo()
									+ "有监制编号,未找到监制要求。";
							continue;
						}else
						{
							if (ordEntity.getMonitordemand().equals("")) {
								message[0] = "合同：" + ordEntity.getOrderNo() + "/"
										+ ordEntity.getOrderSeq() + "/"
										+ ordEntity.getDeliveryNo()
										+ "有监制编号,未找到监制要求。";
								continue;
							}
						}

					}
					ordProcEntity.setPrdcrpro(CoreOrdLinePrdcrLst
							.getOrdPrdcrpro(con, ordEntity.getPrdcrNo(),
									ordProcEntity.getIndexSeq()));
					// 查询接箍码
					String[] jgCodeArr = PlnHelper.getArray(con,
							"CorePlnSaleOrder.queryJgCode",
							new String[] { desginKey }, new String[] {
									"CODE_JG", "LENGTH_JG", "WEIGHT_JG",
									"CHECK_J_VAL" });
					if (jgCodeArr != null) {
						ordEntity.setCodeJg(jgCodeArr[0]);
						ordEntity.setLengthJg(jgCodeArr[1]);
						ordEntity.setWeightJg(Double.parseDouble(jgCodeArr[2]));
						ordEntity
								.setCheckJVal(Double.parseDouble(jgCodeArr[3]));
					}
					String outsBilletFl = "0";

					if (ordEntity.getOutsStlPipeFl().equals("")
							|| ordEntity.getOutsStlPipeFl().equals("121901")) {
						if (ordEntity.getOutsBilletFl().equals("121801")) {
							outsBilletFl = "1";
						}else{
							outsBilletFl = "0";
						}
					}else{
						if (ordEntity.getOutsBilletFl().equals("121802")) {
							outsBilletFl = "0";
						}else{
							outsBilletFl = "1";
						}
					}
					// 查询BOM信息
					List<SlmOrdDesignBomEntity> bomList = PlnHelper
							.getEntityDatas(
									con,
									new String[] { desginKey,
											ordEntity.getMsc(),
											ordProcEntity.getIndexSeq()},
									"CoreOrdDesginBom.getOrdLineMscBom",
									SlmOrdDesignBomEntity.class);
					// if (outsBilletFl.equals("1")) {
					if (bomList == null || bomList.size() == 0) {
						message[0] = "合同：" + ordEntity.getOrderNo() + "/"
								+ ordEntity.getOrderSeq() + "/"
								+ ordEntity.getDeliveryNo() + "未找到BOM物料信息。";
						continue;
					}
					// }
					// else {
					// if (bomList == null || bomList.size() == 0) {
					// message[0] = "合同：" + ordEntity.getOrderNo() + "/"
					// + ordEntity.getOrderSeq() + "/"
					// + ordEntity.getDeliveryNo() + "未找到自炼物料信息。";
					// continue;
					// }
					// }
					// 获取钢种索引码
					String groupcic = "";
					String sqlcic = CoreXmlSqlParsersFactory
							.getSql("CorePlnSaleOrder.getSelectCicGroup");
					PreparedStatement pst = con.prepareStatement(sqlcic);
					pst.setObject(1, desginKey);
					//pst.setObject(2, ordProcEntity.getIndexSeq());
					ResultSet rst = pst.executeQuery();
//					if (rst.next()) {
//						groupcic = rst.getString("CIC");
//					}
					while(rst.next())
					{
						groupcic = groupcic+","+rst.getString("CIC");
					}
					rst.close();
					pst.close();
					//groupcic = groupcic.substring(0,groupcic.length()-1);
					String[] groupCic1 = null;
					if (mscPlEntity.getWholeBacklog().contains("A")) {
						if (groupcic == null || groupcic.equals("")) {
							message[0] = "合同：" + ordEntity.getOrderNo() + "/"
									+ ordEntity.getOrderSeq() + "/"
									+ ordEntity.getDeliveryNo() + "未找到钢种索引码。";
							continue;
						}
						groupCic1 = groupcic.split(",");
						// 去除数组中的空格
						List<String> tmp = new ArrayList<String>();
						for (String str : groupCic1) {
							if (str != null && str.length() != 0) {
								tmp.add(str.trim());
							}
						}
						groupCic1 = tmp.toArray(new String[0]);
					}




					for (SlmOrdDesignBomEntity bomEntity : bomList) {

						if(bomList.size()>1 && abc.equals("A")) {
							if (ordEntity.getSupplyUnitCode().equals("120501") || ordEntity.getSupplyUnitCode().equals("")) {
								if (bomEntity.getdPlineCode().equals("C072")) {
									continue;
								}

							} else if (ordEntity.getSupplyUnitCode().equals("120504")) {
								if (!bomEntity.getdPlineCode().equals("C072")) {
									continue;
								}
							}
						}
						int countS = 0;
						// 查询是否自炼，外购钢种
						String sqlGrade = "SELECT COUNT(*) COUNT FROM COM_BASE_GRADE T WHERE T.GRADECODE=? AND T.ALLOW_BUY=? AND T.VALIDFLAG='1'";
						pst = con.prepareStatement(sqlGrade);
						pst.setObject(1, bomEntity.getGradecode());
						pst.setObject(2, outsBilletFl);
						rst = pst.executeQuery();
						if (rst.next()) {
							countS = 1;
						}
						rst.close();
						pst.close();
						if (countS == 0) {
							if (outsBilletFl.equals("0")) {
								message[0] = "合同：" + ordEntity.getOrderNo()
										+ "/" + ordEntity.getOrderSeq() + "/"
										+ ordEntity.getDeliveryNo()
										+ "未找到自炼钢种。";
							} else {
								message[0] = "合同：" + ordEntity.getOrderNo()
										+ "/" + ordEntity.getOrderSeq() + "/"
										+ ordEntity.getDeliveryNo()
										+ "未找到外购钢种。";
							}
							continue;
						}
						int coun = 0;
						String sqlc = CoreXmlSqlParsersFactory
								.getSql("FrmBomConfirm.getQueryGrade");
						sqlc += " AND INSTR(T.GRADECODE,'"
								+ bomEntity.getGradecode() + "') > 0";
						sqlc += CoreConverter.toSqlConditionString("T.CIC",
								groupCic1);
						sqlc += " AND T1.PURCHASE_STD='" + outsBilletFl + "' ";
						pst = con.prepareStatement(sqlc);
						rst = pst.executeQuery();
						if (rst.next()) {
							coun = 1;
						}
						rst.close();
						pst.close();
						if (ordEntity.getOutsStlPipeFl().equals("")
								|| ordEntity.getOutsStlPipeFl()
										.equals("121901")) {
							if (coun == 0) {
								if (outsBilletFl.equals("0")) {
									message[0] = "合同：" + ordEntity.getOrderNo()
											+ "/" + ordEntity.getOrderSeq()
											+ "/" + ordEntity.getDeliveryNo()
											+ "未找到自炼钢种索引码。";
								} else {
									message[0] = "合同：" + ordEntity.getOrderNo()
											+ "/" + ordEntity.getOrderSeq()
											+ "/" + ordEntity.getDeliveryNo()
											+ "未找到外购钢种索引码。";
								}
								continue;
							}
						}
						String dinMaterial = "";
						String dPline = "";
						if (ordProcEntity.getProcessSeq().contains("D")) {
							dPline = getOrdPline(con,
									bomEntity.getDInMaterialNo(),
									bomEntity.getDOutMaterialNo(), desginKey,
									ordProcEntity.getIndexSeq(),
									ordEntity.getFinalUser(),
									ordEntity.getProduccode(),
									ordEntity.getOrdLnPk());
							if (dPline.equals("")) {
								message[0] = "未找到轧管产线!";
								continue;
							}
							ordProcEntity.setGroupRoll(dPline);
						}
						ordProcEntity.setBom(bomEntity.getBom());
						ordEntity.setMaterialNo(bomEntity.getMaterialNo());
						ordEntity.setMaterialDesc(bomEntity.getMaterialDesc());
						ordProcEntity.setMaterialNo(bomEntity.getMaterialNo());
						ordProcEntity.setMaterialDesc(bomEntity
								.getMaterialDesc());

						ordProcEntity.setGroupRollAll(bomEntity.getdPline());
						ordProcEntity.setGradecode(bomEntity.getGradecode());
						ordProcEntity.setEInMaterialDesc(bomEntity
								.getEInMaterialDesc());
						ordProcEntity.setEInMaterialNo(bomEntity
								.getEInMaterialNo());
						ordProcEntity.setDimaterYlg(bomEntity.getDimater());
						ordProcEntity.setHeightYlg(bomEntity.getHeight());
						ordProcEntity.setGroupJgx(CoreDefGourp.getJgxDefGroup(
								con, desginKey, ordProcEntity.getIndexSeq(),
								bomEntity.getBom()));
						ordProcEntity.setGroupRcl(CoreDefGourp.getRclDefGroup(
								con, desginKey, ordProcEntity.getIndexSeq(),
								bomEntity.getBom(),ordEntity.getSupplyUnitCode()));
						// /轧管投入物料(炼钢末工序产出物料)
						dinMaterial = bomEntity.getDInMaterialNo();
						ordProcEntity.setStuffProperty(CoreOrdBase
								.stuffProperty(dinMaterial));

						// 合同量计算
						if (!getOrdProcAmount(con, desginKey, ordEntity,
								ordProcEntity, message)) {
							continue;
						} else {
							flag = true;
							break;
						}
					}
					// 结束验证制程
					if (flag) {
						break;
					}
				}
				// 验证制程
				if (!flag) {
					messageErr.add("合同：" + ordEntity.getOrderNo() + "/"
							+ ordEntity.getOrderSeq() + "/"
							+ ordEntity.getDeliveryNo() + message[0]);
					continue;
				}
				// 判断有没有接箍、短节
				if (ordEntity.getMergetype().trim().equals("1")
						|| ordEntity.getMergetype().trim().equals("2")) {
					ordEntity.setJgordIsOk("0"); // 接箍合同是否形成
					ordEntity.setJglReqIsOk("0"); // 接箍料需求是否制订
				} else {
					ordEntity.setJgordIsOk("2"); // 无接箍
					ordEntity.setJglReqIsOk("2");// 无接箍
				}
				// 有无短节
				if (ordEntity.getMergetype().trim().equals("0")) {
					String[] blCodeArr = PlnHelper.getArray(con,
							"CorePlnSaleOrder.queryBlCode",
							new String[] { desginKey },
							new String[] { "PSC_BL" });
					if (blCodeArr != null) {
						ordEntity.setDjblReqIsOk("0");// 短节备料是否形成
					} else {
						ordEntity.setDjblReqIsOk("2");// 无短节备料
					}

				} else if (ordEntity.getMergetype().trim().equals("2")) {
					ordEntity.setDjblReqIsOk("0"); // 短节备料是否形成
				} else {
					ordEntity.setDjblReqIsOk("2"); // 无短节备料
				}

				if (ordProcEntity.getProcessSeq().contains("F")) {
					// 判断是否经过热处理工序
					ordProcEntity.setFIsOk("0");
				} else {
					ordProcEntity.setFIsOk("2");
				}

				if (ordProcEntity.getProcessSeq().contains("G")) {
					// 判断是否经过管加工工序
					ordProcEntity.setGIsOk("0");
				} else {
					ordProcEntity.setGIsOk("2");
				}

				if (ordProcEntity.getProcessSeq().contains("D")) {
					// 判断是否经过轧管工序
					ordProcEntity.setDIsOk("0");
				} else {
					ordProcEntity.setDIsOk("2");
				}
				if (ordProcEntity.getProcessSeq().contains("E")) {
					// 判断是否经过镦拔扩工序
					ordProcEntity.setEIsOk("0");
				} else {
					ordProcEntity.setEIsOk("2");
				}
				ordProcEntity.setOutMultD(ordEntity.getOutMultD());
				String region = getOrdRegion(con, ordEntity.getOrdLnDlyPk());
				ordProcEntity.setIfExport(region);
				PlnHelper.deleteOrUpdateByEntity(con,
						"CorePlnSaleOrder.updateSaleOrder", ordEntity);
				PlnHelper.addEntityData(con,
						"CorePlnSaleOrder.addSaleOrderPrc", ordProcEntity);
				
				cou.doCrmEvent(con,"","",ordLnDlyPk,"1");
			}
			con.commit();
			if (messageErr.size() > 0) {
				cro.setResult((list.size() - messageErr.size()) + "条接收成功，"
						+ messageErr.size() + "条接收失败。\n" + messageErr.get(0));
			} else {
				cro.setResult(list.size() + "条操作成功，0条操作失败。");
			}
		} catch (Exception sqle) {
			if (con != null) {
				try {
					con.rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 计算合同量
	 * 
	 * @param conn
	 * @param desginKey
	 * @param ordEntity
	 * @param ordProcEntity
	 * @param reason
	 * @return
	 * @throws SQLException
	 * @throws ScriptException
	 */

	public static boolean getOrdProcAmount(Connection conn, String desginKey,
			PlnSaleordEntity ordEntity, PlnSaleordProcEntity ordProcEntity,
			String[] reason) throws SQLException, ScriptException {
		double wallthick = Double.parseDouble(ordEntity.getWallthick());
		double outdiameter = Double.parseDouble(ordEntity.getOutdiameter());
		double orderQty = Double.parseDouble(ordEntity.getOrderQty());
		if (ordEntity.getMergetype().equals("3")) {
			/*********** 管坯 **************/
			double orderWeight = 0; // 合同量
			double aimlength = 0; // 目标长度
			int planNum = 0;// 合同支数
			double weightMI = CoreOrdBase.GpweightOfmi(outdiameter);// 米单重

			double rate = 0;
			double rateMin = 0;// 最小排产系数
			double putRate = 0;// 排产原则
			double delvryRangeMax = Double.parseDouble(ordEntity
					.getDelvryRangeMax());
			double delvryRangeMin = Double.parseDouble(ordEntity
					.getDelvryRangeMin());
			if (ordEntity.getDelvryRangeTpe().trim().equals("绝对值")) {
				delvryRangeMax = (delvryRangeMax / orderQty) * 100;
				delvryRangeMin = (delvryRangeMin / orderQty) * 100;
			}

			if (ordEntity.getOrderUnit().equals("米")) {
				orderWeight = orderQty * weightMI;
			} else if (ordEntity.getOrderUnit().equals("英尺")) {
				double lengqty = CoreUnitConvert.FootoMi(orderQty);
				orderWeight = lengqty * weightMI;
			} else if (ordEntity.getOrderUnit().equals("英磅")) {
				orderWeight = CoreUnitConvert.PoundtoTon(orderQty);
			} else {
				orderWeight = orderQty;
			}

			// 目标长度，取长度上下限中间值,计算计划支数
			if (!ordEntity.getLengthmax().trim().equals("")
					&& !ordEntity.getLengthmin().trim().equals("")) {
				aimlength = (Double.parseDouble(ordEntity.getLengthmax()) + Double
						.parseDouble(ordEntity.getLengthmin())) / 2;
				if ((orderWeight % (aimlength * weightMI)) == 0) {
					planNum = (int) (orderWeight / (aimlength * weightMI));
				} else {
					planNum = (int) (orderWeight / (aimlength * weightMI)) + 1;
				}
			}
			if (!ordEntity.getRollWellMonth().equals("")
					&& ordEntity.getRollWellMonth().length() >= 7) {
				int year = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(0, 4));
				int month = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(5, 7));

				putRate = queryPutRate(conn, year, month);
				rate = 1 + ((delvryRangeMax + delvryRangeMin) * putRate - delvryRangeMin) / 100;
				rateMin = 1 - delvryRangeMin / 100;
			}

			ordEntity.setPlanweight(String.valueOf(orderWeight));
			ordEntity.setOrderweight(String.valueOf(orderWeight));
			ordEntity.setOrdernum(String.valueOf(planNum));
			ordEntity.setWeightPerM(String.valueOf(weightMI));
			ordEntity.setPaydownWtMax(String.valueOf(orderWeight
					* (100 + delvryRangeMax) / 100));
			ordEntity.setPaydownWtMin(String.valueOf(orderWeight
					* (100 - delvryRangeMin) / 100));

			ordProcEntity.setPlanWtD(String.valueOf(orderWeight));
			ordProcEntity.setPlanNumD(String.valueOf(planNum));
			ordProcEntity.setWeightPerM(String.valueOf(weightMI));
			ordProcEntity.setAimLenEnd(String.valueOf(aimlength));
			ordProcEntity.setPlanPMain(String.valueOf(rate * orderWeight));
			ordProcEntity.setHeightNkMax("0");
			ordProcEntity.setHeightNkMin("0");
			ordProcEntity.setAimLenRoll("0");
			ordProcEntity.setAimOutdiameter("0");
			ordProcEntity.setFeedRate(String.valueOf(putRate));
			ordProcEntity.setCoefficient(String.valueOf(rate));
			ordProcEntity.setCoefficientMin(String.valueOf(rateMin));
			ordProcEntity
					.setPlanPMainMin(String.valueOf(rateMin * orderWeight));
			ordProcEntity.setWeightKzM("0");
			ordProcEntity.setAimWtEnd(String.valueOf(ordEntity.getWeightJg()
					/ 1000 + weightMI
					* (aimlength - ordEntity.getCheckJVal() / 1000)));
		} else if (ordProcEntity.getProcessSeq().contains("D")
				&& !ordProcEntity.getGroupRoll().trim().equals("C072")
				&& !ordEntity.getOutsStlPipeFl().equals("121903")
				&& !ordEntity.getOutsStlPipeFl().equals("121902")
				|| ordEntity.getOrderUnit().trim().equals("支")) {
			/*********** 计算 **************/
			OutOrdParamEntity outOrdParam = new OutOrdParamEntity();
			InOrdParamEntity inOrdParam = new InOrdParamEntity();
			double putRate = 1;
			double height = 0;
			if (!ordProcEntity.getHeightYlg().trim().equals("")) {
				height = Double.parseDouble(ordProcEntity.getHeightYlg());
			}
			if (!ordEntity.getRollWellMonth().equals("")
					&& ordEntity.getRollWellMonth().length() >= 7) {
				int year = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(0, 4));
				int month = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(5, 7));
				putRate = queryPutRate(conn, year, month);
			}
			inOrdParam = CoreGetOrdAmount.getInOrdEntity(conn, desginKey,
					ordProcEntity.getIndexSeq(), ordEntity.getOrdLnDlyPk(),
					ordProcEntity.getGroupRoll(), ordProcEntity.getBom(),
					ordEntity.getCodeJg(), putRate);
			// 内控公差标准合理性验证
			/*if (inOrdParam.getNkWallthickMax() < 0
					|| inOrdParam.getNkWallthickMin() > 0) {
				reason[0] = "内控壁厚公差上下限维护不合理，上限必须>=0,下限必须<=0";
				return false;
			}*/
			// if (inOrdParam.getNkAimthickMax() < 0
			// || inOrdParam.getNkAimthickMin() > 0) {
			// reason[0] = "内控外径公差上下限维护不合理，上限必须>=0,下限必须<=0";
			// return false;
			// }
			if (!isRightParam(conn, inOrdParam, desginKey,
					ordEntity.getCodeJg(), ordProcEntity.getBom(),
					ordProcEntity.getGroupRoll(), reason)) {
				return false;
			}
			outOrdParam = PlnProducCal.calculate(conn, inOrdParam);
			if (outOrdParam.getErrCode() == -1) {
				reason[0] = "合同量转换出错（" + outOrdParam.getErrMessage() + "）。";
				return false;
			}
			ordEntity.setOutMultD(outOrdParam.getOutMultD());
			ordEntity.setOrdernum(String.valueOf(outOrdParam.getPlanNum()));
			ordEntity
					.setOrderweight(String.valueOf(outOrdParam.getEstWeight()));
			// ordEntity.setOrderweightunit(outOrdParam.getWeightUnit());
			ordEntity.setPlanweight(String.valueOf(outOrdParam.getWeightInA()));
			ordEntity.setPaydownWtMax(String.valueOf(outOrdParam
					.getWeightInAMax()));
			ordEntity.setPaydownWtMin(String.valueOf(outOrdParam
					.getWeightInAMin()));
			ordEntity.setWeightPerM(String.valueOf(outOrdParam.getWeightMi()));
			ordEntity.setLenToendMax(String.valueOf(outOrdParam
					.getLenToendMax()));
			ordEntity.setLenToendMin(String.valueOf(outOrdParam
					.getLenToendMin()));
			if (wallthick > 0) {
				ordEntity.setHeightOrdMin(String.valueOf(100
						* inOrdParam.getStdWallthickMin() / wallthick));
				ordEntity.setHeightOrdMax(String.valueOf(100
						* inOrdParam.getStdWallthickMax() / wallthick));
			}

			ordProcEntity.setWeightPerM(String.valueOf(outOrdParam
					.getWeightMi()));
			ordProcEntity
					.setPlanWtD(String.valueOf(outOrdParam.getWeightInA()));
			ordProcEntity.setPlanNumD(String.valueOf(outOrdParam.getPlanNum()));
			ordProcEntity.setAimLenRoll(String.valueOf(outOrdParam
					.getAimlengthZg()));
			ordProcEntity.setAimLenEnd(String.valueOf(outOrdParam
					.getAimLength()));
			ordProcEntity
					.setPlanPMain(String.valueOf(outOrdParam.getWeightPc()));
			ordProcEntity.setPlanTotLenD(String.valueOf((outOrdParam
					.getPlanNum() * outOrdParam.getAimLength())));
			ordProcEntity.setTotLenOneP(String.valueOf(outOrdParam
					.getTotLenOneP()));
			ordProcEntity.setCutNumP(String.valueOf(outOrdParam.getCutNumP()));
			ordProcEntity.setRollLength(String.valueOf(outOrdParam
					.getRollLength()));
			ordProcEntity.setAimWallthick(String.valueOf(outOrdParam
					.getAimWallthick()));
			ordProcEntity.setLenRollMax(String.valueOf(outOrdParam
					.getLenRollMax()));
			ordProcEntity.setLenRollMin(String.valueOf(outOrdParam
					.getLenRollMin()));
			if (inOrdParam.getNkWallthickMax() == 0
					&& inOrdParam.getNkWallthickMin() == 0) {
				ordProcEntity.setHeightNkMin(ordEntity.getHeightOrdMin());
				ordProcEntity.setHeightNkMax(ordEntity.getHeightOrdMax());
			} else if (height > 0) {
				ordProcEntity.setHeightNkMin(String.valueOf(100
						* inOrdParam.getNkWallthickMin() / height));
				ordProcEntity.setHeightNkMax(String.valueOf(100
						* inOrdParam.getNkWallthickMax() / height));
			}
			ordEntity.setOutdOrdMax(String.valueOf(inOrdParam.getOutdOrdMax()));
			ordEntity.setOutdOrdMin(String.valueOf(inOrdParam.getOutdOrdMin()));
			ordProcEntity.setAimOutdiameter(String.valueOf(outOrdParam
					.getAimOutdiameter()));
			ordProcEntity
					.setFeedRate(String.valueOf(outOrdParam.getFeedRate()));
			ordProcEntity.setCoefficient(String.valueOf(outOrdParam
					.getCoefficient()));
			ordProcEntity.setCoefficientMin(String.valueOf(outOrdParam
					.getCoefficientMin()));
			ordProcEntity.setPlanPMainMin(String.valueOf(outOrdParam
					.getPlanPMainMin()));
			ordProcEntity.setWeightKzM(String.valueOf(outOrdParam
					.getWeightKzM()));
			ordProcEntity
					.setAimWtEnd(String.valueOf(outOrdParam.getAimWtEnd()));
		} else {
			/*********** 外购管 **************/
			double orderWeight = 0; // 合同量
			double aimlength = 0; // 目标长度
			int planNum = 0;// 合同支数
			double rate = 0;
			double rateMin = 0;
			double putRate = 0;
			double aimWallthick = wallthick;
			// 轧管内控壁厚公差
			CoreTolerOfNk tolerOfNk = new CoreTolerOfNk();
			CoreTolerOfNkParam nkParam = new CoreTolerOfNkParam();
			nkParam.setBias_code("404019");
			nkParam.setOutdiameter(outdiameter);
			nkParam.setWallthick(wallthick);
			nkParam.setLengthmax(Double.parseDouble(ordEntity.getLengthmax()));
			nkParam.setLengthmin(Double.parseDouble(ordEntity.getLengthmin()));
			nkParam = tolerOfNk.queryTolerance(nkParam, desginKey,
					ordProcEntity.getIndexSeq(), "1");
			if (nkParam != null) {
				double wallUpper = nkParam.getWallUpper();
				double wallLower = nkParam.getWallLower();
				if (wallUpper == 0 && wallLower == 0) {
					reason[0] = "未找到内控壁厚公差。";
					return false;
				}
			}
			// 内控公差标准合理性验证
			/*if (nkParam.getWallUpper() < 0 || nkParam.getWallLower() > 0) {
				reason[0] = "内控壁厚公差上下限维护不合理，上限必须>=0,下限必须<=0";
				return false;
			}*/
			Double[] stdTole = CoreOrderStdSic.getConnStdTole(conn, desginKey,
					outdiameter, wallthick);
			// if (stdTole == null || (stdTole[0] == 0 && stdTole[1] == 0)) {
			// reason[0] = "未找到交货标准公差。";
			// return false;
			// }
			aimWallthick = wallthick
					+ (nkParam.getWallUpper() - Math
							.abs(nkParam.getWallLower())) / 2;

			double weightMI = CoreOrdBase.WeightOfMi(outdiameter, aimWallthick);// 米单重
			double delvryRangeMax = Double.parseDouble(ordEntity
					.getDelvryRangeMax());
			double delvryRangeMin = Double.parseDouble(ordEntity
					.getDelvryRangeMin());

			if (ordEntity.getDelvryRangeTpe().trim().equals("绝对值")) {
				delvryRangeMax = (delvryRangeMax / orderQty) * 100;
				delvryRangeMin = (delvryRangeMin / orderQty) * 100;
			}
			if (ordEntity.getOrderUnit().equals("米")) {
				orderWeight = orderQty * weightMI;
			} else if (ordEntity.getOrderUnit().equals("英尺")) {
				double lengqty = CoreUnitConvert.FootoMi(orderQty);
				orderWeight = lengqty * weightMI;
			} else if (ordEntity.getOrderUnit().equals("英磅")) {
				orderWeight = CoreUnitConvert.PoundtoTon(orderQty);
			} else {
				orderWeight = orderQty;
			}

			// 目标长度，取长度上下限中间值,计算计划支数
			if (!ordEntity.getLengthmax().trim().equals("")
					&& !ordEntity.getLengthmin().trim().equals("")) {
				double lengthMax = Double.parseDouble(ordEntity.getLengthmax());
				double lengthMin = Double.parseDouble(ordEntity.getLengthmin());
				aimlength = (lengthMax + lengthMin) / 2;
				if ((orderWeight % (aimlength * weightMI)) == 0) {
					planNum = (int) (orderWeight / (aimlength * weightMI));
				} else {
					planNum = (int) (orderWeight / (aimlength * weightMI)) + 1;
				}
			}

			if (!ordEntity.getRollWellMonth().equals("")
					&& ordEntity.getRollWellMonth().length() >= 7) {
				int year = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(0, 4));
				int month = Integer.parseInt(ordEntity.getRollWellMonth()
						.substring(5, 7));
				putRate = queryPutRate(conn, year, month);
				rate = 1 + ((delvryRangeMax + delvryRangeMin) * putRate - delvryRangeMin) / 100;
				rateMin = 1 - delvryRangeMin / 100;
			}

			ordEntity.setOrderweight(String.valueOf(orderWeight));
			ordEntity.setOrdernum(String.valueOf(planNum));
			ordEntity.setWeightPerM(String.valueOf(weightMI));
			ordEntity.setPlanweight(String.valueOf(orderWeight));
			ordEntity.setPaydownWtMax(String.valueOf((orderWeight
					* delvryRangeMax / 100)));
			ordEntity.setPaydownWtMin(String.valueOf((orderWeight
					* delvryRangeMin / 100)));

			if (wallthick > 0) {
				ordEntity.setHeightOrdMax(String
						.valueOf((100 * stdTole[0] / wallthick)));
				ordEntity.setHeightOrdMin(String
						.valueOf((100 * stdTole[1] / wallthick)));
				ordProcEntity.setHeightNkMax(String.valueOf((100 * nkParam
						.getWallUpper() / wallthick)));
				ordProcEntity.setHeightNkMin(String.valueOf((100 * nkParam
						.getWallUpper() / wallthick)));
			}

			ordProcEntity.setPlanWtD(String.valueOf(orderWeight));
			ordProcEntity.setPlanNumD(String.valueOf(planNum));
			ordProcEntity.setWeightPerM(String.valueOf(weightMI));
			ordProcEntity.setAimLenEnd(String.valueOf(aimlength));
			ordProcEntity.setPlanPMain(String.valueOf((rate * orderWeight)));
			ordProcEntity.setPlanTotLenD(String.valueOf((planNum * aimlength)));
			ordProcEntity.setAimWallthick(String.valueOf(aimWallthick));
			ordProcEntity.setAimOutdiameter(String.valueOf(outdiameter));
			ordProcEntity.setFeedRate(String.valueOf(putRate));
			ordProcEntity.setCoefficient(String.valueOf(rate));
			ordProcEntity.setCoefficientMin(String.valueOf(rateMin));
			ordProcEntity
					.setPlanPMainMin(String.valueOf(rateMin * orderWeight));
			ordProcEntity.setWeightKzM(String.valueOf(weightMI));
			ordProcEntity.setAimWtEnd(String.valueOf(ordEntity.getWeightJg()
					/ 1000 + weightMI
					* (aimlength - ordEntity.getCheckJVal() / 1000)));
		}
		return true;
	}

	/**
	 * 获取投料率
	 * 
	 * @param conn
	 * @param year
	 * @param month
	 * @return
	 * @throws SQLException
	 */
	public static double queryPutRate(Connection conn, int year, int month)
			throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		double putRate = 1;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryPutRate");
		ps = conn.prepareStatement(sql);
		ps.setString(1, String.valueOf(year));
		ps.setString(2, String.valueOf(month));
		rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getDouble("PUT_RATE") > 0) {
				putRate = rs.getDouble("PUT_RATE");
			}
		}
		rs.close();
		ps.close();
		return putRate;
	}

	/**
	 * 获取组合类型（0不需配箍/1需配箍/2需短节和箍）
	 * 
	 * @param conn
	 *            链接字符串
	 * @param desginKey
	 *            质量设计主键
	 * @param processSeq
	 *            途径工序代码
	 * @return
	 * @throws SQLException
	 */
	public static int getMergeType(Connection conn, String desginKey,
			String processSeq) throws SQLException {
		ResultSet rs = null;
		PreparedStatement ps = null;
		String sqlJg = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryJgCode");
		String sqlBl = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryBlCode");
		if (!processSeq.equals("")) {
			String endcode = processSeq.substring(processSeq.length() - 1,
					processSeq.length());
			if (endcode.compareTo("D") < 0) {
				return 3;
			}
		}
		ps = conn.prepareStatement(sqlJg);
		ps.setObject(1, desginKey);
		rs = ps.executeQuery();
		if (rs.next()) {
			PreparedStatement pst = conn.prepareStatement(sqlBl);
			pst.setObject(1, desginKey);
			ResultSet rst = pst.executeQuery();
			if (rst.next()) {
				rst.close();
				pst.close();
				return 2;
			} else {
				rst.close();
				pst.close();
				return 1;
			}
		}
		rs.close();
		ps.close();
		return 0;
	}

	/**
	 * 获取合同默认轧管产线
	 * 
	 * @param conn
	 * @param dInMaterialNo
	 * @param dOutMaterialNo
	 * @param desginKey
	 * @param mscPline
	 * @param finalUser
	 * @param produccode
	 * @param ordLnPk
	 * @return
	 * @throws SQLException
	 */
	public String getOrdPline(Connection conn, String dInMaterialNo,
			String dOutMaterialNo, String desginKey, String mscPline,
			String finalUser, String produccode, String ordLnPk)
			throws SQLException {
		String dPine = "";
		ResultSet rs = null;
		PreparedStatement ps = null;
		ResultSet rst = null;
		PreparedStatement pst = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreOrdDesginBom.getCustomRpline");
		ps = conn.prepareStatement(sql);
		ps.setString(1, finalUser);
		ps.setString(2, produccode);
		rs = ps.executeQuery();
		if (rs.next()) {
			sql = CoreXmlSqlParsersFactory
					.getSql("CoreOrdDesginBom.getBomCustomRDpl");
			pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			pst.setString(1, dInMaterialNo);
			pst.setString(2, dOutMaterialNo);
			pst.setString(3, desginKey);
			pst.setString(4, mscPline);
			pst.setString(5, finalUser);
			pst.setString(6, produccode);
		} else {
			sql = CoreXmlSqlParsersFactory
					.getSql("CoreOrdDesginBom.getBomMaterialDpl");
			pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			pst.setString(1, dInMaterialNo);
			pst.setString(2, dOutMaterialNo);
			pst.setString(3, desginKey);
			pst.setString(4, mscPline);
		}

		rst = pst.executeQuery();
		if (rst.next()) {
			boolean isAssel = false;
			boolean alAssel = isAssel(conn, ordLnPk);
			do {
				if (rst.getString("PLINE_CODE").equals("C012")) {
					isAssel = true;
					if (alAssel) {
						// 存在Assel产线，并默认Assel
						dPine = "C012";
					}
					break;
				}
			} while (rst.next());

			rst.first();
			if (isAssel) {
				if (dPine.equals("")) {
					do {
						if (!rst.getString("PLINE_CODE").equals("C012")) {
							// 存在Assel产线，不默认Assel
							dPine = rst.getString("PLINE_CODE");
							break;
						}
					} while (rst.next());
				}
			}

			if (dPine.equals("") && rst.first()) {
				// 不存在Assel产线
				dPine = rst.getString("PLINE_CODE");
			}
		}
		rst.close();
		pst.close();

		rs.close();
		ps.close();
		return dPine;
	}

	/**
	 * 合同行是否Assel
	 * 
	 * @param conn
	 * @param ordLnPk
	 * @return
	 * @throws SQLException
	 */
	public boolean isAssel(Connection conn, String ordLnPk) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		boolean isAssel = false;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.queryAsselFl");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, ordLnPk);
		rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getString("ASSEL_FL") != null
					&& rs.getString("ASSEL_FL").trim().equals("1")) {
				isAssel = true;
			}
		}
		rs.close();
		ps.close();
		return isAssel;
	}

	/**
	 * 验证交货行唯一
	 * 
	 * @param conn
	 * @param orderNo
	 * @param orderSeq
	 * @param deliveryNo
	 * @return
	 * @throws SQLException
	 */
	public boolean isNotRepeatOrd(Connection conn, String orderNo,
			String orderSeq, String deliveryNo) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnSaleOrder.querySaleByPrimary");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, orderNo);
		ps.setObject(2, orderSeq);
		ps.setObject(3, deliveryNo);
		rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getInt("DLY_NUM") > 1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 合同长度英尺转换米
	 * 
	 * @param ordEntity
	 */
	public static void getLenUnitConvert(PlnSaleordEntity ordEntity) {
		if (ordEntity == null) {
			return;
		}
		if ((ordEntity.getTotlengthUnit() == null || ordEntity
				.getTotlengthUnit().isEmpty())
				&& !ordEntity.getTotlength().trim().equals("")) {
			ordEntity.setTotlengthUnit(ordEntity.getLenUnit());
		}
		if (ordEntity.getTotlengthUnit().trim().equals("英尺")) {
			double totLength = CoreUnitConvert.FootoMi(Double
					.parseDouble(ordEntity.getTotlength()));
			ordEntity.setTotlengthM(String.valueOf(totLength));
		} else if (ordEntity.getTotlengthUnit().trim().equals("米")) {
			ordEntity.setTotlengthM(ordEntity.getTotlength());
		}

		if (ordEntity.getLenUnit().trim().equals("英尺")) {
			ordEntity.setLenUnit("米");
			if (!ordEntity.getLengthmax().trim().equals("")) {
				// /最大长度
				double lengthMax = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getLengthmax()));
				ordEntity.setLengthmax(String.valueOf(lengthMax));
			}
			if (!ordEntity.getLengthmin().trim().equals("")) {
				// /最小长度
				double lengthMin = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getLengthmin()));
				ordEntity.setLengthmin(String.valueOf(lengthMin));
			}
			if (!ordEntity.getShortest().trim().equals("")) {
				// /短尺最短
				double shortest = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getShortest()));
				ordEntity.setShortest(String.valueOf(shortest));
			}
			if (!ordEntity.getTotlengthM().trim().equals("")) {
				// /订货长度(保总长)、保米长
				double totlengthm = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getTotlengthM()));
				ordEntity.setTotlengthM(String.valueOf(totlengthm));
			}
			if (!ordEntity.getLongest().trim().equals("")) {
				// /长尺最长
				double longest = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getLongest()));
				ordEntity.setLongest(String.valueOf(longest));
			}
			if (!ordEntity.getAvgLenMin().trim().equals("")) {
				// /平均长度大于
				double avglenmin = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getAvgLenMin()));
				ordEntity.setAvgLenMin(String.valueOf(avglenmin));
			}
			if (!ordEntity.getDifrncLenMax().trim().equals("")) {
				// /最长最短差小于
				double difrnclenmax = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getDifrncLenMax()));
				ordEntity.setDifrncLenMax(String.valueOf(difrnclenmax));
			}
			if (!ordEntity.getSiglLen().trim().equals("")) {
				// /单倍尺长
				double sigllen = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getSiglLen()));
				ordEntity.setSiglLen(String.valueOf(sigllen));
			}
			if (!ordEntity.getEndlenSpecstd().trim().equals("")) {
				// /成品长度公差
				double endlenspecstd = CoreUnitConvert.FootoMi(Double
						.parseDouble(ordEntity.getEndlenSpecstd()));
				ordEntity.setEndlenSpecstd(String.valueOf(endlenspecstd));
			}
		}
	}

	/**
	 * 验证数据
	 * 
	 * @param inEntity
	 * @param desginKey
	 * @param codeJg
	 * @param bom
	 * @param dPline
	 * @param errMessage
	 * @return
	 * @throws SQLException
	 */
	public static boolean isRightParam(Connection conn,
			InOrdParamEntity inEntity, String desginKey, String codeJg,
			String bom, String dPline, String[] errMessage) throws SQLException {
		errMessage[0] = "";
		if (desginKey.equals("")) {
			errMessage[0] = "未找到工艺评审。";
			return false;
		}
		if (inEntity == null) {
			errMessage[0] = "查询合同量转换参数出错。";
			return false;
		}
		if (!inEntity.getOrderUnit().equals("支")
				&& !inEntity.getOrderUnit().equals("英磅")
				&& !inEntity.getOrderUnit().equals("吨")
				&& !inEntity.getOrderUnit().equals("米")
				&& !inEntity.getOrderUnit().equals("英尺")) {
			errMessage[0] = "合同订货单位未知！";
			return false;
		}
		if (inEntity.getOrderQty() <= 0) {
			errMessage[0] = "合同订货量必须大于零！";
			return false;
		}
		if (inEntity.getTotlength() > 0) {
			if (!inEntity.getTotlengthUnit().equals("米")
					&& !inEntity.getTotlengthUnit().equals("英尺")) {
				errMessage[0] = "合同有保总长，但保总长单位未知！";
				return false;
			}
		}
		if (inEntity.getTotlength() < 0) {
			errMessage[0] = "合同保总长不能为负数！";
			return false;
		}
		if (!inEntity.getOrderUnit().equals("支")) {
			String plineName = "";
			if (inEntity.getLengthMax() <= 0) {
				errMessage[0] = "合同长度上限必须大于零！";
				return false;
			}
			if (inEntity.getLengthMin() < 0) {
				errMessage[0] = "合同长度下限不能为负数！";
				return false;
			}
			if (inEntity.getLengthMax() < inEntity.getLengthMin()) {
				errMessage[0] = "合同长度上限不能小于下限！";
				return false;
			}
			if (inEntity.getOutdiameter() <= 0) {
				errMessage[0] = "合同外径必须大于零！";
				return false;
			}
			if (inEntity.getWallthick() <= 0) {
				errMessage[0] = "合同壁厚必须大于零！";
				return false;
			}
			if (inEntity.getOutdiameter() < inEntity.getWallthick()) {
				errMessage[0] = "合同外径不能小于壁厚！";
				return false;
			}
			if (inEntity.getDiameterZg() <= 0) {
				errMessage[0] = "轧管工序，轧管规格外径必须大于零！\n BOM：" + bom;
				return false;
			}
			if (inEntity.getHeightZg() <= 0) {
				errMessage[0] = "轧管工序，轧管规格壁厚必须大于零！\n BOM：" + bom;
				return false;
			}
			if (inEntity.getDiameterZg() < inEntity.getHeightZg()) {
				errMessage[0] = "轧管规格外径不能小于壁厚！\n BOM：" + bom;
				return false;
			}
			if (inEntity.getDiameterPl() == null
					|| inEntity.getDiameterPl().size() == 0) {
				errMessage[0] = "管坯坯料断面规格未知！\n BOM：" + bom;
				return false;
			} else {
				for (int i = 0; i < inEntity.getDiameterPl().size(); i++) {
					if (inEntity.getDiameterPl().get(0) <= 0) {
						errMessage[0] = "管坯坯料断面必须大于零！\n BOM：" + bom;
						return false;
					}
				}
			}
			plineName = getPlineName(conn, dPline);
			if (inEntity.getCutHeadEnd() < 0) {
				errMessage[0] = "轧管工序，切头尾不能为负数！\n BOM：" + bom + "，轧管机组："
						+ plineName;
				return false;
			}
			if (inEntity.getLengthMaxRing() <= 0) {
				errMessage[0] = "轧管工序，环形炉最大长度未知！\n 轧管机组：" + plineName;
				return false;
			}
			if (inEntity.getLengthColdbed() <= 0) {
				errMessage[0] = "轧管工序，产线冷床长度必须大于零！\n 轧管机组：" + plineName;
				return false;
			}
			if (inEntity.getSigllen() < 0) {
				errMessage[0] = "单倍尺长不能为负数！";
				return false;
			}
			if (inEntity.getBurnoutRate() < 0
					|| inEntity.getBurnoutRate() > 100) {
				errMessage[0] = "轧管烧损率有误！\n 烧损率" + inEntity.getBurnoutRate()
						+ "%\n 轧管机组：" + plineName;
				return false;
			}
			if (inEntity.getBurnoutDbk() < 0 || inEntity.getBurnoutDbk() > 100) {
				errMessage[0] = "镦拔扩烧损率有误！\n 烧损率" + inEntity.getBurnoutDbk()
						+ "%。";
				return false;
			}
			if (inEntity.getFootmin() < 0) {
				errMessage[0] = "短尺最短不能为负数！";
				return false;
			}
			if (inEntity.getStdWallthickMax() == 0
					&& inEntity.getStdWallthickMin() == 0) {
				errMessage[0] = "未找到交货标准公差。";
				return false;
			}
			if (inEntity.getAddLengthDbk() < 0) {
				errMessage[0] = "镦拔扩切头尾长度不能为负数！\n BOM：" + bom;
				return false;
			}
			if (inEntity.getAddLengthDc() < 0) {
				errMessage[0] = "镦粗影响长度不能为负数！\n BOM：" + bom;
				return false;
			}
			if (inEntity.getInspectLen() < 0) {
				errMessage[0] = "探伤盲区切长度值不能为负数！";
				return false;
			}
		}
		if (inEntity.getOrderUnit().equals("英磅")
				|| inEntity.getOrderUnit().equals("吨")) {
			if (inEntity.getTotlength() == 0) {
				if (inEntity.getWeightType() != 0
						&& inEntity.getWeightType() != 1
						&& inEntity.getWeightType() != -1) {
					errMessage[0] = "合同按重量交货，但未知计重方式！";
					return false;
				}
			}
		}
		if (inEntity.getDelvryRangeMax() < 0
				|| inEntity.getDelvryRangeMin() < 0) {
			errMessage[0] = "合同交货量差有误！";
			return false;
		}
		if (inEntity.getDelvryRangeTpe() != 1
				&& inEntity.getDelvryRangeTpe() != 2) {
			errMessage[0] = "合同交货量差方式未知！";
			return false;
		}
		if (inEntity.getWeightJg() < 0) {
			errMessage[0] = "接箍单重不能为负数！\n 接箍码：" + codeJg;
			return false;
		}
		if (inEntity.getCheckJVal() < 0) {
			errMessage[0] = "接箍测量J值不能为负数！\n 接箍码：" + codeJg;
			return false;
		}
		return true;
	}

	/**
	 * 获取产线名称
	 * 
	 * @param plineCode
	 * @return
	 * @throws SQLException
	 */
	public static String getPlineName(Connection conn, String plineCode)
			throws SQLException {
		String plinName = "";

		String sql = "SELECT T.PLINE_NAME FROM COM_BASE_PLINE T WHERE T.PLINE_CODE = ?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setObject(1, plineCode);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			plinName = rs.getString("PLINE_NAME");
		}
		rs.close();
		ps.close();

		return plinName;
	}

}