package com.steering.pss.plnsaleord.GpOptimize;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import net.sf.json.JSONObject;

import com.google.gson.JsonObject;
import com.ibm.websphere.security.Result;
import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.GpOptimize.model.PlnOrderZgSEntity;
import com.steering.pss.plnsaleord.GpOptimize.model.*;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.lenthCal.CoreLenRecalCulation;
import com.steering.pss.plnsaleord.lenthCal.LenCalculateInObject;
import com.steering.pss.plnsaleord.lenthCal.LenCalculateOutObject;
import com.steering.pss.plnsaleord.lenthCal.PlnZglenthCal;
import com.steering.pss.plnsaleord.ordAmCal.PlnProducCal;
import com.steering.pss.plnsaleord.ordAmCal.PlnZgProcCal;
import com.steering.pss.plnsaleord.ordAmCal.model.InZgOrdCalEntity;
import com.steering.pss.plnsaleord.ordAmCal.model.OutZgOrdCalEntity;
import com.steering.pss.plnsaleord.order.baseMethod.CoreOrdBase;
import com.steering.pss.plnsaleord.order.baseMethod.CoreTolerOfNk;
import com.steering.pss.plnsaleord.order.model.*;
import com.steering.pss.plnsaleord.processOrder.CorePlnOrdProUseTime;
import com.steering.pss.plnsaleord.processOrder.base.BaseHelper;
//import com.steering.pss.plnsaleord.processOrder.base.LoggableStatement;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.processOrder.entity.TimeEntity;

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 java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 管坯需求编辑
 * 
 * @author xiaohai
 */
public class CorePlnZgMStoGp extends DBCommon {
	private static double Pi = 3.1415926; // 圆周率

