package com.steering.pss.plnsaleord.planStove;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.planStove.entity.MatGpTrackEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.corePlnZyFurnM;
import com.steering.pss.plnsaleord.stove.entity.MatGpMEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnOrderZgSEntityL;
import com.steering.pss.plnsaleord.stove.entity.PlnZyZgCEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyZgMEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;

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

/**
 * 管坯材料信息
 * 
 * @author teng 2017.11.21
 */
public class FrmPlanMaterialSelection extends DBCommon {
	private static double Pi = 3.1415926; // 圆周率

	/**
	 * 查询管坯库存信息
	 *
	 * @return
	 */
	public CoreReturnObject queryMaterial(String inMaterialName,
										  String gradeName, String dimater, String surplusflag,
										  String[] zggradeName, String plineCode, String typeFlag) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.queryMaterial");
		if (surplusflag.equals("1")) {
			sql += " AND T.HANGING_FLAG='1' AND T.CUT_YU_LONG='0' ";
		} else if (surplusflag.equals("0")) {
			sql += " AND T.HANGING_FLAG='0'";
		}
		if (typeFlag.equals("双经销")) {
			typeFlag = "1";
		} else if (typeFlag.equals("定销订购")) {
			typeFlag = "3";
		} else {
			typeFlag = "0";
			if (plineCode.equals("C072")) {
				typeFlag = "0','2";
			}
		}
		/*if (!plineCode.equals("C072")) {
			sql += " AND T.BELONG_CODE='002001001'";
		} else {
			sql += " AND T.BELONG_CODE='002023005'";
		}*/
		sql += " AND T.IS_DEALER IN ('" + typeFlag + "')";
		sql += CoreConverter.toSqlConditionString("T.GRADENAME", zggradeName);
		// AND T.GRADENAME IN (?)
		sql += "  GROUP BY T.MATERIAL_NO, T.MATERIAL_NAME,T.FLAG_STOVE_NO,T.JUDGE_STOVE_NO, T.STOVE_NO,"
				+ " T.BELONG_CODE,T.BELONG_NAME,T.PRO_PLAN_ID,T.GX_PLAN_NO,T.PRO_PLAN_ID_ZG,T.GX_PLAN_NO_ZG, T.GRADECODE,"
				+ " T.GRADENAME,T.DIMATER,T.CIC, T.ACT_LEN, T.FIX_NUM, T.FIX_LEN,T.PRODUCT_FLAG, T.MAT_STATUS,T.CHEM_JUDGE_ID,T.IS_DEALER,T.SUPPLY_UNIT_CODE,T.SUPPLY_UNIT,"
				+ " S.AIMLENGTH,S.ROLL_LENGTH,S.LEN_CUTHEAD,S.LEN_CUTEND, S.OUTNUM_CUT, S.LEN_GP_SINGLE,T.CUT_YU_LONG,t.HANGING_FLAG,T.ORDER_NO,T.ORDER_SEQ "
				+ " ORDER BY  CASE\r\n" + 
				"    WHEN T.ACT_LEN - NVL(T.CUT_YU_LONG, 0) BETWEEN 3300 AND 3350 THEN 1\r\n" + 
				"    ELSE 2\r\n" + 
				"  END,"
				+ "T.JUDGE_STOVE_NO, T.FIX_NUM";
		// inMaterialName,gradeName
		// --AND T.MATERIAL_NAME=?
		// --AND INSTR(?, T.CIC) > 0
		return this.getData(sql, new Object[]{dimater});
	}


	/***
	 * 查询库存详细信息
	 * @param matGpTity
	 * @return
	 */
	public CoreReturnObject queryMatGpInfo(String matGpTity) {
		MatGpMEntity matGpEntity = EntityTool.getEntityByJSONStr(matGpTity, MatGpMEntity.class);
		if (matGpEntity.getIsDealer().equals("双经销")) {
			matGpEntity.setIsDealer("1");
		} else if (matGpEntity.getIsDealer().equals("否")) {
			matGpEntity.setIsDealer("0,2,4");
		} else if (matGpEntity.getIsDealer().equals("定销订购")) {
			matGpEntity.setIsDealer("3");
		}
		if (matGpEntity.getMatStatus().equals("材料产出待判")) {
			matGpEntity.setMatStatus("80150101");
		} else if (matGpEntity.getMatStatus().equals("材料产出(已判定)")) {
			matGpEntity.setMatStatus("80150102");
		}
		String sql = CoreXmlSqlParsersFactory.getSql("FrmPlanMaterialSelection.queryMatGpInfo");
		sql = EntityTool.fillSqlByEntity(sql, matGpEntity);
		return this.getData(sql);
	}

	/***
	 * 查询详细材料号
	 * @return
	 */
	public CoreReturnObject queryGpMatNo(String matTity) {

		MatGpMEntity matGpEntity = EntityTool.getEntityByJSONStr(matTity, MatGpMEntity.class);
		if (matGpEntity.getIsDealer().equals("是")) {
			matGpEntity.setIsDealer("1");
		} else if (matGpEntity.getIsDealer().equals("否")) {
			matGpEntity.setIsDealer("0");
		}
		if (matGpEntity.getMatStatus().equals("材料产出待判")) {
			matGpEntity.setMatStatus("80150101");
		} else if (matGpEntity.getMatStatus().equals("材料产出(已判定)")) {
			matGpEntity.setMatStatus("80150102");
		}
		String sql = CoreXmlSqlParsersFactory.getSql("FrmPlanMaterialSelection.queryGpMatNo");
		sql = EntityTool.fillSqlByEntity(sql, matGpEntity);
		return this.getData(sql);
	}

	/**
	 * 根据轧管订单编号查询合同信息
	 *
	 * @return
	 */
	public CoreReturnObject queryZgMSStatus(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.queryZgMSStatus");
		return this.getData(sql, new Object[]{proPlanId, gxPlanNo});
	}

	/**
	 * 查询库存重量
	 *
	 * @return
	 */
	public CoreReturnObject queryMatWeigth(String judgNo, String fixNum,
										   String lengthM, String lengSingGp, String num) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.queryMatWeigth");
		return this.getData(sql, new Object[]{judgNo, fixNum, lengthM,
				lengSingGp, num});
	}

	/**
	 * 根据轧管投入产出信息
	 *
	 * @return
	 */
	public CoreReturnObject queryBaseMaterialDPl(String inwlId, String outwlId,
												 String plineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.queryBaseMaterialDPl");
		return this.getData(sql, new Object[]{inwlId, outwlId, plineCode});
	}

	/**
	 * 查询排产信息
	 *
	 * @param con
	 * @param proPlanId 订单编号
	 * @param gxPlanNo  排产序号
	 * @return PlnOrderCastSEntity
	 * @throws SQLException
	 */
	public static <T> T getPlanOrderZg(Connection con, String proPlanId,
									   String gxPlanNo, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ComPlanFurnace.queryPlnOrderZgS");
		sql += " AND T.PRO_PLAN_ID = ?  AND T.GX_PLAN_NO = ?";
		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;
	}

	/**
	 * 查询坯子库存信息
	 *
	 * @param con
	 * @param
	 * @param judgeStoveNo 判定炉号
	 * @param storageNo    仓库号
	 * @param locationNo   库位号
	 * @throws SQLException
	 */
	public static List<MatGpMEntity> getQureyMatGpM(Connection con,
													String judgeStoveNo, String storageNo, String locationNo,
													int takeCount, int cutNumGp, String proPlanIdNo, String actLen)throws SQLException{
		return getQureyMatGpM(con,judgeStoveNo,storageNo,locationNo,takeCount,cutNumGp,proPlanIdNo,actLen,"");
	}

	public static List<MatGpMEntity> getQureyMatGpM(Connection con,
			String judgeStoveNo, String storageNo, String locationNo,
			int takeCount, int cutNumGp, String proPlanIdNo,String actLen,String isDealer)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.QueryMatGp");
		// AND S.STORAGE_NO = ?
		// AND S.LOCATION_NO = ?
		sql += " AND T.FIX_NUM=?";
		sql += " AND T.ACT_LEN = ?";
		if (!proPlanIdNo.equals("")) {
			sql += " AND T.PRO_PLAN_ID_ZG||'/'||T.GX_PLAN_NO_ZG ='"
					+ proPlanIdNo + "'";
		}
		if (!StringUtils.isEmpty(isDealer)) {
			sql += "T.IS_DEALER = '" + isDealer + "'";
		}
		sql += "  ORDER BY T.MAT_NO ASC) where rownum<=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		// ps.setObject(2, storageNo);
		// ps.setObject(3, locationNo);
		ps.setObject(2, cutNumGp);
		ps.setObject(3,actLen);
		ps.setObject(4, takeCount);

		ResultSet rs = ps.executeQuery();
		List<MatGpMEntity> list = EntityTool.getEntitysByRs(rs,
				MatGpMEntity.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (MatGpMEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 查询坯子库存信息
	 *
	 * @param con
	 * @param
	 *
	 * @param judgeStoveNo
	 *            判定炉号
	 * @param storageNo
	 *            仓库号
	 * @param locationNo
	 *            库位号
	 * @throws SQLException
	 */
	public static List<MatGpMEntity> getQureyMatGpMLK(Connection con,
													String judgeStoveNo, String storageNo, String locationNo,
													int takeCount, int cutNumGp, String proPlanIdNo,String actLen,String matNoList)
			throws SQLException {
		String[] matNo = matNoList.split(",");
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.QueryMatGp");
		// AND S.STORAGE_NO = ?
		// AND S.LOCATION_NO = ?
		sql += " AND T.FIX_NUM=?";
		sql += " AND T.ACT_LEN = ?";
		if (!proPlanIdNo.equals("")) {
			sql += " AND T.PRO_PLAN_ID_ZG||'/'||T.GX_PLAN_NO_ZG ='"
					+ proPlanIdNo + "'";
		}
		sql += CoreConverter.toSqlConditionString("T.MAT_NO",matNo);
		sql += "  ORDER BY T.MAT_NO ASC) where rownum<=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		// ps.setObject(2, storageNo);
		// ps.setObject(3, locationNo);
		ps.setObject(2, cutNumGp);
		ps.setObject(3,actLen);
		ps.setObject(4, takeCount);

		ResultSet rs = ps.executeQuery();
		List<MatGpMEntity> list = EntityTool.getEntitysByRs(rs,
				MatGpMEntity.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (MatGpMEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 轧管坯子利库
	 * 
	 * @param jslist
	 * @param userName
	 *            利库人
	 * @param proPlanId
	 *            轧管订单号
	 * @param gxPlanNo
	 *            排产序号
	 * @return
	 * @throws Exception
	 */
	public CoreReturnObject doAddLibrary(ArrayList<ArrayList<String>> jslist,
										 String userName, String proPlanId, String gxPlanNo)
			throws Exception {
		return doAddLibrary(jslist,userName,proPlanId,gxPlanNo,"");
	}
	public CoreReturnObject doAddLibrary(ArrayList<ArrayList<String>> jslist,
			String userName, String proPlanId, String gxPlanNo,String isDealer)
			throws Exception {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat dfMonth = new SimpleDateFormat("yyyyMM");

			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// 查询轧管信息
			PlnOrderZgSEntityL plnZgS = getPlanOrderZg(conn, proPlanId,
					gxPlanNo, PlnOrderZgSEntityL.class);
			if (plnZgS == null) {
				cro.setV_errMsg("未找到轧管订单(" + proPlanId + "/" + gxPlanNo
						+ ")信息!");
				return cro;
			}
			// 判断是否排产订单下发
			// if (plnZgS.getIfStoveIssued().equals("1")) {
			// cro.setV_errMsg("轧管订单(" + proPlanId + "/" + gxPlanNo
			// + ")已下发,不能利该轧管订单,如需利该轧管订单,请拆分订单!");
			// return cro;
			// }
			// int lkNum = 0;
			// double lkWt = 0;
			int seq = 1;
			// 循环库存信息
			for (int i = 0; i < jslist.size(); i++) {
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				DecimalFormat df = new DecimalFormat("0000000000");
				DecimalFormat df1=new DecimalFormat("0.000");
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String judgeStoveNo = list.get(0);
				String proPlanIdZz = list.get(1);
				String gxPlanNoZz = list.get(2);
				int takeCount = Integer.parseInt(list.get(3));// 利库支
				double takeWeight = Double.parseDouble(list.get(4));// 利库吨
				double actLenTake = Integer.parseInt(list.get(5));// 使用倍尺坯长
				double fixLenTake = Integer.parseInt(list.get(6));// 计划单倍
				// String furnaceno = list.get(7);
				// String sequenceno = list.get(8);
				String gradecode = list.get(9);
				String gradename = list.get(10);
				int cutNumGp = (int) (Double.parseDouble(list.get(11)));
				String storageNo = list.get(12);
				String locationNo = list.get(13);
				String stoveNo = list.get(14);
				String flagStoveNo = list.get(15);
				String matStatus = list.get(16);
				String cutTarget = list.get(17);//切余处理类型
				String plnType = list.get(18);
				int oldcutNumGp = Integer.parseInt(list.get(19));
				//int num = takeCount * cutNumGp;
				int num = cutNumGp;
				String outCutNum = list.get(20);
				String aimlength = list.get(21);
				String rollLength = list.get(22);
				String SpecCic = list.get(23);
				int dimater = Integer.parseInt(plnZgS.getDiameterGp());
				if (dimater == 251) {
					dimater = 250;
				}
				double mSingleWeight = (7.8 * Pi / 4 * dimater * dimater) / 1000 / 1000;// 米单重
				// 单倍坯重
				double weightGpOne = mSingleWeight * (fixLenTake / 1000);
				// 倍尺坯单支重=坯米单重*倍尺坯长/1000
				double weightM = mSingleWeight * (actLenTake / 1000);
				List<MatGpMEntity> matGpMlist = null;
				if(list.get(25) == null || list.get(25).equals(""))
				{
					matGpMlist = getQureyMatGpM(conn,
							judgeStoveNo, storageNo, locationNo, takeCount,
							oldcutNumGp, "",list.get(24),isDealer);
				}else
				{
					matGpMlist = getQureyMatGpMLK(conn,
							judgeStoveNo, storageNo, locationNo, takeCount,
							oldcutNumGp, "",list.get(24),list.get(25));
				}

				if (matGpMlist == null) {
					cro.setV_errMsg("管坯物料已发生改变,请刷新!");
					return cro;
				}

				double actTake = 0;
				double actWt = 0;
				String jugdeApplyCode = "";// 是否有申请判定单号
				// String jugdeApplyStrat = "";// 是否申请判定成功

				int countAppCode = 0;
				double cutYuLong = 0;
				double actLenSy = 0;
				double fixLen = 0;
				String furnaceno = "";
				String matOrigin = "";
				// String kcGradecode="";
				// String kcGradename="";
				String inwlDesc = "";
				String cic = "";
				String gradeName = "";

				for (MatGpMEntity matGpM : matGpMlist) {
					countAppCode++;
					cic = matGpM.getCic();
					gradeName = matGpM.getGradename();
					furnaceno = matGpM.getFurnaceno() + "/"
							+ matGpM.getSequenceno();
					jugdeApplyCode = matGpM.getJugdeApplyCode();
					actTake = Double.parseDouble(matGpM.getActLen());
					//actWt += Double.parseDouble(matGpM.getActWeight());
					actWt = Double.parseDouble(matGpM.getActWeight());
					fixLen = Double.parseDouble(matGpM.getFixLen());
					matOrigin = matGpM.getMatOriginCode();
					inwlDesc = matGpM.getMaterialName();

					if (!matGpM.getProductFlag().equals("801401")) {
						cro.setV_errMsg("材料类别不是在制品,不能利库!");
						return cro;
					}
					if (!matStatus.equals("80150101")
							&& !matStatus.equals("80150102")) {
						cro.setV_errMsg("材料状态不是产出待判与产出已判定状态,不能利库");
						return cro;
					}
					if (!matGpM.getQcmStaus().equals("00")) {
						cro.setV_errMsg("交库状态不是合格状态,不能利库!");
						return cro;
					}
					if (matGpM.getHangingFlag().equals("1")) {

						cro.setV_errMsg("你选择的管坯物料已生成实际炉计划不能利库。如需利库,请先删除炉计划!");
						return cro;
					}

					if (matGpM.getCutYuLong() == null
							|| matGpM.getCutYuLong() == "") {
						cutYuLong = 0;
					} else {
						cutYuLong = Double.parseDouble(matGpM.getCutYuLong());
					}
					double actLen = actTake - cutYuLong;
					// 剩余倍尺坯长
					actLenSy = actLen - actLenTake;

					int  matSeq = 0;
					if(matGpM.getStoveNo() == null || matGpM.getStoveNo().equals(""))
					{
						cro.setV_errMsg("坯料原料利库，熔炼炉号不能为空!");
						return  cro;
					}
					if(cutTarget.equals("套尺"))//切余套尺
					{
						double weightMs = Double.parseDouble(df1.format(mSingleWeight * (actLenSy / 1000)));
						MatGpMEntity matGpSetFootEntity = new MatGpMEntity();
						if(matGpM.getIsSetfoot().equals("0"))
						{
							matGpSetFootEntity.setMatNoOld(matGpM.getMatNo());
						}else
						{
							matGpSetFootEntity.setMatNoOld(matGpM.getMatNoOld());
						}

						matGpSetFootEntity.setSetfootSeq(String.valueOf(Integer.parseInt(matGpM.getSetfootSeq())+1));
						matGpSetFootEntity.setActLen(String.valueOf(actLenSy));
						matGpSetFootEntity.setActWeight(String.valueOf(weightMs));
						matGpSetFootEntity.setIsSetfoot("1");
						matGpSetFootEntity.setStoveNo(matGpM.getStoveNo());
						matGpSetFootEntity.setFixLen(String.valueOf(actLenSy));
						matGpSetFootEntity.setFixNum("1");
						matGpSetFootEntity.setMatNo(matGpM.getMatNo());
						matGpSetFootEntity.setDimater(matGpM.getDimater());
						String matGpSetFootSql = CoreXmlSqlParsersFactory.getSql("FrmPlanMaterialSelection.insertMatNoNew");
						matGpSetFootSql = EntityTool.fillSqlByEntity(matGpSetFootSql,matGpSetFootEntity);
						ps = conn.prepareStatement(matGpSetFootSql);
						ps.executeUpdate();
						ps.close();
					}


					// 修改坯子库存信息
					String sqlUpdateMat = CoreXmlSqlParsersFactory
							.getSql("FrmPlanMaterialSelection.UpdateMatGp");
					ps = conn.prepareStatement(sqlUpdateMat);
					ps.setObject(1, "80150103");
					ps.setObject(2, "1");
					ps.setObject(3, proPlanId);
					ps.setObject(4, gxPlanNo);
					ps.setObject(5, plnZgS.getOrderNo());
					ps.setObject(6, plnZgS.getOrderSeq());
					ps.setObject(7, plnZgS.getDeliveryNo());
					if (plnZgS.getOrderSource().equals("备料需求")) {
						ps.setObject(8, "");
						ps.setObject(9, "");
					} else {
						ps.setObject(
								8,
								plnZgS.getOrdLnDlyPk().substring(0,
										plnZgS.getOrdLnDlyPk().length() - 6));
						ps.setObject(
								9,
								plnZgS.getOrdLnDlyPk().substring(0,
										plnZgS.getOrdLnDlyPk().length() - 3));
					}
					ps.setObject(10, plnZgS.getOrdLnDlyPk());
					ps.setObject(11, actLenSy);
					ps.setObject(12, "1");
					if (matGpM.getCic().equals("")) {
						ps.setObject(13, plnZgS.getCicGp());
						if (plnZgS.getPic() == null
								|| plnZgS.getPic().equals("")) {
							ps.setObject(14, plnZgS.getPic());
						} else {
							ps.setObject(14, plnZgS.getPic().split(",")[0]);
						}
						if (plnZgS.getSic() == null
								|| plnZgS.getSic().equals("")) {
							ps.setObject(15, plnZgS.getSic());
						} else {
							ps.setObject(15, plnZgS.getSic().split(",")[0]);
						}
						if (plnZgS.getDic() == null
								|| plnZgS.getDic().equals("")) {
							ps.setObject(16, plnZgS.getDic());
						} else {
							ps.setObject(16, plnZgS.getDic().split(",")[0]);
						}

					} else {
						ps.setObject(13, matGpM.getCic());
						ps.setObject(14, matGpM.getPic());
						ps.setObject(15, matGpM.getSic());
						ps.setObject(16, matGpM.getDic());
					}
					ps.setObject(17, matGpM.getMatNo());
					ps.executeUpdate();
					ps.close();
					// }

					String resumeSeq = dateFormat.format(now) + df.format(seq);
					// 生成利库日志
					MatGpTrackEntity matGpTrack = new MatGpTrackEntity();
					matGpTrack.setResumeSeq(resumeSeq);
					matGpTrack.setEventId("900102");
					matGpTrack.setEventDesc("利库");
					matGpTrack
							.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanMaterialSelection");
					matGpTrack.setCallFuncCoding("doAddLibrary");
					matGpTrack.setKeyvalue1("List<MatGpMEntity> matGpMlist");
					matGpTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
					matGpTrack.setKeyvalue2("String userName");
					matGpTrack.setKeyvalue2Desc2("操作人");
					matGpTrack.setMatNo(matGpM.getMatNo());
					matGpTrack.setProductFlag(matGpM.getProductFlag());
					matGpTrack.setMatStatus(matGpM.getMatStatus());
					matGpTrack.setStoveNo(matGpM.getStoveNo());
					matGpTrack.setFlagStoveNo(matGpM.getFlagStoveNo());
					matGpTrack.setJudgeStoveNo(matGpM.getJudgeStoveNo());
					matGpTrack.setBatchNo("");
					matGpTrack.setGroudNo(matGpM.getGroudNo());
					matGpTrack.setCastNo(matGpM.getCastNo());
					matGpTrack.setCcmid(matGpM.getCcmid());
					matGpTrack.setGradecode(matGpM.getGradecode());
					matGpTrack.setGradename(matGpM.getGradename());
					matGpTrack.setStdCode(matGpM.getStdCode());
					matGpTrack.setStdName(matGpM.getStdName());
					matGpTrack.setActDimater(matGpM.getDimater());
					matGpTrack.setActHeight(matGpM.getHeight());
					matGpTrack.setActLen(String.valueOf(actLenTake));
					matGpTrack.setActLenMax(plnZgS.getLenRollMax());
					matGpTrack.setActLenMin(plnZgS.getLenRollMin());
					matGpTrack.setActFixLen(String.valueOf(fixLenTake));
					matGpTrack.setActFixNum(String.valueOf(cutNumGp));
					matGpTrack.setActCount("1");
					matGpTrack.setActWeight(String.valueOf(new BigDecimal(
							weightM).setScale(3, RoundingMode.HALF_UP)
							.doubleValue()));
					matGpTrack.setActTheoryWeight(matGpM.getActTheoryWeight());
					if (plnZgS.getOrderSource().equals("备料需求")) {
						matGpTrack.setOrdPk("");
						matGpTrack.setOrdLnPk("");
					} else {
						matGpTrack.setOrdPk(plnZgS.getOrdLnDlyPk().substring(0,
								plnZgS.getOrdLnDlyPk().length() - 6));
						matGpTrack.setOrdLnPk(plnZgS.getOrdLnDlyPk().substring(
								0, plnZgS.getOrdLnDlyPk().length() - 3));
					}
					matGpTrack.setOrdLnDlyPk(plnZgS.getOrdLnDlyPk());
					matGpTrack.setOrderNo(plnZgS.getOrderNo());
					matGpTrack.setOrderSeq(plnZgS.getOrderSeq());
					matGpTrack.setOrderSeqNo(plnZgS.getDeliveryNo());
					matGpTrack.setOldOrderNo(matGpM.getOldOrderNo());
					matGpTrack.setOldOrderSeq(matGpM.getOldOrderSeq());
					matGpTrack.setOldOrderSeqNo(matGpM.getOldOrderSeqNo());
					matGpTrack.setMemo("");
					matGpTrack.setCreateName(userName);
					matGpTrack.setCreateTime(dateTime);
					matGpTrack.setOldJudgeStoveNo(matGpM.getOldJudgeStoveNo());
					matGpTrack.setOldBatchNo("");
					matGpTrack.setOldGroudNo(matGpM.getOldGroudNo());
					matGpTrack.setOldGradecode(matGpM.getOldGradecode());
					matGpTrack.setOldGradename(matGpM.getOldGradename());
					matGpTrack.setOldStdCode(matGpM.getOldStdCode());
					matGpTrack.setOldStdName(matGpM.getOldStdName());
					matGpTrack.setOldStoveNo(matGpM.getOldStoveNo());
					seq++;
					String sqlAddTrack = EntityTool
							.fillSqlByEntity(
									CoreXmlSqlParsersFactory
											.getSql("FrmPlanMaterialSelection.addMatGpTrack"),
									matGpTrack);
					ps = conn.prepareStatement(sqlAddTrack);
					ps.executeUpdate();
					ps.close();



					PlnZyZgMEntity plnZgM = new PlnZyZgMEntity();
					int countM = 0;
					String heatPlanNo = "";
					String planStatus = "00";
					String feedHeatNo = "";
					double oldLengSing = 0;
					// 根据判定炉号，轧管订单号查询是否存在虚拟炉计划
					String sqlQuery = "SELECT COUNT(*) COUNT,T.HEAT_PLAN_NO,T.PLANSTATUS,T.FEED_HEAT_NO,T.LEN_GP_SINGLE,T.IF_MATCH_ODD FROM PLN_ZY_ZG_M T WHERE T.JUDGE_STOVE_NO=? "
							+ " AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=? GROUP BY T.HEAT_PLAN_NO,T.PLANSTATUS,T.FEED_HEAT_NO,T.LEN_GP_SINGLE,T.IF_MATCH_ODD";
					ps = conn.prepareStatement(sqlQuery);
					ps.setObject(1, judgeStoveNo);
					ps.setObject(2, proPlanId);
					ps.setObject(3, gxPlanNo);
					rs = ps.executeQuery();
					while (rs.next()) {
						heatPlanNo = rs.getString("HEAT_PLAN_NO");
						planStatus = rs.getString("PLANSTATUS");
						feedHeatNo = rs.getString("FEED_HEAT_NO");
						if (rs.getString("IF_MATCH_ODD").equals("1")
								|| rs.getString("IF_MATCH_ODD").equals("4")) {
							countM = rs.getInt("COUNT");
							if (!planStatus.equals("00")) {
								cro.setV_errMsg("该轧管订单(" + proPlanId + "/"
										+ gxPlanNo + "),判定炉号(" + judgeStoveNo
										+ ")已存在炉计划,并已下发,如需利库,请先撤销炉计划!");
								return cro;
							}
						} else {
							cro.setV_errMsg("该轧管订单(" + proPlanId + "/" + gxPlanNo
									+ "),判定炉号(" + judgeStoveNo
									+ ")已存在不是利库炉计划,如需利库,请先撤销炉计划!");
							return cro;
						}
					}
					rs.close();
					ps.close();
					double singlCpWt = 0;// 单支预计成品吨
					double singlReduWt = 0;// 单支估算吨
					double lengthZg = 0;
					double length = 0;
					int outCut=0;
					// 算预计成品吨
					double aimOutdiam = Double.parseDouble(plnZgS
							.getAimoutdiameter());
					double aimwallthick = Double.parseDouble(plnZgS
							.getAimwallthick());
					double weightOne = (0.02466 * aimwallthick * (aimOutdiam - aimwallthick)) / 1000;


					double cutHeadEnd = (Double.parseDouble(plnZgS.getLenCutend()) + Double
							.parseDouble(plnZgS.getLenCuthead())) / 1000;
					if (fixLenTake != Double.parseDouble(plnZgS.getLenGpSingle())) {
						lengthZg = Double.parseDouble(rollLength);
						length=Double.parseDouble(aimlength);
						outCut=Integer.parseInt(outCutNum);
					} else {
						lengthZg = Double.parseDouble(plnZgS.getRollLength());
						length=Double.parseDouble(plnZgS.getAimlength());
						outCut=Integer.parseInt(plnZgS.getOutnumCut());
					}

					if (plnZgS.getPassive().equals("0")) {// 被动
						singlCpWt = weightOne * (lengthZg - cutHeadEnd);
					} else {
						// 主动
						singlCpWt = weightOne * (length*outCut);
					}

					singlReduWt = (Double.parseDouble(plnZgS.getGpreqWeight()) / Double
							.parseDouble(plnZgS.getWeigthS())) * singlCpWt;
					if (countM == 0) {
						heatPlanNo = corePlnZyFurnM.getMaxHeatPlanNo(conn,
								proPlanId + "6", proPlanId, "D");
						// 获取炉计划顺序号
						int gxProSeq = corePlnZyFurnM.getMaxGxPlnSeq(conn,
								plnZgS.getPlineCode(), "D");
						plnZgM.setHeatPlanNo(heatPlanNo);
						plnZgM.setJudgeStoveNo(judgeStoveNo);
						plnZgM.setStoveNo(stoveNo);
						plnZgM.setFlagStoveNo(flagStoveNo);
						plnZgM.setGxProSeq(String.valueOf(gxProSeq));
						plnZgM.setUpperHeatplanId(furnaceno);
						// plnZgM.setZyBatchId(plnZgS.getZyBatchId());
						plnZgM.setPlanstatus("00");
						if (proPlanIdZz.contains("DP")) {
							plnZgM.setUpperProcessCode("C");
						} else {
							plnZgM.setUpperProcessCode("B");
						}
						plnZgM.setPlineCode(plnZgS.getPlineCode());
						plnZgM.setPlineName(plnZgS.getPlineName());
						if (!plnZgS.getDecision().equals("A")) {
							// 通过制程判定轧管是否末工序
							if (plnZgS.getWholeBacklogDesc().contains("镦拔扩")) {
								plnZgM.setNextProcessCode("E");
							} else if (plnZgS.getWholeBacklogDesc().contains("热处理")) {
								plnZgM.setNextProcessCode("F");
							} else if (plnZgS.getWholeBacklogDesc().contains("加工")) {
								plnZgM.setNextProcessCode("G");
							} else {
								if (plnZgS.getOrdLnDlyPk().contains("ZZBY-J")) {
									plnZgM.setNextProcessCode("H");
								} else if (plnZgS.getOrdLnDlyPk()
										.contains("ZZBY-D")) {
									plnZgM.setNextProcessCode("G");
								} else {
									plnZgM.setNextProcessCode("");
								}
							}
							plnZgM.setIsendgx("0");
						} else {
							plnZgM.setNextProcessCode("");
							plnZgM.setIsendgx("1");
						}
						if (plnZgS.getGpreqId() != null
								&& !plnZgS.getGpreqId().equals("")) {
							plnZgM.setIfMatchOdd("4");
						} else {
							plnZgM.setIfMatchOdd("1");
						}
						plnZgM.setIfDoHeatPlan("1");
						plnZgM.setProPlanId(plnZgS.getProPlanId());
						plnZgM.setGxPlanNo(plnZgS.getGxPlanNo());
						plnZgM.setCcmProPlanId(proPlanIdZz);
						plnZgM.setCcmGxPlanNo(gxPlanNoZz);
						plnZgM.setGradecode(gradecode);
						plnZgM.setGradename(gradename);
						plnZgM.setSteelcode(plnZgS.getSteelcode());
						plnZgM.setSteelname(plnZgS.getSteelname());

						if (!plnZgS.getGradename().equals(gradename)) {
							// 查询产出物料
							String[] bomMat = StoveHelper.getQueryMateratBom(conn,
									gradename, inwlDesc, plnZgS.getDiameterGp(),
									proPlanId, gxPlanNo);
							plnZgM.setInwlId(bomMat[0]);
							plnZgM.setInwlDesc(bomMat[1]);
							plnZgM.setOutwlId(bomMat[2]);
							plnZgM.setOutwlDesc(bomMat[3]);
							plnZgM.setBom(bomMat[4]);
							if (bomMat[7] != null && !bomMat[7].equals("")) {
								String[] strs = bomMat[7].split("x");
								plnZgM.setOutdiameterZg(strs[0]);
								plnZgM.setWallthickZg(strs[1]);
							} else {
								plnZgM.setOutdiameterZg(plnZgS.getOutdiameterZg());
								plnZgM.setWallthickZg(plnZgS.getWallthickZg());
							}
						} else {
							plnZgM.setOutdiameterZg(plnZgS.getOutdiameterZg());
							plnZgM.setWallthickZg(plnZgS.getWallthickZg());
							plnZgM.setInwlId(plnZgS.getInwlId());
							plnZgM.setInwlDesc(plnZgS.getInwlDesc());
							plnZgM.setOutwlId(plnZgS.getOutwlId());
							plnZgM.setOutwlDesc(plnZgS.getOutwlDesc());
							plnZgM.setBom(plnZgS.getBom());
						}

						plnZgM.setPassCode(plnZgS.getPassCode());
						plnZgM.setPassName(plnZgS.getPassName());
						plnZgM.setPlnInsingleNum(String.valueOf(num));
						plnZgM.setPlnInsingleWt(String.valueOf(takeWeight));

						plnZgM.setProcessCodeC(plnZgS.getProcessCodeC());
						plnZgM.setProcessDescC(plnZgS.getProcessDescC());
						plnZgM.setOrderSource(plnZgS.getOrderSource());
						plnZgM.setOrderNo(plnZgS.getOrderNo());
						plnZgM.setOrderSeq(plnZgS.getOrderSeq());
						plnZgM.setDeliveryNo(plnZgS.getDeliveryNo());
						plnZgM.setOrdLnDlyPk(plnZgS.getOrdLnDlyPk());
						plnZgM.setReqBlId(plnZgS.getReqBlId());
						plnZgM.setIfExport(plnZgS.getIfExport());
						plnZgM.setPriority(plnZgS.getPriority());
						plnZgM.setPriorityMemo(plnZgS.getPriorityMemo());
						plnZgM.setProMonth(plnZgS.getProMonth());
						plnZgM.setIfLenControl(plnZgS.getIfLenControl());
						plnZgM.setIfMinusSicRoll(plnZgS.getIfMinusSicRoll());
						plnZgM.setProdStandard(plnZgS.getProdStandard());
						plnZgM.setOutputStandard(plnZgS.getOutputStandard());
						plnZgM.setDecision(plnZgS.getDecision());
						plnZgM.setProgyMemo(plnZgS.getProgyMemo());
						plnZgM.setProduccode(plnZgS.getProduccode());
						plnZgM.setProducname(plnZgS.getProducname());
						plnZgM.setModelCode(plnZgS.getModelCode());
						plnZgM.setModelDesc(plnZgS.getModelDesc());
						plnZgM.setOutdiameter(plnZgS.getOutdiameter());
						plnZgM.setWallthick(plnZgS.getWallthick());
						plnZgM.setAimoutdiameter(plnZgS.getAimoutdiameter());
						plnZgM.setAimwallthick(plnZgS.getAimwallthick());
						plnZgM.setThicknessWall(plnZgS.getThicknessWall());
						plnZgM.setLenCutend(plnZgS.getLenCutend());
						plnZgM.setLenCuthead(plnZgS.getLenCuthead());
						String siglLen = plnZgS.getSiglLen();
						if (siglLen != null && !siglLen.isEmpty()) {
						    try {
						        if(Double.parseDouble(siglLen) > 0) {
						        	double lenMin = Double.parseDouble(plnZgS
											.getAimlength())
											- Double.parseDouble(plnZgS.getEndlenSpecstd());

									lenMin = (int) (Double.parseDouble(plnZgS
											.getAimlength()) / Double.parseDouble(plnZgS
											.getSiglLen()))
											* Double.parseDouble(plnZgS.getSiglLen());
									if (lenMin - Double.parseDouble(plnZgS.getLenRollMin()) < 0) {
										lenMin = Double.parseDouble(plnZgS.getLenRollMin());
									}

									double lenMax = lenMin
											+ Double.parseDouble(plnZgS.getEndlenSpecstd());
									// 判定是否除以单倍尺长可以整除
									plnZgM.setLenRollMax(String.valueOf(lenMax));
									plnZgM.setLenRollMin(String.valueOf(lenMin));
						        }else{
						        	plnZgM.setLenRollMax(plnZgS.getLenRollMax());
									plnZgM.setLenRollMin(plnZgS.getLenRollMin());
						        }
						    } catch (NumberFormatException e) {
						    	throw new Exception("数字转换错误"+e.getMessage());
						    }
						} else {
						    plnZgM.setLenRollMax(plnZgS.getLenRollMax());
						    plnZgM.setLenRollMin(plnZgS.getLenRollMin());
						}
						
						if (!plnZgS.getSiglLen().equals("")
								&&!plnZgS.getSiglLen().equals(null)
								&&Double.parseDouble(plnZgS.getSiglLen())>0) {
							
						} else {
							
						}

						double cpWt = 0;
						// 折算吨
						double reducedWt = 0;
						if (fixLenTake != Double.parseDouble(plnZgS
								.getLenGpSingle())) {
							plnZgM.setOutnumCut(outCutNum);
							plnZgM.setAimlength(aimlength);
							plnZgM.setRollLength(rollLength);

							cpWt = singlCpWt * num;
							reducedWt = singlReduWt * num;
						} else {
							outCutNum = plnZgS.getOutnumCut();
							plnZgM.setOutnumCut(outCutNum);
							plnZgM.setAimlength(plnZgS.getAimlength());
							plnZgM.setRollLength(plnZgS.getRollLength());

							cpWt = singlCpWt * num;
							reducedWt = singlReduWt * num;
						}
						plnZgM.setPlnOutsingleNum(String.valueOf(num
								* Integer.parseInt(outCutNum)));
						plnZgM.setPlnOutsingleW(String.valueOf(cpWt));
						plnZgM.setReducedWt(String.valueOf(reducedWt));
						plnZgM.setLenGpSingle(String.valueOf(fixLenTake));
						plnZgM.setDiameter(plnZgS.getDiameterGp());
						plnZgM.setWtGpSingle(String.valueOf(weightGpOne));

						plnZgM.setCic(SpecCic);
						if (plnZgS.getSic() == null || plnZgS.getSic().equals("")) {
							plnZgM.setSic(plnZgS.getSic());
						} else {
							plnZgM.setSic(plnZgS.getSic().split(",")[0]);
						}
						if (plnZgS.getDic() == null || plnZgS.getDic().equals("")) {
							plnZgM.setDic(plnZgS.getDic());
						} else {
							plnZgM.setDic(plnZgS.getDic().split(",")[0]);
						}
						if (plnZgS.getPic() == null || plnZgS.getPic().equals("")) {
							plnZgM.setPic(plnZgS.getPic());
						} else {
							plnZgM.setPic(plnZgS.getPic().split(",")[0]);
						}
						plnZgM.setProDay(dFormat.format(dFormat.parse(dateTime)));
						plnZgM.setBalYearMonth(dfMonth.format(dfMonth
								.parse(dateTime)));
						plnZgM.setCreateName(userName);
						plnZgM.setCreateTime(dateTime);
						plnZgM.setCutType(plnZgS.getPassive());
						plnZgM.setIfMonitor(plnZgS.getIfMonitorZg());
						plnZgM.setDiameterMandrel(plnZgS.getDiameterMandrel());
						plnZgM.setPrdcrNo(plnZgS.getPrdcrNo());
						plnZgM.setMonitorPoint(plnZgS.getMonitorPoint());
						plnZgM.setWholeBacklog(plnZgS.getWholeBacklog());
						plnZgM.setWholeBacklogDesc(plnZgS.getWholeBacklogDesc());
						plnZgM.setCraftFileMan(plnZgS.getCraftFileMan());
						plnZgM.setCraftFileNo(plnZgS.getCraftFileNo());
						plnZgM.setCraftSeq(plnZgS.getCraftSeq());
						plnZgM.setSecCraftFileNo(plnZgS.getSecCraftFileNo());
						plnZgM.setStationRoad(plnZgS.getStationRoad());
						plnZgM.setIndexSeq(plnZgS.getIndexSeq());
						plnZgM.setGptype("1");
						if (matOrigin.equals("801301")) {
							plnZgM.setOutsBilletFl("1");// 外购
						} else {
							plnZgM.setOutsBilletFl("0");// 自炼
						}
						if (plnType.equals("正常计划")) {

							plnType = "0";
						} else if (plnType.equals("试轧料")) {
							plnType = "1";
						}
						plnZgM.setPlnType(plnType);
						// 新增轧管虚拟炉计划
						String sqlZgM = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("FrmPlanMaterialSelection.addPlnZyZgM"),
										plnZgM);
						ps = conn.prepareStatement(sqlZgM);
						ps.executeUpdate();
						ps.close();
					}

					int countC = 0;
					String heatPlanSqe = "";
					// 判定是否存在相同坯长，倍尺，单倍坯长，判定炉号，判定单号，同炉计划ID，相同使用坯长数据
					String sqlC = "SELECT COUNT(*) COUNT1,T.HEAT_PLAN_SQE FROM PLN_ZY_ZG_C T WHERE "
							+ "T.HEAT_PLAN_NO=? AND NVL(T.JUGDE_APPLY_CODE,'/')=NVL(?,'/') AND T.JUDGE_STOVE_NO=? "
							+ "AND T.CUT_NUM_OLD=? AND T.LENGTH_M_OLD=? AND T.LEN_GP_SINGLE_OLD=? AND T.LENGTH_M = ? GROUP BY T.HEAT_PLAN_SQE";
					ps = conn.prepareStatement(sqlC);
					ps.setObject(1, heatPlanNo);
					ps.setObject(2, jugdeApplyCode);
					ps.setObject(3, judgeStoveNo);
					ps.setObject(4, oldcutNumGp);
					ps.setObject(5, actTake);
					ps.setObject(6, fixLen);
					ps.setObject(7,actLenTake);
					rs = ps.executeQuery();
					if (rs.next()) {
						countC = rs.getInt("COUNT1");
						heatPlanSqe = rs.getString("HEAT_PLAN_SQE");
					}
					rs.close();
					ps.close();

					double cutLength = actTake - actLenTake;
					double weightMs = Double.parseDouble(df1.format(mSingleWeight * (cutLength / 1000)));
					//double cutWeight = weightMs * takeCount;
					double cutWeight = weightMs;
					if (countC == 0) {
						PlnZyZgCEntity plnZgC = new PlnZyZgCEntity();
						plnZgC.setHeatPlanNo(heatPlanNo);
						plnZgC.setJugdeApplyCode(jugdeApplyCode);
						plnZgC.setStoveNo(stoveNo);
						plnZgC.setJudgeStoveNo(judgeStoveNo);
						plnZgC.setFlagStoveNo(flagStoveNo);
						plnZgC.setProPlanId(plnZgS.getProPlanId());
						plnZgC.setGxPlanNo(plnZgS.getGxPlanNo());
						plnZgC.setPlineCode(plnZgS.getPlineCode());
						plnZgC.setPlineName(plnZgS.getPlineName());
						plnZgC.setLenGpSingle(String.valueOf(fixLenTake));
						plnZgC.setDiameter(plnZgS.getDiameterGp());
						plnZgC.setWtGpSingle(String.valueOf(weightGpOne));
						plnZgC.setCutNumGp(String.valueOf(cutNumGp));
						plnZgC.setLengthM(String.valueOf(actLenTake));
						plnZgC.setWeightM(String.valueOf(weightM));
						plnZgC.setPlanIndoubleNum("1");
						plnZgC.setPlanIndoubleWt(matGpM.getActWeight());
						plnZgC.setCreateName(userName);
						plnZgC.setCreateTime(dateTime);
						plnZgC.setCutNumOld(String.valueOf(oldcutNumGp));
						plnZgC.setLenGpSingleOld(String.valueOf(fixLen));
						if (actLenSy > 0) {
							plnZgC.setCutLength(String.valueOf(cutLength));
							plnZgC.setCutWeight(String.valueOf(cutWeight));
							plnZgC.setCutTarget(cutTarget);
						} else {
							plnZgC.setCutLength("");
							plnZgC.setCutWeight("");
							plnZgC.setCutTarget("");
						}
						plnZgC.setLengthMOld(String.valueOf(actTake));
						plnZgC.setPlanWeigth(String.valueOf(actWt - cutWeight));
						// 获取炉计划顺序号
						heatPlanSqe = corePlnZyFurnM.getHeatPlanSeq(conn,
								heatPlanNo, "D");
						plnZgC.setHeatPlanSqe(heatPlanSqe);
						// 新增轧管实际炉计划
						String sqlZgC = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("FrmPlanMaterialSelection.addPlnZyZgC"),
										plnZgC);
						ps = conn.prepareStatement(sqlZgC);
						ps.executeUpdate();
						ps.close();
					} else {
						// 修改炉计划实表
						String updateC = "UPDATE PLN_ZY_ZG_C T SET T.PLAN_INDOUBLE_NUM=T.PLAN_INDOUBLE_NUM+TO_NUMBER(?),"
								+ "T.PLAN_INDOUBLE_WT=T.PLAN_INDOUBLE_WT+TO_NUMBER(?) ,T.PLAN_WEIGTH=T.PLAN_WEIGTH+? ";
						if (actLenSy > 0) {
							updateC += ",T.CUT_WEIGHT='"
									+ cutWeight + "',T.CUT_LENGTH = '"+actLenSy+"'";
						}
						updateC += " WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
						ps = conn.prepareStatement(updateC);
						ps.setObject(1, 1);
						ps.setObject(2, actWt);
						ps.setObject(3, actWt - cutWeight);
						ps.setObject(4, heatPlanNo);
						ps.setObject(5, heatPlanSqe);
						ps.executeUpdate();
						ps.close();
					}
					if (countM > 0) {
						// 修改炉计划主表量
						String sqlUpdate = CoreXmlSqlParsersFactory
								.getSql("FrmPlanMaterialSelection.updatePlnZgM");
						ps = conn.prepareStatement(sqlUpdate);
						ps.setObject(1, heatPlanNo);
						ps.setObject(2, singlCpWt);
						ps.setObject(3, singlReduWt);
						ps.setObject(4, heatPlanNo);
						ps.executeUpdate();
						ps.close();
					}
					// 修改有管坯需求号的铸造订单利库量
					if (plnZgS.getGpreqId() != null
							&& !plnZgS.getGpreqId().equals("")) {
						updateCastS(conn, plnZgS.getGpreqId(), judgeStoveNo, actWt
								- cutWeight, takeCount, "1");
					}
					// 回写库存下工序炉计划Id
					String sqlUpdate = "UPDATE MAT_GP_M T SET T.HEAT_PLAN_NO_NEXT=? WHERE T.JUDGE_STOVE_NO=? AND T.PRO_PLAN_ID_ZG=? AND T.GX_PLAN_NO_ZG=?";
					ps = conn.prepareStatement(sqlUpdate);
					ps.setObject(1, heatPlanNo);
					ps.setObject(2, judgeStoveNo);
					ps.setObject(3, plnZgS.getProPlanId());
					ps.setObject(4, plnZgS.getGxPlanNo());
					ps.executeUpdate();
					ps.close();
				}

//				PlnZyZgMEntity plnZgM = new PlnZyZgMEntity();
//				int countM = 0;
//				String heatPlanNo = "";
//				String planStatus = "00";
//				String feedHeatNo = "";
//				double oldLengSing = 0;
//				// 根据判定炉号，轧管订单号查询是否存在虚拟炉计划
//				String sqlQuery = "SELECT COUNT(*) COUNT,T.HEAT_PLAN_NO,T.PLANSTATUS,T.FEED_HEAT_NO,T.LEN_GP_SINGLE,T.IF_MATCH_ODD FROM PLN_ZY_ZG_M T WHERE T.JUDGE_STOVE_NO=? "
//						+ " AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=? GROUP BY T.HEAT_PLAN_NO,T.PLANSTATUS,T.FEED_HEAT_NO,T.LEN_GP_SINGLE,T.IF_MATCH_ODD";
//				ps = conn.prepareStatement(sqlQuery);
//				ps.setObject(1, judgeStoveNo);
//				ps.setObject(2, proPlanId);
//				ps.setObject(3, gxPlanNo);
//				rs = ps.executeQuery();
//				while (rs.next()) {
//					heatPlanNo = rs.getString("HEAT_PLAN_NO");
//					planStatus = rs.getString("PLANSTATUS");
//					feedHeatNo = rs.getString("FEED_HEAT_NO");
//					if (rs.getString("IF_MATCH_ODD").equals("1")
//							|| rs.getString("IF_MATCH_ODD").equals("4")) {
//						countM = rs.getInt("COUNT");
//						if (!planStatus.equals("00")) {
//							cro.setV_errMsg("该轧管订单(" + proPlanId + "/"
//									+ gxPlanNo + "),判定炉号(" + judgeStoveNo
//									+ ")已存在炉计划,并已下发,如需利库,请先撤销炉计划!");
//							return cro;
//						}
//					} else {
//						cro.setV_errMsg("该轧管订单(" + proPlanId + "/" + gxPlanNo
//								+ "),判定炉号(" + judgeStoveNo
//								+ ")已存在不是利库炉计划,如需利库,请先撤销炉计划!");
//						return cro;
//					}
//				}
//				rs.close();
//				ps.close();
//				double singlCpWt = 0;// 单支预计成品吨
//				double singlReduWt = 0;// 单支估算吨
//				double lengthZg = 0;
//				double length = 0;
//				int outCut=0;
//				// 算预计成品吨
//				double aimOutdiam = Double.parseDouble(plnZgS
//						.getAimoutdiameter());
//				double aimwallthick = Double.parseDouble(plnZgS
//						.getAimwallthick());
//				double weightOne = (0.0246615 * aimwallthick * (aimOutdiam - aimwallthick)) / 1000;
//
//
//				double cutHeadEnd = (Double.parseDouble(plnZgS.getLenCutend()) + Double
//						.parseDouble(plnZgS.getLenCuthead())) / 1000;
//				if (fixLenTake != Double.parseDouble(plnZgS.getLenGpSingle())) {
//					lengthZg = Double.parseDouble(rollLength);
//					length=Double.parseDouble(aimlength);
//					outCut=Integer.parseInt(outCutNum);
//				} else {
//					lengthZg = Double.parseDouble(plnZgS.getRollLength());
//					length=Double.parseDouble(plnZgS.getAimlength());
//					outCut=Integer.parseInt(plnZgS.getOutnumCut());
//				}
//
//				if (plnZgS.getPassive().equals("0")) {// 被动
//					singlCpWt = weightOne * (lengthZg - cutHeadEnd);
//				} else {
//					// 主动
//					singlCpWt = weightOne * (length*outCut);
//				}
//
//				singlReduWt = (Double.parseDouble(plnZgS.getGpreqWeight()) / Double
//						.parseDouble(plnZgS.getWeigthS())) * singlCpWt;
//				if (countM == 0) {
//					heatPlanNo = corePlnZyFurnM.getMaxHeatPlanNo(conn,
//							proPlanId + "6", proPlanId, "D");
//					// 获取炉计划顺序号
//					int gxProSeq = corePlnZyFurnM.getMaxGxPlnSeq(conn,
//							plnZgS.getPlineCode(), "D");
//					plnZgM.setHeatPlanNo(heatPlanNo);
//					plnZgM.setJudgeStoveNo(judgeStoveNo);
//					plnZgM.setStoveNo(stoveNo);
//					plnZgM.setFlagStoveNo(flagStoveNo);
//					plnZgM.setGxProSeq(String.valueOf(gxProSeq));
//					plnZgM.setUpperHeatplanId(furnaceno);
//					// plnZgM.setZyBatchId(plnZgS.getZyBatchId());
//					plnZgM.setPlanstatus("00");
//					if (proPlanIdZz.contains("DP")) {
//						plnZgM.setUpperProcessCode("C");
//					} else {
//						plnZgM.setUpperProcessCode("B");
//					}
//					plnZgM.setPlineCode(plnZgS.getPlineCode());
//					plnZgM.setPlineName(plnZgS.getPlineName());
//					if (!plnZgS.getDecision().equals("A")) {
//						// 通过制程判定轧管是否末工序
//						if (plnZgS.getWholeBacklogDesc().contains("镦拔扩")) {
//							plnZgM.setNextProcessCode("E");
//						} else if (plnZgS.getWholeBacklogDesc().contains("热处理")) {
//							plnZgM.setNextProcessCode("F");
//						} else if (plnZgS.getWholeBacklogDesc().contains("加工")) {
//							plnZgM.setNextProcessCode("G");
//						} else {
//							if (plnZgS.getOrdLnDlyPk().contains("ZZBY-J")) {
//								plnZgM.setNextProcessCode("H");
//							} else if (plnZgS.getOrdLnDlyPk()
//									.contains("ZZBY-D")) {
//								plnZgM.setNextProcessCode("G");
//							} else {
//								plnZgM.setNextProcessCode("");
//							}
//						}
//						plnZgM.setIsendgx("0");
//					} else {
//						plnZgM.setNextProcessCode("");
//						plnZgM.setIsendgx("1");
//					}
//					if (plnZgS.getGpreqId() != null
//							&& !plnZgS.getGpreqId().equals("")) {
//						plnZgM.setIfMatchOdd("4");
//					} else {
//						plnZgM.setIfMatchOdd("1");
//					}
//					plnZgM.setIfDoHeatPlan("1");
//					plnZgM.setProPlanId(plnZgS.getProPlanId());
//					plnZgM.setGxPlanNo(plnZgS.getGxPlanNo());
//					plnZgM.setCcmProPlanId(proPlanIdZz);
//					plnZgM.setCcmGxPlanNo(gxPlanNoZz);
//					plnZgM.setGradecode(gradecode);
//					plnZgM.setGradename(gradename);
//					plnZgM.setSteelcode(plnZgS.getSteelcode());
//					plnZgM.setSteelname(plnZgS.getSteelname());
//
//					if (!plnZgS.getGradename().equals(gradename)) {
//						// 查询产出物料
//						String[] bomMat = StoveHelper.getQueryMateratBom(conn,
//								gradename, inwlDesc, plnZgS.getDiameterGp(),
//								proPlanId, gxPlanNo);
//						plnZgM.setInwlId(bomMat[0]);
//						plnZgM.setInwlDesc(bomMat[1]);
//						plnZgM.setOutwlId(bomMat[2]);
//						plnZgM.setOutwlDesc(bomMat[3]);
//						plnZgM.setBom(bomMat[4]);
//						if (bomMat[7] != null && !bomMat[7].equals("")) {
//							String[] strs = bomMat[7].split("x");
//							plnZgM.setOutdiameterZg(strs[0]);
//							plnZgM.setWallthickZg(strs[1]);
//						} else {
//							plnZgM.setOutdiameterZg(plnZgS.getOutdiameterZg());
//							plnZgM.setWallthickZg(plnZgS.getWallthickZg());
//						}
//					} else {
//						plnZgM.setOutdiameterZg(plnZgS.getOutdiameterZg());
//						plnZgM.setWallthickZg(plnZgS.getWallthickZg());
//						plnZgM.setInwlId(plnZgS.getInwlId());
//						plnZgM.setInwlDesc(plnZgS.getInwlDesc());
//						plnZgM.setOutwlId(plnZgS.getOutwlId());
//						plnZgM.setOutwlDesc(plnZgS.getOutwlDesc());
//						plnZgM.setBom(plnZgS.getBom());
//					}
//
//					plnZgM.setPassCode(plnZgS.getPassCode());
//					plnZgM.setPassName(plnZgS.getPassName());
//					plnZgM.setPlnInsingleNum(String.valueOf(num));
//					plnZgM.setPlnInsingleWt(String.valueOf(takeWeight));
//
//					plnZgM.setProcessCodeC(plnZgS.getProcessCodeC());
//					plnZgM.setProcessDescC(plnZgS.getProcessDescC());
//					plnZgM.setOrderSource(plnZgS.getOrderSource());
//					plnZgM.setOrderNo(plnZgS.getOrderNo());
//					plnZgM.setOrderSeq(plnZgS.getOrderSeq());
//					plnZgM.setDeliveryNo(plnZgS.getDeliveryNo());
//					plnZgM.setOrdLnDlyPk(plnZgS.getOrdLnDlyPk());
//					plnZgM.setReqBlId(plnZgS.getReqBlId());
//					plnZgM.setIfExport(plnZgS.getIfExport());
//					plnZgM.setPriority(plnZgS.getPriority());
//					plnZgM.setPriorityMemo(plnZgS.getPriorityMemo());
//					plnZgM.setProMonth(plnZgS.getProMonth());
//					plnZgM.setIfLenControl(plnZgS.getIfLenControl());
//					plnZgM.setIfMinusSicRoll(plnZgS.getIfMinusSicRoll());
//					plnZgM.setProdStandard(plnZgS.getProdStandard());
//					plnZgM.setOutputStandard(plnZgS.getOutputStandard());
//					plnZgM.setDecision(plnZgS.getDecision());
//					plnZgM.setProgyMemo(plnZgS.getProgyMemo());
//					plnZgM.setProduccode(plnZgS.getProduccode());
//					plnZgM.setProducname(plnZgS.getProducname());
//					plnZgM.setModelCode(plnZgS.getModelCode());
//					plnZgM.setModelDesc(plnZgS.getModelDesc());
//					plnZgM.setOutdiameter(plnZgS.getOutdiameter());
//					plnZgM.setWallthick(plnZgS.getWallthick());
//					plnZgM.setAimoutdiameter(plnZgS.getAimoutdiameter());
//					plnZgM.setAimwallthick(plnZgS.getAimwallthick());
//					plnZgM.setThicknessWall(plnZgS.getThicknessWall());
//					plnZgM.setLenCutend(plnZgS.getLenCutend());
//					plnZgM.setLenCuthead(plnZgS.getLenCuthead());
//					if (!plnZgS.getSiglLen().equals("")) {
//						double lenMin = Double.parseDouble(plnZgS
//								.getAimlength())
//								- Double.parseDouble(plnZgS.getEndlenSpecstd());
//
//						lenMin = (int) (Double.parseDouble(plnZgS
//								.getAimlength()) / Double.parseDouble(plnZgS
//								.getSiglLen()))
//								* Double.parseDouble(plnZgS.getSiglLen());
//						if (lenMin - Double.parseDouble(plnZgS.getLenRollMin()) < 0) {
//							lenMin = Double.parseDouble(plnZgS.getLenRollMin());
//						}
//
//						double lenMax = lenMin
//								+ Double.parseDouble(plnZgS.getEndlenSpecstd());
//						// 判定是否除以单倍尺长可以整除
//						plnZgM.setLenRollMax(String.valueOf(lenMax));
//						plnZgM.setLenRollMin(String.valueOf(lenMin));
//					} else {
//						plnZgM.setLenRollMax(plnZgS.getLenRollMax());
//						plnZgM.setLenRollMin(plnZgS.getLenRollMin());
//					}
//
//					double cpWt = 0;
//					// 折算吨
//					double reducedWt = 0;
//					if (fixLenTake != Double.parseDouble(plnZgS
//							.getLenGpSingle())) {
//						plnZgM.setOutnumCut(outCutNum);
//						plnZgM.setAimlength(aimlength);
//						plnZgM.setRollLength(rollLength);
//
//						cpWt = singlCpWt * num;
//						reducedWt = singlReduWt * num;
//					} else {
//						outCutNum = plnZgS.getOutnumCut();
//						plnZgM.setOutnumCut(outCutNum);
//						plnZgM.setAimlength(plnZgS.getAimlength());
//						plnZgM.setRollLength(plnZgS.getRollLength());
//
//						cpWt = singlCpWt * num;
//						reducedWt = singlReduWt * num;
//					}
//					plnZgM.setPlnOutsingleNum(String.valueOf(num
//							* Integer.parseInt(outCutNum)));
//					plnZgM.setPlnOutsingleW(String.valueOf(cpWt));
//					plnZgM.setReducedWt(String.valueOf(reducedWt));
//					plnZgM.setLenGpSingle(String.valueOf(fixLenTake));
//					plnZgM.setDiameter(plnZgS.getDiameterGp());
//					plnZgM.setWtGpSingle(String.valueOf(weightGpOne));
//
//					plnZgM.setCic(SpecCic);
//					if (plnZgS.getSic() == null || plnZgS.getSic().equals("")) {
//						plnZgM.setSic(plnZgS.getSic());
//					} else {
//						plnZgM.setSic(plnZgS.getSic().split(",")[0]);
//					}
//					if (plnZgS.getDic() == null || plnZgS.getDic().equals("")) {
//						plnZgM.setDic(plnZgS.getDic());
//					} else {
//						plnZgM.setDic(plnZgS.getDic().split(",")[0]);
//					}
//					if (plnZgS.getPic() == null || plnZgS.getPic().equals("")) {
//						plnZgM.setPic(plnZgS.getPic());
//					} else {
//						plnZgM.setPic(plnZgS.getPic().split(",")[0]);
//					}
//					plnZgM.setProDay(dFormat.format(dFormat.parse(dateTime)));
//					plnZgM.setBalYearMonth(dfMonth.format(dfMonth
//							.parse(dateTime)));
//					plnZgM.setCreateName(userName);
//					plnZgM.setCreateTime(dateTime);
//					plnZgM.setCutType(plnZgS.getPassive());
//					plnZgM.setIfMonitor(plnZgS.getIfMonitorZg());
//					plnZgM.setDiameterMandrel(plnZgS.getDiameterMandrel());
//					plnZgM.setPrdcrNo(plnZgS.getPrdcrNo());
//					plnZgM.setMonitorPoint(plnZgS.getMonitorPoint());
//					plnZgM.setWholeBacklog(plnZgS.getWholeBacklog());
//					plnZgM.setWholeBacklogDesc(plnZgS.getWholeBacklogDesc());
//					plnZgM.setCraftFileMan(plnZgS.getCraftFileMan());
//					plnZgM.setCraftFileNo(plnZgS.getCraftFileNo());
//					plnZgM.setCraftSeq(plnZgS.getCraftSeq());
//					plnZgM.setSecCraftFileNo(plnZgS.getSecCraftFileNo());
//					plnZgM.setStationRoad(plnZgS.getStationRoad());
//					plnZgM.setIndexSeq(plnZgS.getIndexSeq());
//					plnZgM.setGptype("1");
//					if (matOrigin.equals("801301")) {
//						plnZgM.setOutsBilletFl("1");// 外购
//					} else {
//						plnZgM.setOutsBilletFl("0");// 自炼
//					}
//					if (plnType.equals("正常计划")) {
//
//						plnType = "0";
//					} else if (plnType.equals("试轧料")) {
//						plnType = "1";
//					}
//					plnZgM.setPlnType(plnType);
//					// 新增轧管虚拟炉计划
//					String sqlZgM = EntityTool
//							.fillSqlByEntity(
//									CoreXmlSqlParsersFactory
//											.getSql("FrmPlanMaterialSelection.addPlnZyZgM"),
//									plnZgM);
//					ps = conn.prepareStatement(sqlZgM);
//					ps.executeUpdate();
//					ps.close();
//				}
//
//				int countC = 0;
//				String heatPlanSqe = "";
//				// 判定是否存在相同坯长，倍尺，单倍坯长，判定炉号，判定单号，同炉计划ID数据
//				String sqlC = "SELECT COUNT(*) COUNT1,T.HEAT_PLAN_SQE FROM PLN_ZY_ZG_C T WHERE "
//						+ "T.HEAT_PLAN_NO=? AND T.JUGDE_APPLY_CODE=? AND T.JUDGE_STOVE_NO=? "
//						+ "AND T.CUT_NUM_OLD=? AND T.LENGTH_M_OLD=? AND T.LEN_GP_SINGLE_OLD=? GROUP BY T.HEAT_PLAN_SQE";
//				ps = conn.prepareStatement(sqlC);
//				ps.setObject(1, heatPlanNo);
//				ps.setObject(2, jugdeApplyCode);
//				ps.setObject(3, judgeStoveNo);
//				ps.setObject(4, oldcutNumGp);
//				ps.setObject(5, actTake);
//				ps.setObject(6, fixLen);
//				rs = ps.executeQuery();
//				if (rs.next()) {
//					countC = rs.getInt("COUNT1");
//					heatPlanSqe = rs.getString("HEAT_PLAN_SQE");
//				}
//				rs.close();
//				ps.close();
//
//				double cutLength = actTake - actLenTake;
//				double weightMs = Double.parseDouble(df1.format(mSingleWeight * (cutLength / 1000)));
//				double cutWeight = weightMs * takeCount;
//				if (countC == 0) {
//					PlnZyZgCEntity plnZgC = new PlnZyZgCEntity();
//					plnZgC.setHeatPlanNo(heatPlanNo);
//					plnZgC.setJugdeApplyCode(jugdeApplyCode);
//					plnZgC.setStoveNo(stoveNo);
//					plnZgC.setJudgeStoveNo(judgeStoveNo);
//					plnZgC.setFlagStoveNo(flagStoveNo);
//					plnZgC.setProPlanId(plnZgS.getProPlanId());
//					plnZgC.setGxPlanNo(plnZgS.getGxPlanNo());
//					plnZgC.setPlineCode(plnZgS.getPlineCode());
//					plnZgC.setPlineName(plnZgS.getPlineName());
//					plnZgC.setLenGpSingle(String.valueOf(fixLenTake));
//					plnZgC.setDiameter(plnZgS.getDiameterGp());
//					plnZgC.setWtGpSingle(String.valueOf(weightGpOne));
//					plnZgC.setCutNumGp(String.valueOf(cutNumGp));
//					plnZgC.setLengthM(String.valueOf(actLenTake));
//					plnZgC.setWeightM(String.valueOf(weightM));
//					plnZgC.setPlanIndoubleNum(String.valueOf(takeCount));
//					plnZgC.setPlanIndoubleWt(String.valueOf(takeWeight));
//					plnZgC.setCreateName(userName);
//					plnZgC.setCreateTime(dateTime);
//					plnZgC.setCutNumOld(String.valueOf(oldcutNumGp));
//					plnZgC.setLenGpSingleOld(String.valueOf(fixLen));
//					if (actLenSy > 0) {
//						plnZgC.setCutLength(String.valueOf(cutLength));
//						plnZgC.setCutWeight(String.valueOf(cutWeight));
//						plnZgC.setCutTarget(cutTarget);
//					} else {
//						plnZgC.setCutLength("");
//						plnZgC.setCutWeight("");
//						plnZgC.setCutTarget("");
//					}
//					plnZgC.setLengthMOld(String.valueOf(actTake));
//					plnZgC.setPlanWeigth(String.valueOf(actWt - cutWeight));
//					// 获取炉计划顺序号
//					heatPlanSqe = corePlnZyFurnM.getHeatPlanSeq(conn,
//							heatPlanNo, "D");
//					plnZgC.setHeatPlanSqe(heatPlanSqe);
//					// 新增轧管实际炉计划
//					String sqlZgC = EntityTool
//							.fillSqlByEntity(
//									CoreXmlSqlParsersFactory
//											.getSql("FrmPlanMaterialSelection.addPlnZyZgC"),
//									plnZgC);
//					ps = conn.prepareStatement(sqlZgC);
//					ps.executeUpdate();
//					ps.close();
//				} else {
//					// 修改炉计划实表
//					String updateC = "UPDATE PLN_ZY_ZG_C T SET T.PLAN_INDOUBLE_NUM=T.PLAN_INDOUBLE_NUM+TO_NUMBER(?),"
//							+ "T.PLAN_INDOUBLE_WT=T.PLAN_INDOUBLE_WT+TO_NUMBER(?) ,T.PLAN_WEIGTH=T.PLAN_WEIGTH+? ";
//					if (actLenSy > 0) {
//						updateC += ",T.CUT_WEIGHT=To_NUMBER(NVL(T.CUT_WEIGHT,0))+TO_NUMBER('"
//								+ cutWeight + "'),T.CUT_LENGTH = TO_NUMBER(T.CUT_LENGTH) + TO_NUMBER('"+actLenSy+"')";
//					}
//					updateC += " WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
//					ps = conn.prepareStatement(updateC);
//					ps.setObject(1, takeCount);
//					ps.setObject(2, takeWeight);
//					ps.setObject(3, actWt - cutWeight);
//					ps.setObject(4, heatPlanNo);
//					ps.setObject(5, heatPlanSqe);
//					ps.executeUpdate();
//					ps.close();
//				}
//				if (countM > 0) {
//					// 修改炉计划主表量
//					String sqlUpdate = CoreXmlSqlParsersFactory
//							.getSql("FrmPlanMaterialSelection.updatePlnZgM");
//					ps = conn.prepareStatement(sqlUpdate);
//					ps.setObject(1, heatPlanNo);
//					ps.setObject(2, singlCpWt);
//					ps.setObject(3, singlReduWt);
//					ps.setObject(4, heatPlanNo);
//					ps.executeUpdate();
//					ps.close();
//				}
//				// 修改有管坯需求号的铸造订单利库量
//				if (plnZgS.getGpreqId() != null
//						&& !plnZgS.getGpreqId().equals("")) {
//					updateCastS(conn, plnZgS.getGpreqId(), judgeStoveNo, actWt
//							- cutWeight, takeCount, "1");
//				}
//				// 回写库存下工序炉计划Id
//				String sqlUpdate = "UPDATE MAT_GP_M T SET T.HEAT_PLAN_NO_NEXT=? WHERE T.JUDGE_STOVE_NO=? AND T.PRO_PLAN_ID_ZG=? AND T.GX_PLAN_NO_ZG=?";
//				ps = conn.prepareStatement(sqlUpdate);
//				ps.setObject(1, heatPlanNo);
//				ps.setObject(2, judgeStoveNo);
//				ps.setObject(3, plnZgS.getProPlanId());
//				ps.setObject(4, plnZgS.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 conn
	 * @param gpreqId
	 * @param judgeStoveNo
	 * @throws Exception
	 */
	public static void updateCastS(Connection conn, String gpreqId,
			String judgeStoveNo, double actWt, int actNum, String flag)
			throws Exception {
		PreparedStatement ps = null;
		PreparedStatement ps1 = null;
		ResultSet rs = null;

		int countStee = 0;

		// 通过炉号查询是否存在组炉信息
		String sqlOrd = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialSelection.queryOrdStee");
		ps = conn.prepareStatement(sqlOrd);
		ps.setObject(1, gpreqId);
		ps.setObject(2, judgeStoveNo);
		rs = ps.executeQuery();
		if (rs.next()) {
			countStee = rs.getInt("COUNT");
			// throw new Exception("");
		}
		rs.close();
		ps.close();
		if (countStee == 0) {
			int lkNum = 0;
			double lkWt = 0;
			// 查询可修改利库量的铸造订单
			String sqlZz = CoreXmlSqlParsersFactory
					.getSql("FrmPlanMaterialSelection.queryCastS");
			if (flag.equals("1")) {
				sqlZz += "AND TO_NUMBER(NVL(T.PLAN_WT_S, '0')) - TO_NUMBER(NVL(T.PLANED_WT, '0'))"
						+ " - TO_NUMBER(NVL(T.PLAN_WT_SOLD, '0')) > 0";
			} else {
				sqlZz += " AND TO_NUMBER(NVL(T.PLAN_NUM_SOLD,0))>0";
			}
			ps = conn.prepareStatement(sqlZz);
			ps.setObject(1, gpreqId);
			rs = ps.executeQuery();
			while (rs.next()) {
				String proPlanId = rs.getString("PRO_PLAN_ID");
				String gxPlanNo = rs.getString("GX_PLAN_NO");
				double canWat = 0;
				int canNum = 0;
				if (flag.equals("1")) {
					canWat = rs.getDouble("CAN_WGT");
					canNum = rs.getInt("CAN_NUM");
				} else {
					canWat = rs.getDouble("PLAN_WT_SOLD");
					canNum = rs.getInt("PLAN_NUM_SOLD");
				}
				if (actNum != 0) {
					if (actWt - canWat < 0 || actNum - canNum < 0) {
						lkWt = actWt;
						lkNum = actNum;
					} else {
						lkWt = canWat;
						lkNum = canNum;
					}
					// 修改铸造订单利库量
					String updateZz = CoreXmlSqlParsersFactory
							.getSql("FrmPlanMaterialSelection.UpdateOrdStee");
					ps1 = conn.prepareStatement(updateZz);
					if (flag.equals("1")) {
						ps1.setObject(1, lkNum);
						ps1.setObject(2, lkWt);
					} else {
						ps1.setObject(1, -lkNum);
						ps1.setObject(2, -lkWt);
					}
					ps1.setObject(3, proPlanId);
					ps1.setObject(4, gxPlanNo);
					ps1.executeUpdate();
					ps1.close();
				}
				actNum = actNum - lkNum;
				actWt = actWt - lkWt;
			}
			rs.close();
			ps.close();
		}

	}

	/**
	 * 轧管坯子脱单（删除轧管订单号）
	 * 
	 * @param jslist
	 * @param userName
	 *            脱单人
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doDeleteMonomer(
			ArrayList<ArrayList<String>> jslist, String userName)
			throws ParseException {
		return doDeleteMonomer(jslist,userName,"");
	}
	public CoreReturnObject doDeleteMonomer(
			ArrayList<ArrayList<String>> jslist, String userName,String isDealer)
			throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// ResultSet rs = null;
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			DecimalFormat df = new DecimalFormat("0000000000");
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// 循环库存信息
			int seq = 1;
			for (int i = 0; i < jslist.size(); i++) {

				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String judgeStoveNo = list.get(0);
				int takeCount = Integer.parseInt(list.get(1));// 利库支
				int actLenTake = Integer.parseInt(list.get(2));// 使用倍尺坯长
				int fixLenTake = Integer.parseInt(list.get(3));// 计划单倍
				int cutNumGp = Integer.parseInt(list.get(4));
				String storageNo = list.get(5);
				String locationNo = list.get(6);
				String proPlanIdNo = list.get(8);
				double dimater = Double.parseDouble(list.get(7));
				if (dimater == 251) {
					dimater = 250;
				}

				// double mSingleWeight = (7.8 * Pi / 4 * dimater * dimater) /
				// 1000 / 1000;// 米单重
				// 单倍坯重
				// double weightGpOne = mSingleWeight * (fixLenTake / 1000);
				// 倍尺坯单支重=坯米单重*倍尺坯长/1000
				// double weightM = mSingleWeight * (actLenTake / 1000);
				List<MatGpMEntity> matGpMlist = getQureyMatGpM(conn,
						judgeStoveNo, storageNo, locationNo, takeCount,
						cutNumGp, proPlanIdNo,list.get(2),isDealer);
				if (matGpMlist == null) {
					cro.setV_errMsg("管坯物料已发生改变,请刷新!");
					return cro;
				}

				for (MatGpMEntity matGpM : matGpMlist) {
					// if (!matGpM.getProductFlag().equals("801401")) {
					// cro.setV_errMsg("材料类别不是成品,不能脱单!");
					// return cro;
					// }
					// if (!matStatus.equals("80150103")
					// && !matStatus.equals("80150102")) {
					// cro.setV_errMsg("材料状态不是产出待判或产出已判定状态,不能脱单");
					// return cro;
					// }
					if (!matGpM.getQcmStaus().equals("00")) {
						cro.setV_errMsg("交库状态不是合格状态,不能脱单!");
						return cro;
					}
					if (matGpM.getHangingFlag().equals("1")) {
						cro.setV_errMsg("你选择的管坯物料已生成实际炉计划,不能脱单，如需脱单,请先删除炉计划!");
						return cro;
					}
					String proPlanZg = matGpM.getProPlanIdZg() + "/"
							+ matGpM.getGxPlanNoZg();
					if (proPlanZg.equals("/")) {
						cro.setV_errMsg("你选择的管坯物料未分配其他轧管订单,不能脱单!");
						return cro;
					}
					// 修改坯子库存信息
					String sqlUpdateMat = "UPDATE MAT_GP_M T SET T.PRO_PLAN_ID_ZG = '',T.GX_PLAN_NO_ZG  = '', T.ORDER_NO= '',T.ORDER_SEQ= '',"
							+ " T.ORDER_SEQ_NO = '',T.ORD_PK= '',T.ORD_LN_PK= '', T.ORD_LN_DLY_PK  = '',T.HEAT_PLAN_NO_NEXT='' WHERE T.MAT_NO = ? AND T.MNG_LOCK_FLAG = '0'";
					ps = conn.prepareStatement(sqlUpdateMat);
					ps.setObject(1, matGpM.getMatNo());
					ps.executeUpdate();
					ps.close();

					String resumeSeq = dateFormat.format(now) + df.format(seq);
					// 生成利库日志
					MatGpTrackEntity matGpTrack = new MatGpTrackEntity();
					matGpTrack.setResumeSeq(resumeSeq);
					matGpTrack.setEventId("900101");
					matGpTrack.setEventDesc("轧管脱单");
					matGpTrack
							.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanMaterialSelection");
					matGpTrack.setCallFuncCoding("doDeleteMonomer");
					matGpTrack.setKeyvalue1("List<MatGpMEntity> matGpMlist");
					matGpTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
					matGpTrack.setKeyvalue2("String userName");
					matGpTrack.setKeyvalue2Desc2("操作人");
					matGpTrack.setMatNo(matGpM.getMatNo());
					matGpTrack.setProductFlag(matGpM.getProductFlag());
					matGpTrack.setMatStatus(matGpM.getMatStatus());
					matGpTrack.setStoveNo(matGpM.getStoveNo());
					matGpTrack.setFlagStoveNo(matGpM.getFlagStoveNo());
					matGpTrack.setJudgeStoveNo(matGpM.getJudgeStoveNo());
					matGpTrack.setBatchNo("");
					matGpTrack.setGroudNo(matGpM.getGroudNo());
					matGpTrack.setCastNo(matGpM.getCastNo());
					matGpTrack.setCcmid(matGpM.getCcmid());
					matGpTrack.setGradecode(matGpM.getGradecode());
					matGpTrack.setGradename(matGpM.getGradename());
					matGpTrack.setStdCode(matGpM.getStdCode());
					matGpTrack.setStdName(matGpM.getStdName());
					matGpTrack.setActDimater(matGpM.getDimater());
					matGpTrack.setActHeight(matGpM.getHeight());
					matGpTrack.setActLen(String.valueOf(actLenTake));
					matGpTrack.setActLenMax("");
					matGpTrack.setActLenMin("");
					matGpTrack.setActFixLen(String.valueOf(fixLenTake));
					matGpTrack.setActFixNum(matGpM.getFixNum());
					matGpTrack.setActCount("1");
					matGpTrack.setActWeight(matGpM.getActWeight());
					matGpTrack.setActTheoryWeight(matGpM.getActTheoryWeight());
					matGpTrack.setOrdPk("");
					matGpTrack.setOrdLnPk("");
					matGpTrack.setOrdLnDlyPk("");
					matGpTrack.setOrderNo("");
					matGpTrack.setOrderSeq("");
					matGpTrack.setOrderSeqNo("");
					// matGpTrack.setOldOrdPk(matGpM.getOrdPk());
					// matGpTrack.setOldOrdLnPk(matGpM.getOrdLnPk());
					// matGpTrack.setOldOrdLnDlyPk(matGpM.getOrdLnDlyPk());
					matGpTrack.setOldOrderNo(matGpM.getOrderNo());
					matGpTrack.setOldOrderSeq(matGpM.getOrderSeq());
					matGpTrack.setOldOrderSeqNo(matGpM.getOrderSeqNo());
					matGpTrack.setMemo("");
					matGpTrack.setCreateName(userName);
					matGpTrack.setCreateTime(dateTime);
					matGpTrack.setOldJudgeStoveNo(matGpM.getJudgeStoveNo());
					matGpTrack.setOldBatchNo("");
					matGpTrack.setOldGroudNo(matGpM.getGroudNo());
					matGpTrack.setOldGradecode(matGpM.getGradecode());
					matGpTrack.setOldGradename(matGpM.getGradename());
					matGpTrack.setOldStdCode(matGpM.getStdCode());
					matGpTrack.setOldStdName(matGpM.getStdName());
					matGpTrack.setOldStoveNo(matGpM.getStoveNo());
					seq++;
					String sqlAddTrack = EntityTool
							.fillSqlByEntity(
									CoreXmlSqlParsersFactory
											.getSql("FrmPlanMaterialSelection.addMatGpTrack"),
									matGpTrack);
					ps = conn.prepareStatement(sqlAddTrack);
					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;
	}
}
