package com.steering.pss.plnsaleord.planStove;

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;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.planStove.entity.MatBcTrackEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnGxJgPropSEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.corePlanFurnProM;
import com.steering.pss.plnsaleord.stove.entity.*;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

/**
 * 管坯材料信息
 * 
 * @author teng 2017.11.21
 */
public class FrmPlanMaterialJg extends DBCommon {
	/**
	 * 查询管坯库存信息
	 * 
	 * @return
	 */
	public CoreReturnObject queryMaterial(String materialNo,String codeJgBl) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.queryMaterial");
		// new Object[] { materialNo
		return this.getData(sql, new Object[] { materialNo,codeJgBl });
	}


	public CoreReturnObject queryMaterialJg(String materialNo,String codeJgBl,String codeJg,String steelCode,String steelName) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.queryMaterialJg");
		// new Object[] { materialNo
		return this.getData(sql, new Object[] { codeJg,codeJg,steelCode,steelCode });
	}
	/**
	 * 查询库存重量
	 * 
	 * @return
	 */
	public CoreReturnObject queryMatWeigth(String judgNo, String batchNo,
			String groudNo, String inMaterialNo, String num) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.queryMatWeigth");
		return this.getData(sql, new Object[] { judgNo, batchNo, groudNo,
				inMaterialNo, num });
	}

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

	/**
	 * 查询Bom投入物料
	 * 
	 * @return
	 */
	public CoreReturnObject queryBaseMaterial(String codeJg, String codeJgBl) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.queryBaseMaterialHPl");

		return this.getData(sql, new Object[] { codeJgBl, codeJg });
	}

	/**
	 * 查询排产信息
	 * 
	 * @param con
	 * @param proPlanId
	 *            订单编号
	 * @param gxPlanNo
	 *            排产序号
	 * @return PlnOrderCastSEntity
	 * @throws SQLException
	 */
	public static <T> T getPlanOrderS(Connection con, String proPlanId,
			String gxPlanNo, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("PlanFurnProduction.queryPlnOrderJg");
		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
	 *
	 * @throws SQLException
	 */
	public static List<MatBcMEntityPln> getQureyMatGpM(Connection con,
			String judgeStoveNo, String batchNo, String batchGroupBy,
			String materialNo, int takeCount, String proPlanIdNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.QueryMatGp");
		if (!proPlanIdNo.equals("")) {
			sql += " AND T.PRO_PLAN_ID_NEXT||'/'||T.GX_PLAN_NO_NEXT ='"
					+ proPlanIdNo + "'";
		} else {
			sql += " AND T.PRO_PLAN_ID_NEXT IS NULL";
		}
		sql += "  ORDER BY T.MAT_NO ASC) where rownum<=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		ps.setObject(2, batchNo);
		ps.setObject(3, batchGroupBy);
		// ps.setObject(4, proessCode);
		ps.setObject(4, takeCount);
		ResultSet rs = ps.executeQuery();
		List<MatBcMEntityPln> list = EntityTool.getEntitysByRs(rs,
				MatBcMEntityPln.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (MatBcMEntityPln listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	// 查询库存信息赋值履历表
	public static <T> T getQureyMatTrack(Connection con, String judgeStoveNo,
			String batchNo, String batchGroupBy, int takeCount,
			String hangingflag, String proPlanIdNo, Class<T> cls)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanMaterialJg.getQureyMatTrack");
		if (!proPlanIdNo.equals("")) {
			sql += " AND PRO_PLAN_ID_NEXT||'/'||GX_PLAN_NO_NEXT ='"
					+ proPlanIdNo + "'";
		} else {
			sql += " AND PRO_PLAN_ID_NEXT IS NULL";
		}
		sql += " AND HANGING_FLAG = '" + hangingflag + "'";
		sql += " AND rownum<=?";
		sql += " GROUP BY PRODUCT_FLAG,MAT_STATUS,LOT_NO,STOVE_NO,JUDGE_STOVE_NO,BATCH_NO,BATCH_GROUD_NO,"
				+ "MATERIAL_NO, MATERIAL_NAME,PRODUCCODE,PRODUCNAME,STEELCODE,STEELNAME,STD_CODE,STD_NAME,"
				+ "STD_STYLE,STD_STYLE_DESC,SPEC_CODE,SPEC_NAME,MODEL_CODE,MODEL_DESC,ACT_LEN,ACT_LEN_MIN,"
				+ "ACT_LEN_MAX,PRO_ORDER_NO,PRO_ORDER_ID,ORD_PK,ORD_LN_PK,ORD_LN_DLY_PK,ORDER_NO,ORDER_SEQ,"
				+ "ORDER_SEQ_NO, BELONG_CODE,BELONG_NAME, PROCESS_CDOE, GRADECODE, GRADENAME";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		ps.setObject(2, batchNo);
		ps.setObject(3, batchGroupBy);
		ps.setObject(4, takeCount);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 坯子利库
	 * 
	 * @param proPlanId
	 *            订单号
	 * @param gxPlanNo
	 *            排产序号
	 * @throws ParseException
	 */
	public CoreReturnObject doAddLibrary(ArrayList<ArrayList<String>> jslist,
			String userName, String proPlanId, String gxPlanNo)
			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;
			// SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
			// SimpleDateFormat dfMonth = new SimpleDateFormat("yyyyMM");

			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// 查询接箍信息
			PlnGxJgPropSEntity plnJgS = getPlanOrderS(conn, proPlanId,
					gxPlanNo, PlnGxJgPropSEntity.class);
			if (plnJgS == null) {
				cro.setV_errMsg("未找到接箍订单(" + proPlanId + "/" + gxPlanNo
						+ ")信息!");
				return cro;
			}
			// 判断是否排产订单下发
			// if (plnOrderS.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");
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String judgeStoveNo = list.get(0);
				String batchNo = list.get(1);
				String batchGroupBy = list.get(2);
				String materialNo = list.get(3);
				int takeCount = Integer.parseInt(list.get(4));// 利库支
				// String proPlanIdNo = list.get(5);// 本工序订单号
				String UpproPlanIdNo = list.get(6);// 上工序订单号
				String plineCode = list.get(7);
				List<MatBcMEntityPln> matGpMlist = getQureyMatGpM(conn,
						judgeStoveNo, batchNo, batchGroupBy, materialNo,
						takeCount, "");
				if (matGpMlist == null) {
					cro.setV_errMsg("管坯物料已发生改变,请刷新!");
					return cro;
				}
				MatBcTrackEntity matTrack = getQureyMatTrack(conn,
						judgeStoveNo, batchNo, batchGroupBy, takeCount, "0",
						"", MatBcTrackEntity.class);

				double actWt = 0;
				String jugdeApplyCode = "";// 是否有申请判定单号
				int countAppCode = 0;
				String stoveNo = "";
				String inwlId = "";
				String inwlDesc = "";
				String lengthIn = "";
				String lengthmaxIn = "";
				String lengthminIn = "";
				String outdiameterIn = "";
				String wallthickIn = "";
				String upperHeatplanId = "";
				String flagStoveNo = "";
				String upProessCode = "";
				String codeJgBl="";
				for (MatBcMEntityPln matGpM : matGpMlist) {
					countAppCode++;
					codeJgBl=matGpM.getCodeJgBl();
					upProessCode = matGpM.getProcessCdoe();
					jugdeApplyCode = matGpM.getJugdeApplyCode();
					stoveNo = matGpM.getStoveNo();
					inwlId = matGpM.getMaterialNo();
					inwlDesc = matGpM.getMaterialName();
					lengthIn = matGpM.getActLen();
					lengthmaxIn = matGpM.getActLenMax();
					lengthminIn = matGpM.getActLenMin();
					outdiameterIn = matGpM.getActDimater();
					wallthickIn = matGpM.getActHeight();
					upperHeatplanId = matGpM.getHeatPlanNo();
					//actWt += Double.parseDouble(matGpM.getActWeight());
					actWt = Double.parseDouble(matGpM.getActWeight());
					flagStoveNo = matGpM.getFlagStoveNoZg();

					takeCount = 1;
					if (!matGpM.getProductFlag().equals("801401")) {
						cro.setV_errMsg("材料类别不是在制品,不能利库!");
						return cro;
					}
					if (!matGpM.getMatStatus().equals("80150102")&&!matGpM.getInstancyFlag().equals("1")) {
						cro.setV_errMsg("材料状态不是产出已判定状态并且不是紧急放行状态,不能利库");
						return cro;
					}
					if (!matGpM.getQcmStaus().equals("00")) {
						cro.setV_errMsg("交库状态不是合格状态,不能利库!");
						return cro;
					}


					// 修改坯子库存信息
					String sqlUpdateMat = CoreXmlSqlParsersFactory
							.getSql("FrmPlanMaterialJg.UpdateMatGp");
					ps = conn.prepareStatement(sqlUpdateMat);
					ps.setObject(1, "80150103");
					ps.setObject(2, proPlanId);
					ps.setObject(3, gxPlanNo);
					ps.setObject(4, "1");
					ps.setObject(5, "1");
					ps.setObject(6, "H");
					ps.setObject(7, "接箍");
					ps.setObject(8, matGpM.getMatNo());
					ps.executeUpdate();
					ps.close();


					String resumeSeq = dateFormat.format(now) + df.format(seq);
					// 生成利库日志
					matTrack.setResumeSeq(resumeSeq);
					matTrack.setEventId("900102");
					matTrack.setEventDesc("利库");
					matTrack
							.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanMaterialJg");
					matTrack.setCallFuncCoding("doAddLibrary");
					matTrack.setKeyvalue1("List<MatBcMEntityPln> matGpMlist");
					matTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
					matTrack.setKeyvalue2("String userName");
					matTrack.setKeyvalue2Desc2("操作人");
					matTrack.setProcessCdoe("H");
					matTrack.setMemo("");
					matTrack.setCreateName(userName);
					matTrack.setCreateTime(dateTime);
					seq++;
					// 新增利库记录
					String sqlAddTrack = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("FrmPlanMaterialJg.addMatBcTrack"),
							matTrack);
					ps = conn.prepareStatement(sqlAddTrack);
					ps.executeUpdate();
					ps.close();

					int countM = 0;
					String heatPlanNo = "";
					String planStatus = "00";
					// 根据判定炉号，订单号查询是否存在虚拟炉计划
					String sqlQuery = "SELECT COUNT(*) COUNT,T.HEAT_PLAN_NO,T.PLANSTATUS,T.IF_MATCH_ODD FROM PLN_ZY_JG_M T WHERE T.FEED_HEAT_NO=? "
							+ " AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=? GROUP BY T.HEAT_PLAN_NO,T.PLANSTATUS,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");
						if (rs.getString("IF_MATCH_ODD").equals("1")) {
							if (planStatus.equals("20") || planStatus.equals("30")
									|| planStatus.equals("40")) {
								cro.setV_errMsg("该接箍订单(" + proPlanId + "/"
										+ gxPlanNo + "),判定炉号(" + judgeStoveNo
										+ ")已存在炉计划,并已上料,如需利库,请先撤销上料或拆分订单!");
								return cro;
							} else {
								countM = rs.getInt("COUNT");
							}
						} else {
							cro.setV_errMsg("该接箍订单(" + proPlanId + "/" + gxPlanNo
									+ "),(" + judgeStoveNo
									+ ")已存在不是利库炉计划,如需利库,请先撤销炉计划!");
							return cro;
						}
					}
					rs.close();
					ps.close();

					// 如果存在同炉,同订单号只执行一次新增虚拟炉计划
					if (countM == 0) {
						PlnZyJgMEntity plnJgM = new PlnZyJgMEntity();
						heatPlanNo = corePlanFurnProM.getMaxHeatPlanNo(conn, plnJgS
								.getProPlanId(), plnJgS.getProPlanId(), "H");
						// 获取炉计划顺序号
						int gxProSeq = corePlanFurnProM.getMaxGxPlnSeq(conn, plnJgM
								.getPlineCode(), "H");
						plnJgM.setStoveNo(stoveNo);
						plnJgM.setFeedHeatNo(judgeStoveNo);
						if(plineCode.equals("C072")||plineCode.equals("C091"))
						{
							plnJgM.setJudgeStoveNo("");
							plnJgM.setFlagStoveNo("");
						}else
						{
							plnJgM.setJudgeStoveNo(judgeStoveNo);
							plnJgM.setFlagStoveNo(judgeStoveNo);
						}


						plnJgM.setPlanstatus("00");
						plnJgM.setUpperHeatplanId(upperHeatplanId);
						plnJgM.setPlineCode(plnJgS.getPlineCode());
						plnJgM.setPlineName(plnJgS.getPlineName());
						plnJgM.setIfMatchOdd("1");
						plnJgM.setIfDoHeatPlan("1");
						plnJgM.setUpperProcessCode(upProessCode);
						plnJgM.setProPlanId(plnJgS.getProPlanId());
						plnJgM.setGxPlanNo(plnJgS.getGxPlanNo());
						plnJgM.setJgGroupId(plnJgS.getJgGroupId());
						plnJgM.setCodeJg(plnJgS.getCodeJg());
						plnJgM.setMinD(plnJgS.getMinD());
						plnJgM.setMinH(plnJgS.getMinH());
						plnJgM.setAimCutLen(plnJgS.getAimCutLen());
						plnJgM.setAimlengthBl(plnJgS.getAimlengthBl());
						plnJgM.setGradecode(matGpM.getGradecode());
						plnJgM.setGradename(matGpM.getGradename());
						plnJgM.setSteelcode(plnJgS.getSteelcode());
						plnJgM.setSteelname(plnJgS.getSteelname());
						// 查询轧管排产信息
						String sqlZg = CoreXmlSqlParsersFactory
								.getSql("PlanFurnProduction.QueryWgZg");
						ps = conn.prepareStatement(sqlZg);
						ps.setObject(1, plnJgS.getOrdLnDlyPk());
//					ps.setObject(2, plnJgS.getPlnDivideId());
						rs = ps.executeQuery();
						if (rs.next()) {
							plnJgM.setProdStandard(rs.getString("PROD_STANDARD"));
							plnJgM.setOutputStandard(rs
									.getString("Output_Standard"));
						}
						rs.close();
						ps.close();
						plnJgM.setBlWlId(inwlId);
						plnJgM.setBlWlDesc(inwlDesc);
						plnJgM.setOutwlId(plnJgS.getOutwlId());
						plnJgM.setOutwlDesc(plnJgS.getOutwlDesc());
						plnJgM.setModelCode(plnJgS.getModelCode());
						plnJgM.setModelDesc(plnJgS.getModelDesc());
						plnJgM.setLengthMax(plnJgS.getLengthMax());
						plnJgM.setLengthMin(plnJgS.getLengthMin());
						plnJgM.setTaper(plnJgS.getTaper());
//					if(codeJgBl.equals("")){
						plnJgM.setCodeJgBl(plnJgS.getCodeJgBl());
//					}else{
//						plnJgM.setCodeJgBl(codeJgBl);
//					}
						plnJgM.setSpecJg(plnJgS.getSpecJg());
						plnJgM.setSpecJgDesc(plnJgS.getSpecJgDesc());
						plnJgM.setSingleCutNun(plnJgS.getSingleCutNun());
						// 查询接箍信息
						String sqlCodeJg = CoreXmlSqlParsersFactory
								.getSql("PlanFurnProduction.queryCodeJg");
						ps = conn.prepareStatement(sqlCodeJg);
						ps.setObject(1, plnJgS.getCodeJg());
						rs = ps.executeQuery();
						if (rs.next()) {
							plnJgM.setOutdiameter(rs.getString("DIAMETER_JG"));
							plnJgM.setWallthick(rs.getString("HEIGHT_JG"));
							plnJgM.setStyleJg(rs.getString("STYLE_JG"));
							plnJgM.setDiameter(rs.getString("DIAMETER"));
							plnJgM.setCheckJVal(rs.getString("CHECK_J_VAL"));
							plnJgM.setSingleweight(rs.getString("WEIGHT_JG"));
							plnJgM.setAimlength(rs.getString("LENGTH_JG"));
							plnJgM.setProduccodeJg(rs.getString("PRODUCCODE_JG"));
							plnJgM.setProduccodeJgDesc(rs
									.getString("PRODUCCODE_JG_DESC"));
							plnJgM.setStdCode(rs.getString("STD_CODE"));
							plnJgM.setStdName(rs.getString("STD_NAME"));
							plnJgM.setStdStyle(rs.getString("STD_STYLE"));
							plnJgM.setStdStyleDesc(rs.getString("STD_STYLE_DESC"));
						}
						rs.close();
						ps.close();
						plnJgM.setDemandCopper(plnJgS.getDemandCopper());
						// 计划支吨
						plnJgM.setPlanJgNum(String.valueOf(takeCount
								* Integer.parseInt(plnJgS.getSingleCutNun())));
						plnJgM.setPlanBlNum(String.valueOf(takeCount));
						plnJgM.setPlanBlWt(String.valueOf(actWt));

						plnJgM.setOrdLnDlyPk(plnJgS.getOrdLnDlyPk());
						plnJgM
								.setProDay(dateTime.substring(0, 10).replace("-",
										""));
						plnJgM.setBalYearMonth(dateTime.substring(0, 7).replace(
								"-", ""));

						plnJgM.setPrdcrNo(plnJgS.getPrdcrNo());
						plnJgM.setCraftFileNo(plnJgS.getCraftFileNo());
						plnJgM.setCraftSeq(plnJgS.getCraftSeq());

						plnJgM.setCreateName(userName);
						plnJgM.setCreateTime(dateTime);
						plnJgM.setHeatPlanNo(heatPlanNo);
						plnJgM.setGxProSeq(String.valueOf(gxProSeq));


						if(!plnJgS.getIfMonitorJg().equals("")){
							plnJgM.setMonitordemand("接箍监制。");
							plnJgM.setIfMonitorJg("1");
						}else if(!plnJgS.getIfMonitorBl().equals("")){
							plnJgM.setMonitordemand("接箍料监制。");
							plnJgM.setIfMonitorJg("1");
						}else if(!plnJgS.getIfMonitorBl().equals("")&&!plnJgS.getIfMonitorJg().equals("")){
							plnJgM.setMonitordemand("接箍、接箍料监制。");
							plnJgM.setIfMonitorJg("1");
						}else{
							plnJgM.setMonitordemand("");
							plnJgM.setIfMonitorJg("0");
						}
						// 新增
						String addPlnGxZg = EntityTool.fillSqlByEntity(
								CoreXmlSqlParsersFactory
										.getSql("PlanFurnProduction.addPlnZyJg"),
								plnJgM);
						ps = conn.prepareStatement(addPlnGxZg);
						ps.executeUpdate();
						ps.close();
					}
					int countC = 0;
					String heatPlanSqe = "";
					// 判定是否存在判定炉号，判定单号，同炉计划ID数据
					String sqlC = "SELECT COUNT(*) COUNT1,T.HEAT_PLAN_SQE FROM PLN_ZY_JG_C T WHERE "
							+ "T.HEAT_PLAN_NO=? AND NVL(T.JUGDE_APPLY_CODE,'/')=NVL(?,'/') AND T.FEED_HEAT_NO=? AND T.BATCH_NO=? AND NVL(T.BATCH_GROUD_NO,'/')=NVL(?,'/')"
							+ " 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, batchNo);
					ps.setObject(5, batchGroupBy);
					rs = ps.executeQuery();
					if (rs.next()) {
						countC = rs.getInt("COUNT1");
						heatPlanSqe = rs.getString("HEAT_PLAN_SQE");
					}
					rs.close();
					ps.close();

					if (countC == 0) {
						PlnZyJgCEntity plnJgC = new PlnZyJgCEntity();
						// 获取炉计划顺序号
						heatPlanSqe = corePlanFurnProM.getHeatPlanSeq(conn,
								heatPlanNo, "H");
						plnJgC.setHeatPlanNo(heatPlanNo);
						plnJgC.setJugdeApplyCode(jugdeApplyCode);
						plnJgC.setFeedHeatNo(judgeStoveNo);
						if(plineCode.equals("C072")||plineCode.equals("C091"))
						{
							plnJgC.setJudgeStoveNo("");
							plnJgC.setFlagStoveNo("");
						}else
						{
							plnJgC.setJudgeStoveNo(judgeStoveNo);
							plnJgC.setFlagStoveNo(judgeStoveNo);
						}

						plnJgC.setBatchNo(batchNo);
						plnJgC.setBatchGroudNo(batchGroupBy);

						plnJgC.setStoveNo(stoveNo);
						plnJgC.setProPlanId(plnJgS.getProPlanId());
						plnJgC.setGxPlanNo(plnJgS.getGxPlanNo());
						plnJgC.setPlineCode(plnJgS.getPlineCode());
						plnJgC.setPlineName(plnJgS.getPlineName());
						plnJgC.setUseBlNum(String.valueOf(takeCount));
						plnJgC.setUseBlWt(String.valueOf(actWt));
						plnJgC.setHeatPlanSqe(heatPlanSqe);
						// 新增
						String addPlnGxZg = EntityTool.fillSqlByEntity(
								CoreXmlSqlParsersFactory
										.getSql("PlanFurnProduction.addPlnZyJgC"),
								plnJgC);
						ps = conn.prepareStatement(addPlnGxZg);
						ps.executeUpdate();
						ps.close();
					} else {
						// 修改炉计划实表
						String updateC = "UPDATE PLN_ZY_JG_C T SET T.USE_BL_NUM=T.USE_BL_NUM+TO_NUMBER(?),"
								+ "T.USE_BL_WT=T.USE_BL_WT+TO_NUMBER(?) ";
						updateC += " WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
						ps = conn.prepareStatement(updateC);
						ps.setObject(1, takeCount);
						ps.setObject(2, actWt);
						ps.setObject(3, heatPlanNo);
						ps.setObject(4, heatPlanSqe);
						ps.executeUpdate();
						ps.close();
					}

					if (countM > 0) {
						// 修改炉计划主表量
						String sqlUpdate = CoreXmlSqlParsersFactory
								.getSql("FrmPlanMaterialJg.updatePlnZgM");
						ps = conn.prepareStatement(sqlUpdate);
						ps.setObject(1, heatPlanNo);
						ps.setObject(2, heatPlanNo);
						ps.executeUpdate();
						ps.close();
					}
					// 修改坯子库存下工序炉计划ID
					String sqlUpdateMatId = "UPDATE MAT_BC_M T SET T.HEAT_PLAN_NO_NEXT=? WHERE T.PRO_PLAN_ID_NEXT=? AND T.GX_PLAN_NO_NEXT=? AND T.JUDGE_STOVE_NO=?";
					ps = conn.prepareStatement(sqlUpdateMatId);
					ps.setObject(1, heatPlanNo);
					ps.setObject(2, proPlanId);
					ps.setObject(3, gxPlanNo);
					ps.setObject(4, judgeStoveNo);
					ps.executeUpdate();
					ps.close();
				}
//				String resumeSeq = dateFormat.format(now) + df.format(seq);
//				// 生成利库日志
//				matTrack.setResumeSeq(resumeSeq);
//				matTrack.setEventId("900102");
//				matTrack.setEventDesc("利库");
//				matTrack
//						.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanMaterialJg");
//				matTrack.setCallFuncCoding("doAddLibrary");
//				matTrack.setKeyvalue1("List<MatBcMEntityPln> matGpMlist");
//				matTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
//				matTrack.setKeyvalue2("String userName");
//				matTrack.setKeyvalue2Desc2("操作人");
//				matTrack.setProcessCdoe("H");
//				matTrack.setMemo("");
//				matTrack.setCreateName(userName);
//				matTrack.setCreateTime(dateTime);
//				seq++;
//				// 新增利库记录
//				String sqlAddTrack = EntityTool.fillSqlByEntity(
//						CoreXmlSqlParsersFactory
//								.getSql("FrmPlanMaterialJg.addMatBcTrack"),
//						matTrack);
//				ps = conn.prepareStatement(sqlAddTrack);
//				ps.executeUpdate();
//				ps.close();
//
//				int countM = 0;
//				String heatPlanNo = "";
//				String planStatus = "00";
//				// 根据判定炉号，订单号查询是否存在虚拟炉计划
//				String sqlQuery = "SELECT COUNT(*) COUNT,T.HEAT_PLAN_NO,T.PLANSTATUS,T.IF_MATCH_ODD FROM PLN_ZY_JG_M T WHERE T.FEED_HEAT_NO=? "
//						+ " AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=? GROUP BY T.HEAT_PLAN_NO,T.PLANSTATUS,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");
//					if (rs.getString("IF_MATCH_ODD").equals("1")) {
//						if (planStatus.equals("20") || planStatus.equals("30")
//								|| planStatus.equals("40")) {
//							cro.setV_errMsg("该接箍订单(" + proPlanId + "/"
//									+ gxPlanNo + "),判定炉号(" + judgeStoveNo
//									+ ")已存在炉计划,并已上料,如需利库,请先撤销上料或拆分订单!");
//							return cro;
//						} else {
//							countM = rs.getInt("COUNT");
//						}
//					} else {
//						cro.setV_errMsg("该接箍订单(" + proPlanId + "/" + gxPlanNo
//								+ "),(" + judgeStoveNo
//								+ ")已存在不是利库炉计划,如需利库,请先撤销炉计划!");
//						return cro;
//					}
//				}
//				rs.close();
//				ps.close();
//
//				// 如果存在同炉,同订单号只执行一次新增虚拟炉计划
//				if (countM == 0) {
//					PlnZyJgMEntity plnJgM = new PlnZyJgMEntity();
//					heatPlanNo = corePlanFurnProM.getMaxHeatPlanNo(conn, plnJgS
//							.getProPlanId(), plnJgS.getProPlanId(), "H");
//					// 获取炉计划顺序号
//					int gxProSeq = corePlanFurnProM.getMaxGxPlnSeq(conn, plnJgM
//							.getPlineCode(), "H");
//					plnJgM.setStoveNo(stoveNo);
//					plnJgM.setFeedHeatNo(judgeStoveNo);
//					if(plineCode.equals("C072")||plineCode.equals("C091"))
//					{
//						plnJgM.setJudgeStoveNo("");
//						plnJgM.setFlagStoveNo("");
//					}else
//					{
//						plnJgM.setJudgeStoveNo(judgeStoveNo);
//						plnJgM.setFlagStoveNo(judgeStoveNo);
//					}
//
//
//					plnJgM.setPlanstatus("00");
//					plnJgM.setUpperHeatplanId(upperHeatplanId);
//					plnJgM.setPlineCode(plnJgS.getPlineCode());
//					plnJgM.setPlineName(plnJgS.getPlineName());
//					plnJgM.setIfMatchOdd("1");
//					plnJgM.setIfDoHeatPlan("1");
//					plnJgM.setUpperProcessCode(upProessCode);
//					plnJgM.setProPlanId(plnJgS.getProPlanId());
//					plnJgM.setGxPlanNo(plnJgS.getGxPlanNo());
//					plnJgM.setJgGroupId(plnJgS.getJgGroupId());
//					plnJgM.setCodeJg(plnJgS.getCodeJg());
//					plnJgM.setMinD(plnJgS.getMinD());
//					plnJgM.setMinH(plnJgS.getMinH());
//					plnJgM.setAimCutLen(plnJgS.getAimCutLen());
//					plnJgM.setAimlengthBl(plnJgS.getAimlengthBl());
//					plnJgM.setGradecode(plnJgS.getGradecode());
//					plnJgM.setGradename(plnJgS.getGradename());
//					plnJgM.setSteelcode(plnJgS.getSteelcode());
//					plnJgM.setSteelname(plnJgS.getSteelname());
//					// 查询轧管排产信息
//					String sqlZg = CoreXmlSqlParsersFactory
//							.getSql("PlanFurnProduction.QueryWgZg");
//					ps = conn.prepareStatement(sqlZg);
//					ps.setObject(1, plnJgS.getOrdLnDlyPk());
////					ps.setObject(2, plnJgS.getPlnDivideId());
//					rs = ps.executeQuery();
//					if (rs.next()) {
//						plnJgM.setProdStandard(rs.getString("PROD_STANDARD"));
//						plnJgM.setOutputStandard(rs
//								.getString("Output_Standard"));
//					}
//					rs.close();
//					ps.close();
//					plnJgM.setBlWlId(inwlId);
//					plnJgM.setBlWlDesc(inwlDesc);
//					plnJgM.setOutwlId(plnJgS.getOutwlId());
//					plnJgM.setOutwlDesc(plnJgS.getOutwlDesc());
//					plnJgM.setModelCode(plnJgS.getModelCode());
//					plnJgM.setModelDesc(plnJgS.getModelDesc());
//					plnJgM.setLengthMax(plnJgS.getLengthMax());
//					plnJgM.setLengthMin(plnJgS.getLengthMin());
//					plnJgM.setTaper(plnJgS.getTaper());
////					if(codeJgBl.equals("")){
//						plnJgM.setCodeJgBl(plnJgS.getCodeJgBl());
////					}else{
////						plnJgM.setCodeJgBl(codeJgBl);
////					}
//					plnJgM.setSpecJg(plnJgS.getSpecJg());
//					plnJgM.setSpecJgDesc(plnJgS.getSpecJgDesc());
//					plnJgM.setSingleCutNun(plnJgS.getSingleCutNun());
//					// 查询接箍信息
//					String sqlCodeJg = CoreXmlSqlParsersFactory
//							.getSql("PlanFurnProduction.queryCodeJg");
//					ps = conn.prepareStatement(sqlCodeJg);
//					ps.setObject(1, plnJgS.getCodeJg());
//					rs = ps.executeQuery();
//					if (rs.next()) {
//						plnJgM.setOutdiameter(rs.getString("DIAMETER_JG"));
//						plnJgM.setWallthick(rs.getString("HEIGHT_JG"));
//						plnJgM.setStyleJg(rs.getString("STYLE_JG"));
//						plnJgM.setDiameter(rs.getString("DIAMETER"));
//						plnJgM.setCheckJVal(rs.getString("CHECK_J_VAL"));
//						plnJgM.setSingleweight(rs.getString("WEIGHT_JG"));
//						plnJgM.setAimlength(rs.getString("LENGTH_JG"));
//						plnJgM.setProduccodeJg(rs.getString("PRODUCCODE_JG"));
//						plnJgM.setProduccodeJgDesc(rs
//								.getString("PRODUCCODE_JG_DESC"));
//						plnJgM.setStdCode(rs.getString("STD_CODE"));
//						plnJgM.setStdName(rs.getString("STD_NAME"));
//						plnJgM.setStdStyle(rs.getString("STD_STYLE"));
//						plnJgM.setStdStyleDesc(rs.getString("STD_STYLE_DESC"));
//					}
//					rs.close();
//					ps.close();
//					plnJgM.setDemandCopper(plnJgS.getDemandCopper());
//					// 计划支吨
//					plnJgM.setPlanJgNum(String.valueOf(takeCount
//							* Integer.parseInt(plnJgS.getSingleCutNun())));
//					plnJgM.setPlanBlNum(String.valueOf(takeCount));
//					plnJgM.setPlanBlWt(String.valueOf(actWt));
//
//					plnJgM.setOrdLnDlyPk(plnJgS.getOrdLnDlyPk());
//					plnJgM
//							.setProDay(dateTime.substring(0, 10).replace("-",
//									""));
//					plnJgM.setBalYearMonth(dateTime.substring(0, 7).replace(
//							"-", ""));
//
//					plnJgM.setPrdcrNo(plnJgS.getPrdcrNo());
//					plnJgM.setCraftFileNo(plnJgS.getCraftFileNo());
//					plnJgM.setCraftSeq(plnJgS.getCraftSeq());
//
//					plnJgM.setCreateName(userName);
//					plnJgM.setCreateTime(dateTime);
//					plnJgM.setHeatPlanNo(heatPlanNo);
//					plnJgM.setGxProSeq(String.valueOf(gxProSeq));
//
//
//					if(!plnJgS.getIfMonitorJg().equals("")){
//						plnJgM.setMonitordemand("接箍监制。");
//						plnJgM.setIfMonitorJg("1");
//					}else if(!plnJgS.getIfMonitorBl().equals("")){
//						plnJgM.setMonitordemand("接箍料监制。");
//						plnJgM.setIfMonitorJg("1");
//					}else if(!plnJgS.getIfMonitorBl().equals("")&&!plnJgS.getIfMonitorJg().equals("")){
//						plnJgM.setMonitordemand("接箍、接箍料监制。");
//						plnJgM.setIfMonitorJg("1");
//					}else{
//						plnJgM.setMonitordemand("");
//						plnJgM.setIfMonitorJg("0");
//					}
//					// 新增
//					String addPlnGxZg = EntityTool.fillSqlByEntity(
//							CoreXmlSqlParsersFactory
//									.getSql("PlanFurnProduction.addPlnZyJg"),
//							plnJgM);
//					ps = conn.prepareStatement(addPlnGxZg);
//					ps.executeUpdate();
//					ps.close();
//				}
//				int countC = 0;
//				String heatPlanSqe = "";
//				// 判定是否存在判定炉号，判定单号，同炉计划ID数据
//				String sqlC = "SELECT COUNT(*) COUNT1,T.HEAT_PLAN_SQE FROM PLN_ZY_JG_C T WHERE "
//						+ "T.HEAT_PLAN_NO=? AND NVL(T.JUGDE_APPLY_CODE,'/')=NVL(?,'/') AND T.FEED_HEAT_NO=? AND T.BATCH_NO=? AND NVL(T.BATCH_GROUD_NO,'/')=NVL(?,'/')"
//						+ " 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, batchNo);
//				ps.setObject(5, batchGroupBy);
//				rs = ps.executeQuery();
//				if (rs.next()) {
//					countC = rs.getInt("COUNT1");
//					heatPlanSqe = rs.getString("HEAT_PLAN_SQE");
//				}
//				rs.close();
//				ps.close();
//
//				if (countC == 0) {
//					PlnZyJgCEntity plnJgC = new PlnZyJgCEntity();
//					// 获取炉计划顺序号
//					heatPlanSqe = corePlanFurnProM.getHeatPlanSeq(conn,
//							heatPlanNo, "H");
//					plnJgC.setHeatPlanNo(heatPlanNo);
//					plnJgC.setJugdeApplyCode(jugdeApplyCode);
//					plnJgC.setFeedHeatNo(judgeStoveNo);
//					if(plineCode.equals("C072")||plineCode.equals("C091"))
//					{
//						plnJgC.setJudgeStoveNo("");
//						plnJgC.setFlagStoveNo("");
//					}else
//					{
//						plnJgC.setJudgeStoveNo(judgeStoveNo);
//						plnJgC.setFlagStoveNo(judgeStoveNo);
//					}
//
//					plnJgC.setBatchNo(batchNo);
//					plnJgC.setBatchGroudNo(batchGroupBy);
//
//					plnJgC.setStoveNo(stoveNo);
//					plnJgC.setProPlanId(plnJgS.getProPlanId());
//					plnJgC.setGxPlanNo(plnJgS.getGxPlanNo());
//					plnJgC.setPlineCode(plnJgS.getPlineCode());
//					plnJgC.setPlineName(plnJgS.getPlineName());
//					plnJgC.setUseBlNum(String.valueOf(takeCount));
//					plnJgC.setUseBlWt(String.valueOf(actWt));
//					plnJgC.setHeatPlanSqe(heatPlanSqe);
//					// 新增
//					String addPlnGxZg = EntityTool.fillSqlByEntity(
//							CoreXmlSqlParsersFactory
//									.getSql("PlanFurnProduction.addPlnZyJgC"),
//							plnJgC);
//					ps = conn.prepareStatement(addPlnGxZg);
//					ps.executeUpdate();
//					ps.close();
//				} else {
//					// 修改炉计划实表
//					String updateC = "UPDATE PLN_ZY_JG_C T SET T.USE_BL_NUM=T.USE_BL_NUM+TO_NUMBER(?),"
//							+ "T.USE_BL_WT=T.USE_BL_WT+TO_NUMBER(?) ";
//					updateC += " WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
//					ps = conn.prepareStatement(updateC);
//					ps.setObject(1, takeCount);
//					ps.setObject(2, actWt);
//					ps.setObject(3, heatPlanNo);
//					ps.setObject(4, heatPlanSqe);
//					ps.executeUpdate();
//					ps.close();
//				}
//
//				if (countM > 0) {
//					// 修改炉计划主表量
//					String sqlUpdate = CoreXmlSqlParsersFactory
//							.getSql("FrmPlanMaterialJg.updatePlnZgM");
//					ps = conn.prepareStatement(sqlUpdate);
//					ps.setObject(1, heatPlanNo);
//					ps.setObject(2, heatPlanNo);
//					ps.executeUpdate();
//					ps.close();
//				}
//				// 修改坯子库存下工序炉计划ID
//				String sqlUpdateMat = "UPDATE MAT_BC_M T SET T.HEAT_PLAN_NO_NEXT=? WHERE T.PRO_PLAN_ID_NEXT=? AND T.GX_PLAN_NO_NEXT=? AND T.JUDGE_STOVE_NO=?";
//				ps = conn.prepareStatement(sqlUpdateMat);
//				ps.setObject(1, heatPlanNo);
//				ps.setObject(2, proPlanId);
//				ps.setObject(3, gxPlanNo);
//				ps.setObject(4, judgeStoveNo);
//				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 jslist
	 * @param userName
	 *            脱单人
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doDeleteMonomer(
			ArrayList<ArrayList<String>> jslist, String userName)
			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;
			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++) {

				Date now = new Date();
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String judgeStoveNo = list.get(0);
				String batchNo = list.get(1);
				String batchGroupBy = list.get(2);
				String materialNo = list.get(3);
				int takeCount = Integer.parseInt(list.get(4));// 利库支
				String proPlanIdNo = list.get(5);

				List<MatBcMEntityPln> matGpMlist = getQureyMatGpM(conn,
						judgeStoveNo, batchNo, batchGroupBy, materialNo,
						takeCount, proPlanIdNo);
				if (matGpMlist == null) {
					cro.setV_errMsg("管坯物料已发生改变,请刷新!");
					return cro;
				}
				MatBcTrackEntity matTrack = getQureyMatTrack(conn,
						judgeStoveNo, batchNo, batchGroupBy, takeCount, "0",
						proPlanIdNo, MatBcTrackEntity.class);

				for (MatBcMEntityPln matGpM : matGpMlist) {
					String proPlanZg = matGpM.getProPlanIdNext() + "/"
							+ matGpM.getGxPlanNoNext();
					if (proPlanZg.equals("/")) {
						cro.setV_errMsg("你选择的管坯物料未分配其他接箍订单,不能脱单!");
						return cro;
					}
					String sqlUpdateMat = CoreXmlSqlParsersFactory
							.getSql("FrmPlanMaterialJg.UpdateMatGp");
					ps = conn.prepareStatement(sqlUpdateMat);
					ps.setObject(1, "80150102");
					ps.setObject(2, "");
					ps.setObject(3, "");
					ps.setObject(4, "0");
					ps.setObject(5, "0");
					ps.setObject(6, "");
					ps.setObject(7, "");
					ps.setObject(8, matGpM.getMatNo());
					ps.executeUpdate();
					ps.close();
				}
				String resumeSeq = dateFormat.format(now) + df.format(seq);
				// 生成利库日志
				matTrack.setResumeSeq(resumeSeq);
				matTrack.setEventId("900101");
				matTrack.setEventDesc("接箍脱单");
				matTrack
						.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanMaterialJg");
				matTrack.setCallFuncCoding("doDeleteMonomer");
				matTrack.setKeyvalue1("List<MatBcMEntityPln> matGpMlist");
				matTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
				matTrack.setKeyvalue2("String userName");
				matTrack.setKeyvalue2Desc2("操作人");
				matTrack.setKeyvalue3("doDeleteMonomer");
				matTrack.setKeyvalue3Desc3("删除订单号");
				matTrack.setProcessCdoe("H");
				matTrack.setMemo("");
				matTrack.setCreateName(userName);
				matTrack.setCreateTime(dateTime);
				seq++;
				String sqlAddTrack = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("FrmPlanMaterialJg.addMatBcTrack"),
						matTrack);
				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;
	}
}
