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.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.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 FrmRollTubeLibraryZg extends DBCommon {

	/**
	 * 查询轧管虚拟炉计划
	 * 
	 * @param proPlanId
	 * @param gxPlanNo
	 * @return
	 */
	public CoreReturnObject queryPlanStoveD(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanStoveD");
		List<String> param = new ArrayList<String>();
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID=?";
			param.add(proPlanId);
		}
		if (!gxPlanNo.equals("")) {
			sql += " AND T.GX_PLAN_NO =?";
			param.add(gxPlanNo);
		}
		sql += " ORDER BY T.GX_PRO_SEQ ASC ";
		return this.getData(sql, param.toArray());
	}

	/**
	 * 查询轧管实际炉计划
	 * 
	 * @param
	 * @param
	 * @return
	 */
	public CoreReturnObject queryPlanStoveDc(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanStoveDc");
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID='" + proPlanId + "'";
			sql += " AND T.GX_PLAN_NO ='" + gxPlanNo + "'";
		}
		sql += " ORDER BY T.HEAT_PLAN_SQE ASC";
		return this.getData(sql);
	}

	/**
	 * 查询轧管排产(界面展示)
	 * 
	 * @param plineCode
	 *            产线
	 * @param proPlanId
	 *            　订单编号
	 * @param orderNo
	 *            　合同号
	 * @param statusArray
	 *            　生产状态
	 * @return CoreReturnObject
	 */
	public CoreReturnObject queryPlanOrderD(String[] plineCode,
			String proPlanId, String orderNo, String[] statusArray,
			String proMonth, String comPlineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanOrderD");
		List<String> params = new ArrayList<String>();

		// --AND GP.MATERIAL_NAME = T.INWL_DESC
		// --AND INSTR(T.GRADECODE || ',' || T.GRADECODE_LK, GP.GRADECODE) > 0
		if (!comPlineCode.equals("")) {
			params.add(comPlineCode);
			sql += " AND T.PLINE_CODE=? ";
		} else {
			sql += CoreConverter.toSqlConditionString("PLINE_CODE", plineCode);
		}
		if (!proPlanId.equals("")) {
			params.add(proPlanId);
			sql += " AND T.PRO_PLAN_ID LIKE '%'||?||'%'";
		}
		if (!orderNo.equals("")) {
			params.add(orderNo);
			sql += " AND T.ORDER_NO||'/'||T.ORDER_SEQ LIKE '%'||?||'%'";
		}

		if (!proMonth.equals("")) {
			params.add(proMonth);
			sql += " AND T.PRO_MONTH=?";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		// sql +=" and T.GPREQ_ID IS NULL";
		sql += "  ORDER BY  T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ))S";
		return this.getData(sql, params.toArray());
	}

	/**
	 * 查询轧管
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getPlnOrderZgS(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanOrderD");
		sql += " AND T.PRO_PLAN_ID ='" + proPlanId + "'";
		sql += " AND T.GX_PLAN_NO ='" + gxPlanNo + "') S";
		return this.getData(sql);
	}

	/**
	 * 查询产线环形炉最小
	 * 
	 * @param plineCode
	 * @return
	 */
	public CoreReturnObject queryPline(String plineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPline");
		return this.getData(sql, new Object[] { plineCode });
	}

	/**
	 * 查询轧管成分元素
	 * 
	 * @param
	 *            　
	 * @param
	 *            　
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getStlChemicalStd(String cic, String desginKey,
			String mscPline) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.getStlChemicalStd");
		return this.getData(sql, new Object[] {desginKey, mscPline });
	}

	/**
	 * 查询轧管
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getPlnOrderZg(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.getPlnOrderZg");
		return this.getData(sql, new Object[] { proPlanId, gxPlanNo });
	}

	/**
	 * 查询判定成分元素
	 * 
	 * @param
	 *            　
	 * @param
	 *            　
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getStlChemicalData(String judgeStoveNo,
			String chemJudgeId) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.getStlChemicalData");
		return this.getData(sql, new Object[] { judgeStoveNo, chemJudgeId });
	}

	/**
	 * 查询坯子库存信息
	 * 
	 * @param
	 * @param
	 *
	 * @param
	 *
	 * @param
	 *
	 * @param
	 *
	 * @throws SQLException
	 */
	public static List<MatGpMEntity> getQureyMatGpM(Connection con,
			String judgeStoveNo, String stoveNo, String proPlanId,
			String gxPlanNo, int plnNumGp, double actLen,String judgeApplyCode) throws SQLException {
		String sql = "Select * from (select t.* from MAT_GP_M t where T.HANGING_FLAG='1' AND t.judge_stove_no=? and t.stove_no=? "
				+ " AND t.PRO_PLAN_ID_ZG=? and t.gx_plan_no_zg=? AND T.ACT_LEN =TO_NUMBER(?) AND NVL(T.JUGDE_APPLY_CODE,'/') = NVL(?,'/') ORDER BY T.MAT_NO ASC) where  ROWNUM <=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		ps.setObject(2, stoveNo);
		ps.setObject(3, proPlanId);
		ps.setObject(4, gxPlanNo);
		ps.setObject(5, actLen);
		ps.setObject(6,judgeApplyCode);
		ps.setObject(7, plnNumGp);
		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
	 * @param
	 * @return
	 */
	public CoreReturnObject queryMatGpTrack(String styeSj, String judgeNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryMatGpTrack");
		List<String> param = new ArrayList<String>();
		if (!styeSj.equals("")) {
			sql += " AND T.EVENT_ID=?";
			param.add(styeSj);
		}
		if (!judgeNo.equals("")) {
			sql += " AND T.JUDGE_STOVE_NO LIKE '%' || ? || '%'";
			param.add(judgeNo);
		}
		sql += " GROUP BY T.EVENT_ID, T.EVENT_DESC, T.FORM_NAME, T.CALL_FUNC_CODING,  T.KEYVALUE_1, T.KEYVALUE_1_DESC, "
				+ " T.KEYVALUE_2, T.KEYVALUE_2_DESC2,  T.KEYVALUE_3, T.KEYVALUE_3_DESC3, T.KEYVALUE_4, T.KEYVALUE_4_DESC4, "
				+ " T.KEYVALUE_5, T.KEYVALUE_5_DESC5, T.KEYVALUE_6, T.KEYVALUE_6_DESC6,   T.KEYVALUE_7, T.KEYVALUE_7_DESC7, "
				+ " T.PRODUCT_FLAG, T.MAT_STATUS, T.STOVE_NO, T.FLAG_STOVE_NO, T.LOT_NO, T.JUDGE_STOVE_NO, T.GROUD_NO, T.BATCH_NO, "
				+ " T.CAST_NO,  T.CCMID, T.GRADECODE, T.GRADENAME, T.STD_CODE, T.STD_NAME, T.ACT_DIMATER,  T.ACT_HEIGHT, T.ACT_LEN, "
				+ " T.ACT_LEN_MIN, T.ACT_LEN_MAX, T.ACT_FIX_NUM,  T.ACT_FIX_LEN, T.PRO_ORDER_NO, T.PRO_ORDER_ID, T.PRO_ORDER_NO1, "
				+ " T.PRO_ORDER_ID1, T.ORD_PK, T.ORD_LN_PK, T.ORD_LN_DLY_PK, T.ORDER_NO,  T.ORDER_SEQ, T.ORDER_SEQ_NO, T.OLD_ORD_PK, "
				+ " T.OLD_ORD_LN_PK,  T.OLD_ORD_LN_DLY_PK, T.OLD_ORDER_NO, T.OLD_ORDER_SEQ, T.OLD_ORDER_SEQ_NO,  T.BELONG_CODE, T.BELONG_NAME,"
				+ " T.MEMO, T.CREATE_NAME, T.CREATE_TIME,  T.DEPARTMENT_CODE, T.DEPARTMENT_DESC, T.MANAGEMENT_NO, T.MANAGEMENT_NAME,  T.OLD_JUDGE_STOVE_NO,"
				+ " T.OLD_GROUD_NO, T.OLD_BATCH_NO, T.OLD_GRADECODE,  T.OLD_GRADENAME, T.OLD_STD_CODE, T.OLD_STD_NAME, T.OLD_STOVE_NO  ";
		sql += " ORDER BY T.CREATE_TIME ASC ";
		return this.getData(sql, param.toArray());
	}

	/**
	 * 轧管炉计划撤销
	 * 
	 * @param jslist
	 * @param userName
	 *            操作人
	 * @return
	 * @throws Exception
	 * @throws NumberFormatException
	 */
	public CoreReturnObject doDelete(ArrayList<ArrayList<String>> jslist,
			String userName) throws NumberFormatException, Exception {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			DecimalFormat df = new DecimalFormat("0000000000");
			// 循环库存信息
			int seq = 1;
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String heatPlanNo = list.get(0);

				List<PlnZyZgMEntity> plnzg = StoveHelper.getPlanOrderZyM(conn,
						heatPlanNo, "D");
				if (plnzg == null) {
					cro.setV_errMsg("轧管炉计划数据已发生改变,请刷新!");
					return cro;
				}
				int plnNum = 0;
				double plnWt = 0;
				String proPlanId = "";
				String gxPlanNo = "";
				String ifMatchOdd = "";
				for (PlnZyZgMEntity plnzgM : plnzg) {
					proPlanId = plnzgM.getProPlanId();
					gxPlanNo = plnzgM.getGxPlanNo();
					ifMatchOdd = plnzgM.getIfMatchOdd();
					plnNum = Integer.parseInt(plnzgM.getPlnInsingleNum());// 单倍支数
					plnWt = Double.parseDouble(plnzgM.getPlnInsingleWt());
					if (!plnzgM.getPlanstatus().equals("00")) {
						cro.setV_errMsg("轧管炉计划状态不是计划状态!,请确认!");
						return cro;
					}
					// 删除轧管虚拟炉计划
					String deleteZgM = "DELETE PLN_ZY_ZG_M WHERE HEAT_PLAN_NO = ?";
					ps = conn.prepareStatement(deleteZgM);
					ps.setObject(1, heatPlanNo);
					ps.executeUpdate();
					ps.close();

					// 是否存在实际炉计划
					if (plnzgM.getHeatPlanSqe().equals("")) {
						String matZgMHangingFlag = "1";
						String sqlmat = "SELECT DECODE(MAX(T.HANGING_FLAG),'','1',MAX(T.HANGING_FLAG))  HANGING_FLAG FROM MAT_GP_M T WHERE T.JUDGE_STOVE_NO=? AND T.PRO_PLAN_ID_ZG=? AND T.GX_PLAN_NO_ZG=?";
						ps = conn.prepareStatement(sqlmat);
						ps.setObject(1, plnzgM.getJudgeStoveNo());
						ps.setObject(2, proPlanId);
						ps.setObject(3, gxPlanNo);
						rs = ps.executeQuery();
						if (rs.next()) {
							matZgMHangingFlag = rs.getString("HANGING_FLAG");
						}
						rs.close();
						ps.close();
						if (matZgMHangingFlag.equals("0")) {
							// 删除库存轧管订单号
							String updateMat = "UPDATE MAT_GP_M T SET T.PRO_PLAN_ID_ZG='' , T.GX_PLAN_NO_ZG='',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(updateMat);
							ps.setObject(1, plnzgM.getJudgeStoveNo());
							ps.setObject(2, proPlanId);
							ps.setObject(3, gxPlanNo);
							ps.executeUpdate();
							ps.close();
						}
						continue;
					}
					// 删除轧管实际炉计划
					String deleteZgC = "DELETE PLN_ZY_ZG_C WHERE HEAT_PLAN_NO = ?";
					ps = conn.prepareStatement(deleteZgC);
					ps.setObject(1, heatPlanNo);
					ps.executeUpdate();
					ps.close();

					double fixLenTake = Double.parseDouble(plnzgM
							.getLenGpSingle());
					//double actLenTake = Double.parseDouble(plnzgM.getLengthM());
					double actLenTake = Double.parseDouble(plnzgM.getLengthMOld());
					double cutYuLong = Double
							.parseDouble(plnzgM.getCutLength());// 切余剩余长
					int cutNum = Integer.parseInt(plnzgM.getCutNumGp());
					int plnNumGp = plnNum / cutNum;

					List<MatGpMEntity> matGpMlist = getQureyMatGpM(conn, plnzgM
							.getJudgeStoveNo(), plnzgM.getStoveNo(), plnzgM
							.getProPlanId(), plnzgM.getGxPlanNo(), Integer.parseInt(plnzgM.getPlanIndoubleNum()),
							actLenTake,plnzgM.getJugdeApplyCode());
					if (matGpMlist == null) {
						cro.setV_errMsg("管坯物料已发生改变,请刷新!");
						return cro;
					}

					for (MatGpMEntity matGpM : matGpMlist) {

						if (!matGpM.getMatStatus().equals("80150103")) {
							cro.setV_errMsg("判定炉号为:" + matGpM.getJudgeStoveNo()
									+ ",不是材料已编计划状态,不能删除炉计划!");
							return cro;
						}
						// double cutYuLong = 0;// 切余剩余长
						// String matStatus = "80150101";
						// String hangingFalg = "0";
						// if (plnzgM.getIfMatchOdd().equals("1")) {// 利库计划撤销
						cutYuLong = Double.parseDouble(matGpM.getActLen())
								- actLenTake
								- Double.parseDouble(matGpM.getCutYuLong());


						String setFootSql = CoreXmlSqlParsersFactory.getSql("FrmRollTubeLibraryZg.selectMatSetfoot");
						ps = conn.prepareStatement(setFootSql);
						if(matGpM.getSetfootSeq().equals("0"))
						{
							ps.setString(1,matGpM.getMatNo());
							ps.setString(2,matGpM.getSetfootSeq());
						}else
						{
							ps.setString(1,matGpM.getMatNoOld());
							ps.setString(2,matGpM.getSetfootSeq());
						}

						rs = ps.executeQuery();
						List<MatGpMEntity> matGpSetfootList = EntityTool.getEntitysByRs(rs,MatGpMEntity.class);
						rs.close();
						ps.close();
						if(matGpSetfootList.size()>0)
						{
							for(MatGpMEntity ms : matGpSetfootList)
							{
								if(ms.getMatStatus().equals("80150103"))
								{
									cro.setV_errMsg("炉号"+matGpM.getJudgeStoveNo()+"的套尺已进行装炉,该炉计划不允许删除炉计划,请依次删除炉计划!");
									return cro;
								}else
								{
									String deleteMatSetFootSql = CoreXmlSqlParsersFactory.getSql("FrmRollTubeLibraryZg.deleteMatSetFoot");
									deleteMatSetFootSql = EntityTool.fillSqlByEntity(deleteMatSetFootSql,ms);
									ps = conn.prepareStatement(deleteMatSetFootSql);
									ps.executeUpdate();
									ps.close();
								}
							}

						}

						// 修改库坯料库存
						String sqlUpdateZgS = "UPDATE MAT_GP_M T SET T.HANGING_FLAG=?,T.MAT_STATUS=?,"
								+ " T.CUT_YU_LONG=?,T.UPDATE_NAME=?,"
								+ " T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS'),"
								+ " T.LK_FLAG='0',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=?";
						// T.PRO_PLAN_ID_ZG=?,T.GX_PLAN_NO_ZG=?,
						ps = conn.prepareStatement(sqlUpdateZgS);
						ps.setObject(1, "0");
						ps.setObject(2, "80150102");
						ps.setObject(3, "0");
						ps.setObject(4, userName);
						ps.setObject(5, dateTime);
						ps.setObject(6, 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.FrmRollTubeLibraryZg");
						matGpTrack.setCallFuncCoding("doDelete");
						matGpTrack
								.setKeyvalue1("List<MatGpMEntity> matGpMlist");
						matGpTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
						matGpTrack.setKeyvalue2("String userName");
						matGpTrack.setKeyvalue2Desc2("操作人");
						matGpTrack.setKeyvalue3("doDeleteZGC");
						matGpTrack.setKeyvalue3Desc3("删除炉计划");
						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.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.setActFixLen(String.valueOf(fixLenTake));
						matGpTrack.setActFixNum(matGpM.getFixNum());
						matGpTrack.setActCount("1");
						matGpTrack.setActWeight(matGpM.getActWeight());
						matGpTrack.setActTheoryWeight(matGpM
								.getActTheoryWeight());
						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.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();
					}
					if (plnzgM.getIfMatchOdd().equals("4")) {
						String gpreqId = "";
						// 查询是否有管坯需求号
						String sqlGpID = "SELECT T.GPREQ_ID FROM PLN_ORDER_ZG_S T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
						ps = conn.prepareStatement(sqlGpID);
						ps.setObject(1, proPlanId);
						ps.setObject(2, gxPlanNo);
						rs = ps.executeQuery();
						if (rs.next()) {
							gpreqId = rs.getString("GPREQ_ID");
						}
						rs.close();
						ps.close();
						// 修改有管坯需求号的铸造订单利库量
						if (gpreqId != null && gpreqId != "") {
							FrmPlanMaterialSelection.updateCastS(conn, gpreqId,
									plnzgM.getJudgeStoveNo(),
									Double.parseDouble(plnzgM.getPlanWeigth()),
									plnNumGp, "0");
						}
					}
				}
				// 修改轧管利库信息
				// String sqlUpdateZgS =
				// "UPDATE PLN_ORDER_ZG_S T  SET T.STATE_SINGLE = '0',"
				// +
				// "T.BATCHED_WT_G  = TO_NUMBER(NVL(T.BATCHED_WT_G, 0)) - TO_NUMBER('"
				// + plnWt
				// + "'),"
				// +
				// "T.BATCHED_NUM_G = TO_NUMBER(NVL(T.BATCHED_NUM_G, 0)) - TO_NUMBER('"
				// + plnNum + "')";
				// if (ifMatchOdd.equals("1")) {// 利库计划撤销
				// sqlUpdateZgS +=
				// " ,T.MATCH_WT_IN  = TO_NUMBER(NVL(T.MATCH_WT_IN, 0)) - TO_NUMBER('"
				// + plnWt
				// + "'),"
				// +
				// "T.MATCH_NUM_IN = TO_NUMBER(NVL(T.MATCH_NUM_IN, 0)) - TO_NUMBER('"
				// + plnNum + "')";
				// }
				// sqlUpdateZgS += " WHERE T.PRO_PLAN_ID = '" + proPlanId
				// + "' AND T.GX_PLAN_NO = '" + gxPlanNo + "' ";
				// ps = conn.prepareStatement(sqlUpdateZgS);
				// ps.executeUpdate();
				// ps.close();
			}
			cro.setV_errMsg("删除成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询虚拟炉计划
	 * 
	 * @param con
	 * @param
	 *
	 * @param
	 *
	 * @return PlnOrderCastSEntity
	 * @throws SQLException
	 */
	public static List<PlnZyZgMEntity> getPlanZyZgM(Connection con,
			String heatPlanNo) throws SQLException {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanMZg");
		sql += " AND T.HEAT_PLAN_NO = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, heatPlanNo);
		ResultSet rs = ps.executeQuery();
		List<PlnZyZgMEntity> list = EntityTool.getEntitysByRs(rs,
				PlnZyZgMEntity.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (PlnZyZgMEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 查询实际炉计划
	 * 
	 * @param con
	 * @throws SQLException
	 */
	public static List<PlnZyZgCEntity> getPlanZyZgC(Connection con,
			String heatPlanNo, String heartPlanSeq) throws SQLException {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryZg.queryPlanCZg");
		sql += " AND T.HEAT_PLAN_NO = ?";
		sql += " AND T.HEAT_PLAN_SQE = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, heatPlanNo);
		ps.setObject(2, heartPlanSeq);
		ResultSet rs = ps.executeQuery();
		List<PlnZyZgCEntity> list = EntityTool.getEntitysByRs(rs,
				PlnZyZgCEntity.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (PlnZyZgCEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 轧管炉计划撤销
	 * 
	 * @param
	 * @param userName
	 *            操作人
	 * @return
	 * @throws Exception
	 * @throws NumberFormatException
	 */
	@SuppressWarnings("null")
	public CoreReturnObject doDeleteZGC(String heatPlanNo, String heatPlanSeq,
			String userName) throws NumberFormatException, Exception {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			DecimalFormat df = new DecimalFormat("0000000000");
			// 循环库存信息
			int seq = 1;
			// for (int i = 0; i < jslist.size(); i++) {
			// ArrayList<String> list = (ArrayList<String>) jslist.get(i);
			// String heatPlanNo = list.get(0);

			int plnNum = 0;
			double plnWt = 0;
			String proPlanId = "";
			String gxPlanNo = "";
			String ifMatchOdd = "";
			List<PlnZyZgMEntity> plnM = getPlanZyZgM(conn, heatPlanNo);

			for (PlnZyZgMEntity plnzgM : plnM) {
				plnNum = Integer.parseInt(plnzgM.getPlnInsingleNum());// 单倍支数
				plnWt = Double.parseDouble(plnzgM.getPlnInsingleWt());
				proPlanId = plnzgM.getProPlanId();
				gxPlanNo = plnzgM.getGxPlanNo();
				ifMatchOdd = plnzgM.getIfMatchOdd();
				if (plnM == null) {
					cro.setV_errMsg("轧管炉计划数据已发生改变,请刷新!");
					return cro;
				}
				if (!plnzgM.getPlanstatus().equals("00")) {
					cro.setV_errMsg("轧管炉计划状态不是计划状态!,请确认!");
					return cro;
				}
				if (heatPlanSeq.equals("")) {// 只有虚拟炉计划
					if (!plnzgM.getPlanstatus().equals("00")) {
						cro.setV_errMsg("轧管炉计划状态不是计划状态!,请确认!");
						return cro;
					}
					// 删除轧管虚拟炉计划
					String deleteZgM = "DELETE PLN_ZY_ZG_M WHERE HEAT_PLAN_NO = ?";
					ps = conn.prepareStatement(deleteZgM);
					ps.setObject(1, heatPlanNo);
					ps.executeUpdate();
					ps.close();

					String matZgMHangingFlag = "1";
					String sqlmat = "SELECT DECODE(MAX(T.HANGING_FLAG),'','1',MAX(T.HANGING_FLAG))  HANGING_FLAG FROM MAT_GP_M T WHERE T.JUDGE_STOVE_NO=? AND T.PRO_PLAN_ID_ZG=? AND T.GX_PLAN_NO_ZG=?";
					ps = conn.prepareStatement(sqlmat);
					ps.setObject(1, plnzgM.getJudgeStoveNo());
					ps.setObject(2, proPlanId);
					ps.setObject(3, gxPlanNo);
					rs = ps.executeQuery();
					if (rs.next()) {
						matZgMHangingFlag = rs.getString("HANGING_FLAG");
					}
					rs.close();
					ps.close();
					if (matZgMHangingFlag.equals("0")) {
						// 删除库存轧管订单号
						String updateMat = "UPDATE MAT_GP_M T SET T.PRO_PLAN_ID_ZG='', T.GX_PLAN_NO_ZG='' WHERE T.JUDGE_STOVE_NO=? AND T.PRO_PLAN_ID_ZG=? AND T.GX_PLAN_NO_ZG=?";
						ps = conn.prepareStatement(updateMat);
						ps.setObject(1, plnzgM.getJudgeStoveNo());
						ps.setObject(2, proPlanId);
						ps.setObject(3, gxPlanNo);
						ps.executeUpdate();
						ps.close();
					}
				} else {
					List<PlnZyZgCEntity> plnzg = getPlanZyZgC(conn, heatPlanNo,
							heatPlanSeq);

					double weight = 0;
					int cutNumCount = 0;
					for (PlnZyZgCEntity plnzgC : plnzg) {
						if (plnzg == null) {
							cro.setV_errMsg("轧管炉计划数据已发生改变,请刷新!");
							return cro;
						}
						proPlanId = plnzgC.getProPlanId();
						gxPlanNo = plnzgC.getGxPlanNo();
						int num = Integer.parseInt(plnzgC.getPlanIndoubleNum());
						weight += Double
								.parseDouble(plnzgC.getPlanIndoubleWt());
						cutNumCount += num
								* Integer.parseInt(plnzgC.getCutNumGp());
						// 删除轧管实际炉计划
						String deleteZgC = "DELETE PLN_ZY_ZG_C WHERE HEAT_PLAN_NO = ? AND HEAT_PLAN_SQE=?";
						ps = conn.prepareStatement(deleteZgC);
						ps.setObject(1, heatPlanNo);
						ps.setObject(2, heatPlanSeq);
						ps.executeUpdate();
						ps.close();

						double fixLenTake = Double.parseDouble(plnzgC
								.getLenGpSingle());
						double actLenTake = Double.parseDouble(plnzgC
								.getLengthMOld());
						double cutYuLong = Double.parseDouble(plnzgC
								.getCutLength());// 切余剩余长
						int cutNum = Integer.parseInt(plnzgC.getCutNumGp());

						List<MatGpMEntity> matGpMlist = getQureyMatGpM(conn,
								plnzgC.getJudgeStoveNo(), plnzgC.getStoveNo(),
								plnzgC.getProPlanId(), plnzgC.getGxPlanNo(),
								num, actLenTake,plnzgC.getJugdeApplyCode());
						if (matGpMlist == null) {
							cro.setV_errMsg("管坯物料已发生改变,请刷新!");
							return cro;
						}
						for (MatGpMEntity matGpM : matGpMlist) {
							if (!matGpM.getMatStatus().equals("80150103")) {
								cro.setV_errMsg("判定炉号为:"
										+ matGpM.getJudgeStoveNo()
										+ ",不是材料已编计划状态,不能删除炉计划!");
								return cro;
							}
							cutYuLong = Double.parseDouble(matGpM.getActLen())
									- actLenTake
									- Double.parseDouble(matGpM.getCutYuLong());

							if(matGpM.getIsSetfoot().equals("1"))
							{
								cro.setV_errMsg("此炉计划中含有套尺坯,请去轧管坯料利库界面进行删除炉计划!");
								return  cro;
							}
							String sqlUpdateZgS = "UPDATE MAT_GP_M T SET T.HANGING_FLAG=?,T.MAT_STATUS=?,"
									+ " T.CUT_YU_LONG=?,T.UPDATE_NAME=?,"
									+ " T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS'),"
									+ " T.LK_FLAG='0',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=?";
							// T.PRO_PLAN_ID_ZG=?,T.GX_PLAN_NO_ZG=?,
							ps = conn.prepareStatement(sqlUpdateZgS);
							ps.setObject(1, "0");

							if(matGpM.getJudgeResultCode().equals("") && matGpM.getInstancyFlag().equals("1"))
							{
								ps.setObject(2, "80150101");
							}else
							{
								ps.setObject(2, "80150102");
							}

							ps.setObject(3, "0");
							ps.setObject(4, userName);
							ps.setObject(5, dateTime);
							ps.setObject(6, 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.FrmRollTubeLibraryZg");
							matGpTrack.setCallFuncCoding("doDeleteZGC");
							matGpTrack
									.setKeyvalue1("List<MatGpMEntity> matGpMlist");
							matGpTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
							matGpTrack.setKeyvalue2("String userName");
							matGpTrack.setKeyvalue2Desc2("操作人");
							matGpTrack.setKeyvalue3("doDeleteZGC");
							matGpTrack.setKeyvalue3Desc3("删除炉计划");
							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.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.setActFixLen(String.valueOf(fixLenTake));
							matGpTrack.setActFixNum(matGpM.getFixNum());
							matGpTrack.setActCount("1");
							matGpTrack.setActWeight(matGpM.getActWeight());
							matGpTrack.setActTheoryWeight(matGpM
									.getActTheoryWeight());
							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.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();
						}
						if (plnzgM.getIfMatchOdd().equals("4")) {
							String gpreqId = "";
							// 查询是否有管坯需求号
							String sqlGpID = "SELECT T.GPREQ_ID FROM PLN_ORDER_ZG_S T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
							ps = conn.prepareStatement(sqlGpID);
							ps.setObject(1, proPlanId);
							ps.setObject(2, gxPlanNo);
							rs = ps.executeQuery();
							if (rs.next()) {
								gpreqId = rs.getString("GPREQ_ID");
							}
							rs.close();
							ps.close();
							// 修改有管坯需求号的铸造订单利库量
							if (gpreqId != null && gpreqId != "") {
								FrmPlanMaterialSelection.updateCastS(conn,
										gpreqId, plnzgC.getJudgeStoveNo(),
										Double.parseDouble(plnzgC
												.getPlanWeigth()), num, "0");
							}
						}
					}
					int countM = 0;
					// 查询是否实际炉计划全部删除
					String sqlM = "SELECT COUNT(*) COUNT FROM PLN_ZY_ZG_C T WHERE T.HEAT_PLAN_NO = ?";
					ps = conn.prepareStatement(sqlM);
					ps.setObject(1, heatPlanNo);
					rs = ps.executeQuery();
					if (rs.next()) {
						countM = rs.getInt("COUNT");
					}
					rs.close();
					ps.close();

					if (countM == 0) {
						// 删除轧管虚拟炉计划
						String deleteZgM = "DELETE PLN_ZY_ZG_M WHERE HEAT_PLAN_NO = ?";
						ps = conn.prepareStatement(deleteZgM);
						ps.setObject(1, heatPlanNo);
						ps.executeUpdate();
						ps.close();
						// 修改轧管利库信息
						// String sqlUpdateZgS =
						// "UPDATE PLN_ORDER_ZG_S T  SET T.STATE_SINGLE = '0',"
						// +
						// "T.BATCHED_WT_G  = TO_NUMBER(NVL(T.BATCHED_WT_G, 0)) - TO_NUMBER('"
						// + plnWt
						// + "'),"
						// +
						// "T.BATCHED_NUM_G = TO_NUMBER(NVL(T.BATCHED_NUM_G, 0)) - TO_NUMBER('"
						// + plnNum + "')";
						// if (ifMatchOdd.equals("1")) {// 利库计划撤销
						// sqlUpdateZgS +=
						// " ,T.MATCH_WT_IN  = TO_NUMBER(NVL(T.MATCH_WT_IN, 0)) - TO_NUMBER('"
						// + plnWt
						// + "'),"
						// +
						// "T.MATCH_NUM_IN = TO_NUMBER(NVL(T.MATCH_NUM_IN, 0)) - TO_NUMBER('"
						// + plnNum + "')";
						// }
						// sqlUpdateZgS += " WHERE T.PRO_PLAN_ID = '" +
						// proPlanId
						// + "' AND T.GX_PLAN_NO = '" + gxPlanNo + "' ";
						// ps = conn.prepareStatement(sqlUpdateZgS);
						// ps.executeUpdate();
						// ps.close();
					} else {
						// 修改虚拟炉计划量
						String sqlUpdate = CoreXmlSqlParsersFactory
								.getSql("FrmRollTubeLibraryZg.updatePlnZgMOld");
						ps = conn.prepareStatement(sqlUpdate);
						ps.setObject(1, cutNumCount);
						ps.setObject(2, weight);
						ps.setObject(3, cutNumCount);
						ps.setObject(4, weight);
						ps.setObject(5, heatPlanNo);
						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;
	}
}