	/**
	 * 查询工艺文件路径
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject selectCraftPath(String proPlanId, String gxPlanNo,
			String craftFileNo, String craftSeq) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectCraftPath",
				new Object[] { proPlanId, gxPlanNo });
		return cro;
	}

	/**
	 * 查询是否存在余量
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject selectProZgPlnAnaly(ArrayList<String> list) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectProZgPlnAnaly",
				list.toArray());
		return cro;
	}

	/**
	 * 查询钢种及钢种索引码
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject getQueryGrade() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getQueryGrade");
		return cro;
	}

	/**
	 * 查询钢种及钢种索引码
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject getQueryGrade1(String outsBilletFl) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getQueryGrade1",
				new Object[] { outsBilletFl });
		return cro;
	}

	/**
	 * 查询钢种
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject getQueryGradeChoose() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getQueryGradeChoose");
		return cro;
	}

	/**
	 * 通过管坯需求号查订单
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject selectPlnOrderFun() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectPlnOrderFun");
		return cro;
	}

	/**
	 * 查询锭型规格
	 * 
	 * @param weight
	 * @return
	 */
	public CoreReturnObject selectSpecWt(String weight) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectSpecWt",
				new Object[] { Double.parseDouble(weight) * 1000 });
		return cro;
	}

	/**
	 * 查询管坯规格
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject selectSpecDimater(String dimater) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectSpecDimater");
		if (!dimater.equals("")) {
			sql += "  AND T.DIMATER = TO_NUMBER('" + dimater + "')";
		}
		sql += " ORDER BY T.DIMATER ASC";
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询工序产线
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject getProcessPline(String str) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getProcessPline",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询管坯需求号
	 * 
	 * @return
	 */
	public CoreReturnObject getGpreqId() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getGpreqId");
		return cro;
	}

	/**
	 * 查询轧管投料编码名称
	 * 
	 * @return
	 */
	public CoreReturnObject selectDMaterial() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectDMaterial");
		return cro;
	}

	/**
	 * 查询轧管订单号
	 * 
	 * @return
	 */
	public CoreReturnObject getProPlanId() {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.getProPlanId");
		return cro;
	}

	/**
	 * 获取轧管订单投料
	 * 
	 * @param proPlanId
	 * @param gxPlanNo
	 * @return
	 */
	public CoreReturnObject getZgMsInMaterial(String proPlanId,
			String gxPlanNo, String dimater, String gradeName) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.getZgMsInMaterial");
		sql += "AND S.DIMATER=TO_NUMBER('" + dimater + "')";
		if (!gradeName.equals("")) {
			String[] stringArr = gradeName.split(",");
			sql += CoreConverter.toSqlConditionString("B.GRADENAME", stringArr);
		}
		cro = this.getData(sql, new Object[] { proPlanId, gxPlanNo });
		return cro;
	}

	/**
	 * 查询轧管排产
	 * 
	 * @param zgMsPlanNo
	 * @param ordHead
	 * @param ordLine
	 * @param proMonth
	 * @return
	 */
	public CoreReturnObject selectProZgMsPln(String zgMsPlanNo, String ordHead,
			String ordLine, String proMonth, String zgStrat,
			String outsBilletFl, String gpReid,String custom) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProZgMsPln");
		if (!proMonth.equals("")) {
			sql += " AND T.PRO_MONTH = '" + proMonth + "'";
		}
		if (zgStrat.equals("1")) {
			sql += "  AND T.IS_PLAN_OK= '" + zgStrat + "'";
		} else if (zgStrat.equals("0")) {
			sql += " AND (T.IS_PLAN_OK ='0' OR T.IS_PLAN_OK IS NULL)";
		}
		sql += " AND T.EXE_STATUS = '0' AND (T.IS_REPAIR_PLN IS NULL OR T.IS_REPAIR_PLN = '0')"
				+ "   AND T.PRO_PLAN_ID LIKE '%' || '"
				+ zgMsPlanNo
				+ "' || '%'  "
				+ "   AND T.ORDER_NO LIKE '%' || NLS_UPPER('"
				+ ordHead
				+ "') || '%' "
				+ "   AND T.ORDER_SEQ LIKE '%' || NLS_UPPER('"
				+ ordLine
				+ "') || '%'";
		if (!outsBilletFl.equals("")) {
			sql += " AND T.OUTS_BILLET_FL='" + outsBilletFl + "'";
		}
		if (!gpReid.equals("")) {
			sql += " AND T.GPREQ_ID IS NULL";
		}
		sql += " AND T.PLINE_CODE IN ('C008','C009','C010','C012','C017','C072')";
		if(custom.equals("2"))
		{
			sql += " AND T.PLINE_CODE = 'C072'";
			//sql += " AND T1.SUPPLY_UNIT_CODE = '120504'";
		}else if(custom.equals("1"))
		{
			//sql += " AND T1.SUPPLY_UNIT_CODE = '120501'";
			sql += " AND T.PLINE_CODE IN ('C008','C009','C010','C012','C017')";
		}
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询轧管排产
	 * 
	 * @param
	 * @param
	 * @param
	 * @param
	 * @return
	 */
	public CoreReturnObject selectProZgMsPlnZ(String gperqId,
			ArrayList<String> list) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProZgMsPln");
		// if (!gperqId.equals("")) {
		// sql += " AND T.GPREQ_ID = '" + gperqId + "'";
		// }
		if (list.size() > 0) {
			sql += " AND (T.GPREQ_ID = '" + gperqId + "' OR (T.CIC_GP = '"
					+ list.get(0) + "' AND T.LEN_GP_SINGLE = TO_NUMBER('"
					+ list.get(1) + "' ) AND T.INWL_ID = '" + list.get(2)
					+ "'   AND T.OUTS_BILLET_FL = '" + list.get(4)
					+ "'   AND T.WHOLE_BACKLOG_DESC LIKE '%' || '"
					+ list.get(5) + "' || '%'  AND T.GPREQ_ID IS NULL";
			if (!list.get(6).equals("")) {
				sql += " AND T.PIC_GP ='" + list.get(6) + "'";
			}
			if (!list.get(7).equals("")) {
				sql += " AND T.SIC_GP ='" + list.get(7) + "'";
			}
			if (!list.get(8).equals("")) {
				sql += "  AND (SELECT LISTAGG(S.STATION_DESC, ',') WITHIN GROUP(ORDER BY S.STATION_CODE)  "
						+ "FROM CRAFT_ORD_DESIGN_MSC_PL_STI S,   "
						+ "CRAFT_ORD_DESIGN   C,   "
						+ "CRAFT_ORD_DESIGN_MSC_PL_PRC C1     "
						+ "WHERE S.DESGIN_KEY = C1.DESGIN_KEY "
						+ "AND S.MSC_PLINE = C1.MSC_PLINE   "
						+ "AND S.PROCESS_CODE = C1.PROCESS_CODE  "
						+ "AND C.ORD_LN_PK = T1.ORD_LN_PK   "
						+ "AND C.CRAFT_SEQ = T2.CRAFT_SEQ "
						+ "AND C1.DESGIN_KEY = C.DESGIN_KEY  "
						+ "AND C1.MSC_PLINE = T2.INDEX_SEQ  "
						+ "AND C1.PROCESS_CODE IN ('A')) LIKE '%'"
						+ list.get(8) + "'%'";
			}
			if (list.get(3).equals("1")) {
				sql += " AND (SELECT TO_CHAR(WM_CONCAT(PRL.STATION_CODE))"
						+ "   FROM SLM_ORDER_LINE_PRDCR_LST PRL, SLM_ORDER_LINE_PRDCR PR  "
						+ "   WHERE PRL.PRDCR_NO = PR.PRDCR_NO    "
						+ "   AND PRL.PRDCR_INDEX = PR.PRDCR_INDEX        "
						+ "   AND PRL.PROCESS_CODE < 'D'         "
						+ "   AND PR.PRDCR_NO = T.PRDCR_NO      "
						+ "   AND PR.CODE_JG IS NULL   AND PR.CODE_BL IS NULL  "
						+ "   AND PR.MSC_PLINE = T2.INDEX_SEQ) IS NOT NULL))";
			} else {
				sql += " AND (SELECT TO_CHAR(WM_CONCAT(PRL.STATION_CODE))"
						+ "   FROM SLM_ORDER_LINE_PRDCR_LST PRL, SLM_ORDER_LINE_PRDCR PR  "
						+ "   WHERE PRL.PRDCR_NO = PR.PRDCR_NO    "
						+ "   AND PRL.PRDCR_INDEX = PR.PRDCR_INDEX        "
						+ "   AND PRL.PROCESS_CODE < 'D'         "
						+ "   AND PR.PRDCR_NO = T.PRDCR_NO      "
						+ "   AND PR.CODE_JG IS NULL   AND PR.CODE_BL IS NULL  "
						+ "   AND PR.MSC_PLINE = T2.INDEX_SEQ) IS  NULL))";
			}

		}
		sql += " AND T.EXE_STATUS = '0' AND (T.IS_REPAIR_PLN IS NULL OR T.IS_REPAIR_PLN = '0')"
				+ " AND (T.IS_PLAN_OK ='1' OR T.IS_PLAN_OK IS NULL)";
		sql += " AND T.PLINE_CODE IN ('C008','C009','C010','C012','C017')";
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询管坯需求内控标准项集合
	 * 
	 * @param str
	 * @return
	 */
	public CoreReturnObject selectGpIcList(String str) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CorePlnZgMStoGp.selectGpIcList",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询管坯
	 * 
	 * @param str
	 * @return
	 */
	public CoreReturnObject selectProGpReqPln(String str, ArrayList<String> list) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProGpReqPln");
		if (str.equals("")) {
			sql += " AND T.GRADECODE = '" + list.get(0) + "'  "
					+ " AND T.LEN_GP_SINGLE = TO_NUMBER('" + list.get(1)
					+ "')  " + " AND T.MATERIAL_NO = '" + list.get(2) + "'  "
					+ " AND T.IF_MONITOR_LG = '" + list.get(3) + "'   "
					+ " AND T.IFBUYPLAN = '" + list.get(4) + "'   "
					+ " AND T.WHOLE_BACKLOG_DESC = '" + list.get(5)
					+ "' AND T.REQ_DONESTATUS ='0'";

		} else {
			sql += "AND T.GPREQ_ID ='" + str + "'";
		}
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询管坯
	 * 
	 * @param str
	 * @return
	 */
	public CoreReturnObject selectProGpReqPlnP(String str,
			String[] statusArray, String proMonth, String outsBilletFl,String custom) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProGpReqPln");
		if (!str.equals("")) {
			sql += "AND T.GPREQ_ID LIKE '%' || NLS_UPPER('" + str
					+ "') || '%' ";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.REQ_DONESTATUS",
					statusArray);
		}
		if (!proMonth.equals("")) {
			sql += "AND T.PRO_MONTH = '" + proMonth + "'";
		}
		if (!outsBilletFl.equals("")) {
			sql += " AND T.IFBUYPLAN='" + outsBilletFl + "'";
		}
		if(custom.equals("1"))
		{
			sql += " AND T.SUPPLY_UNIT_CODE = '120501'";
		}else if(custom.equals("2"))
		{
			sql += " AND T.SUPPLY_UNIT_CODE = '120504'";
		}
		sql += " ORDER BY T.CREATE_TIME DESC";
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询管坯(锻坯界面)
	 * 
	 * @param str
	 * @return
	 */
	public CoreReturnObject selectProGpReqPlnPZ(String str, String plineCode,
			String[] statusArr, String outsBilletFl) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProGpReqPln");
		if (!str.equals("")) {
			sql += "AND T.GPREQ_ID LIKE '%' || NLS_UPPER('" + str
					+ "') || '%' ";
		}
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE_DZ='" + plineCode + "'";
		}
		if (statusArr.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.REQ_DONESTATUS",
					statusArr);
		}
		if (!outsBilletFl.equals("")) {
			sql += " AND T.IFBUYPLAN='" + outsBilletFl + "'";
		}
		sql += "  AND T.GPTYPE='2'  ORDER BY T.CREATE_TIME DESC";
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 根据钢种过滤成分
	 * 
	 * @param gradeCode
	 * @param listCic
	 * @return
	 */
	public CoreReturnObject screenCicByGrade(String gradeCode, String[] listCic) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.screenCicByGrade");
		List<String> tmp = new ArrayList<String>();
		for (String str : listCic) {
			if (str != null && str.length() != 0) {
				tmp.add(str.trim());
			}
		}
		listCic = tmp.toArray(new String[0]);
		sql += " AND INSTR(T.GRADECODE,'" + gradeCode + "') > 0";
		sql += CoreConverter.toSqlConditionString("T.CIC", listCic);
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 材质
	 * 
	 * @param listPic
	 * @return
	 */
	public CoreReturnObject screenPic(String[] listPic) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.screenPic");
		sql += CoreConverter.toSqlConditionString("T.PIC", listPic);
		sql = sql.replace(" AND ", " WHERE ");
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 公差
	 * 
	 * @param listSic
	 * @return
	 */
	public CoreReturnObject screenSic(String[] listSic) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.screenSic");
		sql += CoreConverter.toSqlConditionString("T.SIC", listSic);
		sql = sql.replace(" AND ", " WHERE ");
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 探伤
	 * 
	 * @param listDic
	 * @return
	 */
	public CoreReturnObject screenDic(String[] listDic) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.screenDic");
		sql += CoreConverter.toSqlConditionString("T.DIC", listDic);
		sql = sql.replace(" AND ", " WHERE ");
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 修改单倍坯长，切头
	 * 
	 * @param
	 * @return
	 */
	@SuppressWarnings("null")
	public CoreReturnObject modifyGpAimWall(ArrayList<String> jsonList,
			String isInWlChange) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			ArrayList<String> message = new ArrayList<String>();
			for (PlnOrderZgSEntity zgSentity : list) {
				PreparedStatement ps = null;
				PreparedStatement pst = null;
				ResultSet rst = null;
				LenCalculateInObject lenCalentity = new LenCalculateInObject();
				LenCalculateOutObject lenCalOutentity = null;
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				String sqlUpdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updateZgMsInMaterial");// 更新轧管订单投料

				List<Double> diameter = new ArrayList<Double>();
				PlnOrderZgSEntity zgSRelentity = null;
				double aimWallthickOld = 0;
				double aimlengthOld = 0;
				double aimlength = 0;// 目标轧管转移长度
				double diameterGp = 0;
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSentity.getProPlanId());
				ps.setObject(2, zgSentity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				zgSRelentity = EntityTool.getEntityByRs(rs,
						PlnOrderZgSEntity.class);
				if (zgSRelentity == null) {
					message.add("找不到订单" + zgSentity.getProPlanId() + "/"
							+ zgSentity.getGxPlanNo() + "。");
					continue;
				}
				//TZH 24.8.27 取消坯料需求申报的处理
//				if (!zgSRelentity.getGpreqId().equals("")) {
//					message.add("订单" + zgSRelentity.getProPlanId() + "/"
//							+ zgSRelentity.getGxPlanNo() + "已组坯料需求，不能重算。");
//					continue;
//				}
				int countM = 0;
				// 查询是否存在炉计划
				String sqlZgM = "SELECT COUNT(*) COUNTZG FROM PLN_ZY_ZG_M T WHERE T.PRO_PLAN_ID='"
						+ zgSentity.getProPlanId()
						+ "' AND T.GX_PLAN_NO='"
						+ zgSentity.getGxPlanNo() + "'";
				PreparedStatement psM = conn.prepareStatement(sqlZgM);
				ResultSet rsM = psM.executeQuery();
				if (rsM.next()) {
					countM = rsM.getInt("COUNTZG");
				}
				rsM.close();
				psM.close();
				if (countM > 0) {
					message.add("订单号：" + zgSentity.getProPlanId() + "/"
							+ zgSentity.getGxPlanNo() + "已生成炉计划，不能重算。");
					continue;
				}
				if (!zgSRelentity.getInwlId().trim()
						.equals(zgSentity.getInwlId().trim())) {
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.getZgMsInMaterial");
					sql += " AND B.D_IN_MATERIAL_NO = ?";
					pst = conn.prepareStatement(sql);
					pst.setObject(1, zgSRelentity.getProPlanId());
					pst.setObject(2, zgSRelentity.getGxPlanNo());
					pst.setObject(3, zgSentity.getInwlId());
					rst = pst.executeQuery();
					if (rst.next()) {
						// diameterGp = rst.getDouble("DIMATER");
						// zgSRelentity.setDiameterGp(String.valueOf(diameterGp));
						zgSRelentity.setInwlId(zgSentity.getInwlId());
						if (rst.getString("D_IN_MATERIAL_DESC") != null) {
							zgSRelentity.setInwlDesc(rst
									.getString("D_IN_MATERIAL_DESC"));
						}
						if (rst.getString("GRADECODE") != null) {
							zgSRelentity.setGradecode(rst
									.getString("GRADECODE"));
						}
						if (rst.getString("GRADENAME") != null) {
							zgSRelentity.setGradename(rst
									.getString("GRADENAME"));
						}
						if (rst.getString("BOM") != null) {
							zgSRelentity.setBom(rst.getString("BOM"));
						}
					}
					rst.close();
					pst.close();
				}
				if (isInWlChange.equals("0")) {
					double cuthead = Double.parseDouble(zgSentity
							.getLenCuthead());
					double cutend = Double
							.parseDouble(zgSentity.getLenCutend());
					double tubeEndRatio = Double.parseDouble(zgSentity
							.getTubeEndRatio());
					double aimWallthick = Double.parseDouble(zgSentity
							.getAimwallthick());
					double lenGpSingle = 10 * Math.floor((Double
							.parseDouble(zgSentity.getLenGpSingle())) / 10);
					if (zgSRelentity.getIsPlanOk().equals("1")) {
						message.add("订单" + zgSRelentity.getProPlanId() + "/"
								+ zgSRelentity.getGxPlanNo() + "已确认，不能再修改。");
						continue;
					}

					if ((lenGpSingle) > rs.getDouble("LENGTH_MAX_RING")) {
						message.add("订单" + zgSRelentity.getProPlanId() + "/"
								+ zgSRelentity.getGxPlanNo()
								+ "单倍坯长必须小于等于产线的环形炉最大长度。\n" + "(产线："
								+ zgSRelentity.getPlineName() + "的环形炉最大长度"
								+ rs.getDouble("LENGTH_MAX_RING") + "mm)");
						continue;
					}

					diameterGp = rs.getDouble("DIAMETER_GP");
					aimWallthickOld = rs.getDouble("AIMWALLTHICK");
					// if (aimWallthickOld <= 0) {
					// message.add("订单" + zgSRelentity.getProPlanId() + "/"
					// + zgSRelentity.getGxPlanNo() + "原轧管控制壁厚数据有误！");
					// continue;
					// }
					aimlengthOld = rs.getDouble("AIMLENGTH");
					double cutMax = 0;// 最大分切数
					double capacity = 0;
					double wasteRate = 0;//
					// 成材率
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnProcessOrd.queryBaseMaterialDPl");
					PreparedStatement psc = conn.prepareStatement(sql);
					psc.setString(1, zgSentity.getInwlId());
					psc.setString(2, zgSentity.getOutwlId());
					psc.setString(3, zgSentity.getPlineCode());
					ResultSet rsc = psc.executeQuery();
					if (rsc.next()) {
						cutMax = rsc.getDouble("DBL_LEN_MAX");
						capacity = rsc.getDouble("HR_CAPCTY");
						wasteRate = rsc.getDouble("WASTE_RATE") / 10000;
					}
					rsc.close();
					psc.close();

					lenCalentity.setOutdiameter(rs.getDouble("AIMOUTDIAMETER"));
					lenCalentity.setWallthick(aimWallthick);
					if (rs.getDouble("SHRT_LEN_RATO") > 0) {
						lenCalentity.setShrtstove(true);
					} else {
						lenCalentity.setShrtstove(false);
					}
					lenCalentity.setTubeEndRatio(tubeEndRatio);
					lenCalentity.setCutMax(cutMax);
					lenCalentity.setEndlenSpecstd(Double
							.parseDouble(zgSRelentity.getEndlenSpecstd()));
					lenCalentity.setSigllen(rs.getDouble("SIGL_LEN"));
					lenCalentity.setBurning(rs.getDouble("BURNOUT_RATE"));
					diameter.add(diameterGp);
					lenCalentity.setDiameter(diameter);
					lenCalentity.setLengthmax(rs.getDouble("LENGTHMAX"));
					lenCalentity.setLengthmin(rs.getDouble("LENGTHMIN"));
					lenCalentity.setLengthmaxZg(rs.getDouble("LEN_ROLL_MAX"));
					lenCalentity.setLengthminZg(rs.getDouble("LEN_ROLL_MIN"));
					lenCalentity.setCutheadtail((cuthead + cutend) / 1000);
					lenCalentity.setBilletmax(lenGpSingle);
					lenCalentity.setSizing(rs.getDouble("LENGTH_COLDBED"));
					lenCalentity.setAvgLenMin(rs.getDouble("AVG_LEN_MIN"));
					lenCalentity.setCheckJVal(rs.getDouble("CHECK_J_VAL"));
					lenCalentity.setLengthMinTube(rs
							.getDouble("LENGTH_MIN_TUBE"));
					lenCalentity.setLengthMaxTube(rs
							.getDouble("LENGTH_MAX_TUBE"));
					lenCalentity.setToleranceZone(rs
							.getDouble("TOLERANCE_ZONE"));
					lenCalentity.setDiameterMandrel(rs
							.getString("DIAMETER_MANDREL"));
					lenCalentity.setCutnum(rs.getInt("OUTNUM_CUT"));
					lenCalentity.setAimlength(rs.getDouble("AIMLENGTH"));
					lenCalentity.setPassMame(rs.getString("PASS_NAME"));

					lenCalOutentity = CoreLenRecalCulation.recaComput(
							lenCalentity, false);
					if (!lenCalOutentity.getisOutput()) {
						message.add("订单" + zgSRelentity.getProPlanId() + "/"
								+ zgSRelentity.getGxPlanNo() + "的"
								+ lenCalOutentity.getReason() + "。");
						continue;
					}
					aimlength = Double.parseDouble(lenCalOutentity
							.getAimlength());
					if (aimlength > new BigDecimal(
							lenCalentity.getLengthmaxZg()).setScale(2,
							RoundingMode.HALF_UP).doubleValue()
							|| aimlength < new BigDecimal(
									lenCalentity.getLengthminZg()).setScale(2,
									RoundingMode.HALF_UP).doubleValue()) {
						message.add("订单" + zgSRelentity.getProPlanId() + "/"
								+ zgSRelentity.getGxPlanNo() + "的" + "目标长度:"
								+ aimlength + ",超过转移长度范围("
								+ lenCalentity.getLengthminZg() + "-"
								+ lenCalentity.getLengthmaxZg() + ")!");
						continue;
					}

					// zgSRelentity.setAimwallthick(String.valueOf(aimWallthick));
					zgSRelentity.setAimlength(lenCalOutentity.getAimlength());
					zgSRelentity.setLenGpSingle(String.valueOf(lenGpSingle));
					zgSRelentity.setRollLength(lenCalOutentity.getLengthZz());
					zgSRelentity.setLenCuthead(String.valueOf(cuthead));
					zgSRelentity.setLenCutend(String.valueOf(cutend));
					zgSRelentity.setOutnumCut(lenCalOutentity.getCutnum());
					zgSRelentity.setTubeEndRatio(String.valueOf(tubeEndRatio));
					zgSRelentity.setVerify1(lenCalOutentity.getVerify1());
					zgSRelentity.setVerify2(lenCalOutentity.getVerify2());
					zgSRelentity.setVerify3(lenCalOutentity.getVerify3());
					// 需求支=
					// (轧管排产吨+轧管加投吨）/（轧管管单重*（轧制长度-管余长-切头尾）+轧管管单重*管端增厚系数*切头尾）
					int demandNum = (int) Math
							.ceil((rs.getDouble("WEIGTH_S") + rs
									.getDouble("ADD_WT_IN"))
									/ (lenCalOutentity.getMiGtWt() * (Double
											.parseDouble(lenCalOutentity
													.getLengthZz())
											- lenCalOutentity.getTubeYuLong() - (cuthead + cutend) / 1000)));

					// addWeight = _ordEntity.getAddNum() * lenGp * weightMi;

					// 需求吨
					double demandWt = demandNum
							* Double.parseDouble(lenCalOutentity
									.getBilletWeight());
					int demandNumMin = (int) Math
							.ceil((rs.getDouble("WEIGTH_S_MIN") + rs
									.getDouble("ADD_WT_IN"))
									/ (lenCalOutentity.getMiGtWt() * (Double
											.parseDouble(lenCalOutentity
													.getLengthZz())
											- lenCalOutentity.getTubeYuLong() - (cuthead + cutend) / 1000)));

					// addWeight = _ordEntity.getAddNum() * lenGp * weightMi;

					// 需求吨
					double demandWtMin = demandNumMin
							* Double.parseDouble(lenCalOutentity
									.getBilletWeight());
					int plansNum = (int) Math
							.ceil((demandNum
									* Integer.parseInt(lenCalOutentity
											.getCutnum()) * (1 - wasteRate)));
					zgSRelentity.setPlansNum(String.valueOf(plansNum));
					zgSRelentity.setGpreqWeightMin(demandWtMin);
					updateZgMSInfo(conn, zgSRelentity, demandNum, demandWt,
							capacity);
				}
				// 投料修改
				else {
					String sqlUp = "";
					// String sqlIc = CoreXmlSqlParsersFactory
					// .getSql("CorePlnZgMStoGp.selectGpIcList");
					// pst = conn.prepareStatement(sqlIc);
					// pst.setObject(1, zgSRelentity.getProPlanId());
					// rst = pst.executeQuery();
					// if (rst.next()) {
					// if (rst.getString("CIC") != null) {
					// String cicGroup = "";
					// PreparedStatement psta = null;
					// String[] listCic = rst.getString("CIC").split(",");
					// // List<String> list1 = new ArrayList<String>();
					// // for (int i = 0; i < listCic.length; i++) {
					// // list1.add(listCic[i].trim());
					// // }
					// // 去除数组中的空格
					// List<String> tmp = new ArrayList<String>();
					// for (String str : listCic) {
					// if (str != null && str.length() != 0) {
					// tmp.add(str.trim());
					// }
					// }
					// listCic = tmp.toArray(new String[0]);
					// sqlIc = CoreXmlSqlParsersFactory
					// .getSql("CorePlnZgMStoGp.screenCicByGrade");
					// sqlIc
					// +=" AND INSTR(T.GRADECODE,'"+zgSRelentity.getGradecode()+"') > 0";
					// sqlIc += CoreConverter.toSqlConditionString(
					// "T.CIC", listCic);
					// psta = conn.prepareStatement(sqlIc);
					// // psta.setObject(1, zgSRelentity.getGradecode());
					// ResultSet rsta = psta.executeQuery();
					// if (rsta.next()) {
					// if (rsta.getString("CIC") != null) {
					// zgSRelentity.setCicGp(zgSentity.getCicGp());
					// // cicGroup += rsta.getString("CIC").trim()
					// // + ",";
					// }
					// }
					// // if (!cicGroup.equals("") && cicGroup.contains(",")) {
					// // cicGroup = cicGroup.substring(0, cicGroup
					// // .length() - 1);
					// // }
					// //
					// // zgSRelentity.setCicGroupGp(cicGroup);
					// rsta.close();
					// psta.close();
					// }
					// }
					// rst.next();
					// pst.close();
					zgSRelentity.setCicGp(zgSentity.getCicGp());
					sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, zgSRelentity);
					pst = conn.prepareStatement(sqlUp);
					pst.executeUpdate();
					pst.close();
				}

				rs.close();
				ps.close();
				conn.commit();
			}
			cro.setResult(EntityTool.getGsonByEntity(message));
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (ParseException pe) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(pe.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改控制壁厚
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject modifyThicknesWall(ArrayList<String> jsonList,
			String userName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			for (PlnOrderZgSEntity zgSentity : list) {
				PreparedStatement ps = null;
				PreparedStatement pst = null;
				ResultSet rst = null;
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				double aimWallthick = Double.parseDouble(zgSentity
						.getAimwallthick());
				PlnOrderZgSEntity zgSRelentity = null;
				double aimWallthickOld = 0;// 原控制壁厚
				double aimlengthOld = 0;// 目标轧管转移长度
				int numSOld = 0;// 原排产支
				double weigthSOld = 0;// 原排产吨
				double wtMiOld = 0;
				double wtMiNew = 0;
				double planWtMax = 0;
				double planWtMin = 0;
				double addWt = 0;// 变化吨数
				int addNum = 0;// 变化支数

				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSentity.getProPlanId());
				ps.setObject(2, zgSentity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				zgSRelentity = EntityTool.getEntityByRs(rs,
						PlnOrderZgSEntity.class);
				if (zgSRelentity == null) {
					cro.setV_errMsg("找不到订单" + zgSentity.getProPlanId() + "/"
							+ zgSentity.getGxPlanNo() + "。");
					return cro;
				}
				if (zgSRelentity.getIsPlanOk().equals("1")) {
					cro.setV_errMsg("订单" + zgSRelentity.getProPlanId() + "/"
							+ zgSRelentity.getGxPlanNo() + "已确认，不能再修改。");
					return cro;
				}
				//TZH 24.8.27 取消坯料需求申报的处理
//				if (!zgSRelentity.getGpreqId().equals("")) {
//					cro.setV_errMsg("订单" + zgSRelentity.getProPlanId() + "/"
//							+ zgSRelentity.getGxPlanNo() + "已组坯料需求，不能再修改。");
//					return cro;
//				}

				// if (!rs.getString("WEIGTH_S_OLD").equals("0")) {
				// weigthSOld = rs.getDouble("WEIGTH_S_OLD");
				// }
				// else {
				weigthSOld = rs.getDouble("WEIGTH_S");
				// }
				// if (!rs.getString("NUM_S_OLD").equals("0")) {
				// numSOld = rs.getInt("NUM_S_OLD");
				// }
				// else {
				numSOld = rs.getInt("NUM_S");
				// }
				// if (!rs.getString("AIMWALLTHICK_OLD").equals("0")) {
				// aimWallthickOld = rs.getDouble("AIMWALLTHICK_OLD");
				// }
				// else {
				aimWallthickOld = rs.getDouble("AIMWALLTHICK");
				// }
				if (aimWallthick == rs.getDouble("AIMWALLTHICK")) {
					cro.setV_errMsg("订单" + zgSRelentity.getProPlanId() + "/"
							+ zgSRelentity.getGxPlanNo() + "控制壁厚未变化！");
					return cro;
				}
				if (aimWallthickOld <= 0) {
					cro.setV_errMsg("订单" + zgSRelentity.getProPlanId() + "/"
							+ zgSRelentity.getGxPlanNo() + "原轧管控制壁厚数据有误！");
					return cro;
				}
				aimlengthOld = rs.getDouble("AIMLENGTH");
				planWtMax = rs.getDouble("PLAN_WT_MAX");
				planWtMin = rs.getDouble("PLAN_WT_MIN");

				double lenMax = 0;// 长度上限
				double lenMin = 0;// 长度下限
				// 查询交货行信息
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreGetOrdAmount.getPlnSaleOrdInf");
				pst = conn.prepareStatement(sql);
				pst.setObject(1, zgSentity.getOrdLnDlyPk());
				rst = pst.executeQuery();
				if (rst.next()) {
					String lenUnit = "";// 长度单位
					if (rst.getString("LEN_UNIT") != null) {
						lenUnit = rst.getString("LEN_UNIT");
					}
					lenMax = CoreOrdBase.lenConversion(lenUnit,
							rst.getDouble("LENGTHMAX"));
					lenMin = CoreOrdBase.lenConversion(lenUnit,
							rst.getDouble("LENGTHMIN"));
				}
				rst.close();
				pst.close();
				double toleranZone = 0;// 机组公差能力带默认壁厚的20%
				// 查询轧管产线基础信息
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreGetOrdAmount.getZgBasePline");
				pst = conn.prepareStatement(sql);
				pst.setObject(1, zgSentity.getPlineCode());
				rst = pst.executeQuery();
				if (rst.next()) {
					toleranZone = rst.getDouble("TOLERANCE_ZONE") / 100;
				}
				rst.close();
				pst.close();
				String sicZg = "";
				// /查询轧管内控壁厚公差标准索引号
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreGetOrdAmount.queryMscPlPrc");
				pst = conn.prepareStatement(sql);
				pst.setObject(1, zgSRelentity.getDesginKey());
				pst.setObject(2, zgSRelentity.getIndexSeq());
				pst.setObject(3, "D");
				rst = pst.executeQuery();
				if (rst.next()) {
					if (rst.getString("SIC") != null) {
						sicZg = rst.getString("SIC");
						if (sicZg.contains(",")) {
							String[] sicList = sicZg.split(",");
							if (sicList.length > 0) {
								sicZg = sicList[0];
							}
						}
					}
				}
				rst.close();
				pst.close();

				double wallUpper = 0;// 内控壁厚上限
				double wallLower = 0;// 内控壁厚下限
				// 轧管内控壁厚公差
				CoreTolerOfNk tolerOfNk = new CoreTolerOfNk();
				CoreTolerOfNkParam nkParam = new CoreTolerOfNkParam();
				nkParam.setBias_code("404019");
				nkParam.setOutdiameter(Double.parseDouble(zgSentity
						.getOutdiameterZg()));
				nkParam.setWallthick(Double.parseDouble(zgSentity
						.getWallthickZg()));
				nkParam.setSic(sicZg);
				nkParam.setLengthmax(lenMax);
				nkParam.setLengthmin(lenMin);
				nkParam = tolerOfNk.queryTolerance(nkParam,
						zgSRelentity.getDesginKey(),
						zgSRelentity.getIndexSeq(), "D");
				if (nkParam != null) {
					wallUpper = nkParam.getWallUpper();
					wallLower = nkParam.getWallLower();

				}
				// if (aimWallthick > wallUpper
				// + Double.parseDouble(zgSentity.getWallthickZg())
				// || aimWallthick < wallLower
				// + Double
				// .parseDouble(zgSentity.getWallthickZg())) {
				// cro.setV_errMsg("订单" + zgSRelentity.getProPlanId() + "/"
				// + zgSRelentity.getGxPlanNo() + "修改后的控制壁厚："
				// + aimWallthick + ";不在内控壁厚公差范围内(下偏差：" + wallLower
				// + ";上偏差：" + wallUpper + "),不能修改！");
				// return cro;
				// }
				double heightF = 0;
				// 壁厚内控的范围与公差带比较
				if (wallUpper - Math.abs(wallLower) >= toleranZone) {
					heightF = Double.parseDouble(zgSentity.getWallthickZg())
							+ wallLower
							+ (toleranZone
									* Double.parseDouble(zgSentity
											.getWallthickZg()) / 2);
				} else {
					heightF = aimWallthick;
				}
				// 原米单重
				wtMiOld = PlnProducCal.tubeWeightMi(
						Double.parseDouble(zgSentity.getAimoutdiameter()),
						aimWallthickOld);
				// 米单重
				wtMiNew = PlnProducCal.tubeWeightMi(
						Double.parseDouble(zgSentity.getAimoutdiameter()),
						aimWallthick);

				// 末工序控制壁厚或目标长度变化部分的成品重量支数
				// double wtChanged = wtEndM * rs.getDouble("RATE");
				// int numChanged = (int) Math
				// .ceil(numEndM * rs.getDouble("RATE"));

				// 按长度缴货，控制壁厚变化，缴货重量变化
				if ((rs.getString("ORDER_UNIT").equals("米")
						|| rs.getString("ORDER_UNIT").equals("英尺") || rs
						.getDouble("TOTLENGTH") > 0)
				// && Math.abs(aimWallthick - aimWallthickOld) >= 0.001
				) {
					// 总长度
					double lenord = weigthSOld / wtMiOld;
					// 末工序控制壁厚或目标长度变化部分 变化后的支数
					// double numWt1 = lenord * wtMiNew;
					double numWt = new BigDecimal(lenord * wtMiNew).setScale(3,
							RoundingMode.HALF_UP).doubleValue();
					// int numNew = (int) Math.ceil(lenord / endAimlength);
					addWt = numWt - weigthSOld;
					// addNum = numNew - numChanged;

					// if (planWtMax - (numWt) < -0.0000001) {
					// cro.setV_errMsg("订单" + zgSRelentity.getProPlanId()
					// + "/" + zgSRelentity.getGxPlanNo()
					// + "修改后，排产重量超上限,排产重量上限：" + planWtMax
					// + ",修改控制壁厚后排产量：" + numWt + "。");
					// return cro;
					// }
					// if (planWtMin - (numWt) > 0.0000001) {
					// cro.setV_errMsg("订单" + zgSRelentity.getProPlanId()
					// + "/" + zgSRelentity.getGxPlanNo()
					// + "修改后，排产重量低于下限，排产重量下限：" + planWtMin
					// + ",修改控制壁厚后排产量：" + numWt + "。");
					// return cro;
					// }
				}
				// else if (Math.abs(aimWallthick - aimWallthickOld) >= 0.001
				// || Math.abs(aimlength - aimlengthOld) >= 0.001) {
				// // 缴货支数变化
				// // int numNew = (int) Math.ceil(wtMiOld * endAimlength
				// // * numChanged / (wtMiNew * endAimlength));
				// int numNew=(int)
				// Math.ceil(weigthSOld/(wtMiNew*aimlengthOld));
				// addNum = numNew - numSOld;
				// }
				// if (addNum != 0 || addWt != 0) {
				// // 轧管到末工序的废品率
				// double rateWaste = Math.abs((rs.getInt("NUM_S") - numSOld)
				// / numSOld);
				// addNum = (int) Math.ceil((1 - rateWaste) * addNum);
				// addWt = (int) Math.ceil((1 - rateWaste) * addWt);
				// }
				rs.close();
				ps.close();
				zgSRelentity.setAimwallthick(String.valueOf(aimWallthick));

				Date dt = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				// double planUseTime = Double.parseDouble(zgSentity
				// .getPlanUsetime());
				// int numS = Integer.parseInt(zgSentity.getNumS());
				// int addTime = (int) Math.ceil(planUseTime * addNum / numS);
				// Date planEndtime = sdf.parse(zgSentity.getPlanTimeE());
				// Calendar cal = Calendar.getInstance();
				//
				// planUseTime += addTime;
				// cal.setTime(planEndtime);
				// cal.add(Calendar.MINUTE, addTime);
				// planEndtime = cal.getTime();
				// zgSentity.setPlanUsetime(String.valueOf(planUseTime));
				// zgSentity.setPlanTimeE(sdf.format(planEndtime));
				// 修改壁厚，排产支吨
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updateZgMsInfoWall");
				ps = conn.prepareStatement(sql);
				String sqlUp = EntityTool.fillSqlByEntity(sql, zgSentity);
				ps = conn.prepareStatement(sqlUp);
				ps.setObject(1, addWt);
				ps.setObject(2, addNum);
				ps.setObject(3, aimWallthickOld);
				ps.setObject(4, weigthSOld);
				ps.setObject(5, numSOld);
				ps.setObject(6, userName);
				ps.setObject(7, sdf.format(dt));
				ps.executeUpdate();
				ps.close();
				// ProducHelperBean helperBean = new ProducHelperBean();
				// helperBean.timeIncrease(conn, Integer.parseInt(zgSentity
				// .getGxProSeq()), zgSentity.getPlineCode(), sdf
				// .format(planEndtime), "D");
			}
			cro.setV_errMsg("调整控制壁厚成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 轧管
	 * 
	 * @param conn
	 * @param zgSentity
	 * @param demandNum
	 *            需求支
	 * @param demandWt
	 *            需求吨
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 */
	public boolean updateZgMSInfo(Connection conn, PlnOrderZgSEntity zgSentity,
			int demandNum, double demandWt, double capacity)
			throws SQLException, ParseException {
		PreparedStatement ps = null;
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// double planUseTime = Double.parseDouble(zgSentity.getPlanUsetime());
		double planUseTime = 0;
		if (capacity > 0) {
			planUseTime = demandNum * 60 / capacity;
		}

		// int numS = Integer.parseInt(zgSentity.getNumS());
		// int addTime = (int) Math.ceil(planUseTime * demandNum / numS);
		// Date planEndtime = sdf.parse(zgSentity.getPlanTimeE());
		// Calendar cal = Calendar.getInstance();

		// planUseTime += addTime;
		// cal.setTime(planEndtime);
		// cal.add(Calendar.MINUTE, addTime);
		// planEndtime = cal.getTime();
		ProducHelperBean helperBean = new ProducHelperBean();
		TimeEntity TimeEntiy = helperBean.calculateTime(demandNum, capacity,
				zgSentity.getPlanTimeB());
		// 计划结束时间
		String planTimeE = TimeEntiy.getEndTime();
		zgSentity.setPlanUsetime(String.valueOf(planUseTime));
		zgSentity.setPlanTimeE(planTimeE);

		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updateZgMsInfo");
		ps = conn.prepareStatement(sql);
		String sqlUp = EntityTool.fillSqlByEntity(sql, zgSentity);
		ps = conn.prepareStatement(sqlUp);
		ps.setObject(1, demandNum);
		ps.setObject(2, demandWt);
		ps.executeUpdate();
		ps.close();

		helperBean.timeIncrease(conn,
				Integer.parseInt(zgSentity.getGxProSeq()),
				zgSentity.getPlineCode(), planTimeE, "D");
		return true;
	}
	
	/**
	 * tzh 2024.9.13 新增修改坯料需求的需求重量
	 * 
	 
	 * @param list
	 * @return
	 */
	public CoreReturnObject updateZgMSWt(ArrayList<PlnOrderZgSEntity> list,String userName){
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ArrayList<String> message = new ArrayList<String>();
			for (PlnOrderZgSEntity zgSentity : list) {
				String sqlUp = "";
				PreparedStatement ps = null;
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updateZgMSWt");
//				sqlUp = EntityTool.fillSqlByEntity(sql, zgSentity);
//				ps = conn.prepareStatement(sqlUp);
				System.out.print(zgSentity.getMatchWtIn());
				System.out.print(zgSentity.getProPlanId());
				System.out.print(zgSentity.getGxPlanNo());
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSentity.getMatchWtIn());
				ps.setObject(2, zgSentity.getProPlanId());
				ps.setObject(3, zgSentity.getGxPlanNo());
				ps.executeUpdate();
				ps.close();

				
				
				
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.insertZgMSWt");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSentity.getProPlanId());
				ps.setObject(2, zgSentity.getGxPlanNo());
				ps.setObject(3, zgSentity.getMatchWtIn());
				ps.setObject(4, zgSentity.getMatchWtIn());
				ps.setObject(5, userName);
				ps.executeUpdate();
				ps.close();
				conn.commit();
			}
			cro.setResult(EntityTool.getGsonByEntity(message));
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;

	}

	/**
	 * 保存轧管订单管坯内控标准
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject saveZgMsGpIc(ArrayList<PlnOrderZgSEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ArrayList<String> message = new ArrayList<String>();
			for (PlnOrderZgSEntity zgSentity : list) {
				String sqlUp = "";
				PreparedStatement ps = null;
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSentity.getProPlanId());
				ps.setObject(2, zgSentity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				if (!rs.next()) {
					message.add("未找到订单" + zgSentity.getProPlanId() + "/"
							+ zgSentity.getGxPlanNo() + "，请刷新数据。");
					continue;
				}
				//TZH 24.8.27 取消坯料需求申报的处理
//				if (rs.getString("GPREQ_ID") != null
//						&& !rs.getString("GPREQ_ID").equals("")) {
//					message.add("订单" + zgSentity.getProPlanId() + "/"
//							+ zgSentity.getGxPlanNo() + "已组坯料需求，不能再修改。");
//					continue;
//				}
				rs.close();
				ps.close();

				// sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.selectGpIcList");
				// ps = conn.prepareStatement(sql);
				// ps.setObject(1, zgSentity.getProPlanId());
				// rs = ps.executeQuery();
				// if (rs.next()) {
				// if (rs.getString("CIC") != null) {
				// if (!rs.getString("CIC").equals("")) {
				// String cicGroup = "";
				// String gradeCode = "";
				// PreparedStatement pst = null;
				// String[] groupCic = rs.getString("CIC").split(",");
				// String sqlc = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.screenCicByGrade");
				// if (rs.getString("GRADECODE") != null) {
				// gradeCode = rs.getString("GRADECODE");
				// }
				// List<String> tmp = new ArrayList<String>();
				// for (String str : groupCic) {
				// if (str != null && str.length() != 0) {
				// tmp.add(str.trim());
				// }
				// }
				// groupCic = tmp.toArray(new String[0]);
				// sqlc +=" AND INSTR(T.GRADECODE,'"+gradeCode+"') > 0";
				// sqlc += CoreConverter.toSqlConditionString("T.CIC",
				// groupCic);
				// pst = conn.prepareStatement(sqlc);
				// // pst.setObject(1, gradeCode);
				// ResultSet rst = pst.executeQuery();
				// while (rst.next()) {
				// if (rst.getString("CIC") != null) {
				// cicGroup += rst.getString("CIC") + ",";
				// }
				// }
				// if (!cicGroup.equals("") && cicGroup.contains(",")) {
				// cicGroup = cicGroup.substring(0, cicGroup
				// .length() - 1);
				// }
				// zgSentity.setCicGroupGp(cicGroup);
				// rst.close();
				// pst.close();
				// }
				// }
				// if (rs.getString("PIC") != null) {
				// zgSentity.setPicGroupGp(rs.getString("PIC"));
				// }
				// if (rs.getString("SIC") != null) {
				// zgSentity.setSicGroupGp(rs.getString("SIC"));
				// }
				// if (rs.getString("DIC") != null) {
				// zgSentity.setDicGroupGp(rs.getString("DIC"));
				// }
				// if (rs.getString("WIC") != null) {
				// zgSentity.setWicGroupGp(rs.getString("WIC"));
				// }
				// if (rs.getString("GIC") != null) {
				// zgSentity.setGicGroupGp(rs.getString("GIC"));
				// }
				// }
				// rs.close();
				// ps.close();

				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.saveZgMsGpIc");
				sqlUp = EntityTool.fillSqlByEntity(sql, zgSentity);
				ps = conn.prepareStatement(sqlUp);
				ps.executeUpdate();
				ps.close();

				conn.commit();
			}
			cro.setResult(EntityTool.getGsonByEntity(message));
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 获取轧管订单排产信息
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject getMergerGroup(ArrayList<PlnOrderZgSEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = null;
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectZgStoGp");
			ArrayList<PlnZgSToGpEntity> listReq = new ArrayList<PlnZgSToGpEntity>();
			for (PlnOrderZgSEntity zgSEntity : list) {
				PlnZgSToGpEntity zgStoGp = null;
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				zgStoGp = EntityTool.getEntityByRs(rs, PlnZgSToGpEntity.class);
				if (zgStoGp == null) {
					zgStoGp = new PlnZgSToGpEntity();
					zgStoGp.setSucceed(-1);
					zgStoGp.setReason("未找到订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "的信息。");
				} else if (rs.getString("EXE_STATUS") != null
						&& !rs.getString("EXE_STATUS").trim().equals("0")) {
					zgStoGp.setSucceed(-1);
					zgStoGp.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "不在计划状态。");
				} else if (rs.getString("GPREQ_ID") != null
						&& !rs.getString("GPREQ_ID").trim().equals("")) {
					zgStoGp.setSucceed(-1);
					zgStoGp.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "已组管坯需求。");
				} else if (rs.getInt("OUTNUM_CUT") <= 0) {
					zgStoGp.setSucceed(-1);
					zgStoGp.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "单坯分切数有误。");
				} else if (rs.getString("CIC_GP") == null
						|| rs.getString("CIC_GP").trim().equals("")) {
					zgStoGp.setSucceed(-1);
					zgStoGp.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "的管坯成分标准索引项不能为空。");
				}
				rs.close();
				ps.close();
				if (zgStoGp.getOutsStlPipeFl() != null) {
					if (zgStoGp.getOutsStlPipeFl().equals("121902")
							|| zgStoGp.getOutsStlPipeFl().equals("121903")) {
						zgStoGp.setSucceed(-1);
						zgStoGp.setReason("订单" + zgSEntity.getProPlanId() + "/"
								+ zgSEntity.getGxPlanNo() + "的是外购管,不能生成管坯需求。");
					}
				}

				zgStoGp.setReallNum(zgSEntity.getReallNum());
				zgStoGp.setReallWt(zgSEntity.getReallWt());
				zgStoGp.setReallWtMin(zgSEntity.getReallWtMin());
				if(zgStoGp.getPlineCode().equals("C072"))
				{
					zgStoGp.setSupplyUnitCode("120504");
					zgStoGp.setSupplyUnit("江苏天淮钢管有限公司");
				}else
				{
					zgStoGp.setSupplyUnitCode("120501");
					zgStoGp.setSupplyUnit("天津钢管制造有限公司");
				}
				listReq.add(zgStoGp);
			}
			cro.setResult(EntityTool.getGsonByEntity(listReq));
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询钢种优先级是否大于等于100
	 * 
	 * @param con
	 * @param gradCode
	 * @return
	 * @throws SQLException
	 */
	public String getgradCodePir(Connection con, String gradCode,
			String desginKey, String mscPline) throws SQLException {
		String gradPri = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updateGradCodePri");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, desginKey);
		ps.setObject(2, mscPline);
		ps.setObject(3, gradCode);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			gradPri = rs.getString("PRIORITY");
		}
		rs.close();
		ps.close();
		return gradPri;
	}

	/**
	 * 查询监制工序点
	 */
	public static String getMonitorPoint(Connection con, String prdcrNo,
			String mscPline, String prcossCode) throws SQLException {
		String monitPoint = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.getMonitorPoint");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, prdcrNo);
		ps.setObject(2, mscPline);
		ps.setObject(3, prcossCode);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			monitPoint = rs.getString("STATION_DESC");
		}
		rs.close();
		ps.close();
		return monitPoint;
	}

	public String sendGpReqInf(PlnReqinfGpEntity gpReqEntity) {
		String Result = "";
		try {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("plan_no", gpReqEntity.getGpreqId());
			jsonObj.put("wall_thickness", "");
			jsonObj.put("product_category_code", gpReqEntity.getDiameterGp());
			jsonObj.put("product_category", "");
			jsonObj.put("outer_diam", "");
			jsonObj.put("length", gpReqEntity.getLenGpSingle());
			jsonObj.put("ruler_length", gpReqEntity.getLengthGp());
			jsonObj.put("gtecstan_no", "");
			jsonObj.put("xtecstan_no", "");
			jsonObj.put("plan_type", gpReqEntity.getRecType());
			jsonObj.put("length_range", "");
			jsonObj.put("controls_thickness", "");
			jsonObj.put("pass", "");
			jsonObj.put("brand", gpReqEntity.getGradename());
			jsonObj.put("head_tail_length", gpReqEntity.getCutLoseLen());
			jsonObj.put("contract_lengt", gpReqEntity.getLengthZz());
			jsonObj.put("contracted_quantity", "");
			jsonObj.put("quantity_purchased", gpReqEntity.getGpWeight());
			jsonObj.put("delivery_status", "");
			jsonObj.put("section", gpReqEntity.getDiameterGp());//TZH 新增断面/坯料直径
			jsonObj.put("contract_buyer", gpReqEntity.getBuyplanWtLong());
			jsonObj.put("delivery_data", "");
			jsonObj.put("product_contract_nonumber", gpReqEntity.getOrderNo());
			jsonObj.put("product_contract_no_num", gpReqEntity.getOrderSeq());
			jsonObj.put("flag", "I"); //TZH 新增状态
			DefaultWebServiceRequest request = new DefaultWebServiceRequest();
			request.setMsgBody(jsonObj.toString());
			request.setServiceId("MESTHPO01");
			Object[] values = new Object[2];
			values[0] = "{\"KEY\":"+jsonObj.toString()+"}";
			Result  = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx", request,
					"receiveMessage","");	
			return Result+values[0].toString().substring(0, 100);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	//新增删除接口 TZH 24.9.15
	public String sendGpReqInD(String sendGpReqInd) {
		String Result = "";
		try {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("plan_no", sendGpReqInd);
			jsonObj.put("wall_thickness", "");
			jsonObj.put("product_category_code", "");
			jsonObj.put("product_category", "");
			jsonObj.put("outer_diam", "");
			jsonObj.put("length", "");
			jsonObj.put("ruler_length", "");
			jsonObj.put("gtecstan_no", "");
			jsonObj.put("xtecstan_no", "");
			jsonObj.put("plan_type", "");
			jsonObj.put("length_range", "");
			jsonObj.put("controls_thickness", "");
			jsonObj.put("pass", "");
			jsonObj.put("brand", "");
			jsonObj.put("head_tail_length", "");
			jsonObj.put("contract_lengt", "");
			jsonObj.put("contracted_quantity", "");
			jsonObj.put("quantity_purchased", "");
			jsonObj.put("delivery_status", "");
			jsonObj.put("section", "");//TZH 新增断面/坯料直径
			jsonObj.put("contract_buyer", "");
			jsonObj.put("delivery_data", "");
			jsonObj.put("product_contract_nonumber", "");
			jsonObj.put("product_contract_no_num", "");
			jsonObj.put("flag", "D"); //TZH 新增状态
			DefaultWebServiceRequest request = new DefaultWebServiceRequest();
			request.setMsgBody(jsonObj.toString());
			request.setServiceId("MESTHPO01");
			Object[] values = new Object[2];
			values[0] = "{\"KEY\":"+jsonObj.toString()+"}";
			Result  = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx", request,
					"receiveMessage","");	
			return Result+values[0].toString().substring(0, 100);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}
	/**
	 * 新增一条管坯需求
	 * 
	 * @param gpReqEntity
	 * @param listZgMs
	 * @return
	 */
	public CoreReturnObject addGpReqInf(PlnReqinfGpEntity gpReqEntity,
			ArrayList<PlnZgSToGpEntity> listZgMs, String outbuy) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			String message = "";
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			String nowTime = "";
			// 查询数据库服务器当前时间
			String sqlTime = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.selectSystemTime");
			PreparedStatement psta1 = conn.prepareStatement(sqlTime);
			ResultSet rs1 = psta1.executeQuery();
			if (rs1.next()) {
				nowTime = rs1.getString("DATIME").substring(0, 7);
			}
			rs1.close();
			psta1.close();
			if (listZgMs.size() == 0) {
				message = "管坯合并轧管订单数至少一条。";
				cro.setResult(message);
				return cro;
			}

			String[] errMessage = new String[1];
			PreparedStatement pst = null;
			PlnZgSToGpEntity zgMs = listZgMs.get(0);

			String wholeBacklog = "";
			String desginKey = "";
			String mscPline = "";
			String sqlAdd = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.addGpReqinf");
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateZgMsGpReqId");
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectZgMsPreviousGx");
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setObject(1, zgMs.getProPlanId());
			ps.setObject(2, zgMs.getGxPlanNo());
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				desginKey = rs.getString("DESGIN_KEY");
				mscPline = rs.getString("MSC_PLINE");
				wholeBacklog = rs.getString("WHOLE_BACKLOG");
				double diameterGp = 0;
				double lenGpsin = 0;
				// int numAfterCut = 0;// 管坯切后支数
				// numAfterCut = Integer.parseInt(gpReqEntity.getGpNum());
				diameterGp = Double.parseDouble(gpReqEntity.getDiameterGp());
				lenGpsin = Double.parseDouble(gpReqEntity.getLenGpSingle());
				if (lenGpsin == 0) {
					message = "轧管订单" + zgMs.getProPlanId() + "/"
							+ zgMs.getGxPlanNo() + "单倍坯长有误，请核对订单信息。";
					cro.setResult(message);
					return cro;
				}
				if (diameterGp == 0) {
					message = "轧管订单" + zgMs.getProPlanId() + "/"
							+ zgMs.getGxPlanNo() + ",管坯直径有误，请核对信息。";
					cro.setResult(message);
					return cro;
				}
				if (rs.getString("BOM").equals("")) {
					message = "轧管订单" + zgMs.getProPlanId() + "/"
							+ zgMs.getGxPlanNo() + ",Bom为空。";
					cro.setResult(message);
					return cro;
				}
				gpReqEntity.setWlidZz(rs.getString("B_OUT_MATERIAL_NO"));
				gpReqEntity.setWldescZz(rs.getString("B_OUT_MATERIAL_DESC"));
				// 查询钢种优先级是否大于等于100
				String gradPriority = getgradCodePir(conn, zgMs.getGradecode(),
						desginKey, mscPline);
				if (!gradPriority.equals("")
						&& Integer.parseInt(gradPriority) >= 100) {
					message = "轧管订单" + zgMs.getProPlanId() + "/"
							+ zgMs.getGxPlanNo()
							+ ",钢种优先级大于等于100是利库钢种，不能生成管坯需求";
					cro.setResult(message);
					return cro;
				}
			} else {
				message = "轧管订单" + zgMs.getProPlanId() + "/"
						+ zgMs.getGxPlanNo() + "未找到炼钢工序。";
				cro.setResult(message);
				return cro;
			}
			rs.close();
			ps.close();

			String gpReqIdQ = "";
			// 查询是否有相同数据 合并（单倍坯长,投入物料,钢种索引码,外购自炼,监制工序点,炼钢、铸造、锻造 制程一致）
			String sqlGp = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectPlnReqinfP");
			// 理华
			if (zgMs.getPicGp() == null || zgMs.getPicGp().equals("")) {
				sqlGp += " AND T.PIC IS NULL";
			} else {
				sqlGp += " AND T.PIC='" + zgMs.getPicGp() + "'";
			}
			// 公差
			if (zgMs.getSicGp() == null || zgMs.getSicGp().equals("")) {
				sqlGp += " AND T.SIC IS NULL";
			} else {
				sqlGp += " AND T.SIC='" + zgMs.getSicGp() + "'";
			}
			// 真空处理
			if (zgMs.getStationRoadLg() == null
					|| zgMs.getStationRoadLg().equals("")) {
				sqlGp += " AND T.STATION_ROAD_LG IS NULL";
			} else {
				sqlGp += " AND T.STATION_ROAD_LG='" + zgMs.getStationRoadLg()
						+ "'";
			}
			if (outbuy.equals("自炼")) {
				sql += " AND T.GOWHERE_NAME='" + zgMs.getGowhereName() + "'";
			}
			sql += " AND T.GRADECODE='" + zgMs.getGradecode() + "'";
			ps = conn.prepareStatement(sqlGp);
			ps.setObject(1, zgMs.getCicGp());
			ps.setObject(2, zgMs.getLenGpSingle());
			ps.setObject(3, zgMs.getInwlId());
			ps.setObject(4, zgMs.getIfMonitorLg());
			ps.setObject(5, zgMs.getIfbuyplan());
			ps.setObject(6, zgMs.getProcess());
			rs = ps.executeQuery();
			if (rs.next()) {
				gpReqIdQ = rs.getString("GPREQ_ID");
			}
			rs.close();
			ps.close();

			gpReqEntity.setProMonth(nowTime);
	
			// 判定是铸造还是锻造工序
			if (!wholeBacklog.contains("C")) {
				// 铸造
				gpReqEntity.setGptype("1");
				gpReqEntity.setCastingtype("1");
				if (!CoreLenMsGp.getZzCuttolen(conn, gpReqEntity, errMessage,
						zgMs.getPlineCode(), desginKey, mscPline)) {
					cro.setResult(errMessage[0]);
					return cro;
				}
				int numDb = 0;
				double wtDb = 0;
				double greqNum = 0;
				double greqWt = 0;
				for (PlnZgSToGpEntity zgMsEntity : listZgMs) {
					greqNum += Double.parseDouble(zgMsEntity.getGpreqNum());
					greqWt += Double.parseDouble(zgMsEntity.getGpreqWeight());
				}
				int num = (int) Math.ceil(greqNum
						/ Integer.parseInt(gpReqEntity.getCutNumGp()));
				numDb = num;
				double dbWtSing = greqWt / greqNum;
				wtDb = num * dbWtSing;
				int gpNumLong =num;
				int gpNumMin = (int) Math.ceil(Double.parseDouble(gpReqEntity
						.getGpWeightMin())
						/ Double.parseDouble(gpReqEntity.getWtOneZz()));
				// 倍尺需坯吨=倍尺需坯支*倍尺坯单支重
				double gpWtLong = gpNumLong
						* Double.parseDouble(gpReqEntity.getWtOneZz());
				gpReqEntity.setGpNumLong(String.valueOf(gpNumLong));
				gpReqEntity.setGpWtLong(String.valueOf(CoreLenMsGp
						.intThe(gpWtLong)));
				gpReqEntity.setOutWtZz(String.valueOf(CoreLenMsGp
						.intThe(gpWtLong)));
				gpReqEntity.setOutNumZz(String.valueOf(gpNumLong));
				double gpWtLongMin = gpNumMin * Double.parseDouble(gpReqEntity.getWtOneZz());
				gpReqEntity.setWlidZz(gpReqEntity.getMaterialNo());
				gpReqEntity.setWldescZz(gpReqEntity.getMaterialName());
				gpReqEntity.setInwlIsokDz("2");
				gpReqEntity.setGpWtLongMin(String.valueOf(CoreLenMsGp.intThe(gpWtLongMin)));
			} else {
				// 锻造
				PreparedStatement psta = null;
				gpReqEntity.setGptype("2");
				String processCodeC = "";
				// 锻造推铸造
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectMscPlProc");
				psta = conn.prepareStatement(sql);
				psta.setObject(1, desginKey);
				psta.setObject(2, mscPline);
				psta.setObject(3, "B");
				ResultSet rsta = psta.executeQuery();
				if (rsta.next()) {
					if (rsta.getString("PROCESS_CODE_C") == null) {
						message = "轧管订单" + zgMs.getProPlanId() + "/"
								+ zgMs.getGxPlanNo() + "未找到铸造二级工序。";
						cro.setResult(message);
						return cro;
					} else {
						processCodeC = rsta.getString("PROCESS_CODE_C");
					}
				}
				rsta.close();
				psta.close();
				if (processCodeC.trim().equals("B002")) {
					// 连铸
					gpReqEntity.setCastingtype("1");
					gpReqEntity.setInwlIsokDz("0");
					if (!CoreLenMsGp.getCuttolen(conn, gpReqEntity, errMessage,
							zgMs.getPlineCode(), desginKey, mscPline)) {
						cro.setResult(errMessage[0]);
						return cro;
					}
				} else if (processCodeC.trim().equals("B003")) {
					// 模铸
					gpReqEntity.setCastingtype("2");
					gpReqEntity.setInwlIsokDz("0");
					if (!CoreLenMsGp.getSpindle(conn, gpReqEntity, errMessage,
							zgMs.getPlineCode(), desginKey, mscPline)) {
						cro.setResult(errMessage[0]);
						return cro;
					}
				}
			}

			if (!gpReqIdQ.equals("")) {

				gpReqEntity.setGpreqId(gpReqIdQ);
				String sqlupdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updateGpReqinfDzAdd");
				String sqlUp = EntityTool.fillSqlByEntity(sqlupdate,
						gpReqEntity);
				pst = conn.prepareStatement(sqlUp);
				pst.executeUpdate();
				pst.close();

				for (PlnZgSToGpEntity zgMsEntity : listZgMs) {
					zgMsEntity.setGpreqId(gpReqIdQ);
					sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, zgMsEntity);
					pst = conn.prepareStatement(sqlUp);
					pst.executeUpdate();
					pst.close();
				}
			} else {
				String gpreq = "";
				if (wholeBacklog.contains("C")) { // 锻造
					// 管坯需求规则
					gpreq = "DP_Z";
					gpReqEntity.setReqDonestatus("0");
					if (gpReqEntity.getIfbuyplan().equals("1")) {
						gpreq = "DP_W";
						gpReqEntity.setReqDonestatus("1");
					}
				} else { // 铸造
					gpreq = "GP_Z";
					gpReqEntity.setReqDonestatus("0");
					if (gpReqEntity.getIfbuyplan().equals("1")) {
						gpreq = "GP_W";
						gpReqEntity.setReqDonestatus("1");
					}
				}
				// 获取管坯需求号
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.getGpReqinfId");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, gpreq);
				ps.setObject(2, gpReqEntity.getIfbuyplan());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getString("GPREQ_ID") != null) {
						String gpReqId = rs.getString("GPREQ_ID");
						gpReqEntity.setGpreqId(gpReqId);

						String sqlUp = EntityTool.fillSqlByEntity(sqlAdd,
								gpReqEntity);
						pst = conn.prepareStatement(sqlUp);
						pst.setObject(1, zgMs.getProcess());
						pst.executeUpdate();
						pst.close();

						for (PlnZgSToGpEntity zgMsEntity : listZgMs) {
							zgMsEntity.setGpreqId(gpReqId);
							sqlUp = EntityTool.fillSqlByEntity(sqlUpdate,
									zgMsEntity);
							pst = conn.prepareStatement(sqlUp);
							pst.executeUpdate();
							pst.close();
						}
					} else {
						message = "生产管坯需求编号出错！。";
						cro.setResult(message);
						return cro;
					}
				} else {
					message = "生产管坯需求编号出错！。";
					cro.setResult(message);
					return cro;
				}
				rs.close();
				ps.close();

			}
			if (gpReqEntity.getIfbuyplan().equals("0")) {// 自炼
				if (!wholeBacklog.contains("C")) { // 不经过锻造直接生产铸造订单
					String plineCodeMay = "";
					String plineNameMay = "";
					String sqlAddZz = "";
					String sqlAddCast = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.addPlnGxCastM");
					PlnGxCastMEntity gxCastMEntity = new PlnGxCastMEntity();
					// 管坯是铸坯，新增连铸坯订单

					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectProcessBPline1");
					sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, gpReqEntity.getGradecode());
					ps.setObject(2, gpReqEntity.getMaterialNo());
					rs = ps.executeQuery();
					while (rs.next()) {
						plineCodeMay += rs.getString("PLINE_CODE") + ",";
						plineNameMay += rs.getString("PLINE_NAME") + ",";
					}
					rs.close();
					ps.close();
					if (plineCodeMay.length() > 0 && plineCodeMay.contains(",")) {
						plineCodeMay = plineCodeMay.substring(0,
								plineCodeMay.lastIndexOf(","));
					}
					if (plineNameMay.length() > 0 && plineNameMay.contains(",")) {
						plineNameMay = plineNameMay.substring(0,
								plineNameMay.lastIndexOf(","));
					}
					if (!plineCodeMay.equals("")) {
						String[] strs = plineCodeMay.split(",");
						gxCastMEntity.setPlineCode(strs[0].toString().trim());
					}
					if (!plineNameMay.equals("")) {
						String[] strs = plineNameMay.split(",");
						gxCastMEntity.setPlineName(strs[0].toString().trim());
					}
					gxCastMEntity.setProPlanId(gpReqEntity.getGpreqId());
					gxCastMEntity.setGptype("1");
					gxCastMEntity.setCastingtype("1");
					gxCastMEntity.setPlineCodeMay(plineCodeMay);
					gxCastMEntity.setPlineNameMay(plineNameMay);
					gxCastMEntity.setGradecode(gpReqEntity.getGradecode());
					gxCastMEntity.setGradename(gpReqEntity.getGradename());
					// if(gpReqEntity.getCastingtype().equals("1")){//连铸
					gxCastMEntity.setDiameterLz(gpReqEntity.getDiameterZz());
					// }else{
					// gxCastMEntity.setDiameterLz(gpReqEntity.getDiameterZz());
					// }
					gxCastMEntity.setLenGpSingle(gpReqEntity.getLenGpSingle());
					gxCastMEntity.setCutNumGp(gpReqEntity.getCutNumGp());
					gxCastMEntity.setCutLoseLen(gpReqEntity.getCutLoseLen());
					gxCastMEntity.setLengthLz(String.valueOf(Double
							.parseDouble(gpReqEntity.getLengthZz()) * 1000));
					gxCastMEntity.setMaterialNo(gpReqEntity.getMaterialNo());
					gxCastMEntity
							.setMaterialName(gpReqEntity.getMaterialName());
					gxCastMEntity.setCic(gpReqEntity.getCic());
					gxCastMEntity.setPic(gpReqEntity.getPic());
					gxCastMEntity.setSic(gpReqEntity.getSic());
					gxCastMEntity.setDic(gpReqEntity.getDic());
					gxCastMEntity.setWic(gpReqEntity.getWic());
					gxCastMEntity.setGic(gpReqEntity.getGic());
					gxCastMEntity.setIfMonitorLg(gpReqEntity.getIfMonitorLg());
					gxCastMEntity.setPrdcrNo(gpReqEntity.getPrdcrNo());
					// 查询炼钢监制点
					String monitPoint = getMonitorPoint(conn,
							gpReqEntity.getPrdcrNo(), mscPline, "A");
					gxCastMEntity.setMonitorPoint(monitPoint);
					gxCastMEntity.setWtCastOne(gpReqEntity.getWtOneZz());
					gxCastMEntity.setPlanWt(gpReqEntity.getOutWtZz());
					gxCastMEntity.setPlanNum(gpReqEntity.getOutNumZz());
					gxCastMEntity.setReqStatus("1");
					gxCastMEntity.setCreateName(gpReqEntity.getCreateName());
					gxCastMEntity.setCreateTime(gpReqEntity.getCreateTime());
					sqlAddZz = EntityTool.fillSqlByEntity(sqlAddCast,
							gxCastMEntity);
					ps = conn.prepareStatement(sqlAddZz);
					ps.executeUpdate();
					ps.close();

					CorePlnOrdProUseTime cuseTime = new CorePlnOrdProUseTime();
					// 工序排产
					if (cuseTime.addOrderCastS(conn, gpReqEntity.getGpreqId(),
							gpReqEntity.getCreateName(),
							gpReqEntity.getProMonth(),
							gpReqEntity.getCreateTime(),
							gpReqEntity.getPlineCodeZz(),
							gpReqEntity.getPlineNameZz(),
							gpReqEntity.getGpWtLongMin(),
							gpReqEntity.getGowhereCode(),
							gpReqEntity.getGowhereName())) {

					} else {
						cro.setResult(cuseTime.getVerrMsg());
						return cro;
					}

					// 修改轧管排产表管坯确认状态
					String sqlUpdatePln = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.updatePlnOrderZgGpStart");
					ps = conn.prepareStatement(sqlUpdatePln);
					ps.setObject(1, "1");
					ps.setObject(2, gpReqEntity.getGpreqId());
					ps.executeUpdate();
					ps.close();
					gpReqEntity.setReqDonestatus("1");
					gpReqEntity.setIssuedMan(gpReqEntity.getCreateName());
					gpReqEntity.setIssuedTime(gpReqEntity.getCreateTime());
					// 回写管坯需求状态
					String sqlUpGp = EntityTool
							.fillSqlByEntity(
									CoreXmlSqlParsersFactory
											.getSql("CorePlnZgMStoGp.updateReqinfGpConfirm"),
									gpReqEntity);
					ps = conn.prepareStatement(sqlUpGp);
					ps.setObject(1, "");
					ps.executeUpdate();
					ps.close();
				}
			} else {
				// 修改轧管排产表管坯确认状态
				String sqlUpdatePln = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatePlnOrderZgGpStart");
				ps = conn.prepareStatement(sqlUpdatePln);
				ps.setObject(1, "1");
				ps.setObject(2, gpReqEntity.getGpreqId());
				ps.executeUpdate();
				ps.close();
				gpReqEntity.setReqDonestatus("1");
				// 回写管坯需求状态
				gpReqEntity.setInwlIsokDz("2");
				String sqlUpGp = EntityTool
						.fillSqlByEntity(
								CoreXmlSqlParsersFactory
										.getSql("CorePlnZgMStoGp.updateReqinfGpConfirm"),
								gpReqEntity);
				ps = conn.prepareStatement(sqlUpGp);
				ps.setObject(1, "0");
				ps.executeUpdate();
				ps.close();
			}
			//日量这个家伙没写注释，24。7.19 tzh 采购坯料需求接口   接口编码 MESTHPO01
            sendGpReqInf(gpReqEntity);
			conn.commit();
			
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 预排Excel导入
	 * @return
	 */
	public CoreReturnObject addWalktHroughExcel(ArrayList<ArrayList<String>> lists,
										   String outsBilletFl,String custom) {
		CoreReturnObject cro = new CoreReturnObject();
		try {
			int success = 0;
			int fail = 0;
			String msg ="";
			StringBuffer stringBuffer = new StringBuffer();
			for (ArrayList<String> list : lists) {
				try {
					CoreReturnObject returnObject = addWalktHrough(list, outsBilletFl, custom);
					if("保存成功!".equals(returnObject.getV_errMsg())){
						success++;
					} else{
						fail++;
						stringBuffer.append("钢种：" + list.get(2) + "："+returnObject.getV_errMsg());
					}
				} catch (Exception e) {
					fail++;
				}
			}
			msg += "导入成功" +success+"条";
			if(fail > 0){
				msg += "，导入失败" + fail+ "条！";
				msg += "失败原因：" +stringBuffer.toString();
			}
			cro.setV_errCode(0);
			cro.setV_errMsg(msg);
		} catch (Exception e){
			cro.setV_errCode(-1);
			cro.setV_errMsg("Excel导入失败！");
		}
		return cro;
	}
	/**
	 * 新增预排
	 * 
	 * @param
	 * @param
	 * @return
	 */
	public CoreReturnObject addWalktHrough(ArrayList<String> list,
			String outsBilletFl,String custom) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement pst = null;
			DateFormat df = new SimpleDateFormat("yyyy-MM");
			Date time = new Date();
			String proMonth = df.format(time);
			PlnReqinfGpEntity gpReqEntity = new PlnReqinfGpEntity();

			String ifbuyplan = outsBilletFl;// 外购，自炼
			String gptype = list.get(0);// 管坯类型
			String gradecode = list.get(1);// 钢种代码
			String gradename = list.get(2);// 钢种
			String cic = list.get(3);// 钢种索引码
			String lenGpSingle = list.get(5);// 单倍坯长
			String diameterGp = list.get(4);// 断面
			String gpWtLong = list.get(6);// 需求量
			String gpReqId = "";
			String createName = list.get(7);
			String createTime = list.get(8);
			String isDear = list.get(9);//坯料用途
			String lengthGp = list.get(10);//管坯长度
			String cutNumGp = list.get(11);//倍尺数
			String gperId = "";
			String messg = "";
			String supplyCode = "";
			String supplyName= "";
			if (ifbuyplan.equals("1")) {
				if (gptype.equals("2")) { // 铸坯
					gperId = "DP_W";
				} else {
					gperId = "GP_W";
				}
				messg = "外购";
				gpReqEntity.setIssuedMan(createName);
				gpReqEntity.setIssuedTime(createTime);
				gpReqEntity.setReqStatus("0");
			} else {
				if (gptype.equals("2")) { // 铸坯
					gperId = "DP_Z";
				} else {
					gperId = "GP_Z";
				}
				messg = "自炼";
				gpReqEntity.setReqStatus("");
			}
			if(custom.equals("1"))
			{
				supplyCode = "120501";
				supplyName = "天津钢管制造有限公司";
			}else if(custom.equals("2"))
			{
				supplyCode = "120504";
				supplyName = "江苏天淮钢管有限公司";
			}
			gpReqEntity.setSupplyUnitCode(supplyCode);
			gpReqEntity.setSupplyUnit(supplyName);
			// 管坯需求规则
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.getGpReqinfId");
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setObject(1, gperId);
			ps.setObject(2, ifbuyplan);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				if (rs.getString("GPREQ_ID") != null) {
					gpReqId = rs.getString("GPREQ_ID");
				}
			}
			rs.close();
			ps.close();
			String specCode = "";
			String specName = "";
			// 可选产线
			String plineCodeMay = "";
			String plineNameMay = "";

			String plineCode = "";
			String plineName = "";
			if (gptype.equals("2")) {
				// 锻坯
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectSpecDimater");
				sql += "  AND T.DIMATER = TO_NUMBER(?) ";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, diameterGp);
				rs = ps.executeQuery();
				if (rs.next()) {
					specCode = rs.getString("SPEC_CODE");
					specName = rs.getString("SPEC_NAME");
				}
				rs.close();
				ps.close();
				if (!specCode.equals("")) {
					gpReqEntity.setMaterialNo("PB" + specCode + gradecode);
					gpReqEntity.setMaterialName("PB" + specName + ","
							+ gradename);
				}
				// // 管坯是锻造
				// sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.selectProcessCPline1");
				// if (ifbuyplan.equals("1")) {
				// sql += " AND T.PLINE_CODE ='C064'";
				// }
				// else {
				// sql += " AND T.PLINE_CODE NOT IN ('C064')";
				// }
				// sql += " ORDER BY T.PLINE_LEVEL ASC, T.PLINE_CODE ASC";
				// ps = conn.prepareStatement(sql);
				// ps.setObject(1, gpReqEntity.getGradecode());
				// ps.setObject(2, gpReqEntity.getMaterialNo());
				// rs = ps.executeQuery();
				// while (rs.next()) {
				// plineCodeMay += rs.getString("PLINE_CODE") + ",";
				// plineNameMay += rs.getString("PLINE_NAME") + ",";
				// }
				// rs.close();
				// ps.close();
				// if (plineCodeMay.length() > 0 && plineCodeMay.contains(","))
				// {
				// plineCodeMay = plineCodeMay.substring(0, plineCodeMay
				// .lastIndexOf(","));
				// }
				// else {
				// cro.setV_errMsg("未找到" + messg + "锻造产线!");
				// return cro;
				// }
				// if (plineNameMay.length() > 0 && plineNameMay.contains(","))
				// {
				// plineNameMay = plineNameMay.substring(0, plineNameMay
				// .lastIndexOf(","));
				// }
				// if (!plineCodeMay.equals("")) {
				// String[] strs = plineCodeMay.split(",");
				// plineCode = strs[0].toString().trim();
				// }
				// if (!plineNameMay.equals("")) {
				// String[] strs = plineNameMay.split(",");
				// plineName = strs[0].toString().trim();
				// }
				gpReqEntity.setCastingtype("1");
				gpReqEntity.setInwlIsokDz("0");
				gpReqEntity.setReqDonestatus("1");
				// gpReqEntity.setPlineCodeDz(plineCode);
				// gpReqEntity.setPlineNameDz(plineName);
			} else { // 铸坯
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectSpecDimater");
				sql += "  AND T.DIMATER = TO_NUMBER(?) ";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, diameterGp);
				rs = ps.executeQuery();
				if (rs.next()) {
					specCode = rs.getString("SPEC_CODE");
					specName = rs.getString("SPEC_NAME");
				}
				rs.close();
				ps.close();
				if (!specCode.equals("")) {
					gpReqEntity.setMaterialNo("PA" + specCode + gradecode);
					gpReqEntity.setMaterialName("PA" + specName + ","
							+ gradename);
				}
				// if (ifbuyplan.equals("0")) {
				//
				// }
				gpReqEntity.setCastingtype("1");
				gpReqEntity.setInwlIsokDz("2");
				gpReqEntity.setReqDonestatus("1");
				// gpReqEntity.setIssuedMan(createName);
				// gpReqEntity.setIssuedTime(createTime);
				// gpReqEntity.setProPlanIdZz(gpReqId);

			}
			// 管坯是铸坯，新增连铸坯订单
			if(gptype.equals("2"))
			{
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessBPline2");
				if (ifbuyplan.equals("0")) {
					sql += " AND T.PLINE_CODE NOT IN ('C064')";
				} else {
					sql += " AND T.PLINE_CODE ='C064'";
				}
				ps = conn.prepareStatement(sql);
				ps.setObject(1, gpReqEntity.getMaterialNo());
			}else
			{
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessBPline1");
				if (ifbuyplan.equals("0")) {
					sql += " AND T.PLINE_CODE NOT IN ('C063')";
				} else {
					sql += " AND T.PLINE_CODE ='C063'";
				}
				sql += " ORDER BY T.PLINE_LEVEL ASC, T.PLINE_CODE ASC";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, gradecode);
				ps.setObject(2, gpReqEntity.getMaterialNo());
			}

			rs = ps.executeQuery();
			while (rs.next()) {
				plineCodeMay += rs.getString("PLINE_CODE") + ",";
				plineNameMay += rs.getString("PLINE_NAME") + ",";
			}
			rs.close();
			ps.close();
			if (plineCodeMay.length() > 0 && plineCodeMay.contains(",")) {
				plineCodeMay = plineCodeMay.substring(0,
						plineCodeMay.lastIndexOf(","));
			} else {
				cro.setV_errMsg("未找到" + messg + "铸造产线!");
				return cro;
			}
			if (plineNameMay.length() > 0 && plineNameMay.contains(",")) {
				plineNameMay = plineNameMay.substring(0,
						plineNameMay.lastIndexOf(","));
			}
			if (!plineCodeMay.equals("")) {
				String[] strs = plineCodeMay.split(",");
				plineCode = strs[0].toString().trim();
			}
			if (!plineNameMay.equals("")) {
				String[] strs = plineNameMay.split(",");
				plineName = strs[0].toString().trim();
			}
			gpReqEntity.setPlineCodeZz(plineCode);
			gpReqEntity.setPlineNameZz(plineName);
			gpReqEntity.setGpreqId(gpReqId);
			gpReqEntity.setCic(cic);
			gpReqEntity.setGptype(gptype);
			gpReqEntity.setGradecode(gradecode);
			gpReqEntity.setGradename(gradename);
			gpReqEntity.setLenGpSingle(lenGpSingle);
			gpReqEntity.setDiameterGp(diameterGp);
			gpReqEntity.setGpWtLong(gpWtLong);
			gpReqEntity.setIfbuyplan(ifbuyplan);
			gpReqEntity.setProMonth(proMonth);
			gpReqEntity.setCreateName(createName);
			gpReqEntity.setCreateTime(createTime);
			gpReqEntity.setTypeFlag(isDear);
			gpReqEntity.setLengthGp(lengthGp);
			gpReqEntity.setCutNumGp(cutNumGp);
			if (!gpReqId.equals("")) {
				String sqlAdd = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.addWalktHrough"),
						gpReqEntity);
				pst = conn.prepareStatement(sqlAdd);
				pst.executeUpdate();
				pst.close();
			} else {
				cro.setV_errMsg("生产管坯需求编号出错！。");
				return cro;
			}
			rs.close();
			ps.close();

			if (ifbuyplan.equals("0")) {// 自炼
				if (gptype.equals("1")) { // 不经过锻造直接生产铸造订单
					String sqlAddZz = "";
					String sqlAddCast = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.addPlnGxCastM");
					PlnGxCastMEntity gxCastMEntity = new PlnGxCastMEntity();
					gxCastMEntity.setPlineCode(plineCode);
					gxCastMEntity.setPlineName(plineName);
					gxCastMEntity.setProPlanId(gpReqEntity.getGpreqId());
					gxCastMEntity.setGptype("1");
					gxCastMEntity.setCastingtype("1");
					gxCastMEntity.setPlineCodeMay(plineCodeMay);
					gxCastMEntity.setPlineNameMay(plineNameMay);
					gxCastMEntity.setGradecode(gpReqEntity.getGradecode());
					gxCastMEntity.setGradename(gpReqEntity.getGradename());
					gxCastMEntity.setDiameterLz(gpReqEntity.getDiameterZz());
					gxCastMEntity.setLenGpSingle(gpReqEntity.getLenGpSingle());
					gxCastMEntity.setCutNumGp(gpReqEntity.getCutNumGp());
					gxCastMEntity.setCutLoseLen(gpReqEntity.getCutLoseLen());
					gxCastMEntity.setLengthLz(gpReqEntity.getLengthZz());
					gxCastMEntity.setMaterialNo(gpReqEntity.getMaterialNo());
					gxCastMEntity
							.setMaterialName(gpReqEntity.getMaterialName());
					gxCastMEntity.setCic(gpReqEntity.getCic());
					gxCastMEntity.setPic(gpReqEntity.getPic());
					gxCastMEntity.setSic(gpReqEntity.getSic());
					gxCastMEntity.setDic(gpReqEntity.getDic());
					gxCastMEntity.setWic(gpReqEntity.getWic());
					gxCastMEntity.setGic(gpReqEntity.getGic());
					gxCastMEntity.setIfMonitorLg(gpReqEntity.getIfMonitorLg());
					gxCastMEntity.setPrdcrNo(gpReqEntity.getPrdcrNo());
					gxCastMEntity.setMonitorPoint("");
					gxCastMEntity.setWtCastOne(gpReqEntity.getWtOneZz());
					gxCastMEntity.setPlanWt(gpReqEntity.getOutWtZz());
					gxCastMEntity.setPlanNum(gpReqEntity.getOutNumZz());
					gxCastMEntity.setReqStatus("1");
					gxCastMEntity.setCreateName(gpReqEntity.getCreateName());
					gxCastMEntity.setCreateTime(gpReqEntity.getCreateTime());

					sqlAddZz = EntityTool.fillSqlByEntity(sqlAddCast,
							gxCastMEntity);
					ps = conn.prepareStatement(sqlAddZz);
					ps.executeUpdate();
					ps.close();
					String gpWtMin = "";
					CorePlnOrdProUseTime cuseTime = new CorePlnOrdProUseTime();
					// 工序排产
					if (cuseTime.addOrderCastS(conn, gpReqEntity.getGpreqId(),
							gpReqEntity.getCreateName(),
							gpReqEntity.getProMonth(),
							gpReqEntity.getCreateTime(), plineCode, plineName,
							gpWtMin, gpReqEntity.getGowhereCode(),
							gpReqEntity.getGowhereName())) {
					} else {
						cro.setV_errMsg(cuseTime.getVerrMsg());
						return cro;
					}

				}
			}
			cro.setV_errMsg("保存成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 获取连铸定尺
	 * 
	 * @param conn
	 * @param gpReqEntity
	 * @param message
	 * @return
	 * @throws SQLException
	 */
	public boolean getCuttolen(Connection conn, PlnReqinfGpEntity gpReqEntity,
			String[] message) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "";
		double dzLoseAdd = 20;
		double dzCutHeadEnd = 200;
		double buring = 1;// 烧损(%)
		double blankSinGpWt = 0;
		double diameterGp = 0;
		double lenGpsin = 0;
		double wastDia = 0;
		int cutNum = 0;// 分切数
		int numAfterCut = 0;// 管坯切后支数
		double cuttolength = 0;// 连铸坯定尺（m）
		double diameterZz = 0;
		String specCodeZz = "";// 铸造规格代码
		String specNameZz = "";// 铸造规格
		String outMaterialNo = "";// 产出物料
		String outMaterialNm = "";// 产出物料

		numAfterCut = Integer.parseInt(gpReqEntity.getGpNum());
		diameterGp = Double.parseDouble(gpReqEntity.getDiameterGp());
		lenGpsin = Double.parseDouble(gpReqEntity.getLenGpSingle());
		blankSinGpWt = CoreLenMsGp.getBlankSinGpWt(diameterGp, lenGpsin,
				dzLoseAdd, dzCutHeadEnd);
		if (blankSinGpWt <= 0) {
			message[0] = "单倍尺毛坯重量必须大于零。";
			return false;
		}

		gpReqEntity.setCastingtype("1");
		gpReqEntity.setInwlIsokDz("0");
		gpReqEntity.setDzLoseAdd(String.valueOf(dzLoseAdd));
		gpReqEntity.setDzCutHeadEnd(String.valueOf(dzCutHeadEnd));
		gpReqEntity.setDzBurnLose(String.valueOf(buring));

		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.getMscCastRForg");
		sql += " AND TRIM(T.SPEC_CODE) IS NOT NULL"
				+ " AND S1.DIMATER IS NOT NULL";
		ps = conn.prepareStatement(sql);
		ps.setObject(1, diameterGp);
		rs = ps.executeQuery();
		while (rs.next()) {
			double wastDiaTemp = 0;
			if (rs.getString("DIMATER") == null) {
				continue;
			}
			diameterZz = Double.parseDouble(rs.getString("DIMATER"));
			if (diameterZz < diameterGp) {
				continue;
			}

			wastDiaTemp = diameterZz - diameterGp;
			if (wastDia > wastDiaTemp || wastDia == 0) {
				wastDia = wastDiaTemp;
				cuttolength = getCuttolength(blankSinGpWt, diameterZz, buring);
				specCodeZz = rs.getString("SPEC_CODE");
				if (rs.getString("SPEC_NAME") != null) {
					specNameZz = rs.getString("SPEC_NAME");
				}
			}
		}
		if (specCodeZz.equals("")) {
			message[0] = "未找到合适连铸坯规格。";
			return false;
		}
		rs.close();
		ps.close();

		// 查询默认铸造产线
		outMaterialNo = "PA" + specCodeZz + "," + gpReqEntity.getGradecode();
		outMaterialNm = "PA" + specNameZz + "," + gpReqEntity.getGradename();
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProcessBPline");
		sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
		ps = conn.prepareStatement(sql);
		ps.setObject(1, gpReqEntity.getGradecode());
		ps.setObject(2, outMaterialNo);
		rs = ps.executeQuery();
		if (rs.next()) {
			gpReqEntity.setPlineCodeZz(rs.getString("PLINE_CODE"));
			gpReqEntity.setPlineNameZz(rs.getString("PLINE_NAME"));
			outMaterialNo = rs.getString("OUT_MATERIAL_NO");
			if (rs.getString("OUT_MATERIAL_DESC") != null) {
				outMaterialNm = rs.getString("OUT_MATERIAL_DESC");
			}
		} else {
			message[0] = "未找到合适连铸坯铸造适用产线。";
			return false;
		}
		rs.close();
		ps.close();

		gpReqEntity.setWlidZz(outMaterialNo);
		gpReqEntity.setWldescZz(outMaterialNm);

		// 获取最佳锻造产线
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProcessCPline");
		sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
		ps = conn.prepareStatement(sql);
		ps.setObject(1, gpReqEntity.getWlidZz());
		ps.setObject(2, gpReqEntity.getMaterialNo());
		rs = ps.executeQuery();
		while (rs.next()) {
			int cutNumTemp = 0;
			double lenMax = 0;
			double lenMin = 0;
			double wtofmiLz = CoreOrdBase.GpweightOfmi(diameterZz);
			lenMin = rs.getDouble("LENGTH_MIN") * 1000;
			lenMax = rs.getDouble("LENGTH_MAX") * 1000;
			cutNumTemp = getlenInRange(lenMax, lenMin, lenGpsin);
			if (cutNumTemp <= 0) {
				continue;
			}
			if (cutNum < cutNumTemp || cutNum == 0) {
				double cutLoseLen = 0;// 切损长度(mm)
				double lenGp = 0;// 管坯长度(mm)
				double weightGpOne = 0;// 长坯单重
				int numBeforeCut = 0;// 切前管坯支数
				cutNum = cutNumTemp;
				cutLoseLen = getCutLoseLen(cutNum);
				lenGp = lenGpsin * cutNum + cutLoseLen;
				numBeforeCut = (int) Math.ceil((double) numAfterCut / cutNum);
				weightGpOne = CoreOrdBase.GpweightOfmi(diameterGp) * lenGp
						/ 1000;

				gpReqEntity.setPlineCodeDz(rs.getString("PLINE_CODE"));
				gpReqEntity.setPlineNameDz(rs.getString("PLINE_NAME"));

				gpReqEntity.setCutNumGp(String.valueOf(cutNum));
				gpReqEntity.setWtOneZz(String.valueOf(cutNum * cuttolength
						* wtofmiLz));
				gpReqEntity.setOutNumZz(String.valueOf(numBeforeCut));
				gpReqEntity.setOutWtZz(String.valueOf(numBeforeCut * cutNum
						* cuttolength * wtofmiLz));

				gpReqEntity.setCutLoseLen(String.valueOf(cutLoseLen));
				gpReqEntity.setLengthGp(String.valueOf(lenGp));
				gpReqEntity.setGpNumLong(String.valueOf(numBeforeCut));
				gpReqEntity.setGpWtLong(String.valueOf(numBeforeCut
						* weightGpOne));

				gpReqEntity.setLengthZz(String.valueOf(cutNum * cuttolength));
				gpReqEntity.setDiameterZz(String.valueOf(diameterZz));
			}
		}
		rs.close();
		ps.close();

		return true;
	}

	/**
	 * 修改管坯需求
	 * 
	 * @param listGp
	 * @param userName
	 * @return
	 */
	public CoreReturnObject modifyGp(ArrayList<PlnReqinfGpEntity> listGp,
			String userName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ArrayList<String> message = new ArrayList<String>();
			String sqlQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectReqinfGpStatus");
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateGpReqinfDz");
			String sqlAddCast = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.addPlnGxCastM");
			String sqlAddDp = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.addPlnGxDpM");
			String sqlUpdatecon = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateReqinfGpConfirm");

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date timeissued = new Date();
			String issuedTime = df.format(timeissued);
			for (PlnReqinfGpEntity reqinfGp : listGp) {
				PlnReqinfGpEntity reqinfGpEntity = null;
				ResultSet rs = null;
				PreparedStatement ps = null;
				String sqlUp = "";

				String gpreqId = reqinfGp.getGpreqId();
				ps = conn.prepareStatement(sqlQ);
				ps.setObject(1, reqinfGp.getGpreqId());
				rs = ps.executeQuery();
				reqinfGpEntity = EntityTool.getEntityByRs(rs,
						PlnReqinfGpEntity.class);
				rs.close();
				ps.close();
				if (reqinfGpEntity == null) {
					cro.setV_errMsg("未找到管坯需求：" + reqinfGp.getGpreqId()
							+ "，请刷新。");
					return cro;
				}
				if (reqinfGpEntity.getReqDonestatus().compareTo("0") > 0) {
					cro.setV_errMsg("管坯需求：" + reqinfGpEntity.getGpreqId()
							+ "已经确认,不允许重复确认。");
					return cro;
				}
				if (reqinfGpEntity.getRecType().equals("1")) {// 预排
					cro.setV_errMsg("管坯需求：" + reqinfGpEntity.getGpreqId()
							+ "是预排需求,不允许确认修改。");
					return cro;
				}
				if (reqinfGpEntity.getGptype().equals("1")) {

					return cro;
				}
				String mscPline = "";
				// 查询制程索引号
				String sqlmscPline = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.QueryMscPline");
				ps = conn.prepareStatement(sqlmscPline);
				ps.setObject(1, reqinfGp.getGpreqId());
				ps.setObject(2, reqinfGp.getPrdcrNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					mscPline = rs.getString("INDEX_SEQ");
				}
				rs.close();
				ps.close();

				reqinfGp.setInwlIsokDz(reqinfGpEntity.getInwlIsokDz());
				reqinfGp.setGradecode(reqinfGpEntity.getGradecode());
				double diameterZz = Double
						.parseDouble(reqinfGp.getDiameterZz());
				if (reqinfGpEntity.getCastingtype().equals("1")) {
					String sql = "";
					double diameterGp = 0;// 管坯断面
					double lenGpsin = 0;// 单倍坯长
					int numAfterCut = 0;// 管坯切后支数

					double dzLoseAdd = Double.parseDouble(reqinfGp
							.getDzLoseAdd());
					double dzCutHeadEnd = Double.parseDouble(reqinfGp
							.getDzCutHeadEnd());
					double buring = Double
							.parseDouble(reqinfGp.getDzBurnLose());

					numAfterCut = Integer.parseInt(reqinfGpEntity.getGpNum());
					diameterGp = Double.parseDouble(reqinfGpEntity
							.getDiameterGp());
					lenGpsin = Double.parseDouble(reqinfGpEntity
							.getLenGpSingle());

					// blankSinGpWt = CoreLenMsGp.getBlankSinGpWt(diameterGp,
					// lenGpsin, dzLoseAdd, dzCutHeadEnd);
					// if (blankSinGpWt <= 0) {
					// cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
					// + "的单倍尺毛坯重量必须大于零。");
					// return cro;;
					// }
					// cuttolength = getCuttolength(blankSinGpWt, diameterZz,
					// buring);

					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectProcessBPline1");
					sql += " AND T.PLINE_CODE = '" + reqinfGp.getPlineCodeZz()
							+ "'";
					sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, reqinfGpEntity.getGradecode());
					ps.setObject(2, reqinfGp.getWlidZz());
					rs = ps.executeQuery();
					if (!rs.next()) {
						cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
								+ "的铸造产线不包含" + reqinfGp.getPlineNameZz());
						return cro;
					}
					rs.close();
					ps.close();

					// 获取最佳锻造产线
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectProcessCPline1");
					sql += " AND T.PLINE_CODE = '" + reqinfGp.getPlineCodeDz()
							+ "'";
					sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, reqinfGp.getWlidZz());
					ps.setObject(2, reqinfGpEntity.getMaterialNo());
					rs = ps.executeQuery();
					if (rs.next()) {
						int cutNum = 0;
						double lenMax = 0;
						double lenMin = 0;
						double cutLoseLen = 0;// 切损长度(mm)
						double lenGp = 0;// 管坯长度(mm)
						// lenMin = rs.getDouble("LENGTH_MIN") * 1000;
						// lenMax = rs.getDouble("LENGTH_MAX") * 1000;
						// cutNum = getlenInRange(lenMax, lenMin, lenGpsin);
						// if (cutNum <= 0) {
						// cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
						// + "的锻造产线" + reqinfGp.getPlineNameDz()
						// + "（长度范围：" + lenMin / 1000 + "-" + lenMax
						// / 1000 + "米）" + "无法切出" + lenGpsin / 1000
						// + "米的单倍坯。");
						// return cro;;
						// }

						// 锻造后外径：=轧管截面+锻坯外径加工余量
						double outDiameter = diameterGp + dzLoseAdd;
						//  锻造后单倍坯长：=单倍坯长+锻坯头尾切损长
						double ZzSingle = lenGpsin + dzCutHeadEnd;
						//  锻造后单倍坯重：=7.8*3.1415926* (轧管截面+锻坯外径加工余量)*
						// (轧管截面+锻坯外径加工余量)/4 *
						// (单倍坯长+锻坯头尾切损长)/1000/1000/1000
						double dzSWtLong = 7.8 * Pi * outDiameter
								* (outDiameter / 4) * ZzSingle / 1000 / 1000
								/ 1000;
						// 最佳原料米单重（连铸）
						double lzDiamWtM = CoreOrdBase.GpweightOfmi(diameterZz);
						// 倍尺坯分切长度损失（mm） =（倍尺数-1）*10mm
						cutLoseLen = (cutNum - 1) * 10;
						//  锻造后N倍坯长：=N*单倍坯长+锻坯头尾切损长+（N-1）*10mm
						double dzSingleN = 2 * lenGpsin + dzCutHeadEnd
								+ cutLoseLen;
						//  锻造后N倍坯重：=7.8*3.1415926* (轧管截面+锻坯外径加工余量)*
						// (轧管截面+锻坯外径加工余量)/4 *
						// (N*单倍坯长+(N-1)*10+锻坯头尾切损长)/1000/1000/1000
						double dzSWtLongN = 7.8 * Pi * outDiameter
								* (outDiameter / 4) * dzSingleN / 1000 / 1000
								/ 1000;
						// 400单倍坯长=锻造2单倍坯重/（1-烧损）/原料断面的米单重
						double lzSingle = dzSWtLongN / (1 - buring / 100)
								/ (lzDiamWtM / 1000);
						// 单倍坯重
						double lzDiamWtSingle = dzSWtLongN / (1 - buring / 100);
						// 400的需坯支：轧管需坯支
						// double lzYlGpNum = (int) (numAfterCut / 2);
						int lzYlGpNum = (int) Math.ceil(Double
								.parseDouble(reqinfGpEntity.getGpWeight())
								/ lzDiamWtSingle);
						// 400的需坯吨：400单倍坯重*轧管需坯支
						double lzYlGpWt = lzDiamWtSingle * lzYlGpNum;
						// int gpNumLongMin = (int) Math.ceil(Double
						// .parseDouble(reqinfGpEntity.getGpWeightMin())
						// / Double.parseDouble(reqinfGpEntity
						// .getWeightGpOne()) / 2);
						int gpNumLongMin = (int) Math.ceil(Double
								.parseDouble(reqinfGpEntity.getGpWeightMin())
								/ lzDiamWtSingle);
						double gpWtLongMin = gpNumLongMin * lzDiamWtSingle;
						reqinfGp.setCutNumGp(String.valueOf("1"));// cutNum
						reqinfGp.setWtOneZz(String.valueOf(CoreLenMsGp
								.intThe(lzDiamWtSingle)));
						reqinfGp.setOutNumZz(String.valueOf(lzYlGpNum));
						reqinfGp.setOutWtZz(String.valueOf(CoreLenMsGp
								.intThe(lzYlGpWt)));
						reqinfGp.setCutLoseLen(String.valueOf(cutLoseLen));
						reqinfGp.setLengthGp(String.valueOf(lzSingle));
						reqinfGp.setGpNumLong(String.valueOf(lzYlGpNum));
						reqinfGp.setGpWtLong(String.valueOf(CoreLenMsGp
								.intThe(lzYlGpWt)));
						reqinfGp.setLengthZz(String.valueOf(lzSingle / 1000));
						reqinfGp.setDiameterZz(String.valueOf(diameterZz));
						reqinfGp.setGpWtLongMin(String.valueOf(CoreLenMsGp
								.intThe(gpWtLongMin)));

					} else {
						cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
								+ "的锻造产线不包含" + reqinfGp.getPlineNameDz());
						return cro;
					}
					rs.close();
					ps.close();
				} else {
					String sql = "";
					int cutNum = 0;// 分切数
					double diameterGp = 0;// 管坯断面
					double lenGpsin = 0;// 单倍坯长
					double cutLoseLen = 0;// 切损长度(mm)
					double burning = Double.parseDouble(reqinfGp
							.getDzBurnLose());// 烧损
					double dzLoseAdd = Double.parseDouble(reqinfGp
							.getDzLoseAdd());
					double dzCutHeadEnd = Double.parseDouble(reqinfGp
							.getDzCutHeadEnd());
					diameterGp = Double.parseDouble(reqinfGpEntity
							.getDiameterGp());
					lenGpsin = Double.parseDouble(reqinfGpEntity
							.getLenGpSingle());
					// 验证铸造产线
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectProcessBPline1");
					sql += " AND T.PLINE_CODE = '" + reqinfGp.getPlineCodeZz()
							+ "'";
					sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, reqinfGpEntity.getGradecode());
					ps.setObject(2, reqinfGp.getWlidZz());
					rs = ps.executeQuery();
					if (!rs.next()) {
						// cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
						// + "的铸造产线不包含" + reqinfGp.getPlineNameZz());
						cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
								+ "的铸造产线不能为空");
						return cro;
					}
					rs.close();
					ps.close();

					// blankSinGpWt = CoreLenMsGp.getBlankSinGpWt(diameterGp,
					// lenGpsin, dzLoseAdd, dzCutHeadEnd);
					// if (blankSinGpWt <= 0) {
					// mcro.setV_errMsg"管坯需求：" + reqinfGp.getGpreqId()
					// + "的单倍尺毛坯重量必须大于零。");
					// return cro;;
					// }

					// cutNum = (int) Math.floor(spindleSin / blankSinGpWt);
					// if (cutNum <= 0) {
					// cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId() + " 锭型："
					// + spindleSin + "吨不满足。（单倍尺毛坯重" + blankSinGpWt
					// + "吨）");
					// return cro;;
					// }
					//  锻造后外径：=轧管截面+锻坯外径加工余量
					double outDiameter = diameterGp + dzLoseAdd;
					//  锻造后单倍坯长：=单倍坯长+锻坯头尾切损长
					double ZzSingle = lenGpsin + dzCutHeadEnd;
					//  锻造后单倍坯重：=7.8*3.1415926* (轧管截面+锻坯外径加工余量)*
					// (轧管截面+锻坯外径加工余量)/4 *
					// (单倍坯长+锻坯头尾切损长)/1000/1000/1000
					double dzSWtLong = 7.8 * Pi * outDiameter
							* (outDiameter / 4) * ZzSingle / 1000 / 1000 / 1000;
					double dzSingleN = 0;// 锻造后N倍坯长
					double dzSWtLongN = 0;//  锻造后N倍坯重
					double blankSinGpWt = 0;// 毛坯重量

					// 查询毛坯重量
					String sqlmpWt = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectSpecWt");
					ps = conn.prepareStatement(sqlmpWt);
					ps.setObject(1,
							Double.parseDouble(reqinfGp.getDiameterZz()) * 1000);
					rs = ps.executeQuery();
					if (rs.next()) {
						blankSinGpWt = rs.getDouble("ACTUAL_WEIGHT");
					}
					rs.close();
					ps.close();

					double wastWt = 0;
					// 验证锻造产线
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectProcessCPline1");
					sql += " AND T.PLINE_CODE = '" + reqinfGp.getPlineCodeDz()
							+ "'";
					sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, reqinfGp.getWlidZz());
					ps.setObject(2, reqinfGpEntity.getMaterialNo());
					rs = ps.executeQuery();
					if (rs.next()) {
						// double lenMax = 0;
						// double lenMin = 0;
						// lenMin = rs.getDouble("LENGTH_MIN") * 1000;
						// lenMax = rs.getDouble("LENGTH_MAX") * 1000;
						// if (lenGp < lenMin || lenMax < lenGp) {
						// cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
						// + " 锻造产线：" + reqinfGp.getPlineNameDz()
						// + "长度范围不满足。（" + lenMin / 1000 + "-"
						// + lenMax / 1000 + "米，管坯长度" + lenGp / 1000
						// + "米）");
						// return cro;;
						// }
						int n = 1;
						do {
							//  锻造后N倍坯长：=N*单倍坯长+锻坯头尾切损长+（N-1）*10mm
							dzSingleN = n * lenGpsin + dzCutHeadEnd + (n - 1)
									* 10;
							//  锻造后N倍坯重：=7.8*3.1415926* (轧管截面+锻坯外径加工余量)*
							// (轧管截面+锻坯外径加工余量)/4
							// *
							// (N*单倍坯长+(N-1)*10+锻坯头尾切损长)/1000/1000/1000
							dzSWtLongN = 7.8 * Pi * outDiameter * outDiameter
									/ 4 * dzSingleN / 1000 / 1000 / 1000;

							if (dzSWtLongN <= 10.5) {

								double wastWted = blankSinGpWt
										* (1 - burning / 100) - dzSWtLongN;
								if (wastWt == 0 || wastWted < wastWt
										&& wastWted >= 0) {
									wastWt = wastWted;
									cutNum = n;// 倍尺数
								}

							}
							n++;
						} while (dzSWtLongN <= 10.5);
					} else {
						cro.setV_errMsg("管坯需求：" + reqinfGp.getGpreqId()
								+ " 的锻造产线不包含：" + reqinfGp.getPlineNameDz()
								+ "。");
						return cro;
					}
					rs.close();
					ps.close();

					// 需锭数量= int (单倍坯支数 / 倍尺数+0.85)
					int gpNumLong = (int) Math.ceil(Double
							.parseDouble(reqinfGpEntity.getGpNum()) / cutNum);
					// 需锭吨=需锭数量*毛坯重t
					double gpWtLong = gpNumLong * blankSinGpWt;

					// int gpNumLongMin = (int)
					// (Double.parseDouble(reqinfGpEntity
					// .getGpWeightMin())
					// / Double.parseDouble(reqinfGpEntity
					// .getWeightGpOne()) / cutNum + 0.85);
					int gpNumLongMin = (int) Math
							.floor((Double.parseDouble(reqinfGpEntity
									.getGpNum())
									/ Double.parseDouble(reqinfGpEntity
											.getGpWeight()) * Double
										.parseDouble(reqinfGpEntity
												.getGpWeightMin()))
									/ cutNum);

					double gpWtLongMin = gpNumLongMin * blankSinGpWt;
					// 倍尺坯分切长度损失（mm） =（倍尺数-1）*10mm
					cutLoseLen = (cutNum - 1) * 10;
					dzSingleN = cutNum * lenGpsin + cutLoseLen + dzCutHeadEnd;
					reqinfGp.setCutNumGp(String.valueOf(cutNum));// cutNum
					reqinfGp.setWtOneZz(String.valueOf(CoreLenMsGp
							.intThe(blankSinGpWt)));
					reqinfGp.setOutNumZz(String.valueOf(gpNumLong));
					reqinfGp.setOutWtZz(String.valueOf(CoreLenMsGp
							.intThe(gpWtLong)));
					reqinfGp.setCutLoseLen(String.valueOf(cutLoseLen));
					reqinfGp.setLengthGp(String.valueOf(dzSingleN));
					reqinfGp.setGpNumLong(String.valueOf(gpNumLong));
					reqinfGp.setGpWtLong(String.valueOf(CoreLenMsGp
							.intThe(gpWtLong)));
					reqinfGp.setLengthZz("");
					reqinfGp.setGpWtLongMin(String.valueOf(CoreLenMsGp
							.intThe(gpWtLongMin)));

				}

				sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, reqinfGp);
				ps = conn.prepareStatement(sqlUp);
				ps.executeUpdate();
				ps.close();

				// 再次查询
				ps = conn.prepareStatement(sqlQ);
				ps.setObject(1, reqinfGp.getGpreqId());
				rs = ps.executeQuery();
				reqinfGpEntity = EntityTool.getEntityByRs(rs,
						PlnReqinfGpEntity.class);
				rs.close();
				ps.close();
				// 修改后确认
				reqinfGpEntity.setIssuedMan(userName);
				reqinfGpEntity.setIssuedTime(issuedTime);
				reqinfGpEntity.setReqDonestatus("1");

				// 锻坯
				PlnGxDpMEntity gxDpMEntity = new PlnGxDpMEntity();
				PlnGxCastMEntity gxCastMEntity = new PlnGxCastMEntity();
				String plineCodeMay = "";
				String plineNameMay = "";
				String plineCodeMayZz = "";
				String plineNameMayZz = "";
				String sqlAdd = "";
				// double dimaterGp = 0;// 管坯断面
				// double lenGp = 0;// 管坯长度
				Date nowTime = new Date();
				SimpleDateFormat time = new SimpleDateFormat("yyyy-MM");

				// dimaterGp =
				// Double.parseDouble(reqinfGpEntity.getDiameterGp());
				// lenGp = Double.parseDouble(reqinfGpEntity.getLengthGp());

				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessCPline1");
				sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, reqinfGpEntity.getWlidZz());
				ps.setObject(2, reqinfGpEntity.getMaterialNo());
				rs = ps.executeQuery();
				while (rs.next()) {
					plineCodeMay += rs.getString("PLINE_CODE") + ",";
					plineNameMay += rs.getString("PLINE_NAME") + ",";
				}
				rs.close();
				ps.close();
				if (plineCodeMay.length() > 0 && plineCodeMay.contains(",")) {
					plineCodeMay = plineCodeMay.substring(0,
							plineCodeMay.lastIndexOf(","));
				}
				if (plineNameMay.length() > 0 && plineNameMay.contains(",")) {
					plineNameMay = plineNameMay.substring(0,
							plineNameMay.lastIndexOf(","));
				}
				gxDpMEntity.setProPlanId(gpreqId);
				gxDpMEntity.setPlineCodeMay(plineCodeMay);
				gxDpMEntity.setPlineNameMay(plineNameMay);
				gxDpMEntity.setPlineCode(reqinfGpEntity.getPlineCodeDz());
				gxDpMEntity.setPlineName(reqinfGpEntity.getPlineNameDz());
				gxDpMEntity.setGradecode(reqinfGpEntity.getGradecode());
				gxDpMEntity.setGradename(reqinfGpEntity.getGradename());
				gxDpMEntity.setDiameterOut(reqinfGpEntity.getDiameterGp());
				gxDpMEntity.setLenGpSingle(reqinfGpEntity.getLenGpSingle());
				gxDpMEntity.setCutNumGp(reqinfGpEntity.getCutNumGp());//
				gxDpMEntity.setLengthOut(String.valueOf(Double
						.parseDouble(reqinfGpEntity.getLenGpSingle())));
				gxDpMEntity.setOutwlId(reqinfGpEntity.getMaterialNo());
				gxDpMEntity.setOutwlDesc(reqinfGpEntity.getMaterialName());
				gxDpMEntity.setOutWtOne(String.valueOf((Double
						.parseDouble(reqinfGpEntity.getLenGpSingle()) / 1000)
						* CoreOrdBase.GpweightOfmi(Double
								.parseDouble(reqinfGpEntity.getDiameterGp()))));
				gxDpMEntity.setOutWtTot(reqinfGpEntity.getGpWtLong());
				gxDpMEntity.setOutNumTot(reqinfGpEntity.getGpNumLong());
				gxDpMEntity.setWtOneIn(reqinfGpEntity.getWtOneZz());
				gxDpMEntity.setWlidIn(reqinfGpEntity.getWlidZz());
				gxDpMEntity.setWldescIn(reqinfGpEntity.getWldescZz());
				gxDpMEntity.setInNum(reqinfGpEntity.getOutNumZz());
				gxDpMEntity.setInWt(reqinfGpEntity.getOutWtZz());
				gxDpMEntity.setZzProPlanId(gpreqId);

				// 监制
				gxDpMEntity.setPrdcrNo(reqinfGpEntity.getPrdcrNo());

				// 查询炼钢监制点
				String monitPointdz = getMonitorPoint(conn,
						reqinfGpEntity.getPrdcrNo(), mscPline, "C");
				if (monitPointdz == null || monitPointdz.equals("")) {
					gxDpMEntity.setIfMonitorDz("0");
				} else {
					gxDpMEntity.setIfMonitorDz("1");
				}
				gxDpMEntity.setMonitorPoint(monitPointdz);
				gxDpMEntity.setCic(reqinfGpEntity.getCic());
				gxDpMEntity.setPic(reqinfGpEntity.getPic());
				gxDpMEntity.setSic(reqinfGpEntity.getSic());
				gxDpMEntity.setDic(reqinfGpEntity.getDic());
				gxDpMEntity.setWic(reqinfGpEntity.getWic());
				gxDpMEntity.setGic(reqinfGpEntity.getGic());
				gxDpMEntity.setProMonth(time.format(nowTime));
				gxDpMEntity.setPlanstatus("1");
				gxDpMEntity.setCreateName(userName);
				gxDpMEntity.setCreateTime(issuedTime);
				// 铸造订单
				gxCastMEntity.setProPlanId(gpreqId);
				gxCastMEntity.setGptype("2");

				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessBPline1");
				sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, reqinfGpEntity.getGradecode());
				ps.setObject(2, reqinfGpEntity.getWlidZz());
				rs = ps.executeQuery();
				while (rs.next()) {
					plineCodeMayZz += rs.getString("PLINE_CODE") + ",";
					plineNameMayZz += rs.getString("PLINE_NAME") + ",";
				}
				rs.close();
				ps.close();
				if (plineCodeMayZz.length() > 0 && plineCodeMayZz.contains(",")) {
					plineCodeMayZz = plineCodeMayZz.substring(0,
							plineCodeMayZz.lastIndexOf(","));
				}
				if (plineNameMayZz.length() > 0 && plineNameMayZz.contains(",")) {
					plineNameMayZz = plineNameMayZz.substring(0,
							plineNameMayZz.lastIndexOf(","));
				}
				gxCastMEntity.setPlineCodeMay(plineCodeMayZz);
				gxCastMEntity.setPlineNameMay(plineNameMayZz);
				gxCastMEntity.setGradecode(reqinfGpEntity.getGradecode());
				gxCastMEntity.setGradename(reqinfGpEntity.getGradename());
				gxCastMEntity.setCutNumGp(reqinfGpEntity.getCutNumGp());
				gxCastMEntity.setCutLoseLen(reqinfGpEntity.getCutLoseLen());
				gxCastMEntity.setMaterialNo(reqinfGpEntity.getWlidZz());
				gxCastMEntity.setMaterialName(reqinfGpEntity.getWldescZz());
				gxCastMEntity.setCic(reqinfGpEntity.getCic());
				gxCastMEntity.setPic(reqinfGpEntity.getPic());
				gxCastMEntity.setSic(reqinfGpEntity.getSic());
				gxCastMEntity.setDic(reqinfGpEntity.getDic());
				gxCastMEntity.setWic(reqinfGpEntity.getWic());
				gxCastMEntity.setGic(reqinfGpEntity.getGic());
				gxCastMEntity.setIfMonitorLg(reqinfGpEntity.getIfMonitorLg());
				gxCastMEntity.setPrdcrNo(reqinfGpEntity.getPrdcrNo());
				// 查询炼钢监制点
				String monitPoint = getMonitorPoint(conn,
						reqinfGpEntity.getPrdcrNo(), mscPline, "A");
				gxCastMEntity.setMonitorPoint(monitPoint);
				gxCastMEntity.setWtCastOne(reqinfGpEntity.getWtOneZz());
				gxCastMEntity.setPlanWt(reqinfGpEntity.getGpWtLong());
				gxCastMEntity.setPlanNum(reqinfGpEntity.getGpNumLong());
				gxCastMEntity.setReqStatus("1");
				gxCastMEntity.setCreateName(userName);
				gxCastMEntity.setCreateTime(issuedTime);
				gxCastMEntity.setPlineCode(reqinfGpEntity.getPlineCodeZz());
				gxCastMEntity.setPlineName(reqinfGpEntity.getPlineNameZz());
				if (reqinfGpEntity.getCastingtype().equals("1")) {
					// 连铸
					gxDpMEntity.setCastingtype("1");
					gxDpMEntity.setDiameterIn(reqinfGpEntity.getDiameterZz());
					gxDpMEntity.setLengthIn(String.valueOf(Double
							.parseDouble(reqinfGpEntity.getLengthZz()) * 1000));

					gxCastMEntity.setCastingtype("1");
					gxCastMEntity.setDiameterLz(reqinfGpEntity.getDiameterZz());
					gxCastMEntity.setLengthLz(String.valueOf(Double
							.parseDouble(reqinfGpEntity.getLengthZz()) * 1000));
				} else {
					// 模铸
					gxDpMEntity.setCastingtype("2");
					gxDpMEntity.setDiameterIn(reqinfGpEntity.getDiameterZz()
							+ "t");
					gxDpMEntity.setLengthIn("1");
					gxCastMEntity.setCastingtype("2");
					gxCastMEntity.setDiameterLz(reqinfGpEntity.getDiameterZz());
					gxCastMEntity.setLengthLz("1");
					gxCastMEntity.setLenGpSingle("1");
				}

				// 新增铸造订单
				sqlAdd = EntityTool.fillSqlByEntity(sqlAddCast, gxCastMEntity);
				ps = conn.prepareStatement(sqlAdd);
				ps.executeUpdate();
				ps.close();

				CorePlnOrdProUseTime cuseTime = new CorePlnOrdProUseTime();
				// 工序排产
				if (cuseTime.addOrderCastS(conn, gpreqId, userName,
						reqinfGpEntity.getProMonth(), issuedTime,
						reqinfGpEntity.getPlineCodeZz(),
						reqinfGpEntity.getPlineNameZz(),
						reqinfGpEntity.getGpWtLongMin(),
						reqinfGpEntity.getGowhereCode(),
						reqinfGpEntity.getGowhereName())) {

				} else {
					cro.setV_errMsg(cuseTime.getVerrMsg());
					return cro;
				}

				// 新增锻造订单
				sqlAdd = EntityTool.fillSqlByEntity(sqlAddDp, gxDpMEntity);
				ps = conn.prepareStatement(sqlAdd);
				ps.executeUpdate();
				ps.close();

				// 工序排产
				CorePlnOrdProUseTime.addOrderDzS(conn, gpreqId, reqinfGpEntity,
						userName, issuedTime);

				reqinfGpEntity.setProPlanIdDz(gpreqId);
				reqinfGpEntity.setProPlanIdZz(gpreqId);
				// }

				// 修改轧管排产表管坯确认状态
				String sqlUpdatePln = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatePlnOrderZgGpStart");
				ps = conn.prepareStatement(sqlUpdatePln);
				ps.setObject(1, "1");
				ps.setObject(2, reqinfGpEntity.getGpreqId());
				ps.executeUpdate();
				ps.close();

				String reqStrat = "";
				if (reqinfGpEntity.getIfbuyplan().equals("1")) {
					reqStrat = "0";
				}
				// 回写订单号
				reqinfGpEntity.setInwlIsokDz("1");
				String sqlUpGp = EntityTool.fillSqlByEntity(sqlUpdatecon,
						reqinfGpEntity);
				ps = conn.prepareStatement(sqlUpGp);
				ps.setObject(1, reqStrat);
				ps.executeUpdate();
				ps.close();

			}
			cro.setV_errMsg("管坯确认成功!");
			conn.commit();

			// if (message.size() > 0) {
			// cro.setResult(listGp.size() - message.size() + "条管坯确认成功，"
			// + message.size() + "条确认失败。\n" + message.get(0));
			// }
			// else {
			// cro.setResult(listGp.size() + "条管坯确认成功，0条确认失败。");
			// }
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改管坯需求
	 * 
	 * @param listGp
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doModify(ArrayList<PlnReqinfGpEntity> listGp,
			String userName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ArrayList<String> message = new ArrayList<String>();
			String sqlQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectReqinfGpStatus");
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateGpReqinfDz");

			String[] errMessage = new String[1];
			ResultSet rs = null;
			PreparedStatement ps = null;
			for (PlnReqinfGpEntity reqinfGp : listGp) {
				String gpreqId = reqinfGp.getGpreqId();
				String desginKey = "";
				String mscPline = "";
				String plineCodezg = "";
				int count = 0;
				// 查询轧管产线
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.seletePlnZgS");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, gpreqId);
				rs = ps.executeQuery();
				if (rs.next()) {
					desginKey = rs.getString("DESGIN_KEY");
					mscPline = rs.getString("MSC_PLINE");
					plineCodezg = rs.getString("PLINE_CODE");
					count++;
				} else {
					message.add("" + count + "未找到轧管信息请刷新。");
					continue;
				}
				rs.close();
				ps.close();
				PlnReqinfGpEntity reqinfGpEntity = null;

				String sqlUp = "";
				ps = conn.prepareStatement(sqlQ);
				ps.setObject(1, gpreqId);
				rs = ps.executeQuery();
				reqinfGpEntity = EntityTool.getEntityByRs(rs,
						PlnReqinfGpEntity.class);
				rs.close();
				ps.close();
				if (reqinfGpEntity == null) {
					message.add("未找到管坯需求：" + reqinfGp.getGpreqId() + "，请刷新。");
					continue;
				}
				reqinfGp.setInwlIsokDz(reqinfGpEntity.getInwlIsokDz());
				reqinfGp.setGradecode(reqinfGpEntity.getGradecode());
				if (reqinfGpEntity.getGptype().equals("1")) {// 铸坯
					if (!CoreLenMsGp.getZzCuttolen(conn, reqinfGpEntity,
							errMessage, plineCodezg, desginKey, mscPline)) {
						message.add(errMessage[0]);
						continue;
					}
					String sqlUpdateCast = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.updatePlnGxCastM");
					ps = conn.prepareStatement(sqlUpdateCast);
					ps.setObject(1, reqinfGpEntity.getCutNumGp());
					ps.setObject(2, reqinfGpEntity.getCutLoseLen());
					ps.setObject(
							3,
							Double.parseDouble(reqinfGpEntity.getLengthZz()) * 1000);
					ps.setObject(4, reqinfGpEntity.getGpWtLong());
					ps.setObject(5, reqinfGpEntity.getGpNumLong());
					ps.setObject(6, gpreqId);
					ps.setObject(7, reqinfGpEntity.getCutNumGp());
					ps.setObject(8, reqinfGpEntity.getCutLoseLen());
					ps.setObject(
							9,
							Double.parseDouble(reqinfGpEntity.getLengthZz()) * 1000);
					ps.setObject(10, reqinfGpEntity.getGpWtLong());
					ps.setObject(11, reqinfGpEntity.getGpNumLong());
					ps.setObject(12, gpreqId);
					ps.executeUpdate();
					ps.close();

				} else {// 锻坯
					if (reqinfGpEntity.getCastingtype().equals("1")) {
						if (!CoreLenMsGp.getCuttolen(conn, reqinfGpEntity,
								errMessage, plineCodezg, desginKey, mscPline)) {
							message.add(errMessage[0]);
							continue;
						}
					} else {
						if (!CoreLenMsGp.getSpindle(conn, reqinfGpEntity,
								errMessage, plineCodezg, desginKey, mscPline)) {
							message.add(errMessage[0]);
							continue;
						}
					}
					String sqlUpdateDp = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.updatePlnGxDpM");
					ps = conn.prepareStatement(sqlUpdateDp);
					ps.setObject(1, reqinfGpEntity.getCutNumGp());
					ps.setObject(2, reqinfGpEntity.getCutLoseLen());
					ps.setObject(3, "");
					ps.setObject(4, reqinfGpEntity.getGpWtLong());
					ps.setObject(5, reqinfGpEntity.getGpNumLong());
					ps.setObject(6, gpreqId);
					ps.setObject(7, reqinfGpEntity.getCutNumGp());
					ps.setObject(8, reqinfGpEntity.getCutLoseLen());
					ps.setObject(9, "");
					ps.setObject(10, reqinfGpEntity.getGpWtLong());
					ps.setObject(11, reqinfGpEntity.getGpNumLong());
					ps.setObject(12, gpreqId);
					ps.setObject(13, reqinfGpEntity.getCutNumGp());
					ps.setObject(14, reqinfGpEntity.getLengthGp());
					ps.setObject(15, reqinfGpEntity.getGpWtLong());
					ps.setObject(16, reqinfGpEntity.getGpNumLong());
					ps.setObject(17, reqinfGpEntity.getGpWtLong());
					ps.setObject(18, reqinfGpEntity.getGpNumLong());
					ps.setObject(19, gpreqId);
					ps.setObject(20, reqinfGpEntity.getLengthGp());
					ps.setObject(21, reqinfGpEntity.getGpWtLong());
					ps.setObject(22, reqinfGpEntity.getGpNumLong());
					ps.setObject(23, reqinfGpEntity.getGpWtLong());
					ps.setObject(24, reqinfGpEntity.getGpNumLong());
					ps.setObject(25, gpreqId);
					ps.executeUpdate();
					ps.close();
				}
				reqinfGpEntity.setInwlIsokDz("1");
				sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, reqinfGpEntity);
				ps = conn.prepareStatement(sqlUp);
				ps.executeUpdate();
				ps.close();

			}
			conn.commit();
			if (message.size() > 0) {
				cro.setResult(listGp.size() - message.size() + "条管坯修改成功，"
						+ message.size() + "条修改失败。\n" + message.get(0));
			} else {
				cro.setResult(listGp.size() + "条管坯修改成功，0条修改失败。");
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除管坯需求
	 * 
	 * @param listGpReqID
	 * @return
	 */
	public CoreReturnObject deleteGpReq(ArrayList<String> listGpReqID) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			ArrayList<String> message = new ArrayList<String>();
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			String slqQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectGpReqStatus");
			String sqlDel = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deleteGpReq");
			String sqlUp = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateZgMsGpReqIdByGpId");
			String sqlDelCast = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deletePlanCastM");
			String sqlOrderGl = CoreXmlSqlParsersFactory.getSql("CorePlnZgMStoGp.selectOrderGl");


			for (String gpReqId : listGpReqID) {
				PreparedStatement ps = null;
				ResultSet rs = null;
				String recType = "";
				String gptype = "";
				int acount = 0;
				ps = conn.prepareStatement(slqQ);
				ps.setObject(1, gpReqId);
				rs = ps.executeQuery();
				if (rs.next()) {
					gptype = rs.getString("GPTYPE").trim();
					if (rs.getString("IFBUYPLAN").trim().equals("0")) {
						if (gptype.equals("2")) {// 锻造
							if (rs.getString("REQ_DONESTATUS") != null
									&& !rs.getString("REQ_DONESTATUS").trim()
											.equals("0")) {
								message.add("管坯类型为【锻造】的管坯需求" + gpReqId
										+ "不是待处理状态，不能删除。");
								continue;
							}
						} else {// 铸造
							if (rs.getString("REQ_DONESTATUS") != null
									&& !rs.getString("REQ_DONESTATUS").equals(
											"1")) {
								message.add("管坯类型为【铸造】的管坯需求" + gpReqId
										+ "是生产或关闭状态，不能删除。");
								continue;
							}
						}

					} else {
						if (rs.getString("REQ_STATUS") != null
								&& !rs.getString("REQ_STATUS").trim()
										.equals("0")) {
							message.add("管坯需求：" + gpReqId + "外购坯状态已生效。");
							continue;
						}
					}
					recType = rs.getString("REC_TYPE");
				}
				rs.close();
				ps.close();


				ps = conn.prepareStatement(sqlOrderGl);
				ps.setString(1,gpReqId);
				rs = ps.executeQuery();
				if(rs.next())
				{
					acount = Integer.parseInt(rs.getString("ACOUNT"));
				}
				rs.close();
				ps.close();
				if(acount > 0)
				{
					cro.setV_errMsg("此管坯需求已生成关联交易合同,请先作废关联交易合同!");
					return  cro;
				}

				ps = conn.prepareStatement(sqlDel);
				ps.setObject(1, gpReqId);
				ps.executeUpdate();
				ps.close();
				if (recType.equals("0")) {// 需求类型（0正常，1预采需求)
					ps = conn.prepareStatement(sqlUp);
					ps.setObject(1, "");
					ps.setObject(2, gpReqId);
					ps.executeUpdate();
					ps.close();
				}
				if (gptype.equals("1")) {// 铸造
					// 删除铸造工序排产
					CorePlnOrdProUseTime.deleteOrderCastS(conn, gpReqId);
					// 删除铸造工序订单
					ps = conn.prepareStatement(sqlDelCast);
					ps.setObject(1, gpReqId);
					ps.executeUpdate();
					ps.close();
				}
				//tzh 24.9.15 新增删掉接口
			 sendGpReqInD(gpReqId);
			}
			conn.commit();
			if (message.size() > 0) {
				cro.setResult(message.get(0));
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 轧管订单状态
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject getZgMsStatus(ArrayList<PlnZgSToGpEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = null;
			ArrayList<PlnZgSToGpEntity> listReq = new ArrayList<PlnZgSToGpEntity>();
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.getZgMsStatus");
			for (PlnZgSToGpEntity zgSEntity : list) {
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				zgSEntity = EntityTool
						.getEntityByRs(rs, PlnZgSToGpEntity.class);
				if (zgSEntity == null) {
					zgSEntity = new PlnZgSToGpEntity();
					zgSEntity.setSucceed(-1);
					zgSEntity.setReason("未找到订单" + zgSEntity.getProPlanId()
							+ "/" + zgSEntity.getGxPlanNo() + "的信息。");
				} else if (rs.getString("GPREQ_ID") == null
						|| rs.getString("GPREQ_ID").trim().equals("")) {
					zgSEntity.setSucceed(-1);
					zgSEntity.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "还未组管坯需求。");
				}
				// else if (rs.getString("REQ_DONESTATUS") != null
				// && !rs.getString("REQ_DONESTATUS").trim().equals("0")) {
				// zgSEntity.setSucceed(-1);
				// zgSEntity.setReason("管坯需求" + zgSEntity.getGpreqId()
				// + "已经确认。");
				// }
				else if (rs.getInt("OUTNUM_CUT") <= 0) {
					zgSEntity.setSucceed(-1);
					zgSEntity.setReason("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "单坯分切数有误。");
				}
				rs.close();
				ps.close();
				listReq.add(zgSEntity);
			}
			cro.setResult(EntityTool.getGsonByEntity(listReq));
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 临时确认
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("null")
	public CoreReturnObject doTemporary(ArrayList<PlnZgSToGpEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = null;
			ArrayList<PlnZgSToGpEntity> listReq = new ArrayList<PlnZgSToGpEntity>();
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.getZgMsStatus");

			for (PlnZgSToGpEntity zgSEntity : list) {
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				ResultSet rs = ps.executeQuery();
				zgSEntity = EntityTool
						.getEntityByRs(rs, PlnZgSToGpEntity.class);
				if (zgSEntity == null) {
					cro.setV_errMsg("未找到订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "的信息。");
					return cro;
				} else if (rs.getString("GPREQ_ID") == null
						|| rs.getString("GPREQ_ID").trim().equals("")) {
					cro.setV_errMsg("订单" + zgSEntity.getProPlanId() + "/"
							+ zgSEntity.getGxPlanNo() + "还未组管坯需求。");
					return cro;
				}
				rs.close();
				ps.close();

				String sqlUpdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updateLinShiCom");
				ps = conn.prepareStatement(sqlUpdate);
				ps.setObject(1, "1");
				ps.setObject(2, zgSEntity.getProPlanId());
				ps.setObject(3, zgSEntity.getGxPlanNo());
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("确认成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 获取锻造对应铸造关系
	 * 
	 * @param gpReqId
	 * @param castingtype
	 * @return
	 */
	public CoreReturnObject getSpindleSinlist(String gpReqId, String castingtype) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.getMscCastRForgGpid");
		if (castingtype.trim().equals("模铸")) {
			sql += " AND TRIM(T.SPEC_CODE_INGOT) IS NOT NULL"
					+ " AND S2.WEIGHT IS NOT NULL"
					+ " ORDER BY TO_NUMBER(S2.WEIGHT) ASC";
		} else {
			sql += " AND TRIM(T.SPEC_CODE) IS NOT NULL"
					+ " AND S1.DIMATER IS NOT NULL"
					+ " ORDER BY TO_NUMBER(S1.DIMATER) ASC";
		}
		cro = this.getData(sql, new Object[] { gpReqId });
		return cro;
	}

	/**
	 * 查找铸造可选产线
	 * 
	 * @param
	 * @param gradeCode
	 * @return
	 */
	public CoreReturnObject getGpZzPinelist(String gradeCode, String wlidZz) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProcessBPline1");
		sql += " ORDER BY T.PLINE_LEVEL ASC, T.PLINE_CODE ASC";
		cro = this.getData(sql, new Object[] { gradeCode, wlidZz });
		return cro;
	}

	/**
	 * 查找锻造可选产线
	 * 
	 * @param
	 * @param
	 * @return
	 */
	public CoreReturnObject getProcessCPline(String inDzWlId, String outDzWlId) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectProcessCPline1");
		sql += " ORDER BY T.PLINE_LEVEL ASC,T.PLINE_CODE ASC";
		cro = this.getData(sql, new Object[] { inDzWlId, outDzWlId });
		return cro;
	}

	/**
	 * 撤销管坯需求部分轧管订单
	 * 
	 * @param gpReqId
	 * @param list
	 * @return
	 */
	public CoreReturnObject deleteGpReqZgMs(String gpReqId,
			ArrayList<PlnZgSToGpEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			String message = "";
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateZgMsGpReqId");
			// String sqlUpGp = CoreXmlSqlParsersFactory
			// .getSql("CorePlnZgMStoGp.updateGpReqAmunt");
			String slqQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectGpReqStatus");
			String sqlDel = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deleteGpReq");
			PreparedStatement ps = null;
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ps = conn.prepareStatement(slqQ);
			ps.setObject(1, gpReqId);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				PreparedStatement pst = null;
				double diameterGp = rs.getDouble("DIAMETER_GP");// 管坯断面
				double lenGpsin = rs.getDouble("LEN_GP_SINGLE");// 单倍坯长
				double cutLoseLen = rs.getDouble("CUT_LOSE_LEN");// 切损长度(mm)
				int numReqGpSin = rs.getInt("GP_NUM");// 管坯需求支（单倍尺）
				double diameterZZ = rs.getDouble("DIAMETER_ZZ");
				double buring = rs.getDouble("DZ_BURN_LOSE");// 烧损
				double dzLoseAdd = rs.getDouble("DZ_LOSE_ADD");// 加工余量
				double dzCutHeadEnd = rs.getDouble("DZ_CUT_HEAD_END");// 切头尾量
				double lengthGp = rs.getDouble("LENGTH_GP");// 倍尺坯长度
				int cutNumSin = rs.getInt("CUT_NUM_GP");// 倍尺数
				if (rs.getString("IFBUYPLAN").equals("1")) {
					if (rs.getString("REQ_STATUS") != null
							&& rs.getString("REQ_STATUS").compareTo("1") > 0) {
						message = "外购管坯需求：" + gpReqId + ",不是编制状态,不允许撤销订单。";
						cro.setResult(message);
					}
				} else {
					if (rs.getString("GPTYPE").equals("1")) {// 铸坯
						if (rs.getString("REQ_DONESTATUS") != null
								&& rs.getString("REQ_DONESTATUS")
										.compareTo("2") > 0) {
							message = "自炼管坯需求：" + gpReqId + ",不是计划状态,不允许撤销订单。";
							cro.setResult(message);
						}
					} else {// 锻坯
						if (rs.getString("REQ_DONESTATUS") != null
								&& rs.getString("REQ_DONESTATUS")
										.compareTo("1") > 0) {
							message = "自炼管坯需求：" + gpReqId + ",不是待处理状态,不允许撤销订单。";
							cro.setResult(message);
						}
					}
				}

				int numSrin = 0;
				for (PlnZgSToGpEntity zgMsEntity : list) {
					String sqlUp = "";
					String numS = zgMsEntity.getGpreqNum();// 订单需求支
					double weightS = Double.parseDouble(zgMsEntity
							.getGpreqWeight());// 订单需求吨
					numSrin += Integer.parseInt(numS);
					int gpNumLong = 0;
					double gpWtLong = 0;
					if (rs.getString("GPTYPE").equals("2")) {// 管坯类型1铸坯2锻坯
						if (rs.getString("CASTINGTYPE").equals("2")) {// 铸造类型1连铸2模铸
							double blankSinGpWt = 0;
							// 查询毛坯重量
							String sqlmpWt = CoreXmlSqlParsersFactory
									.getSql("CorePlnZgMStoGp.selectSpecWt");
							PreparedStatement ps1 = conn
									.prepareStatement(sqlmpWt);
							ps1.setObject(1, diameterZZ * 1000);
							ResultSet rs1 = ps1.executeQuery();
							if (rs1.next()) {
								blankSinGpWt = rs1.getDouble("GROSS_WETGHT");
							}
							rs1.close();
							ps1.close();

							// 需锭数量= int (单倍坯支数 / 倍尺数+0.85)
							gpNumLong = (int) (Double.parseDouble(numS)
									/ cutNumSin + 0.85);
							// 需锭吨=需锭数量*毛坯重t
							gpWtLong = gpNumLong * blankSinGpWt;

						} else {
							//  锻造后外径：=轧管截面+锻坯外径加工余量
							double outDiameter = diameterGp + dzLoseAdd;
							//  锻造后N倍坯长：=N*单倍坯长+锻坯头尾切损长+（N-1）*10mm
							double dzSingleN = 2 * lenGpsin + dzCutHeadEnd
									+ cutLoseLen;
							//  锻造后N倍坯重：=7.8*3.1415926* (轧管截面+锻坯外径加工余量)*
							// (轧管截面+锻坯外径加工余量)/4 *
							// (N*单倍坯长+(N-1)*10+锻坯头尾切损长)/1000/1000/1000
							double dzSWtLongN = 7.8 * Pi * outDiameter
									* (outDiameter / 4) * dzSingleN / 1000
									/ 1000 / 1000;

							// 单倍坯重
							double lzDiamWtSingle = dzSWtLongN
									/ (1 - buring / 100);
							// 需坯支：轧管需坯支
							gpNumLong = (int) (Double.parseDouble(numS) / 2);
							// 的需坯吨：单倍坯重*轧管需坯支
							gpWtLong = lzDiamWtSingle * gpNumLong;
							if (rs.getString("IFBUYPLAN").equals("0")) {// 自炼

							}

						}
					} else {
						double zgwtSingle = CoreOrdBase
								.GpweightOfmi(diameterGp); // 轧管坯米单重
						// 4> 倍尺坯单支重=坯米单重*倍尺坯长/1000
						double wtGpSingle = zgwtSingle * (lengthGp / 1000);
						// 5> 倍尺需坯支= int (单倍坯支数 / 倍尺数+0.85)
						gpNumLong = (int) (Double.parseDouble(numS) / cutNumSin + 0.85);
						// 6> 倍尺需坯吨=倍尺需坯支*倍尺坯单支重
						gpWtLong = gpNumLong * wtGpSingle;

					}
					// 修改订单管坯需求号
					zgMsEntity.setGpreqId("");
					sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, zgMsEntity);
					pst = conn.prepareStatement(sqlUp);
					pst.executeUpdate();
					pst.close();
					// 修改管坯需求量
					String sqlUpGp = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.updateGpReqWetNum");
					pst = conn.prepareStatement(sqlUpGp);
					pst.setObject(1, weightS);
					pst.setObject(2, numS);
					pst.setObject(3, gpWtLong);
					pst.setObject(4, gpNumLong);
					pst.setObject(5, gpReqId);
					pst.executeUpdate();
					pst.close();

				}
				if (numReqGpSin - numSrin <= 0) {
					pst = conn.prepareStatement(sqlDel);
					pst.setObject(1, gpReqId);
					pst.executeUpdate();
					pst.close();
				}
				// if (numReqGpSin <= numSinGp || numReqGpSin <= 0) {
				// pst = conn.prepareStatement(sqlDel);
				// pst.setObject(1, gpReqId);
				// pst.executeUpdate();
				// pst.close();
				// }
				// else {
				// double rate = numSinGp
				// / Double.parseDouble(String.valueOf(numReqGpSin));
				// String sqlUp = sqlUpGp.replaceAll("'#RATE#'", String
				// .valueOf(rate));
				// pst = conn.prepareStatement(sqlUp);
				// pst.setObject(1, gpReqId);
				// pst.executeUpdate();
				// pst.close();
				// }
			} else {
				message = "未找到管坯需求：" + gpReqId + "。";
				cro.setResult(message);
			}
			rs.close();
			ps.close();

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

	/**
	 * 连铸坯的定尺
	 * 
	 * @param blankSinGpWt
	 *            单倍尺毛坯重量（t）
	 * @param diameterLz
	 *            连铸断面(mm)
	 * @param buring
	 *            烧损（%）
	 * @return (m)
	 */
	public static double getCuttolength(double blankSinGpWt, double diameterLz,
			double buring) {
		double cutTolength = 0;
		cutTolength = blankSinGpWt / CoreOrdBase.GpweightOfmi(diameterLz)
				/ (1 - buring / 100);
		return cutTolength;
	}

	/**
	 * 切损长度（mm）
	 * 
	 * @param cutNum
	 * @return
	 */
	public static double getCutLoseLen(int cutNum) {
		return (cutNum - 1) * 10;
	}

	/**
	 * 分切数
	 * 
	 * @param lenMax
	 *            上限（mm）
	 * @param lenMin
	 *            下限（mm）
	 * @param sinlen
	 *            单倍坯长（mm）
	 * @return
	 */
	public static int getlenInRange(double lenMax, double lenMin, double sinlen) {
		int cutNum = 0;
		int a = 0; // 最小倍尺数
		int b = 0; // 最大倍尺数
		int w = 0; // 有多少种分切方案
		double cutlen = 0;// 切损
		BigDecimal big = null;

		if (lenMax < lenMin) {
			double temp = lenMax;
			lenMax = lenMin;
			lenMin = temp;
		}

		a = (int) ((lenMin - cutlen) / sinlen); // 最小倍尺数
		b = (int) ((lenMax - cutlen) / sinlen); // 最大倍尺数
		if (b == 0) {
			return cutNum;
		}

		big = new BigDecimal((a * sinlen));
		double f1 = big.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
		if (f1 <= (lenMin - cutlen)) {
			a = a + 1;
		}
		w = b - a + 1; // 有多少种分切方案
		// 管长度太短，无法分切
		if (w <= 0) {
			return cutNum;
		}

		for (int i = 0; i < w; i++) {
			int numTemp = a + i;
			double lenGp = 0; // 管坯长度
			cutlen = getCutLoseLen(numTemp);
			lenGp = numTemp * sinlen + cutlen;
			if (lenMax - lenGp >= 0.00001 && lenGp - lenMin >= 0.00001) {
				cutNum = numTemp;
				break;
			}
		}
		return cutNum;
	}

	/**
	 * 管坯确认
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject confirmGp(ArrayList<String> list, String createName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			ArrayList<String> message = new ArrayList<String>();
			PreparedStatement ps = null;
			ResultSet rs = null;
			String sqlQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectReqinfGpStatus");
			String sqlAddCast = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.addPlnGxCastM");
			String sqlAddDp = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.addPlnGxDpM");
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateReqinfGpConfirm");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date timeissued = new Date();
			String issuedTime = df.format(timeissued);
			for (String gpreqId : list) {
				PlnReqinfGpEntity reqinfGpEntity = null;
				String sql = "";
				String sqlUpGp = "";
				ps = conn.prepareStatement(sqlQ);
				ps.setObject(1, gpreqId);
				rs = ps.executeQuery();
				reqinfGpEntity = EntityTool.getEntityByRs(rs,
						PlnReqinfGpEntity.class);
				rs.close();
				ps.close();
				if (reqinfGpEntity == null) {
					message.add("未找到管坯需求：" + gpreqId + "，请刷新。");
					continue;
				}
				if (reqinfGpEntity.getReqDonestatus().compareTo("0") > 0) {
					message.add("管坯需求：" + gpreqId + "已经确认过了。");
					continue;
				}

				// sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.getPlnGxCastMPlanId");
				// ps = conn.prepareStatement(sql);
				// rs = ps.executeQuery();
				// if (!rs.next()) {
				// message.add("管坯需求：" + gpreqId + " 生成铸造订单编号时出错。");
				// continue;
				// }
				// if (rs.getString("PLAN_ID") == null
				// || rs.getString("PLAN_ID").trim().equals("")) {
				// message.add("管坯需求：" + gpreqId + " 生成铸造订单编号时出错。");
				// continue;
				// }
				// proPlanIdZz = rs.getString("PLAN_ID");
				// rs.close();
				// ps.close();
				reqinfGpEntity.setIssuedMan(createName);
				reqinfGpEntity.setIssuedTime(issuedTime);
				reqinfGpEntity.setReqDonestatus("1");

				// if (reqinfGpEntity.getGptype().equals("1")) {
				// String plineCodeMay = "";
				// String plineNameMay = "";
				// String sqlAdd = "";
				// PlnGxCastMEntity gxCastMEntity = new PlnGxCastMEntity();
				// // 管坯是铸坯，新增连铸坯订单
				//
				// sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.selectProcessBPline1");
				// sql +=
				// " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
				// ps = conn.prepareStatement(sql);
				// ps.setObject(1, reqinfGpEntity.getGradecode());
				// ps.setObject(2, reqinfGpEntity.getMaterialNo());
				// rs = ps.executeQuery();
				// while (rs.next()) {
				// plineCodeMay += rs.getString("PLINE_CODE") + ",";
				// plineNameMay += rs.getString("PLINE_NAME") + ",";
				// }
				// rs.close();
				// ps.close();
				// if (plineCodeMay.length() > 0 && plineCodeMay.contains(","))
				// {
				// plineCodeMay = plineCodeMay.substring(0, plineCodeMay
				// .lastIndexOf(","));
				// }
				// if (plineNameMay.length() > 0 && plineNameMay.contains(","))
				// {
				// plineNameMay = plineNameMay.substring(0, plineNameMay
				// .lastIndexOf(","));
				// }
				// if (!plineCodeMay.equals("")) {
				// String[] strs = plineCodeMay.split(",");
				// gxCastMEntity.setPlineCode(strs[0].toString().trim());
				// }
				// if (!plineNameMay.equals("")) {
				// String[] strs = plineNameMay.split(",");
				// gxCastMEntity.setPlineName(strs[0].toString().trim());
				// }
				// gxCastMEntity.setProPlanId(proPlanIdZz);
				// gxCastMEntity.setGpreqId(reqinfGpEntity.getGpreqId());
				// gxCastMEntity.setGptype("1");
				// gxCastMEntity.setCastingtype("1");
				// gxCastMEntity.setPlineCodeMay(plineCodeMay);
				// gxCastMEntity.setPlineNameMay(plineNameMay);
				// gxCastMEntity.setGradecode(reqinfGpEntity.getGradecode());
				// gxCastMEntity.setGradename(reqinfGpEntity.getGradename());
				// gxCastMEntity.setDiameterLz(reqinfGpEntity.getDiameterZz());
				// gxCastMEntity.setLenGpSingle(reqinfGpEntity
				// .getLenGpSingle());
				// gxCastMEntity.setCutNumGp(reqinfGpEntity.getCutNumGp());
				// gxCastMEntity.setCutLoseLen(reqinfGpEntity.getCutLoseLen());
				// gxCastMEntity.setLengthLz(reqinfGpEntity.getLengthZz());
				// gxCastMEntity.setMaterialNo(reqinfGpEntity.getMaterialNo());
				// gxCastMEntity.setMaterialName(reqinfGpEntity
				// .getMaterialName());
				// gxCastMEntity.setCic(reqinfGpEntity.getCic());
				// gxCastMEntity.setPic(reqinfGpEntity.getPic());
				// gxCastMEntity.setSic(reqinfGpEntity.getSic());
				// gxCastMEntity.setDic(reqinfGpEntity.getDic());
				// gxCastMEntity.setWic(reqinfGpEntity.getWic());
				// gxCastMEntity.setGic(reqinfGpEntity.getGic());
				// gxCastMEntity.setIfMonitorLg(reqinfGpEntity
				// .getIfMonitorLg());
				// gxCastMEntity.setPrdcrNo(reqinfGpEntity.getPrdcrNo());
				// gxCastMEntity.setMonitorPoint("");
				// gxCastMEntity.setWtCastOne(reqinfGpEntity.getWtOneZz());
				// gxCastMEntity.setPlanWt(reqinfGpEntity.getOutWtZz());
				// gxCastMEntity.setPlanNum(reqinfGpEntity.getOutNumZz());
				// gxCastMEntity.setReqStatus("1");
				// gxCastMEntity.setCreateName(createName);
				// gxCastMEntity.setCreateTime(issuedTime);
				//
				// sqlAdd = EntityTool.fillSqlByEntity(sqlAddCast,
				// gxCastMEntity);
				// ps = conn.prepareStatement(sqlAdd);
				// ps.executeUpdate();
				// ps.close();
				//
				// // 工序排产
				// CorePlnOrdProUseTime.addOrderCastS(conn, proPlanIdZz,
				// createName, reqinfGpEntity.getProMonth(),
				// issuedTime);
				// }
				// else {
				// 锻坯
				PlnGxDpMEntity gxDpMEntity = new PlnGxDpMEntity();
				PlnGxCastMEntity gxCastMEntity = new PlnGxCastMEntity();
				String plineCodeMay = "";
				String plineNameMay = "";
				String plineCodeMayZz = "";
				String plineNameMayZz = "";
				String sqlAdd = "";
				double dimaterGp = 0;// 管坯断面
				double lenGp = 0;// 管坯长度
				Date nowTime = new Date();
				SimpleDateFormat time = new SimpleDateFormat("yyyy-MM");

				dimaterGp = Double.parseDouble(reqinfGpEntity.getDiameterGp());
				lenGp = Double.parseDouble(reqinfGpEntity.getLengthGp());

				// sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.getPlnGxGpMPlanId");
				// ps = conn.prepareStatement(sql);
				// rs = ps.executeQuery();
				// if (!rs.next()) {
				// message.add("管坯需求：" + gpreqId + " 生成锻造订单编号时出错。");
				// continue;
				// }
				// if (rs.getString("PLAN_ID") == null
				// || rs.getString("PLAN_ID").trim().equals("")) {
				// message.add("管坯需求：" + gpreqId + " 生成锻造订单编号时出错。");
				// continue;
				// }
				// proPlanIdDz = rs.getString("PLAN_ID");
				// rs.close();
				// ps.close();

				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessCPline1");
				sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, reqinfGpEntity.getWlidZz());
				ps.setObject(2, reqinfGpEntity.getMaterialNo());
				rs = ps.executeQuery();
				while (rs.next()) {
					plineCodeMay += rs.getString("PLINE_CODE") + ",";
					plineNameMay += rs.getString("PLINE_NAME") + ",";
				}
				rs.close();
				ps.close();
				if (plineCodeMay.length() > 0 && plineCodeMay.contains(",")) {
					plineCodeMay = plineCodeMay.substring(0,
							plineCodeMay.lastIndexOf(","));
				}
				if (plineNameMay.length() > 0 && plineNameMay.contains(",")) {
					plineNameMay = plineNameMay.substring(0,
							plineNameMay.lastIndexOf(","));
				}
				gxDpMEntity.setProPlanId(gpreqId);
				gxDpMEntity.setPlineCodeMay(plineCodeMay);
				gxDpMEntity.setPlineNameMay(plineNameMay);
				gxDpMEntity.setPlineCode(reqinfGpEntity.getPlineCodeDz());
				gxDpMEntity.setPlineName(reqinfGpEntity.getPlineNameDz());
				gxDpMEntity.setGradecode(reqinfGpEntity.getGradecode());
				gxDpMEntity.setGradename(reqinfGpEntity.getGradename());
				gxDpMEntity.setDiameterOut(reqinfGpEntity.getDiameterGp());
				gxDpMEntity.setLenGpSingle(reqinfGpEntity.getLenGpSingle());
				gxDpMEntity.setCutNumGp(reqinfGpEntity.getCutNumGp());
				gxDpMEntity.setLengthOut(reqinfGpEntity.getLengthGp());
				gxDpMEntity.setOutwlId(reqinfGpEntity.getMaterialNo());
				gxDpMEntity.setOutwlDesc(reqinfGpEntity.getMaterialName());
				gxDpMEntity.setOutWtOne(String.valueOf(lenGp
						* CoreOrdBase.GpweightOfmi(dimaterGp)));
				gxDpMEntity.setOutWtTot(reqinfGpEntity.getGpWtLong());
				gxDpMEntity.setOutNumTot(reqinfGpEntity.getGpNumLong());
				gxDpMEntity.setWtOneIn(reqinfGpEntity.getWtOneZz());
				gxDpMEntity.setWlidIn(reqinfGpEntity.getWlidZz());
				gxDpMEntity.setWldescIn(reqinfGpEntity.getWldescZz());
				gxDpMEntity.setInNum(reqinfGpEntity.getOutNumZz());
				gxDpMEntity.setInWt(reqinfGpEntity.getOutWtZz());
				gxDpMEntity.setZzProPlanId(gpreqId);

				// 监制
				gxDpMEntity.setPrdcrNo(reqinfGpEntity.getPrdcrNo());
				gxDpMEntity.setIfMonitorDz("");

				gxDpMEntity.setCic(reqinfGpEntity.getCic());
				gxDpMEntity.setPic(reqinfGpEntity.getPic());
				gxDpMEntity.setSic(reqinfGpEntity.getSic());
				gxDpMEntity.setDic(reqinfGpEntity.getDic());
				gxDpMEntity.setWic(reqinfGpEntity.getWic());
				gxDpMEntity.setGic(reqinfGpEntity.getGic());
				gxDpMEntity.setProMonth(time.format(nowTime));
				gxDpMEntity.setPlanstatus("1");
				gxDpMEntity.setCreateName(createName);
				gxDpMEntity.setCreateTime(issuedTime);
				// 铸造订单
				gxCastMEntity.setProPlanId(gpreqId);
				gxCastMEntity.setGptype("2");

				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProcessBPline1");
				sql += " ORDER BY T.PLINE_LEVEL ASC, T.PRD_RATE DESC, T.PLINE_CODE ASC";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, reqinfGpEntity.getGradecode());
				ps.setObject(2, reqinfGpEntity.getWlidZz());
				rs = ps.executeQuery();
				while (rs.next()) {
					plineCodeMayZz += rs.getString("PLINE_CODE") + ",";
					plineNameMayZz += rs.getString("PLINE_NAME") + ",";
				}
				rs.close();
				ps.close();
				if (plineCodeMayZz.length() > 0 && plineCodeMayZz.contains(",")) {
					plineCodeMayZz = plineCodeMayZz.substring(0,
							plineCodeMayZz.lastIndexOf(","));
				}
				if (plineNameMayZz.length() > 0 && plineNameMayZz.contains(",")) {
					plineNameMayZz = plineNameMayZz.substring(0,
							plineNameMayZz.lastIndexOf(","));
				}
				gxCastMEntity.setPlineCodeMay(plineCodeMayZz);
				gxCastMEntity.setPlineNameMay(plineNameMayZz);
				gxCastMEntity.setGradecode(reqinfGpEntity.getGradecode());
				gxCastMEntity.setGradename(reqinfGpEntity.getGradename());
				gxCastMEntity.setCutNumGp(reqinfGpEntity.getCutNumGp());
				gxCastMEntity.setCutLoseLen(reqinfGpEntity.getCutLoseLen());
				gxCastMEntity.setMaterialNo(reqinfGpEntity.getWlidZz());
				gxCastMEntity.setMaterialName(reqinfGpEntity.getWldescZz());
				gxCastMEntity.setCic(reqinfGpEntity.getCic());
				gxCastMEntity.setPic(reqinfGpEntity.getPic());
				gxCastMEntity.setSic(reqinfGpEntity.getSic());
				gxCastMEntity.setDic(reqinfGpEntity.getDic());
				gxCastMEntity.setWic(reqinfGpEntity.getWic());
				gxCastMEntity.setGic(reqinfGpEntity.getGic());
				gxCastMEntity.setIfMonitorLg(reqinfGpEntity.getIfMonitorLg());
				gxCastMEntity.setPrdcrNo(reqinfGpEntity.getPrdcrNo());
				gxCastMEntity.setMonitorPoint("");
				gxCastMEntity.setWtCastOne(reqinfGpEntity.getWtOneZz());
				gxCastMEntity.setPlanWt(reqinfGpEntity.getOutWtZz());
				gxCastMEntity.setPlanNum(reqinfGpEntity.getOutNumZz());
				gxCastMEntity.setReqStatus("1");
				gxCastMEntity.setCreateName(createName);
				gxCastMEntity.setCreateTime(issuedTime);
				gxCastMEntity.setPlineCode(reqinfGpEntity.getPlineCodeZz());
				gxCastMEntity.setPlineName(reqinfGpEntity.getPlineNameZz());
				gxCastMEntity.setLenGpSingle(reqinfGpEntity.getLenGpSingle());
				if (reqinfGpEntity.getCastingtype().equals("1")) {
					// 连铸
					gxDpMEntity.setCastingtype("1");
					gxDpMEntity.setDiameterIn(reqinfGpEntity.getDiameterZz());
					gxDpMEntity.setLengthIn(reqinfGpEntity.getLengthZz());

					gxCastMEntity.setCastingtype("1");
					gxCastMEntity.setDiameterLz(reqinfGpEntity.getDiameterZz());
					gxCastMEntity.setLengthLz(reqinfGpEntity.getLengthZz());
				} else {
					// 模铸
					gxDpMEntity.setCastingtype("2");

					gxCastMEntity.setCastingtype("2");
				}

				// 新增铸造订单
				sqlAdd = EntityTool.fillSqlByEntity(sqlAddCast, gxCastMEntity);
				ps = conn.prepareStatement(sqlAdd);
				ps.executeUpdate();
				ps.close();

				CorePlnOrdProUseTime cuseTime = new CorePlnOrdProUseTime();
				// 工序排产
				if (cuseTime.addOrderCastS(conn, gpreqId, createName,
						reqinfGpEntity.getProMonth(), issuedTime,
						reqinfGpEntity.getPlineCodeZz(),
						reqinfGpEntity.getPlineNameZz(),
						reqinfGpEntity.getGpWtLongMin(),
						reqinfGpEntity.getGowhereCode(),
						reqinfGpEntity.getGowhereName())) {

				} else {
					message.add(cuseTime.getVerrMsg());
					continue;
				}

				// 新增锻造订单
				sqlAdd = EntityTool.fillSqlByEntity(sqlAddDp, gxDpMEntity);
				ps = conn.prepareStatement(sqlAdd);
				ps.executeUpdate();
				ps.close();

				// 工序排产
				CorePlnOrdProUseTime.addOrderDzS(conn, gpreqId, reqinfGpEntity,
						createName, issuedTime);

				reqinfGpEntity.setProPlanIdDz(gpreqId);
				reqinfGpEntity.setProPlanIdZz(gpreqId);
				// }

				// 修改轧管排产表管坯确认状态
				String sqlUpdatePln = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatePlnOrderZgGpStart");
				ps = conn.prepareStatement(sqlUpdatePln);
				ps.setObject(1, "1");
				ps.setObject(2, reqinfGpEntity.getGpreqId());
				ps.executeUpdate();
				ps.close();

				String reqStrat = "";
				if (reqinfGpEntity.getIfbuyplan().equals("1")) {
					reqStrat = "0";
				}
				// 回写订单号
				reqinfGpEntity.setInwlIsokDz("1");
				sqlUpGp = EntityTool.fillSqlByEntity(sqlUpdate, reqinfGpEntity);
				ps = conn.prepareStatement(sqlUpGp);
				ps.setObject(1, reqStrat);
				ps.executeUpdate();
				ps.close();

			}
			conn.commit();
			if (message.size() > 0) {
				cro.setResult(list.size() - message.size() + "条管坯需求确认成功，"
						+ message.size() + "条确认失败。\n" + message.get(0));
			} else {
				cro.setResult(list.size() + "条管坯需求确认成功，0条确认失败。");
			}

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

	/**
	 * 取消管坯确认
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject concelConfirmGp(ArrayList<String> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			ArrayList<String> message = new ArrayList<String>();
			PreparedStatement ps = null;
			ResultSet rs = null;

			String sqlQ = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.selectReqinfGpStatus");

			String sqlDelCast = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deletePlanCastM");
			String sqlDelDp = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deletePlanDpM");
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateReqinfGpConfirm");

			for (String gpreqId : list) {
				String sqlUp = "";
				PlnReqinfGpEntity reqinfGpEntity = null;
				ps = conn.prepareStatement(sqlQ);
				ps.setObject(1, gpreqId);
				rs = ps.executeQuery();
				reqinfGpEntity = EntityTool.getEntityByRs(rs,
						PlnReqinfGpEntity.class);
				rs.close();
				ps.close();
				if (reqinfGpEntity == null) {
					message.add("未找到管坯需求：" + gpreqId + "，请刷新。");
					continue;
				}
				if (reqinfGpEntity.getReqDonestatus().compareTo("1") > 0) {
					message.add("管坯需求：" + gpreqId + "是生产或关闭状态。");
					continue;
				}
				if (reqinfGpEntity.getReqDonestatus().compareTo("1") < 0) {
					message.add("管坯需求：" + gpreqId + "是待处理状态。");
					continue;
				}
				// if (reqinfGpEntity.getReqStatus().compareTo("1") > 0) {
				// message.add("管坯需求：" + gpreqId + "外购坯状态已生效。");
				// continue;
				// }

				// 删除铸造工序排产
				CorePlnOrdProUseTime.deleteOrderCastS(conn,
						reqinfGpEntity.getProPlanIdZz());
				// 删除铸造工序订单
				ps = conn.prepareStatement(sqlDelCast);
				ps.setObject(1, reqinfGpEntity.getProPlanIdZz());
				ps.executeUpdate();
				ps.close();

				// 删除锻造工序订单
				if (reqinfGpEntity.getGptype().trim().equals("2")) {
					// 删除锻造工序排产
					CorePlnOrdProUseTime.deleteOrderDzS(conn,
							reqinfGpEntity.getProPlanIdDz());

					ps = conn.prepareStatement(sqlDelDp);
					ps.setObject(1, reqinfGpEntity.getProPlanIdDz());
					ps.executeUpdate();
					ps.close();
				}

				// 修改轧管排产表管坯确认状态
				String sqlUpdatePln = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatePlnOrderZgGpStart");
				ps = conn.prepareStatement(sqlUpdatePln);
				ps.setObject(1, "0");
				ps.setObject(2, reqinfGpEntity.getGpreqId());
				ps.executeUpdate();
				ps.close();
				// 回写管坯状态
				reqinfGpEntity.setProPlanIdZz("");
				reqinfGpEntity.setProPlanIdDz("");
				reqinfGpEntity.setReqDonestatus("0");
				reqinfGpEntity.setInwlIsokDz("0");
				sqlUp = EntityTool.fillSqlByEntity(sqlUpdate, reqinfGpEntity);
				ps = conn.prepareStatement(sqlUp);
				ps.setObject(1, "");
				ps.executeUpdate();
				ps.close();

			}
			conn.commit();
			if (message.size() > 0) {
				cro.setResult(list.size() - message.size() + "条管坯需求取消成功，"
						+ message.size() + "条取消失败。\n" + message.get(0));
			} else {
				cro.setResult(list.size() + "条管坯需求取消成功，0条取消失败。");
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (ParseException pe) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(pe.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 重新计算
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculate(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			ProducHelperBean helperBean = new ProducHelperBean();
			PreparedStatement ps = null;
			ResultSet rs = null;
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.queryZgMSStatus");
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updatePlnOrderZgS");
			PlnOrdInfo ordInfo = new PlnOrdInfo();
			// int gxProseq = 0;
			// String plineCode = "";
			// String planTimeE1 = "";
			for (PlnOrderZgSEntity zgSentity : list) {
				double inWeight = 0;
				double inWeightMin = 0;// 排产吨min
				double prdRate = 1; // 成才率
				int addNum = 0;// 加投支数
				double addWeight = 0;// 加投重量
				double outdiameterIn = 0;// 轧管名义外径
				double wallthickIn = 0;// 轧管名义壁厚
				double diameterGp = 0;// 管坯直径
				double lengthColdbed = 0;// 冷床长度
				double lengthMaxRing = 0;// 环形炉最长
				double burnoutRate = 0;// 烧损率
				double cropHead = 0;// 切头
				double cropEnd = 0;// 切尾
				double tubeEndRatio = 0;// 管端系数
				double lengthMinTube = 0;// 脱管机长度下限
				double lengthMaxTube = 0;// 脱管机长度上限
				double toleranceZone = 0;// 机组壁厚公差带能力%
				double capacity = 0;// 产线能力
				String groupJgx = "";
				String groupRcl = "";
				double delvryRangeMax = 0;// 订货量上限
				double delvryRangeMin = 0;// 下限

				int count = 0;
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.SelectPlnOrderZgCaiF");
				PreparedStatement psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getProPlanId());
				rs = psta.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
				}
				rs.close();
				psta.close();
				if (count > 1) {
					cro.setV_errMsg("订单号：" + zgSentity.getProPlanId()
							+ ",存在拆分记录，不能重头计算。");
					return cro;
				}
				// 查询合同信息
				String sic = "";
				String cutHeadDbk = "";
				String cutendDbk = "";
				String longerDbk = "";
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.querySaleProcStatus");
				psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getProPlanId());
				psta.setString(2, zgSentity.getGxPlanNo());
				rs = psta.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0") || !rs.getString("IS_PLAN_OK").equals("0")) {
						cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
								+ "需未确认同时是计划状态，才能重头计算。");
						return cro;
					}
					// if (rs.getString("IS_PLAN_OK") != null
					// && rs.getString("IS_PLAN_OK").equals("1")) {
					// cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
					// + "已确认,不能重头计算。");
					// return cro;
					// }
					//TZH 24.8.27 取消坯料需求申报的处理
//					if (rs.getString("GPREQ_ID") != null
//							&& rs.getString("GPREQ_ID") != "") {
//						cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
//								+ "已组坯料需求，不能重头计算。");
//						return cro;
//					}
					int countM = 0;
					// 查询是否存在炉计划
					String sqlZgM = "SELECT COUNT(*) COUNTZG FROM PLN_ZY_ZG_M T WHERE T.PRO_PLAN_ID='"
							+ zgSentity.getProPlanId()
							+ "' AND T.GX_PLAN_NO='"
							+ zgSentity.getGxPlanNo() + "'";
					PreparedStatement psM = conn.prepareStatement(sqlZgM);
					ResultSet rsM = psM.executeQuery();
					if (rsM.next()) {
						countM = rsM.getInt("COUNTZG");
					}
					rsM.close();
					psM.close();
					if (countM > 0) {
						cro.setV_errMsg("订单号：" + zgSentity.getProPlanId() + "/"
								+ zgSentity.getGxPlanNo() + "已生成炉计划，不能重头计算。");
						return cro;
					}
					if (rs.getString("SIC") != null
							&& rs.getString("SIC") != "") {
						String[] strs = rs.getString("SIC").split(",");
						sic = strs[0].toString().trim();
					}
					delvryRangeMax = rs.getDouble("DELVRY_RANGE_MAX");
					delvryRangeMin = rs.getDouble("DELVRY_RANGE_MIN");
					inWeight = rs.getDouble("PLAN_P_MAIN");
					inWeightMin = rs.getDouble("PLAN_P_MAIN_MIN");

					cutHeadDbk = rs.getString("LEN_CUTHEAD_DBK");
					cutendDbk = rs.getString("LEN_CUTEND_DBK");
					longerDbk = rs.getString("LEN_LONGER_DBK");
					ordInfo.setLenCutheadDbk(rs.getString("LEN_CUTHEAD_DBK"));// ++
					ordInfo.setLenCutendCbk(rs.getString("LEN_CUTEND_DBK"));// +++

					ordInfo.setAddDbkLen(rs.getDouble("LEN_CUTHEAD_DBK")
							+ rs.getDouble("LEN_CUTEND_DBK"));
					ordInfo.setAddDcLen(rs.getDouble("LEN_LONGER_DBK"));
					ordInfo.setRatioDbk(rs.getDouble("RATIO_DBK"));
					ordInfo.setAbc(rs.getString("ABC"));
					ordInfo.setOutputStdNo(rs.getString("OUTPUT_STD_NO"));
					ordInfo.setUseDesc(rs.getString("USE_DESC"));
					ordInfo.setStdName(rs.getString("STD_NAME"));
					ordInfo.setPlanWtD(rs.getDouble("PLAN_WT_D"));
					ordInfo.setPlanNumD(rs.getInt("PLAN_NUM_D"));
					ordInfo.setOutMultD(rs.getInt("OUT_MULT_D"));
					ordInfo.setRollMonth(rs.getString("ROLL_MONTH"));

					ordInfo.setMsc(rs.getString("MSC"));
					ordInfo.setIndexSeq(rs.getString("INDEX_SEQ"));
					ordInfo.setDesginKey(rs.getString("DESGIN_KEY"));
					if (rs.getString("BOM") != null) {
						ordInfo.setBom(rs.getString("BOM"));
					}
					ordInfo.setOutdiameter(rs.getDouble("OUTDIAMETER"));
					ordInfo.setWallthick(rs.getDouble("WALLTHICK"));
					ordInfo.setAimLenRoll(rs.getDouble("AIM_LEN_ROLL"));
					ordInfo.setwJ(rs.getDouble("WEIGHT_PER_M"));

					if (zgSentity.getLenNoN().equals("")) {
						ordInfo.setLengthmin(rs.getDouble("LENGTHMIN"));
						ordInfo.setLengthmax(rs.getDouble("LENGTHMAX"));
						if (rs.getString("SHRT_STOVE") != null) {
							ordInfo.setShrtStove(rs.getString("SHRT_STOVE"));
						}
						ordInfo.setEndlenSpecstd(rs.getDouble("ENDLEN_SPECSTD"));
						ordInfo.setAvgLenMin(rs.getDouble("AVG_LEN_MIN"));
						ordInfo.setSiglLen(rs.getDouble("SIGL_LEN"));
						ordInfo.setShortest(rs.getDouble("SHORTEST"));
					} else {
						// 查询长度描述基础表
						sql = CoreXmlSqlParsersFactory
								.getSql("CoreOrderLenPln.QUERY");
						PreparedStatement pstalen = conn.prepareStatement(sql);
						pstalen.setString(1, zgSentity.getLenNoN());
						ResultSet rslen = pstalen.executeQuery();
						if (rslen.next()) {
							ordInfo.setLengthmin(rslen.getDouble("LEN_MIN"));
							ordInfo.setLengthmax(rslen.getDouble("LEN_MAX"));
							ordInfo.setShrtStove(rslen.getString("SHRT_STOVE"));
							ordInfo.setEndlenSpecstd(rslen
									.getDouble("ENDLEN_SPECSTD"));
							ordInfo.setAvgLenMin(rslen.getDouble("AVG_LEN_MIN"));
							ordInfo.setSiglLen(rslen.getDouble("SIGL_LEN"));
							ordInfo.setShortest(rslen.getDouble("SHORTEST"));
						}
						rslen.close();
						pstalen.close();
					}
					ordInfo.setCheckJVal(rs.getDouble("CHECK_J_VAL"));
					ordInfo.setAddInspect(rs.getDouble("INSPECTION_VALUE"));
					ordInfo.setLenRollMin(rs.getDouble("LEN_ROLL_MIN"));
					ordInfo.setLenRollMax(rs.getDouble("LEN_ROLL_MAX"));
					ordInfo.setOrdLnDlyPk(rs.getString("ORD_LN_DLY_PK"));
					ordInfo.setOrderUnit(rs.getString("ORDER_UNIT"));
					ordInfo.setTotlength(rs.getDouble("TOTLENGTH"));
					ordInfo.setTotlengthUnit(rs.getString("TOTLENGTH_UNIT"));
					ordInfo.setPlineName(rs.getString("GROUP_ROLL_NAME"));
					ordInfo.setProduceSort(rs.getString("PRODUCE_SORT"));
					ordInfo.setOrderSource(rs.getString("ORDER_SOURCE"));
					ordInfo.setLenScope(rs.getDouble("LEN_SCOPE"));
					if (rs.getString("ORDER_UNIT") != null
							&& (rs.getString("ORDER_UNIT").trim().equals("吨") || rs
									.getString("ORDER_UNIT").trim()
									.equals("英磅"))) {
						if (rs.getString("WEIGH_TYPE") != null
								&& rs.getString("WEIGH_TYPE").contains("理")) {
							ordInfo.setWeighType("0");
						} else {
							ordInfo.setWeighType("1");
						}
					} else {
						ordInfo.setWeighType("-1");
					}
					if (rs.getString("PRDCR_NO") != null) {
						ordInfo.setPrdcrNo(rs.getString("PRDCR_NO"));
					}
					if (rs.getString("GROUP_ROLL") != null) {
						ordInfo.setPlineD(rs.getString("GROUP_ROLL"));
					}
					if (rs.getString("MODEL_DESC") != null) {
						ordInfo.setModelDesc(rs.getString("MODEL_DESC"));
					}
					if (rs.getString("GROUP_JGX") != null) {
						groupJgx = rs.getString("GROUP_JGX");
					}
					if (rs.getString("GROUP_RCL") != null) {
						groupRcl = rs.getString("GROUP_RCL");
					}
					if (rs.getString("OUTS_STL_PIPE_FL") != null) {
						ordInfo.setOutsStlPipeFl(rs
								.getString("OUTS_STL_PIPE_FL"));
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSentity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				psta.close();
				if (ordInfo.getBom().equals("")) {
					cro.setV_errMsg("没有Bom。");
					return cro;
				}
				// 获取轧管加长原则，转移长度上下限，加工分切,控制外径壁厚 ，管单重
				ordInfo = PlnZglenthCal.calcPlnInfo(conn, ordInfo);
				if (ordInfo.getErrCode() == -1) {
					cro.setV_errMsg(ordInfo.getErrMessage());
					return cro;
				}
				// 经过工序倒推
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnProcessOrd.queryMscplPrc");
				PreparedStatement psgx = conn.prepareStatement(sql);
				psgx.setString(1, ordInfo.getDesginKey());
				psgx.setString(2, ordInfo.getIndexSeq());
				ResultSet rsgx = psgx.executeQuery();
				while (rsgx.next()) {
					if (rsgx.getString("PROCESS_CODE") == null) {
						cro.setV_errMsg("工序点代码为空。");
						return cro;
					}
					if (rsgx.getString("PROCESS_CODE").trim().equals("G")) {
						PlnOrderJgxEntity jgxEntity = new PlnOrderJgxEntity();
						jgxEntity.setGroupJgx(groupJgx);
						double addWeightJG = 0;// 加投重量
						String sqlJG = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryDesginBomI");
						if (!ordInfo.getOrderUnit().equals("支")) {
							sqlJG += " AND T.MARK = '1'";
						}
						PreparedStatement psJG = conn.prepareStatement(sqlJG);
						psJG.setString(1, ordInfo.getBom());
						ResultSet rsJG = psJG.executeQuery();
						if (rsJG.next()) {
							jgxEntity.setInwlId(rsJG
									.getString("IN_MATERIAL_NO"));
							jgxEntity.setOutwlId(rsJG
									.getString("OUT_MATERIAL_NO"));
						}
						rsJG.close();
						psJG.close();
						// 成材率
						sqlJG = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryBaseMaterialIPl");
						psJG = conn.prepareStatement(sqlJG);
						psJG.setString(1, jgxEntity.getInwlId());
						psJG.setString(2, jgxEntity.getOutwlId());
						psJG.setString(3, ordInfo.getDesginKey());
						psJG.setString(4, ordInfo.getIndexSeq());
						psJG.setString(5, jgxEntity.getGroupJgx());
						rsJG = psJG.executeQuery();
						if (rsJG.next()) {
							double wastRate = rsJG.getDouble("WASTE_RATE") / 10000;
							addWeightJG = wastRate * inWeight
									+ (ordInfo.getFinisWj())
									* (ordInfo.getAddlenZgRuleMax() / 1000)
									* ordInfo.getPlanNumD();
						}
						rsJG.close();
						psJG.close();
						inWeight = addWeightJG + inWeight;
						inWeightMin = inWeightMin + addWeightJG;
					}
					if (rsgx.getString("PROCESS_CODE").trim().equals("F")
							&& !ordInfo.getOrderUnit().equals("支")) {
						PlnOrderRclEntity rclEntity = new PlnOrderRclEntity();
						int backlogSeq = rsgx.getInt("BACKLOG_SEQ");
						double buringRate = 0;// 热处理烧损率（%）
						rclEntity.setGroupRcl(groupRcl);
						double addWeightRcl = 0;// 加投重量
						// 查询投料
						String sqlRCL = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryDesginBom");
						PreparedStatement psRCL = conn.prepareStatement(sqlRCL);
						psRCL.setString(1, ordInfo.getBom());
						ResultSet rsRCL = psRCL.executeQuery();
						if (rsRCL.next()) {
							rclEntity.setInwlId(rsRCL
									.getString("F_IN_MATERIAL_NO"));
							rclEntity.setOutwlId(rsRCL
									.getString("F_OUT_MATERIAL_NO"));
						}
						rsRCL.close();
						psRCL.close();
						// 成材率
						sqlRCL = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryBaseMaterialFPl");
						psRCL = conn.prepareStatement(sqlRCL);
						psRCL.setString(1, rclEntity.getInwlId());
						psRCL.setString(2, rclEntity.getOutwlId());
						psRCL.setString(3, ordInfo.getDesginKey());
						psRCL.setString(4, ordInfo.getIndexSeq());
						psRCL.setString(5, rclEntity.getGroupRcl());
						rsRCL = psRCL.executeQuery();
						if (rsRCL.next()) {
							double wastRate = rsRCL.getDouble("WASTE_RATE") / 10000;
							if (rsRCL.getString("PLINE_CODE") != null) {
								rclEntity.setPlineCode(rsRCL
										.getString("PLINE_CODE"));
							}
							// 查询热处理的烧损率
							String sql1 = CoreXmlSqlParsersFactory
									.getSql("CorePlnProcessOrd.queryBasePlineD");
							PreparedStatement ps1 = conn.prepareStatement(sql1);
							ps1.setString(1, rclEntity.getPlineCode());
							ResultSet rs1 = ps1.executeQuery();
							if (rs1.next()) {
								buringRate = rs1.getDouble("BURNOUT_RATE");
							}
							rs1.close();
							ps1.close();
							// 是否末工序
							if ((ordInfo.getWholeBacklog().length() + 1) / 2 == backlogSeq) {
								addWeightRcl = wastRate * inWeight;
							} else {
								int intCut = 0;// 说明:分切=0（默认1）
								if (ordInfo.getProCut() == 0) {
									intCut = 1;
								} else {
									intCut = (int) ordInfo.getProCut();
								}
								addWeightRcl = (1 + buringRate / 100)
										* (wastRate * inWeight + (ordInfo
												.getFinisWj())
												* (ordInfo.getAddInspect() / 1000)
												* (ordInfo.getPlanNumD() / intCut));
							}
						}
						rsRCL.close();
						psRCL.close();

						inWeight = inWeight + addWeightRcl;
						inWeightMin = inWeightMin + addWeightRcl;
					}
					if (rsgx.getString("PROCESS_CODE").trim().equals("E")
							&& !ordInfo.getOrderUnit().equals("支")) {
						PlnOrderDbkEntity dbkEntity = new PlnOrderDbkEntity();
						int backlogSeq = rsgx.getInt("BACKLOG_SEQ");
						String sqlDBK = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryDesginBom");
						PreparedStatement psDBK = conn.prepareStatement(sqlDBK);
						psDBK.setString(1, ordInfo.getBom());
						ResultSet rsDBK = psDBK.executeQuery();
						if (rsDBK.next()) {
							dbkEntity.setInwlId(rsDBK
									.getString("E_IN_MATERIAL_NO"));
							dbkEntity.setOutwlId(rsDBK
									.getString("E_OUT_MATERIAL_NO"));
						}
						rsDBK.close();
						psDBK.close();
						double addWeightDbk = 0;// 加投
						// 成材率
						sqlDBK = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryBaseMaterialEPl");
						psDBK = conn.prepareStatement(sqlDBK);
						psDBK.setString(1, dbkEntity.getInwlId());
						psDBK.setString(2, dbkEntity.getOutwlId());
						psDBK.setString(3, ordInfo.getDesginKey());
						psDBK.setString(4, ordInfo.getIndexSeq());
						rsDBK = psDBK.executeQuery();
						if (rsDBK.next()) {
							double wastRate = rsDBK.getDouble("WASTE_RATE") / 10000;
							// 是否末工序
							if ((ordInfo.getWholeBacklog().length() + 1) / 2 == backlogSeq) {
								addWeightDbk = wastRate * inWeight;
							} else {
								int intCut = 0; // 说明:分切=0（默认1）
								if (ordInfo.getProCut() == 0) {
									intCut = 1;
								} else {
									intCut = (int) ordInfo.getProCut();
								}
								addWeightDbk = (1 + ordInfo.getBuringRateDbk() / 100)
										* (wastRate * inWeight + (ordInfo
												.getFinisWj())
												* (ordInfo.getAddDbkLen() / 1000)
												* (ordInfo.getPlanNumD() / intCut));
							}
						}
						rsDBK.close();
						psDBK.close();

						inWeight = inWeight + addWeightDbk;
						inWeightMin = inWeightMin + addWeightDbk;
					}
					if (rsgx.getString("PROCESS_CODE").trim().equals("D")
							&& !ordInfo.getOrderUnit().equals("支")) {
						// 查询投入产出
						sql = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryDesginBom");
						ps = conn.prepareStatement(sql);
						ps.setString(1, ordInfo.getBom());
						rs = ps.executeQuery();
						if (rs.next()) {
							outdiameterIn = rs.getDouble("DIMATER");
							wallthickIn = rs.getDouble("HEIGHT");
							if (wallthickIn == 0 || outdiameterIn == 0) {
								cro.setV_errMsg("未找到轧管规格。");
								return cro;
							}
							diameterGp = rs.getDouble("SPEC_SECTION");
						}
						rs.close();
						ps.close();
						// /查询产线基础表
						sql = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryBasePlineD");
						ps = conn.prepareStatement(sql);
						ps.setString(1, zgSentity.getPlineCode());
						rs = ps.executeQuery();
						if (rs.next()) {
							lengthColdbed = rs.getDouble("LENGTH_COLDBED");
							lengthMaxRing = rs.getDouble("LENGTH_MAX_RING");
							burnoutRate = rs.getDouble("BURNOUT_RATE");
							zgSentity.setPlineName(rs.getString("PLINE_NAME"));
							lengthMinTube = rs.getDouble("LENGTH_MIN_TUBE");
							lengthMaxTube = rs.getDouble("LENGTH_MAX_TUBE");
							toleranceZone = rs.getDouble("TOLERANCE_ZONE");

						}
						rs.close();
						ps.close();
						int outMultd = 1;
						if (ordInfo.getOutMultD() == 0) {
							outMultd = ordInfo.getOutMultD();
						}
						double cutMax = 0;// 最大分切数
						// 成材率
						double wastRate = 0;
						sql = CoreXmlSqlParsersFactory
								.getSql("CorePlnProcessOrd.queryBaseMaterialDPl");
						ps = conn.prepareStatement(sql);
						ps.setString(1, zgSentity.getInwlId());
						ps.setString(2, zgSentity.getOutwlId());
						ps.setString(3, zgSentity.getPlineCode());
						rs = ps.executeQuery();
						if (rs.next()) {
							wastRate = rs.getDouble("WASTE_RATE") / 10000;
							addNum = (int) Math.ceil(wastRate
									* Integer.parseInt(zgSentity.getNumS()));
							addWeight = wastRate * inWeight;
							if (zgSentity.getLenCuthead().equals("")) {
								cropHead = rs.getDouble("CROP_HEAD");
							} else {
								cropHead = Double.parseDouble(zgSentity
										.getLenCuthead());
							}
							if (zgSentity.getLenCutend().equals("")) {
								cropEnd = rs.getDouble("CROP_END");
							} else {
								cropEnd = Double.parseDouble(zgSentity
										.getLenCutend());
							}
							if (zgSentity.getTubeEndRatio().equals("")) {
								tubeEndRatio = rs.getDouble("TUBE_END_RATIO");
							} else {
								tubeEndRatio = Double.parseDouble(zgSentity
										.getTubeEndRatio());
							}
							cutMax = rs.getDouble("DBL_LEN_MAX");
							capacity = rs.getDouble("HR_CAPCTY");
							zgSentity.setAddNumIn(String.valueOf(addNum));
							zgSentity.setLenCuthead(String.valueOf(cropHead));
							zgSentity.setLenCutend(String.valueOf(cropEnd));
						}
						rs.close();
						ps.close();

						InZgOrdCalEntity ordEntity = new InZgOrdCalEntity();
						OutZgOrdCalEntity ordCalEntity = new OutZgOrdCalEntity();
						CoreTolerOfNk tolerOfNk = new CoreTolerOfNk();
						CoreTolerOfNkParam nkParam = new CoreTolerOfNkParam();
						List<Double> listDiameter = new ArrayList<Double>();

						// 如果不是外购管，则计算投料管坯
						if (!zgSentity.getPlineCode().trim().equals("C065")
								&& !zgSentity.getPlineCode().trim()
										.equals("C066")) {
							listDiameter.add(diameterGp);
							// 轧管内控壁厚公差
							nkParam.setBias_code("404019");
							nkParam.setOutdiameter(outdiameterIn);
							nkParam.setWallthick(wallthickIn);
							nkParam.setSic(sic);
							nkParam.setLengthmax(ordInfo.getLengthmax());
							nkParam.setLengthmin(ordInfo.getLengthmin());
							nkParam = tolerOfNk.queryTolerance(nkParam,
									ordInfo.getDesginKey(),
									ordInfo.getIndexSeq(), "D");
							if (nkParam != null) {
								if (nkParam.getWallUpper() == 0
										&& nkParam.getWallLower() == 0) {
									ordEntity.setWallUpper(0);
									ordEntity.setWallLower(0);
									zgSentity.setThicknessWall("");
								} else {
									ordEntity.setWallUpper(nkParam
											.getWallUpper());
									ordEntity.setWallLower(nkParam
											.getWallLower());
									zgSentity.setThicknessWall("-"
											+ new BigDecimal(Math.abs(100
													* ordEntity.getWallLower()
													/ wallthickIn)).setScale(2,
													RoundingMode.HALF_UP)
													.doubleValue()
											+ "%~+"
											+ new BigDecimal(100
													* ordEntity.getWallUpper()
													/ wallthickIn).setScale(2,
													RoundingMode.HALF_UP)
													.doubleValue() + "%");
								}

							}
							if (ordInfo.getShrtStove() != null
									&& !ordInfo.getShrtStove().equals("")
									&& !ordInfo.getShrtStove().equals("/")) {
								ordEntity.setShrtstove(true);
							}
							// 轧管内外径公差
							nkParam.setBias_code("404012");
							nkParam.setOutdiameter(outdiameterIn);
							nkParam.setWallthick(wallthickIn);
							nkParam.setSic(sic);
							nkParam.setLengthmax(ordInfo.getLengthmax());
							nkParam.setLengthmin(ordInfo.getLengthmin());
							nkParam = tolerOfNk.queryToleranceAim(nkParam,
									ordInfo.getDesginKey(),
									ordInfo.getIndexSeq(), "D");
							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());
								}
							}

							// 计算轧管投入管坯
							ordEntity.setTubeEndRatio(tubeEndRatio);
							ordEntity.setPlanNum(Integer.parseInt(zgSentity
									.getNumS()));
							ordEntity.setAddNum(addNum);
							ordEntity.setDiameter(outdiameterIn);
							ordEntity.setWallthick(wallthickIn);
							ordEntity.setSigllen(ordInfo.getSiglLen());
							ordEntity.setShortest(ordInfo.getShortest());
							ordEntity.setBurning(burnoutRate);
							ordEntity.setDiame(listDiameter);
							ordEntity.setLengmax(ordInfo.getLengthmax());
							ordEntity.setLengmin(ordInfo.getLengthmin());
							ordEntity.setLengthmax(ordInfo.getLenMax());
							ordEntity.setLengthmin(ordInfo.getLenMin());
							ordEntity.setCutHeadEnd(cropHead + cropEnd);
							ordEntity.setLengthMaxRing(lengthMaxRing);
							ordEntity.setLengthColdbed(lengthColdbed);
							ordEntity.setAvgLenMin(ordInfo.getAvgLenMin());
							ordEntity.setOrdLnDlyPk(zgSentity.getOrdLnDlyPk());
							ordEntity.setPassMame(zgSentity.getPassName());
							ordEntity.setPassCode(zgSentity.getPassCode());
							ordEntity.setLengthMinTube(lengthMinTube);
							ordEntity.setLengthMaxTube(lengthMaxTube);
							ordEntity.setToleranceZone(toleranceZone);
							ordEntity.setPlineCode(zgSentity.getPlineCode());
							ordEntity.setPlineName(zgSentity.getPlineName());
							ordEntity.setWeighType(ordInfo.getWeighType());
							ordEntity.setOrderUnit(ordInfo.getOrderUnit());
							ordEntity.setDimeterGp(diameterGp);
							ordEntity
									.setPlnDivideId(zgSentity.getPlnDivideId());
							ordEntity.setCutMax(cutMax);
							ordEntity.setEndlenSpecstd(ordInfo
									.getEndlenSpecstd());
							ordEntity.setAddWeight(addWeight);
							ordEntity.setPlanWeight(inWeight);
							ordEntity.setRollMonth(ordInfo.getRollMonth());
							ordEntity.setWeigthSMin(inWeightMin);
							ordCalEntity = PlnZgProcCal.getZgOrdCal(conn,
									ordEntity, true);
							if (ordCalEntity.getErrCode() == -1) {
								cro.setV_errMsg("合同号：" + zgSentity.getOrderNo()
										+ "," + ordCalEntity.getErrMessage());
								return cro;
							}
							zgSentity.setPassCode(ordCalEntity.getPassCode());
							zgSentity.setPassName(ordCalEntity.getPassMame());
							zgSentity.setDiameterMandrel(ordCalEntity
									.getDiameterMandrel());
							zgSentity.setVerify1(ordCalEntity.getVerify1());
							zgSentity.setVerify2(ordCalEntity.getVerify2());
							zgSentity.setVerify3(ordCalEntity.getVerify3());
							zgSentity.setGpreqNum(String.valueOf(ordCalEntity
									.getGpreqNum()));
							zgSentity.setGpreqWeight(String
									.valueOf(ordCalEntity.getGpreqWeight()));
							zgSentity.setGpreqWeightMin(ordCalEntity
									.getGpreqWeightMin());
							int plansNum = (int) Math
									.ceil((ordCalEntity.getGpreqNum()
											* ordCalEntity.getCutNum() * (1 - wastRate)));
							zgSentity.setPlansNum(String.valueOf(plansNum));

						} else {
							ordCalEntity
									.setAimZgLen((ordInfo.getLenMin() + ordInfo
											.getLenMax()) / 2);
						}
						if (addWeight == 0) {
							zgSentity.setAddWtIn("0");
						} else {
							zgSentity.setAddWtIn(String.valueOf(new BigDecimal(
									addWeight)
									.setScale(3, RoundingMode.HALF_UP)));
						}
						zgSentity.setWallthickZg(String.valueOf(wallthickIn));
						zgSentity.setOutdiameterZg(String
								.valueOf(outdiameterIn));
						zgSentity.setAimoutdiameter(String.valueOf(ordCalEntity
								.getAimoutdiameter()));
						zgSentity.setAimwallthick(String.valueOf(ordCalEntity
								.getAimWallthick()));
						zgSentity.setLenRollMax(String.valueOf(ordInfo
								.getLenMax()));
						zgSentity.setLenRollMin(String.valueOf(ordInfo
								.getLenMin()));
						zgSentity.setAimlength(String.valueOf(ordCalEntity
								.getAimZgLen()));
						zgSentity.setAimlength(String.valueOf(ordCalEntity
								.getAimZgLen()));
						zgSentity.setRollLength(String.valueOf(ordCalEntity
								.getLenZz()));
						zgSentity.setOutnumCut(String.valueOf(ordCalEntity
								.getCutNum()));
						zgSentity.setDiameterGp(String.valueOf(diameterGp));
						zgSentity.setLenGpSingle(String.valueOf(ordCalEntity
								.getLenGp() * 1000));
						String planTimeB = zgSentity.getPlanTimeB();
						TimeEntity TimeEntiy = helperBean.calculateTime(
								Integer.parseInt(zgSentity.getGpreqNum()),
								capacity, planTimeB);
						// 计划结束时间
						String planTimeE = TimeEntiy.getEndTime();
						zgSentity.setPlanUsetime(TimeEntiy.getUserTime());
						zgSentity.setPlanTimeB(planTimeB);
						zgSentity.setPlanTimeE(planTimeE);
						planTimeB = planTimeE;

						if (ordCalEntity.getInvenWt() > 0.000001) {
							prdRate = inWeight / ordCalEntity.getInvenWt();
						}
						if (ordInfo.getUseDesc() == null
								|| ordInfo.getUseDesc().equals("")
								|| ordInfo.getUseDesc().equals("/")) {

							zgSentity.setProdStandard(ordInfo.getStdName());
						} else {
							zgSentity.setProdStandard(ordInfo.getStdName()
									+ "," + ordInfo.getUseDesc());
						}
						if (ordInfo.getOrderSource().equals("备料需求")) {
							zgSentity.setOutputStandard(ordInfo.getStdName());
						} else {
							if (ordInfo.getOutputStdNo().equals("122701")) {// 产品标准
								zgSentity.setOutputStandard(ordInfo
										.getStdName());
							} else if (ordInfo.getOutputStdNo()
									.equals("122702")) {// 用途码描述
								zgSentity.setOutputStandard(ordInfo
										.getUseDesc());
							} else if (ordInfo.getOutputStdNo()
									.equals("122703")) {// 产品标准+用途码描述
								zgSentity.setOutputStandard(ordInfo
										.getStdName()
										+ ","
										+ ordInfo.getUseDesc());
							}
						}
						zgSentity.setDecision(ordInfo.getAbc());
						zgSentity.setWeigthS(String.valueOf(inWeight));
						zgSentity
								.setNumS(String.valueOf(ordInfo.getPlanNumD()));
						zgSentity.setWeigthSMin(String.valueOf(inWeightMin));
						// 修改轧管排产耗时表
						String sqlUp = EntityTool.fillSqlByEntity(sqlupdate,
								zgSentity);
						ps = conn.prepareStatement(sqlUp);
						ps.executeUpdate();
						ps.close();

						double planWtMax = inWeight
								* (1 + delvryRangeMax / 100);
						double planWtMin = inWeight
								* (1 - delvryRangeMin / 100);
						// 修改轧管排产订单表
						sqlUp = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updateZgOrdGxMNo"),
										zgSentity);
						psta = conn.prepareStatement(sqlUp);
						psta.setObject(1, prdRate);
						psta.setObject(2, ordCalEntity.getWeightGpOne());
						psta.setObject(3, planWtMin);
						psta.setObject(4, planWtMax);
						psta.executeUpdate();
						psta.close();
						// 修改轧管排产合同表
						sqlUp = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updatePlnOrderZg"),
										zgSentity);
						psta = conn.prepareStatement(sqlUp);
						psta.setObject(1, prdRate);
						psta.setObject(2, ordCalEntity.getWeightGpOne());
						psta.executeUpdate();
						psta.close();
						// 修改合同接收表推荐长度
						sqlUp = CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.updatePlnSaorder");
						psta = conn.prepareStatement(sqlUp);
						psta.setObject(1, zgSentity.getLengthdiscN());
						psta.setObject(2, zgSentity.getLenNoN());
						psta.setObject(
								3,
								zgSentity.getOrdLnDlyPk().substring(0,
										zgSentity.getOrdLnDlyPk().length() - 3));
						psta.executeUpdate();
						psta.close();

						// gxProseq = Integer.parseInt(zgSentity.getGxProSeq());
						// plineCode = zgSentity.getPlineCode();
						// planTimeE1 = planTimeE;
						// // 时间自动调整
						// helperBean.timeIncrease(conn, gxProseq, plineCode,
						// planTimeE1, "D");
					}
				}
				rsgx.close();
				psgx.close();
			}
			cro.setV_errMsg("重头计算完成!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		} catch (ParseException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	
	/**
	 * 坯料测算保存按钮
	 * tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculate3(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<TPoDemandPlanEntity> list = PlnHelper.jsonsToEntityList(
					TPoDemandPlanEntity.class, jsonList);
			for (TPoDemandPlanEntity zgSentity : list) {
				int count = 0;
				String sql = CoreXmlSqlParsersFactory
						.getSql("TPoDemandPlan.updateTPoDemandPlan2");
				PreparedStatement psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getDiameterMandrel());
				psta.setString(2, zgSentity.getWgD());
				psta.setString(3, zgSentity.getWgH());
				psta.setString(4, zgSentity.getMgcd());
				psta.setString(5, zgSentity.getZzcd());
				psta.setString(6, zgSentity.getGgfqs());	
				psta.setString(7, zgSentity.getCpcd());
				psta.setString(8, zgSentity.getQt());	
				psta.setString(9, zgSentity.getQw());
				psta.setString(10, zgSentity.getBcs());
				psta.setString(11, zgSentity.getDbcplcd());
				psta.setString(12, zgSentity.getGpzj());
				psta.setString(13, zgSentity.getHtcgzlMax());	
				psta.setString(14, zgSentity.getQuantityPurchased());		
				psta.setString(15, zgSentity.getDbcplzl());
				psta.setString(16, zgSentity.getSsl());
				psta.setString(17, zgSentity.getMz());
				psta.setString(18, zgSentity.getZzzl());
				psta.setString(19, zgSentity.getJhlc());
				psta.setString(20, zgSentity.getHtcgzlMin());
				
				psta.setString(21, zgSentity.getPlanNo());
				
				
				//rs = psta.executeQuery();
				psta.executeUpdate();
				psta.close();
				
					}
				
			
			cro.setV_errMsg("保存成功!");
			conn.commit();
		
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		}  finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
	
	/**
	 * 坯料测算上传按钮
	 * tzh 24.8.24
	 * tzh 24.9.18 新增修改状态
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculate4(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			JSONObject jsonObj = new JSONObject();
			String Result = "";
			List<TPoDemandPlanEntity> list = PlnHelper.jsonsToEntityList(
					TPoDemandPlanEntity.class, jsonList);
			for (TPoDemandPlanEntity zgSentity : list) {
				//修改上传状态 24.9.28 tzh
				String sql = CoreXmlSqlParsersFactory
						.getSql("TPoDemandPlan.updateTPoDemandPlan3");
				PreparedStatement psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getPlanNo());
				psta.executeUpdate();
				psta.close();
				
				jsonObj.put("plan_no", zgSentity.getPlanNo());//计划号
				jsonObj.put("ruler_length", zgSentity.getRulerLength());//倍尺长度
				jsonObj.put("section", zgSentity.getGpzj()); //断面 直径 
				jsonObj.put("length", zgSentity.getDbcplcd());//单倍尺坯料长度
				jsonObj.put("quantity_purchased", zgSentity.getQuantityPurchased());//采购量
				jsonObj.put("flag", "U"); 
				jsonObj.put("plan_type", "1");
				DefaultWebServiceRequest request = new DefaultWebServiceRequest();
				request.setMsgBody(jsonObj.toString());
				request.setServiceId("MESTHPO01");
//				Object[] values = new Object[2];
//				values[0] = "{\"KEY\":"+jsonObj.toString()+"}";
//				//tzh 24.9.24 上次注释掉了  
				Result  = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx", request,
						"receiveMessage","");	
					}

			//return Result+values[0].toString().substring(0, 100);
			cro.setV_errMsg("上传成功！");
			conn.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			cro.setV_errMsg(e.getMessage());;
		}
		return cro;
	}
	
	/**
	 * 高新基础信息查询 tzh 24.10.28 add
	 * 
	 * @param includeDeleted
	 *            是否包含已删除数据
	 * @param name
	 *            高新名称
	 * @return CoreReturnObject 必须返回CoreReturnObject
	 */
	public CoreReturnObject getGXList(Boolean includeDeleted, String name) {
		String deletedFlag = includeDeleted ? "0" : "";
		Object[] params = new Object[] { deletedFlag, name };
		return this.getDataBySqlID("CorePlnZgMStoGp.GXS", params);
	}
	
	/**
	 * 高新基础信息新增  tzh 24.10.28 add
	 * 
	 * @param parm
	 *            参数
	 * @return CoreReturnObject 必须返回CoreReturnObject
	 */
	public CoreReturnObject doAdd(ArrayList<Object> parm) {
		CoreReturnObject cro = new CoreReturnObject();

		String strSql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.GXADD");
		
		try {
				cro = this.getDao("TgDao").ExcuteNonQuery(strSql,
						parm.toArray());
		} catch (SQLException e) {
			cro.setV_errCode(-2);
			cro = cro.SetErrInfo(e.getMessage());
		}

		return cro;
	}
	
	/**
	 * 高新基础信息修改  tzh 24.10.28 add
	 * 
	 * @param parm
	 *            参数
	 * @return CoreReturnObject 必须返回CoreReturnObject
	 */
	public CoreReturnObject doModify(ArrayList<Object> parm) {
		CoreReturnObject cro = new CoreReturnObject();

		String strSql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.GXMODIFY");

		try {
				cro = this.getDao("TgDao").ExcuteNonQuery(strSql,
						parm.toArray());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			cro.setV_errCode(-2);
			cro = cro.SetErrInfo(e.getMessage());
		}

		return cro;
	}
	
	/**
	 * 高新基础信息删除或恢复   tzh 24.10.28 add
	 * 
	 * @param plineCodes
	 *           高新编码集合
	 * @param operator
	 *            操作人
	 * @param isDelete
	 *            true删除 false恢复
	 * @return CoreReturnObject 必须返回CoreReturnObject
	 */
	public CoreReturnObject deleteLineInfo(ArrayList<Object> plineCodes,
			String operator, Boolean isDelete) {
		ArrayList<String> sqlIDList = new ArrayList<String>();
		ArrayList<Object[]> params = new ArrayList<Object[]>();
		for (int i = 0; i < plineCodes.size(); i++) {
			if (isDelete) {
				sqlIDList.add("CorePlnZgMStoGp.GXDELETE");
//				params.add(new Object[] { operator,
//						plineCodes.get(i).toString() });
				params.add(new Object[] { plineCodes.get(i).toString() });
			} else {
				sqlIDList.add("CorePlnZgMStoGp.GXRESUME");
				params.add(new Object[] { plineCodes.get(i).toString() });
			}
		}
		return this.setDataById(sqlIDList, params);
	}
	
	/**
	 * 判断高新信息是否重复  tzh 24.10.28 add
	 * @param code
	 * @return
	 */
	public CoreReturnObject GetCode(String code) {
		Object[] obj = new Object[] { code };
		return this.getDataBySqlID("CorePlnZgMStoGp.GXGetCode", obj);
	}
	
	/*
	 * tzh 2024.8.7 add  
	 */
	public CoreReturnObject queryCXcode(String code) {
		String sql ="";
		List<String> params = new ArrayList<String>();
		
			sql += " select GX_CODE,GX_NAME  from HOT_PRODUCTION_MES_GX t where t.VALIDFLAG = '1' ";
		
		return this.getData(sql, params.toArray());
	}
	
	
	/**
	 * 查询热处理高新数据
	 *  tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject selectrclgx(String acctPeriod) {
		//CoreReturnObject cro = null;

		String sql = CoreXmlSqlParsersFactory
				.getSql("TPoDemandPlan.queryrclgx");
		List<String> params = new ArrayList<String>();

		
		params.add(acctPeriod.replace("-", ""));
		
		return this.getData(sql, params.toArray());
	}
	
	/**
	 * 查询加工高新数据
	 *  tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject selectjggx(String acctPeriod) {
		//CoreReturnObject cro = null;

		String sql = CoreXmlSqlParsersFactory
				.getSql("TPoDemandPlan.queryjggx");
		List<String> params = new ArrayList<String>();

		
		params.add(acctPeriod.replace("-", ""));
		return this.getData(sql, params.toArray());
	}
	
	
	
	/**
	 * 查询加工高新数据
	 *  tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject selectrzgx(String acctPeriod) {
		//CoreReturnObject cro = null;

		String sql = CoreXmlSqlParsersFactory
				.getSql("TPoDemandPlan.queryrzgx");
		List<String> params = new ArrayList<String>();
		params.add(acctPeriod.replace("-", ""));
		return this.getData(sql, params.toArray());
		
	}
	
	
	/**
	 * 保存和撤销热处理高新  1是保存   0是撤销
	 * tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculateRCL(ArrayList<String> jsonList,String idflag) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<HotHeatProductionMesGxEntity> list = PlnHelper.jsonsToEntityList(
					HotHeatProductionMesGxEntity.class, jsonList);
			for (HotHeatProductionMesGxEntity zgSentity : list) {
				int count = 0;
				PreparedStatement psta = null;
				String sql = "";
				if(idflag.equals("1")){
					//判断高新数据是否已存在
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.queryGXCNTRCL");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
					ResultSet rs = null;
					rs = psta.executeQuery();
					if (rs.next()) {
					
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.updateCxMesGxRCL");
						psta = conn.prepareStatement(sql);
						
						psta.setString(1, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(2, zgSentity.getHighTechName());//高新项目名称
						psta.setString(3, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(4, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(5, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(6, zgSentity.getEstimatedCost());//高新预估费用
						psta.setString(7, zgSentity.getJudgeStoveNo());
						psta.setString(8, zgSentity.getOrderId());
						psta.setString(9, zgSentity.getBalYearMonth());
						
					}else{
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.insertCxMesGxRCL");
						psta = conn.prepareStatement(sql);
						psta.setString(1, zgSentity.getJudgeStoveNo());
						psta.setString(2, zgSentity.getOrderId());
						psta.setString(3, zgSentity.getBalYearMonth());
						psta.setString(4, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(5, zgSentity.getHighTechName());//高新项目名称
						psta.setString(6, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(7, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(8, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(9, zgSentity.getEstimatedCost());//高新预估费用
					}
				}
				else {
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.deleteCxMesGxRCL");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
				}
				
				
//				}
//				else {
//					psta.setString(2, "0");//高新坯料重量
//					psta.setString(3, "0");//高新成品重量
//				}
//				psta.setString(4, zgSentity.getCxNo());
		
				psta.executeUpdate();
				psta.close();
					}
			cro.setV_errMsg("保存成功!");
			conn.commit();
		
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		}  finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
	
	/**
	 * 保存和撤销加工高新  1是保存  0是撤销
	 * tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculateJG(ArrayList<String> jsonList,String idflag) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			
			
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<HotProductionMesJgEntity> list = PlnHelper.jsonsToEntityList(
					HotProductionMesJgEntity.class, jsonList);
			for (HotProductionMesJgEntity zgSentity : list) {
				int count = 0;
				PreparedStatement psta = null;
				String sql = "";
				if(idflag.equals("1")){
					//判断高新数据是否已存在
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.queryGXCNTJG");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
					ResultSet rs = null;
					rs = psta.executeQuery();
					if (rs.next()) {
					
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.updateCxMesGxJG");
						psta = conn.prepareStatement(sql);
						
						psta.setString(1, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(2, zgSentity.getHighTechName());//高新项目名称
						psta.setString(3, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(4, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(5, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(6, zgSentity.getEstimatedCost());//高新预估费用
						psta.setString(7, zgSentity.getJudgeStoveNo());
						psta.setString(8, zgSentity.getOrderId());
						psta.setString(9, zgSentity.getBalYearMonth());
						
					}else{
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.insertCxMesGxJG");
						psta = conn.prepareStatement(sql);
						psta.setString(1, zgSentity.getJudgeStoveNo());
						psta.setString(2, zgSentity.getOrderId());
						psta.setString(3, zgSentity.getBalYearMonth());
						psta.setString(4, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(5, zgSentity.getHighTechName());//高新项目名称
						psta.setString(6, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(7, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(8, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(9, zgSentity.getEstimatedCost());//高新预估费用
					}
				}
				else {
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.deleteCxMesGxJG");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
				}
				
				
//				}
//				else {
//					psta.setString(2, "0");//高新坯料重量
//					psta.setString(3, "0");//高新成品重量
//				}
//				psta.setString(4, zgSentity.getCxNo());
		
				psta.executeUpdate();
				psta.close();
					}
			cro.setV_errMsg("保存成功!");
			conn.commit();
		
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		}  finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
	
	
	/**
	 * 保存和撤销加工高新  1是保存   0是撤销
	 * tzh 24.8.24
	 * @param
	 * @return
	 */
	public CoreReturnObject recalculateRZ(ArrayList<String> jsonList,String idflag) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<HotProductionMesJgEntity> list = PlnHelper.jsonsToEntityList(
					HotProductionMesJgEntity.class, jsonList);
			for (HotProductionMesJgEntity zgSentity : list) {
				int count = 0;
				PreparedStatement psta = null;
				String sql = "";
				if(idflag.equals("1")){
					//判断高新数据是否已存在
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.queryGXCNT");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
					ResultSet rs = null;
					rs = psta.executeQuery();
					if (rs.next()) {
					
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.updateCxMesGxRZ");
						psta = conn.prepareStatement(sql);
						
						psta.setString(1, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(2, zgSentity.getHighTechName());//高新项目名称
						psta.setString(3, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(4, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(5, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(6, zgSentity.getEstimatedCost());//高新预估费用
						psta.setString(7, zgSentity.getJudgeStoveNo());
						psta.setString(8, zgSentity.getOrderId());
						psta.setString(9, zgSentity.getBalYearMonth());
						
					}else{
						sql = CoreXmlSqlParsersFactory
								.getSql("TPoDemandPlan.insertCxMesGxRZ");
						psta = conn.prepareStatement(sql);
						psta.setString(1, zgSentity.getJudgeStoveNo());
						psta.setString(2, zgSentity.getOrderId());
						psta.setString(3, zgSentity.getBalYearMonth());
						psta.setString(4, zgSentity.getHighTechCode());//高新项目编码
						psta.setString(5, zgSentity.getHighTechName());//高新项目名称
						psta.setString(6, zgSentity.getHighProdWeight());//高新成品重量
						psta.setString(7, zgSentity.getHighMateWeight());//高新坯料重量
						psta.setString(8, zgSentity.getEstimatedUnitPrice());//高新预估单价
						psta.setString(9, zgSentity.getEstimatedCost());//高新预估费用
					}
				}
				else {
					sql = CoreXmlSqlParsersFactory
							.getSql("TPoDemandPlan.deleteCxMesGxRZ");
					psta = conn.prepareStatement(sql);
					psta.setString(1, zgSentity.getJudgeStoveNo());
					psta.setString(2, zgSentity.getOrderId());
					psta.setString(3, zgSentity.getBalYearMonth());
				}
				
				
//				}
//				else {
//					psta.setString(2, "0");//高新坯料重量
//					psta.setString(3, "0");//高新成品重量
//				}
//				psta.setString(4, zgSentity.getCxNo());
		
				psta.executeUpdate();
				psta.close();
					}
			cro.setV_errMsg("保存成功!");
			conn.commit();
		
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getMessage());
		}  finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
	
	/**
	 * 修改排产年月
	 * 
	 * @param
	 * @return
	 */
	@SuppressWarnings("null")
	public CoreReturnObject updateMonth(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement psta = null;
			ResultSet rs = null;
			int gxProSeq = 0;// 获取生产序号

			DateFormat df = new SimpleDateFormat("yyyy-MM");
			Date time = new Date();
			String nowTime = df.format(time);
			for (PlnOrderZgSEntity zgSentity : list) {
				String exeStatus = "";
				String proMonth = "";
				String isPlanOk = "";// 确认
				String ifStoveiss = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getProPlanId());
				psta.setString(2, zgSentity.getGxPlanNo());
				rs = psta.executeQuery();
				if (rs.next()) {
					exeStatus = rs.getString("EXE_STATUS");
					proMonth = rs.getString("PRO_MONTH");
					gxProSeq = rs.getInt("GX_PRO_SEQ");
					isPlanOk = rs.getString("IS_PLAN_OK");
					ifStoveiss = rs.getString("IF_STOVE_ISSUED");
				} else {
					cro.setV_errMsg("找不到合同：" + zgSentity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				psta.close();
				if (!exeStatus.equals("0")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "不是计划状态,不能调整。");
					return cro;
				}
				// if (isPlanOk != null && isPlanOk.equals("1")) {
				// cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
				// + "已确认,不能调整。");
				// return cro;
				// }
				if (ifStoveiss != null && ifStoveiss.equals("1")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "已炉计划下发,不能调整。");
					return cro;
				}
				// 查询数据库服务器当前时间
				String sqlTime = CoreXmlSqlParsersFactory
						.getSql("ProducHelperBean.selectSystemTime");
				psta = conn.prepareStatement(sqlTime);
				rs = psta.executeQuery();
				if (rs.next()) {
					nowTime = rs.getString("DATIME").substring(0, 7);
				}
				rs.close();
				psta.close();
				if (proMonth.equals(zgSentity.getProMonth())) {
					cro.setV_errMsg("合同：" + zgSentity.getProPlanId() + "/"
							+ zgSentity.getGxPlanNo() + "生产年月未变化,不能调整。");
					return cro;
				}
				// 查询sql年月当前系统年月比较
				if (df.parse(proMonth).getTime() < df.parse(nowTime).getTime()) {
					// 修改年月与系统年月比较
					if (df.parse(zgSentity.getProMonth()).getTime() > df.parse(
							nowTime).getTime()) {
						cro.setV_errMsg("合同号" + zgSentity.getOrderNo()
								+ ",原生产年月小于当前日历年月,不能调整到比当前日历年月大。");
						return cro;
					}
				} else {
					// 修改年月与系统年月比较
					if (df.parse(zgSentity.getProMonth()).getTime() < df.parse(
							nowTime).getTime()) {
						cro.setV_errMsg("合同号" + zgSentity.getOrderNo()
								+ ",原生产年月大于等于当前日历年月,不能调整到比当前日历年月小。");
						return cro;
					}
				}

				// 修改排产月份
				updatePlnOrderZg(conn, zgSentity, gxProSeq);
				updatePlnOrderJgx(conn, zgSentity, gxProSeq);
				updatePlnOrderRcl(conn, zgSentity, gxProSeq);
				updatePlnOrderDbk(conn, zgSentity, gxProSeq);

				// 修改排产分解表排产年月
				String sqlupdate = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updateRollMonth");
				psta = conn.prepareStatement(sqlupdate);
				psta.setObject(1, zgSentity.getProMonth());
				psta.setObject(2, zgSentity.getOrdLnDlyPk());
				psta.setObject(3, zgSentity.getPlnDivideId());
				psta.executeUpdate();
				psta.close();
			}
			cro.setV_errMsg("调整成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (ParseException pe) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(pe.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改加工排产年月
	 * 
	 * @param conn
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void updatePlnOrderJgx(Connection conn, PlnOrderZgSEntity zgSentity,
			int gxProSeqM) throws SQLException, ParseException {

		PreparedStatement ps = null;
		String sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatePlnOrderJGXSMonth"), zgSentity);
		ps = conn.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
		// 修改订单主表年月
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatPlnGxJGXMonth");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, zgSentity.getProMonth());
		ps.setObject(2, zgSentity.getOrdLnDlyPk());
		ps.setObject(3, zgSentity.getPlnDivideId());
		ps.executeUpdate();
		ps.close();

	}

	/**
	 * 修改热处理排产年月
	 * 
	 * @param conn
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void updatePlnOrderRcl(Connection conn, PlnOrderZgSEntity zgSentity,
			int gxProSeqM) throws SQLException, ParseException {
		PreparedStatement ps = null;

		String sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatePlnOrderRCLSMonth"), zgSentity);
		ps = conn.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
		// 修改订单主表年月
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatPlnGxRCLMonth");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, zgSentity.getProMonth());
		ps.setObject(2, zgSentity.getOrdLnDlyPk());
		ps.setObject(3, zgSentity.getPlnDivideId());
		ps.executeUpdate();
		ps.close();

	}

	/**
	 * 修改镦拔扩排产年月
	 * 
	 * @param conn
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void updatePlnOrderDbk(Connection conn, PlnOrderZgSEntity zgSentity,
			int gxProSeqM) throws SQLException, ParseException {

		PreparedStatement ps = null;

		String sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatePlnOrderDBKSMonth"), zgSentity);
		ps = conn.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
		// 修改订单主表年月
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatPlnGxDBKMonth");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, zgSentity.getProMonth());
		ps.setObject(2, zgSentity.getOrdLnDlyPk());
		ps.setObject(3, zgSentity.getPlnDivideId());
		ps.executeUpdate();
		ps.close();

	}

	/**
	 * 修改轧管排产年月
	 * 
	 * @param conn
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void updatePlnOrderZg(Connection conn, PlnOrderZgSEntity zgSentity,
			int gxProSeqM) throws SQLException, ParseException {
		PreparedStatement psta = null;
		// 修改年月
		ProducHelperBean helperBean = new ProducHelperBean();
		String planTimeE = "";
		String planTimeB = "";
		int gxProSeq = helperBean.getMaxGxProSeq(conn,
				zgSentity.getPlineCode(), "D", zgSentity.getProMonth());
		// 调整行操作
		/**
		 * 2. 前移(需要操作步骤:1.)
		 */
		if (gxProSeq <= gxProSeqM) {
			// 3.1计划开始时间(这个时间应该从数据库里查)
			planTimeB = helperBean.getMaxPlanTimeE(conn,
					zgSentity.getPlineCode(), "D", zgSentity.getProMonth(),
					gxProSeq);
			// 2.1序号自动调整
			helperBean.seqIncrease(conn, zgSentity.getPlineCode(), gxProSeq,
					gxProSeqM, 1, "D");
			planTimeE = BaseHelper.addTime(planTimeB,
					zgSentity.getPlanUsetime());
			zgSentity.setGxProSeq(String.valueOf(gxProSeq));
			// 2.3自动调整时间
			helperBean.timeIncrease(conn, gxProSeq, zgSentity.getPlineCode(),
					planTimeE, "D");
		} else {
			/**
			 * 3.后移
			 */
			// 3.1计划开始时间(这个时间应该从数据库里查)
			planTimeB = helperBean.getMaxPlanTimeE(conn,
					zgSentity.getPlineCode(), "D", zgSentity.getProMonth(),
					gxProSeq);
			// 如果不是小于最小序号,那么肯定是大于最大序号,前面加以限制

			planTimeE = BaseHelper.addTime(planTimeB,
					zgSentity.getPlanUsetime());
			// 3.1序号自动调整
			helperBean.seqIncrease(conn, zgSentity.getPlineCode(), gxProSeqM,
					gxProSeq, -1, "D");
			zgSentity.setGxProSeq(String.valueOf(gxProSeq - 1));

			// 获取当选中行上一行记录结束时间
			String planTimeEX = helperBean.getMaxPlanTimeEX(conn,
					zgSentity.getPlineCode(), "D", zgSentity.getProMonth(),
					gxProSeqM - 1);
			// 2.3自动调整时间
			helperBean.timeIncrease(conn, gxProSeqM - 1,
					zgSentity.getPlineCode(), planTimeEX, "D");
		}

		zgSentity.setPlanTimeB(planTimeB);
		zgSentity.setPlanTimeE(planTimeE);
		String sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.updatePlnOrderZgSMonth"), zgSentity);
		psta = conn.prepareStatement(sql);
		psta.executeUpdate();
		psta.close();

		// 查询轧管耗时表最小年月
		sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnZgMStoGp.selectZgPlnSMonthMin");
		psta = conn.prepareStatement(sql);
		psta.setObject(1, zgSentity.getProPlanId());
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			String minMonth = rs.getString("PRO_MONTH");
			String planTime = rs.getString("PLAN_TIME_B");
			String planUsetime = rs.getString("PLAN_USETIME");
			PreparedStatement ps = null;
			// 修改订单主表年月
			sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updatPlnGxZgMonth");
			ps = conn.prepareStatement(sql);
			ps.setObject(1, minMonth);
			ps.setObject(2, planTime);
			ps.setObject(3, planUsetime);
			ps.setObject(4, zgSentity.getProPlanId());
			ps.executeUpdate();
			ps.close();
			zgSentity.setProMonth(minMonth);
		}
		rs.close();
		psta.close();
	}

	/**
	 * 申请审批
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject applyApproval(ArrayList<String> jsonList,
			String applyMan) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement psta = null;
			ResultSet rs = null;

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
			DateFormat df2 = new SimpleDateFormat("yyyyMMdd");
			Date time = new Date();
			String nowTime = df.format(time);
			for (PlnOrderZgSEntity zgSentity : list) {
				PlnSizeUpapplyEntity plnSiz = new PlnSizeUpapplyEntity();
				String exeStatus = "";
				String orderNo = "";
				String orderNoSeq = "";
				String lenNoN = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getProPlanId());
				psta.setString(2, zgSentity.getGxPlanNo());
				rs = psta.executeQuery();
				if (rs.next()) {
					exeStatus = rs.getString("EXE_STATUS");
					orderNo = rs.getString("ORDER_NO");
					orderNoSeq = rs.getString("ORDER_SEQ");
					lenNoN = rs.getString("LEN_NO_N");
					plnSiz.setOrderNo(orderNo);
					plnSiz.setOrderSeq(orderNoSeq);
					plnSiz.setDeliveryNo(rs.getString("DELIVERY_NO"));
					plnSiz.setLengthMin(rs.getString("LEN_MIN"));
					plnSiz.setLengthMax(rs.getString("LEN_MAX"));
					plnSiz.setLengthdisc(rs.getString("LEN_DESC"));
					plnSiz.setLenNo(rs.getString("LEN_NO"));
					plnSiz.setFounderName(rs.getString("FOUNDER_NAME"));
					plnSiz.setLenNoN(lenNoN);
					plnSiz.setLengthdiscN(rs.getString("LENGTHDISC_N"));
				} else {
					cro.setV_errMsg("找不到合同：" + zgSentity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				psta.close();
				if (!exeStatus.equals("0")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "不是计划状态,不允许申请。");
					return cro;
				}
				if (zgSentity.getOrderSource().equals("备料需求")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "是备料需求合同,不允许申请。");
					return cro;
				}
				if (lenNoN == null || lenNoN.equals("")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "推荐长度为空,不允许申请,请重头计算。");
					return cro;
				}
				String orderLnPk = zgSentity.getOrdLnDlyPk().substring(0,
						zgSentity.getOrdLnDlyPk().length() - 3);
				int count = 0;

				// 判断同一个合同行PK 只能申请一次
				String sqlLnPk = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.PlnSizUpApplyNoOrderNo");
				psta = conn.prepareStatement(sqlLnPk);
				psta.setString(1, orderLnPk);
				rs = psta.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
				}
				rs.close();
				psta.close();

				if (count > 0) {
					cro.setV_errMsg("该合同：" + zgSentity.getOrderNo() + "已申请。");
					return cro;
				}
				String applyNo = "";
				// 查询申请单号
				String sqlmax = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.maxPlnSizUpApplyNo");
				psta = conn.prepareStatement(sqlmax);
				psta.setString(1, df2.format(time));
				psta.setString(2, df1.format(time));
				rs = psta.executeQuery();
				if (rs.next()) {
					applyNo = rs.getString("APPLY_NO");
				}
				rs.close();
				psta.close();

				// 新增申请表
				plnSiz.setApplyNo(applyNo);
				plnSiz.setApplyMan(applyMan);
				plnSiz.setOrdLnDlyPk(zgSentity.getOrdLnDlyPk());
				plnSiz.setOrdLnPk(orderLnPk);
				plnSiz.setOrderSource(zgSentity.getOrderSource());
				plnSiz.setPlineCode(zgSentity.getPlineCode());
				plnSiz.setPlineName(zgSentity.getPlineName());
				plnSiz.setSteelcode(zgSentity.getSteelcode());
				plnSiz.setSteelname(zgSentity.getSteelname());
				plnSiz.setGradecode(zgSentity.getGradecode());
				plnSiz.setGradename(zgSentity.getGradename());
				plnSiz.setOutdiameter(zgSentity.getOutdiameter());
				plnSiz.setWallthick(zgSentity.getWallthick());
				plnSiz.setExeStatus("10");
				plnSiz.setApplyTime(nowTime);

				String sqladd = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.AddPlnSizUpApply"),
						plnSiz);
				psta = conn.prepareStatement(sqladd);
				psta.executeUpdate();
				psta.close();

				// 修改排轧管排产表申请单号
				String sqlupdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatplnOrderZgSApply");
				psta = conn.prepareStatement(sqlupdate);
				psta.setObject(1, applyNo);
				psta.setObject(2, "10");
				psta.setObject(3, orderNo);
				psta.setObject(4, orderNoSeq);
				psta.executeUpdate();
				psta.close();
			}
			cro.setV_errMsg("申请成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 撤销申请审批
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject undoApplyApproval(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement psta = null;
			ResultSet rs = null;
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.queryZgMSStatus");
			String exeStatus = "";
			String orderNo = "";
			String orderNoSeq = "";
			String applyNo = jsonList.get(0);
			String orderLnPk = jsonList.get(1).substring(0,
					jsonList.get(1).length() - 3);
			String lenNoN = jsonList.get(4);
			psta = conn.prepareStatement(sql);
			psta.setString(1, jsonList.get(2));
			psta.setString(2, jsonList.get(3));
			rs = psta.executeQuery();
			if (rs.next()) {
				exeStatus = rs.getString("EXE_STATUS");
				orderNo = rs.getString("ORDER_NO");
				orderNoSeq = rs.getString("ORDER_SEQ");

			} else {
				cro.setV_errMsg("找不到合同：" + orderNo + "/" + orderNoSeq + "。");
				return cro;
			}
			rs.close();
			psta.close();
			if (!exeStatus.equals("0")) {
				cro.setV_errMsg("合同：" + orderNo + "/" + orderNoSeq
						+ "不是计划状态,不允许撤销。");
				return cro;
			}
			String strat = "";
			String stratText = "";
			String lenNo = "";
			String lenDecisc = "";
			// 查询申请单状态
			String sqlLnPk = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.PlnSizUpApplyNoStrat");
			psta = conn.prepareStatement(sqlLnPk);
			psta.setString(1, applyNo);
			rs = psta.executeQuery();
			if (rs.next()) {
				strat = rs.getString("EXE_STATUS");
				stratText = rs.getString("EXE_STATUS_TEXT");
				lenNo = rs.getString("LEN_NO");
				lenDecisc = rs.getString("LENGTHDISC");
			}
			rs.close();
			psta.close();
			if (!strat.equals("10")) {
				cro.setV_errMsg("申请单号:" + applyNo + ",已" + stratText
						+ ",不允许撤销。");
				return cro;
			}
			// 删除申请数据
			String sqlDelete = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.DeletePlnSizUpApply");
			psta = conn.prepareStatement(sqlDelete);
			psta.setObject(1, applyNo);
			psta.executeUpdate();
			psta.close();

			// 修改排轧管排产表申请单号
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updatplnOrderZgSApply");
			psta = conn.prepareStatement(sqlupdate);
			psta.setObject(1, "");
			psta.setObject(2, "");
			psta.setObject(3, orderNo);
			psta.setObject(4, orderNoSeq);
			psta.executeUpdate();
			psta.close();

			// 修改提报表推荐长度
			sqlupdate = CoreXmlSqlParsersFactory
					.getSql("FrmApplyRoval.updatePlnSarORDER");
			psta = conn.prepareStatement(sqlupdate);
			psta.setObject(1, "");
			psta.setObject(2, "");
			psta.setObject(3, orderLnPk);
			psta.executeUpdate();
			psta.close();

			// 修改删除长度描述
			sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CoreOrderLenPln.doDelete");
			psta = conn.prepareStatement(sqlupdate);
			psta.setObject(1, lenNoN);
			psta.executeUpdate();
			psta.close();

			cro.setV_errMsg("撤销申请成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改外购坯（外购，自炼）
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject modifyBatter(ArrayList<String> jsonList, String name) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement psta = null;
			ResultSet rs = null;

			for (PlnOrderZgSEntity zgSentity : list) {
				String outsBilletFl = "";
				String exeStatus = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				psta = conn.prepareStatement(sql);
				psta.setString(1, zgSentity.getProPlanId());
				psta.setString(2, zgSentity.getGxPlanNo());
				rs = psta.executeQuery();
				if (rs.next()) {
					exeStatus = rs.getString("EXE_STATUS");
					outsBilletFl = rs.getString("OUTS_BILLET_FL");
				} else {
					cro.setV_errMsg("找不到合同：" + zgSentity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				psta.close();
				if (!exeStatus.equals("0")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "不是计划状态,不能修改。");
					return cro;
				}
				if (zgSentity.getIsPlanOk().equals("是")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "已确认,不能修改。");
					return cro;
				}
				if (zgSentity.getOrderSource().equals("备料需求")) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
							+ "是备料需求合同,不允许修改。");
					return cro;
				}
				// if (outsBilletFl.equals("121802")) {
				// cro.setV_errMsg("合同：" + zgSentity.getOrderNo()
				// + "本身是自炼合同,不允许修改。");
				// return cro;
				// }
				// if (outsBilletFl.equals("121801")) {
				int count = 0;
				// 去除数组中的空格
				String[] groupCic1 = zgSentity.getCicGroupGp().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]);
				String stdCode = "";
				String sqlc = "";
				if (groupCic1 != null && groupCic1.length > 0) {
					// 查询钢种索引集合队列的内控标准
					sqlc = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectCicByGrade");
					sqlc += CoreConverter.toSqlConditionString("T.CIC",
							groupCic1);
					PreparedStatement pst = conn.prepareStatement(sqlc);
					ResultSet rst = pst.executeQuery();
					while (rst.next()) {
						if (rst.getString("STD_CODE_NK") != null) {
							stdCode += rst.getString("STD_CODE_NK").trim()
									+ ",";
						}
					}
					rst.close();
					pst.close();

					if (!stdCode.equals("") && stdCode.contains(",")) {
						stdCode = stdCode.substring(0, stdCode.length() - 1);
					}
				}
				String billFl = "";
				String billName = "";
				if (outsBilletFl.equals("121801")) {
					billFl = "0";
					billName = "自炼";
				} else {
					billFl = "1";
					billName = "外购";
				}
				if (!stdCode.equals("")) {
					// 通过内控标准查询是否有自炼
					sqlc = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectGroupGp");
					sqlc += CoreConverter.toSqlConditionString("T.STD_CODE",
							stdCode.split(","));
					PreparedStatement ps1 = conn.prepareStatement(sqlc);
					ps1.setObject(1, billFl);
					ResultSet rs1 = ps1.executeQuery();
					if (rs1.next()) {
						count = rs1.getInt("COUNT");
					}
					rs1.close();
					ps1.close();
				}

				if (count == 0) {
					cro.setV_errMsg("合同：" + zgSentity.getOrderNo() + "没有"
							+ billName + "钢种索引码,不允许修改。");
					return cro;
				}

				// 修改提报表
				String sqlupdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.updatplnSaleord");
				psta = conn.prepareStatement(sqlupdate);
				psta.setObject(1, zgSentity.getOutsBilletFl());
				psta.setObject(2, zgSentity.getOrdLnDlyPk());
				psta.executeUpdate();
				psta.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 获取索引码
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject updateGroupGp(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;
			String sql = "";
			for (PlnOrderZgSEntity zgSEntity : list) {
				String groupCic = "";
				String gradeCode = "";
				String groupWic = "";// 水压
				String groupPic = "";// 材质
				String groupSic = "";// 公差
				String groupDic = "";// 探伤
				String groupGic = "";// 加工
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setString(1, zgSEntity.getProPlanId());
				ps.setString(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同：" + zgSEntity.getOrderNo()
								+ "不是计划状态,不能修改。");
						return cro;
					}
					if (rs.getString("IS_PLAN_OK") != null
							&& rs.getString("IS_PLAN_OK").equals("是")) {
						cro.setV_errMsg("合同：" + zgSEntity.getOrderNo()
								+ "已确认,不能修改。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();

				// 查询经过工序点
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectDesginKey");
				PreparedStatement psta = conn.prepareStatement(sql);
				psta.setString(1, zgSEntity.getProPlanId());
				psta.setString(2, zgSEntity.getGxPlanNo());
				ResultSet rst = psta.executeQuery();
				while (rst.next()) {
					if (rst.getString("PROCESS_CODE") == null) {
						cro.setV_errMsg("工序点为空。");
						return cro;
					}
					String craftSeq = rst.getString("CRAFT_SEQ");
					String craftFileNo = rst.getString("CRAFT_FILE_NO");
					String cic = rst.getString("CIC");
					String pic = rst.getString("PIC");
					String sic = rst.getString("SIC");
					String dic = rst.getString("DIC");
					String wic = rst.getString("WIC");
					String gic = rst.getString("GIC");
					if (rst.getString("PROCESS_CODE").trim().equals("G")) {
						zgSEntity.setCic(cic);
						zgSEntity.setPic(pic);
						zgSEntity.setSic(sic);
						zgSEntity.setDic(dic);
						zgSEntity.setWic(wic);
						zgSEntity.setGic(gic);
						// 修改加工线
						String sqlupdate = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updatPlnJGXCic"),
										zgSEntity);
						ps = conn.prepareStatement(sqlupdate);
						ps.setObject(1, craftFileNo);
						ps.setObject(2, craftSeq);
						ps.executeUpdate();
						ps.close();

					}
					if (rst.getString("PROCESS_CODE").trim().equals("F")) {
						zgSEntity.setCic(cic);
						zgSEntity.setPic(pic);
						zgSEntity.setSic(sic);
						zgSEntity.setDic(dic);
						zgSEntity.setWic(wic);
						zgSEntity.setGic(gic);
						// 修改热处理
						String sqlupdate = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updatPlnRCLCic"),
										zgSEntity);
						ps = conn.prepareStatement(sqlupdate);
						ps.setObject(1, craftFileNo);
						ps.setObject(2, craftSeq);
						ps.executeUpdate();
						ps.close();
					}
					if (rst.getString("PROCESS_CODE").trim().equals("E")) {
						zgSEntity.setCic(cic);
						zgSEntity.setPic(pic);
						zgSEntity.setSic(sic);
						zgSEntity.setDic(dic);
						zgSEntity.setWic(wic);
						zgSEntity.setGic(gic);
						// 修改墩拔扩
						String sqlupdate = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updatPlnDBKCic"),
										zgSEntity);
						ps = conn.prepareStatement(sqlupdate);
						ps.setObject(1, craftFileNo);
						ps.setObject(2, craftSeq);
						ps.executeUpdate();
						ps.close();
					}
					if (rst.getString("PROCESS_CODE").trim().equals("D")) {
						zgSEntity.setCic(cic);
						zgSEntity.setPic(pic);
						zgSEntity.setSic(sic);
						zgSEntity.setDic(dic);
						zgSEntity.setWic(wic);
						zgSEntity.setGic(gic);
						// 获取管坯索引码
						String sqlCic = CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.selectGpIcList1");
						ps = conn.prepareStatement(sqlCic);
						ps.setObject(1, zgSEntity.getProPlanId());
						ps.setObject(2, zgSEntity.getGxPlanNo());
						rs = ps.executeQuery();
						while (rs.next()) {
							if (rs.getString("CIC") != null) {
								if (!rs.getString("CIC").equals("")) {
									groupCic += rs.getString("CIC") + ",";
								}
							}
							if (rs.getString("GRADECODE") != null) {
								gradeCode = rs.getString("GRADECODE");
							}
							if (rs.getString("PIC") != null) {
								if (!rs.getString("PIC").equals("")) {
									groupPic += rs.getString("PIC") + ",";
								}
							}
							if (rs.getString("SIC") != null) {
								if (!rs.getString("SIC").equals("")) {
									groupSic += rs.getString("SIC") + ",";
								}
							}
							if (rs.getString("DIC") != null) {
								if (!rs.getString("DIC").equals("")) {
									groupDic += rs.getString("DIC") + ",";

								}
							}
							if (rs.getString("WIC") != null) {
								if (!rs.getString("WIC").equals("")) {
									groupWic += rs.getString("WIC") + ",";
								}
							}
							if (rs.getString("GIC") != null) {
								if (!rs.getString("GIC").equals("")) {
									groupGic += rs.getString("GIC") + ",";
								}
							}
						}
						rs.close();
						ps.close();
						if (!groupDic.equals("") && groupDic.contains(",")) {
							groupDic = groupDic.substring(0,
									groupDic.length() - 1);
						}
						zgSEntity.setDicGroupGp(groupDic);
						zgSEntity.setDicGp(groupDic.split(",")[0]);

						if (!groupPic.equals("") && groupPic.contains(",")) {
							groupPic = groupPic.substring(0,
									groupPic.length() - 1);
						}
						zgSEntity.setPicGroupGp(groupPic);
						zgSEntity.setPicGp(groupPic.split(",")[0]);

						if (!groupSic.equals("") && groupSic.contains(",")) {
							groupSic = groupSic.substring(0,
									groupSic.length() - 1);
						}
						zgSEntity.setSicGroupGp(groupSic);
						zgSEntity.setSicGp(groupSic.split(",")[0]);

						if (!groupWic.equals("") && groupWic.contains(",")) {
							groupWic = groupWic.substring(0,
									groupWic.length() - 1);
						}
						zgSEntity.setWicGroupGp(groupWic);
						zgSEntity.setWicGp(groupWic.split(",")[0]);
						if (!groupGic.equals("") && groupGic.contains(",")) {
							groupGic = groupGic.substring(0,
									groupGic.length() - 1);
						}
						zgSEntity.setGicGroupGp(groupGic);
						zgSEntity.setGicGp(groupGic.split(",")[0]);

						if (!groupCic.equals("") && groupCic.contains(",")) {
							groupCic = groupCic.substring(0,
									groupCic.length() - 1);
						}
						String[] groupCic1 = groupCic.split(",");
						zgSEntity.setCicGroupGp(groupCic);

						// 去除数组中的空格
						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]);

						String cicGroup = "";
						if (groupCic1 != null && groupCic1.length > 0) {
							String sqlc = CoreXmlSqlParsersFactory
									.getSql("CorePlnZgMStoGp.screenCicByGrade");
							sqlc += " AND INSTR(T.GRADECODE,'" + gradeCode
									+ "') > 0";
							sqlc += CoreConverter.toSqlConditionString("T.CIC",
									groupCic1);
							PreparedStatement pst = conn.prepareStatement(sqlc);
							// pst.setObject(1, gradeCode);
							ResultSet rstc = pst.executeQuery();
							while (rstc.next()) {
								if (rstc.getString("CIC") != null) {
									cicGroup += rstc.getString("CIC") + ",";
								}
							}
							rstc.close();
							pst.close();
						}
						if (!cicGroup.equals("") && cicGroup.contains(",")) {
							cicGroup = cicGroup.substring(0,
									cicGroup.length() - 1);
						}
						zgSEntity.setCicGp(cicGroup.split(",")[0]);

						// 修改轧管排产索引码
						String sqlupdate = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("CorePlnZgMStoGp.updatplnGroupGp"),
										zgSEntity);
						ps = conn.prepareStatement(sqlupdate);
						ps.executeUpdate();
						ps.close();
					}
				}
				rst.close();
				psta.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改轧批号
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject updateBatch(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;
			for (PlnOrderZgSEntity zgSEntity : list) {
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",不是计划状态,不允许修改。");
						return cro;
					}
					// if (rs.getString("EXE_STATUS").equals("0")
					// && rs.getString("IS_PLAN_OK") != null
					// && rs.getString("IS_PLAN_OK").equals("1")) {
					// cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
					// + ",已确认,不允许修改。");
					// return cro;
					// }
					if (rs.getString("IF_STOVE_ISSUED") != null
							&& rs.getString("IF_STOVE_ISSUED").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已炉计划下发,不允许修改。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();

				// 查询是否有重复轧批号
				int count = 0;
				sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.SelectatchId");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getZyBatchId());
				ps.setObject(2, zgSEntity.getPlineCode());
				rs = ps.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
				}
				rs.close();
				ps.close();
				if (count > 0) {
					cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
							+ ",存在相同轧批号,不允许修改。");
					return cro;
				}
				// 修改轧批号
				String sqlupdate = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.UpdateBatchId"),
						zgSEntity);
				ps = conn.prepareStatement(sqlupdate);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改判定字头
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doDecision(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;

			for (PlnOrderZgSEntity zgSEntity : list) {
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",不是计划状态,不允许修改。");
						return cro;
					}
					if (rs.getInt("COUNTZY") > 0) {
						cro.setV_errMsg("订单号：" + zgSEntity.getProPlanId() + "/"
								+ zgSEntity.getGxPlanNo() + ",已存在炉计划,不能修改。");
						return cro;
					}
					if (rs.getString("EXE_STATUS").equals("0")
							&& rs.getString("IF_STOVE_ISSUED") != null
							&& rs.getString("IF_STOVE_ISSUED").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已炉计划下发,不允许修改。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();

				String isendgx = "0";
				if (zgSEntity.getDecision().equals("A")) {
					isendgx = "1";
				}
				// 修改判定字头
				String sqlupdate = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.UpdateDecision"),
						zgSEntity);
				ps = conn.prepareStatement(sqlupdate);
				ps.setObject(1, isendgx);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改钢种
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject updateGradeCode(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;

			for (PlnOrderZgSEntity zgSEntity : list) {
				String craft_file_no = "";
				String craft_seq = "";
				String desginKey = "";
				String ordLnPk = "";
				String orderSource = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",不是计划状态,不允许修改。");
						return cro;
					}
					if (rs.getString("EXE_STATUS").equals("0")
							&& rs.getString("IS_PLAN_OK") != null
							&& rs.getString("IS_PLAN_OK").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已确认,不允许修改。");
						return cro;
					}
					if (rs.getString("EXE_STATUS").equals("0")
							&& rs.getString("IF_STOVE_ISSUED") != null
							&& rs.getString("IF_STOVE_ISSUED").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已炉计划下发,不允许修改。");
						return cro;
					}

					// if (rs.getString("ORDER_SOURCE").equals("备料需求")) {
					// cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
					// + ",是备料需求合同,不允许修改。");
					// return cro;
					// }
					if (rs.getString("OUTS_BILLET_FL").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",是外购合同,不允许修改。");
						return cro;
					}
					craft_file_no = rs.getString("CRAFT_FILE_NO");
					craft_seq = rs.getString("CRAFT_SEQ");
					desginKey = rs.getString("DESGIN_KEY");
					orderSource = rs.getString("ORDER_SOURCE");
					ordLnPk = rs.getString("ORD_LN_PK");

				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();
				if (orderSource.equals("备料需求")) {
					// 查询工艺文件
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectCraftNo");
					sql += " ORDER BY T.CREATE_TIME DESC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, craft_file_no);
					ps.setObject(2, craft_seq);
					ps.setObject(3, desginKey);
					rs = ps.executeQuery();
					if (rs.next()) {
						if (rs.getString("CRAFT_SOURCE").equals("/")) {
							cro.setV_errMsg("该合同号：" + zgSEntity.getOrderNo()
									+ ",工艺文件不是人工上传的,不允许修改。");
							return cro;
						}
					} else {
						cro.setV_errMsg("该合同：" + zgSEntity.getOrderNo()
								+ ",找不到工艺文件。");
						return cro;
					}
					rs.close();
					ps.close();
				} else {
					// 查询工艺文件
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.selectCraftNo");
					sql += "  AND T.ORD_LN_PK='" + ordLnPk + "'";
					sql += " ORDER BY T.CREATE_TIME DESC";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, craft_file_no);
					ps.setObject(2, craft_seq);
					ps.setObject(3, desginKey);
					rs = ps.executeQuery();
					if (rs.next()) {
						if (rs.getString("CRAFT_SOURCE").equals("/")) {
							cro.setV_errMsg("该合同号：" + zgSEntity.getOrderNo()
									+ ",工艺文件不是人工上传的,不允许修改。");
							return cro;
						}
					}
					// else {
					// cro.setV_errMsg("该合同：" + zgSEntity.getOrderNo()
					// + ",找不到工艺文件。");
					// return cro;
					// }
					rs.close();
					ps.close();
				}
				// 修改钢种
				String sqlupdate = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.updateGradeCode"),
						zgSEntity);
				ps = conn.prepareStatement(sqlupdate);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改工艺备注,计划备注
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doProMemo(ArrayList<String> jsonList, String falsg) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;

			for (PlnOrderZgSEntity zgSEntity : list) {
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",不是计划状态,不允许修改。");
						return cro;
					}

					if (rs.getString("EXE_STATUS").equals("0")
							&& rs.getString("IF_STOVE_ISSUED") != null
							&& rs.getString("IF_STOVE_ISSUED").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已炉计划下发,不允许修改。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();
				if (falsg.equals("0")) {
					// 修改工艺备注
					String sqlupdate = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("CorePlnZgMStoGp.UpdateDoProMemo"),
							zgSEntity);
					ps = conn.prepareStatement(sqlupdate);
					ps.executeUpdate();
					ps.close();
				} else {
					// 修改计划备注
					String sqlupdate = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("CorePlnZgMStoGp.UpdateDoJhMemo"),
							zgSEntity);
					ps = conn.prepareStatement(sqlupdate);
					ps.executeUpdate();
					ps.close();
				}
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 冲余量
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doBluntAllow(ArrayList<ArrayList<String>> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 修改
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.UpdateDoBlunt");
			PreparedStatement psUpdate = conn.prepareStatement(sqlupdate);
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String proPlanId = list.get(0);
				String gxPlanNo = list.get(1);
				String gradecode = list.get(2);
				String lenGpSingle = list.get(3);
				String inwlId = list.get(4);
				String ifMonitorLg = list.get(5);
				String outsBillFl = list.get(6);
				String wholeBacklogDesc = list.get(7);
				int reallNUM = Integer.parseInt(list.get(8));
				double reallWt = Double.parseDouble(list.get(9));

				// String sql = CoreXmlSqlParsersFactory
				// .getSql("CorePlnZgMStoGp.selectDoBlunt");
				// ps = conn.prepareStatement(sql);
				// ps.setObject(1, proPlanId);
				// ps.setObject(2, gxPlanNo);
				// rs = ps.executeQuery();
				// if (rs.next()) {
				// if (!rs.getString("EXE_STATUS").equals("0")) {
				// cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
				// + ",不是计划状态,不允许修改。");
				// return cro;
				// }
				// }
				// rs.close();
				// ps.close();
				double analywt = 0;
				String gpreqId = "";
				String reqStatus = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.selectProZgPlnAnaly");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, gradecode);
				ps.setObject(2, lenGpSingle);
				ps.setObject(3, inwlId);
				ps.setObject(4, ifMonitorLg);
				ps.setObject(5, outsBillFl);
				ps.setObject(6, wholeBacklogDesc);
				rs = ps.executeQuery();
				if (rs.next()) {
					analywt = rs.getDouble("GP_SYWEIGHT");
					gpreqId = rs.getString("GPREQ_ID");
					reqStatus = rs.getString("REQ_STATUS");
				}
				rs.close();
				ps.close();
				if (analywt == 0) {
					cro.setV_errMsg("管坯需求号：" + gpreqId + ",不存在余量。");
					return cro;
				}
				if (reallWt > analywt) {
					cro.setV_errMsg("订单号：" + proPlanId + "/" + gxPlanNo
							+ ",管坯需求大于余量。");
					return cro;
				}
				if (!reqStatus.equals("") && reqStatus.equals("4")) {
					cro.setV_errMsg("管坯需求号：" + gpreqId + ",外购坯已交齐。");
					return cro;
				}
				psUpdate.setObject(1, gpreqId);
				psUpdate.setObject(2, proPlanId);
				psUpdate.setObject(3, gxPlanNo);
				psUpdate.setObject(4, reallWt);
				psUpdate.setObject(5, gpreqId);
				psUpdate.addBatch();
			}
			psUpdate.executeBatch();
			cro.setV_errMsg("冲余量成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除关闭需求号
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject deleteGperId(ArrayList<ArrayList<String>> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = null;
			ResultSet rs = null;
			// 删除管坯需求
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.deleteGperIdZgS");
			PreparedStatement updatePart = conn.prepareStatement(sqlupdate);
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String proPlanId = list.get(0);
				String gxPlanNo = list.get(1);
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, proPlanId);
				ps.setObject(2, gxPlanNo);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("轧管订单：" + proPlanId + '/' + gxPlanNo
								+ ",不是计划状态,不允许修改。");
						return cro;
					}
					if (rs.getString("IF_STOVE_ISSUED") != null
							&& rs.getString("IF_STOVE_ISSUED").equals("1")) {
						cro.setV_errMsg("轧管订单：" + proPlanId + '/' + gxPlanNo
								+ ",已炉计划下发,不允许删除。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到轧管订单：" + proPlanId + '/' + gxPlanNo
							+ "。");
					return cro;
				}
				rs.close();
				ps.close();

				updatePart.setObject(1, proPlanId);
				updatePart.setObject(2, gxPlanNo);
				updatePart.addBatch();
			}
			updatePart.executeBatch();
			cro.setV_errMsg("删除成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改主被动
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doUpdatePase(ArrayList<String> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
					PlnOrderZgSEntity.class, jsonList);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 修改主被动
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.UpdatePlnZgSPass");
			PreparedStatement update = conn.prepareStatement(sqlupdate);
			for (PlnOrderZgSEntity zgSEntity : list) {
				String passive = "";// 主被动
				double weigthS = 0;// 轧管排产
				double weigthSMin = 0;
				double addWtIn = 0;// 轧管加投
				double aimwallthick = 0;// 控制壁厚
				double aimoutdiameter = 0;// 控制外径
				double rollLength = 0;// 轧制长度
				double cutEndLen = 0;// 切头尾
				String gyLen = "";// 管余长
				int cutNum = 0;// 分切
				double aimlength = 0;// 目标长度

				double lenGpSingle = 0;// 单倍坯长
				double diameterGp = 0;// 管坯直径
				double tubeEndRatio = 0;// 管端系数
				double burnoutRate = 0;// 烧损
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, zgSEntity.getProPlanId());
				ps.setObject(2, zgSEntity.getGxPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					passive = rs.getString("PASSIVE");
					weigthS = rs.getDouble("WEIGTH_S");
					weigthSMin = rs.getDouble("WEIGTH_S_MIN");
					addWtIn = rs.getDouble("ADD_WT_IN");
					aimwallthick = rs.getDouble("AIMWALLTHICK");
					aimoutdiameter = rs.getDouble("AIMOUTDIAMETER");
					rollLength = rs.getDouble("ROLL_LENGTH");
					cutEndLen = rs.getDouble("LEN_CUTHEAD")
							+ rs.getDouble("LEN_CUTEND");
					diameterGp = rs.getDouble("DIAMETER_GP");
					lenGpSingle = rs.getDouble("LEN_GP_SINGLE");
					gyLen = rs.getString("VERIFY1");
					cutNum = rs.getInt("OUTNUM_CUT");
					aimlength = rs.getDouble("AIMLENGTH");
					burnoutRate = rs.getDouble("BURNOUT_RATE");
					tubeEndRatio = rs.getDouble("TUBE_END_RATIO");
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",不是计划状态,不允许修改。");
						return cro;
					}
					if (rs.getString("IS_PLAN_OK") != null
							&& rs.getString("IS_PLAN_OK").equals("1")) {
						cro.setV_errMsg("合同号：" + zgSEntity.getOrderNo()
								+ ",已确认,不允许修改。");
						return cro;
					}
				} else {
					cro.setV_errMsg("找不到合同：" + zgSEntity.getOrderNo() + "。");
					return cro;
				}
				rs.close();
				ps.close();

				// 轧管管单重【KG/M】=0.02466*轧管控制壁厚*（轧管控制外径-轧管控制壁厚)/1000
				double weigthOneS = (0.02466 * aimwallthick * (aimoutdiameter - aimwallthick)) / 1000;
				// 坯单重【吨/M】=（7.8*3.1415926/4*断面*断面）/1000/1000
				// 单倍坯重【吨】=坯单重*（单倍坯长/1000）
				double lenSgpOneWt = ((7.8 * 3.1415926 / 4 * diameterGp * diameterGp) / 1000 / 1000)
						* (lenGpSingle / 1000);
				double lenGpY = 0;
				if (gyLen == null || gyLen.equals("")) {
					lenGpY = 0;
				} else {
					// 轧制长度TZ=单倍坯重*（1-烧损）/轧管管单重+（1-管端增厚系数）*切头尾
					// 管余长=轧制长度TZ-分切*目标长度-切头尾
					lenGpY = (lenSgpOneWt * (1 - burnoutRate / 100)
							/ weigthOneS + (1 - tubeEndRatio)
							* (cutEndLen / 1000))
							- cutNum * aimlength - cutEndLen / 1000;
				}

				int gpreqNum = 0;
				int gpreqNumMin = 0;
				double gpreqWeight = 0;
				double gpreqWeightMin = 0;
				String uppassive = "";
				if (passive.equals("1")) {// 主动改被动
					uppassive = "0";
					gpreqNum = (int) Math
							.ceil((weigthS + addWtIn)
									/ (weigthOneS * (rollLength - lenGpY - cutEndLen / 1000)));
					gpreqNumMin = (int) Math
							.ceil((weigthSMin + addWtIn)
									/ (weigthOneS * (rollLength - lenGpY - cutEndLen / 1000)));

				} else {// 被动改主动
					uppassive = "1";
					gpreqNum = (int) Math.ceil((weigthS + addWtIn)
							/ (weigthOneS * (rollLength - cutEndLen / 1000)));
					gpreqNumMin = (int) Math.ceil((weigthSMin + addWtIn)
							/ (weigthOneS * (rollLength - cutEndLen / 1000)));
				}
				gpreqWeight = new BigDecimal(gpreqNum * lenSgpOneWt).setScale(
						3, RoundingMode.HALF_UP).doubleValue();
				gpreqWeightMin = new BigDecimal(gpreqNumMin * lenSgpOneWt)
						.setScale(3, RoundingMode.HALF_UP).doubleValue();
				update.setObject(1, gpreqNum);
				update.setObject(2, gpreqWeight);
				update.setObject(3, gpreqWeightMin);
				update.setObject(4, uppassive);
				update.setObject(5, zgSEntity.getProPlanId());
				update.setObject(6, zgSEntity.getGxPlanNo());
				update.addBatch();

			}
			update.executeBatch();
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 获取铸造产线
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doUpdateZz(ArrayList<ArrayList<String>> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 获取铸造产线
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.updateZzPline");
			PreparedStatement psupdate = conn.prepareStatement(sqlupdate);
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String proPlanId = list.get(0);
				String gxPlanNo = list.get(1);
				String craft_file_no = "";
				String craft_seq = "";
				String desginKey = "";
				String ordLnPk = "";
				String orderSource = "";
				String bom = "";
				String indexSeq = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, proPlanId);
				ps.setObject(2, gxPlanNo);
				rs = ps.executeQuery();
				if (rs.next()) {
					craft_file_no = rs.getString("CRAFT_FILE_NO");
					craft_seq = rs.getString("CRAFT_SEQ");
					desginKey = rs.getString("DESGIN_KEY");
					orderSource = rs.getString("ORDER_SOURCE");
					ordLnPk = rs.getString("ORD_LN_PK");
					bom = rs.getString("BOM");
					indexSeq = rs.getString("INDEX_SEQ");

				} else {
					cro.setV_errMsg("找不到合同：" + "" + "。");
					return cro;
				}
				rs.close();
				ps.close();

				// 查询铸造投入产出
				String materInB = "";
				String materOutB = "";
				String sql1 = CoreXmlSqlParsersFactory
						.getSql("CorePlnProcessOrd.queryDesginBom");
				PreparedStatement ps1 = conn.prepareStatement(sql1);
				ps1.setString(1, bom);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					materInB = rs1.getString("B_IN_MATERIAL_NO");
					materOutB = rs1.getString("B_OUT_MATERIAL_NO");
				}
				rs1.close();
				ps1.close();
				String plinCodeB = "";
				String plinNameB = "";
				// 获取铸造产线
				sql1 = CoreXmlSqlParsersFactory
						.getSql("CorePlnProcessOrd.queryBaseMaterialBPl");
				ps1 = conn.prepareStatement(sql1);
				ps1.setString(1, materInB);
				ps1.setString(2, materOutB);
				ps1.setString(3, desginKey);
				ps1.setString(4, indexSeq);
				rs1 = ps1.executeQuery();
				if (rs1.next()) {
					plinCodeB = rs1.getString("PLINE_CODE");
					plinNameB = rs1.getString("PLINE_NAME");
				}
				rs1.close();
				ps1.close();

				psupdate.setObject(1, plinCodeB);
				psupdate.setObject(2, plinNameB);
				psupdate.setObject(3, proPlanId);
				psupdate.setObject(4, gxPlanNo);
				psupdate.addBatch();
			}
			psupdate.executeBatch();
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 备料需求合并
	 * 
	 * @param
	 * @return
	 */
	public CoreReturnObject doMergePrepares(
			ArrayList<ArrayList<String>> jsonList, String ordLnDlyPk1,
			String plnDivideId1, String proPlanId1, String gxPlanNo1) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			String craftNo = "";
			PlnOrderZgSEntity entityZg = getPlanOrder(conn, proPlanId1,
					gxPlanNo1, "D", PlnOrderZgSEntity.class);
			String ordLnDivid = ordLnDlyPk1 + "/" + plnDivideId1;
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String ordLnDlyPk = list.get(0);
				String plnDivideId = list.get(1);
				String proPlanId = list.get(2);
				String gxPlanNo = list.get(3);
				String orderNo = list.get(4);

				String whpleBacklogDesc = "";
				// 查询轧管信息
				String sql = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.queryZgMSStatus");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, proPlanId);
				ps.setObject(2, gxPlanNo);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (!rs.getString("EXE_STATUS").equals("0")) {
						cro.setV_errMsg("合同号(" + orderNo + ")执行状态不是计划状态,不能合并!");
						return cro;
					}
					if (!rs.getString("ORDER_SOURCE").equals("备料需求")) {
						cro.setV_errMsg("合同号(" + orderNo + ")不是备料需求信息,不能合并!");
						return cro;
					}
					if (rs.getString("GPREQ_ID") != null
							|| !rs.getString("GPREQ_ID").equals("")) {
						cro.setV_errMsg("合同号(" + orderNo + ")已生成管坯需求,不能合并!");
						return cro;
					}
					if (craftNo.equals("")) {
						craftNo = rs.getString("CRAFT_FILE_NO");
					}
					if (rs.getString("CRAFT_FILE_NO").equals(craftNo)) {
						cro.setV_errMsg("工艺号不同,不能合并!");
						return cro;
					}
					whpleBacklogDesc = rs.getString("WHOLE_BACKLOG_DESC");
				} else {
					cro.setV_errMsg("找不到轧管合同信息(" + orderNo + ")。");
					return cro;
				}
				rs.close();
				ps.close();
				if (whpleBacklogDesc.contains("加工")) {
					int countJg = 0;
					// 查询加工信息
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.queryPlnOrderJgS");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, ordLnDlyPk);
					ps.setObject(2, plnDivideId);
					rs = ps.executeQuery();
					while (rs.next()) {
						if (!rs.getString("EXE_STATUS").equals("0")) {
							cro.setV_errMsg("合同号(" + orderNo
									+ ")加工执行状态不是计划状态,不能合并!");
							return cro;
						}
						countJg++;
					}
					rs.close();
					ps.close();
					if (countJg > 1) {
						cro.setV_errMsg("合同信息(" + orderNo + ")在加工排产存在拆分数据!");
						return cro;
					}
					if (countJg == 0) {
						cro.setV_errMsg("找不到加工合同信息(" + orderNo + ")。");
						return cro;
					}
				}
				if (whpleBacklogDesc.contains("热处理")) {
					int countRcl = 0;
					// 查询热处理信息
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.queryPlnOrderRclS");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, ordLnDlyPk);
					ps.setObject(2, plnDivideId);
					rs = ps.executeQuery();
					while (rs.next()) {
						if (!rs.getString("EXE_STATUS").equals("0")) {
							cro.setV_errMsg("合同号(" + orderNo
									+ ")热处理执行状态不是计划状态,不能合并!");
							return cro;
						}
						countRcl++;
					}
					rs.close();
					ps.close();
					if (countRcl > 1) {
						cro.setV_errMsg("合同信息(" + orderNo + ")在热处理排产存在拆分数据!");
						return cro;
					}
					if (countRcl == 0) {
						cro.setV_errMsg("找不到热处理合同信息(" + orderNo + ")。");
						return cro;
					}
				}
				if (whpleBacklogDesc.contains("镦拔扩")) {
					int countDbk = 0;
					// 查询墩拔扩信息
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.queryPlnOrderDbkS");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, ordLnDlyPk);
					ps.setObject(2, plnDivideId);
					rs = ps.executeQuery();
					while (rs.next()) {
						if (!rs.getString("EXE_STATUS").equals("0")) {
							cro.setV_errMsg("合同号(" + orderNo
									+ ")镦拔扩执行状态不是计划状态,不能合并!");
							return cro;
						}
						countDbk++;
					}
					rs.close();
					ps.close();
					if (countDbk > 1) {
						cro.setV_errMsg("合同信息(" + orderNo + ")在镦拔扩排产存在拆分数据!");
						return cro;
					}
					if (countDbk == 0) {
						cro.setV_errMsg("找不到镦拔扩合同信息(" + orderNo + ")。");
						return cro;
					}
				}
				// 判定是否主记录,不是主记录修改有效标志，主记录修改量
				if (!ordLnDivid.equals(ordLnDlyPk + "/" + plnDivideId)) {

					// 修改轧管有效标志
					String sqlUpdateV = CoreXmlSqlParsersFactory
							.getSql("CorePlnZgMStoGp.UpdatePlnOrderZgz");
					ps = conn.prepareStatement(sqlUpdateV);
					ps.setObject(1, ordLnDlyPk1);
					ps.setObject(2, plnDivideId1);
					ps.executeUpdate();
					ps.close();
					if (whpleBacklogDesc.contains("加工")) {
						// 修改加工有效标志
						sqlUpdateV = CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.UpdatePlnOrderJgS");
						ps = conn.prepareStatement(sqlUpdateV);
						ps.setObject(1, ordLnDlyPk);
						ps.setObject(2, plnDivideId);
						ps.executeUpdate();
						ps.close();
					}
					if (whpleBacklogDesc.contains("热处理")) {

						// 修改热处理有效标志
						sqlUpdateV = CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.UpdatePlnOrderRclS");
						ps = conn.prepareStatement(sqlUpdateV);
						ps.setObject(1, ordLnDlyPk);
						ps.setObject(2, plnDivideId);
						ps.executeUpdate();
						ps.close();
					}
					if (whpleBacklogDesc.contains("镦拔扩")) {
						// 修改镦拔扩镦拔扩有效标志
						sqlUpdateV = CoreXmlSqlParsersFactory
								.getSql("CorePlnZgMStoGp.UpdatePlnOrderDbkS");
						ps = conn.prepareStatement(sqlUpdateV);
						ps.setObject(1, ordLnDlyPk);
						ps.setObject(2, plnDivideId);
						ps.executeUpdate();
						ps.close();
					}
				}
			}
			// 合并备料需求
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CorePlnZgMStoGp.UpdatePlnOrderDbkS");
			ps = conn.prepareStatement(sqlUpdate);
			ps.setObject(1, ordLnDlyPk1);
			ps.setObject(2, plnDivideId1);
			ps.executeUpdate();
			ps.close();
			if (entityZg.getWholeBacklogDesc().contains("加工")) {
				// 修改加工有效标志
				sqlUpdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.UpdatePlnOrderJgS");
				ps = conn.prepareStatement(sqlUpdate);
				ps.setObject(1, ordLnDlyPk1);
				ps.setObject(2, plnDivideId1);
				ps.executeUpdate();
				ps.close();
			}
			if (entityZg.getWholeBacklogDesc().contains("热处理")) {

				// 修改热处理有效标志
				sqlUpdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.UpdatePlnOrderRclS");
				ps = conn.prepareStatement(sqlUpdate);
				ps.setObject(1, ordLnDlyPk1);
				ps.setObject(2, plnDivideId1);
				ps.executeUpdate();
				ps.close();
			}
			if (entityZg.getWholeBacklogDesc().contains("镦拔扩")) {
				// 修改镦拔扩镦拔扩有效标志
				sqlUpdate = CoreXmlSqlParsersFactory
						.getSql("CorePlnZgMStoGp.UpdatePlnOrderDbkS");
				ps = conn.prepareStatement(sqlUpdate);
				ps.setObject(1, ordLnDlyPk1);
				ps.setObject(2, plnDivideId1);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询排产信息
	 * 
	 * @param con
	 * @param proPlanId
	 *            订单编号
	 * @param gxPlanNo
	 *            排产序号
	 * @return PlnOrderCastSEntity
	 * @throws SQLException
	 */
	public static <T> T getPlanOrder(Connection con, String proPlanId,
			String gxPlanNo, String processCode, Class<T> cls)
			throws SQLException {
		String sql = "";
		if (processCode.equals("D")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.getPlanOrderD");
			sql += " AND T.PRO_PLAN_ID = ?  AND T.GX_PLAN_NO = ?";
		} else if (processCode.equals("E")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.getPlanOrderE");
			sql += " AND T.ORD_LN_DLY_PK = ?  AND T.PLN_DIVIDE_ID = ?";
		} else if (processCode.equals("F")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.getPlanOrderF");
			sql += " AND T.ORD_LN_DLY_PK = ?  AND T.PLN_DIVIDE_ID = ?";
		} else if (processCode.equals("G")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.getPlanOrderG");
			sql += " AND T.ORD_LN_DLY_PK = ?  AND T.PLN_DIVIDE_ID = ?";
		}
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, proPlanId);
		ps.setObject(2, gxPlanNo);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/***
	 * 查询芯棒最大单倍坯长
	 * @return
	 */
	public CoreReturnObject selectMangageLen(String proPlanId,String gxPlnNo)
	{
		return this.getDataBySqlID("CorePlnZgMStoGp.selectMangageLen",new Object[]{proPlanId,gxPlnNo});
	}
}