package com.steering.pss.plnsaleord.steelMarkingPlan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.*;
import com.steering.pss.plnsaleord.stove.ComPlanFurnace;

/**
 * 炉次订单余材利轧管订单
 * 
 * @author tjg 2017-08-17
 */
public class FrmSteelPlnZg extends DBCommon {
	private static double Pi = 3.1415926; // 圆周率

	/**
	 * 查询管坯需求号
	 * 
	 * @param gpredId
	 * @return
	 */
	public CoreReturnObject selectPlnReqinfGp(String gpredId) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelPlnZg.selectPlnReqinfGp");
		return this.getData(sql, new Object[] { gpredId });
	}

	/**
	 * 通过炉次号查询CIC,工艺路径
	 * 
	 * @param gpredId
	 * @return
	 */
	public CoreReturnObject selectPlanRouteCic(String furnaceno) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelPlnZg.selectPlanRouteCic");
		return this.getData(sql, new Object[] { furnaceno });
	}

	/**
	 * 查询轧管订单
	 * 
	 * @param gpredId
	 * @return
	 */
	public CoreReturnObject selectPlnOrderZgS(String cic, String planRoute,
			String gradCode, String diammterGp, String flag) {
		if (planRoute.contains("R")) {
			planRoute = planRoute.replace("R", "V");
		}
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelPlnZg.selectPlnOrderZgS");
		sql += " AND T.OUTS_BILLET_FL = '0'  AND T.DIAMETER_GP =TO_NUMBER('"
				+ diammterGp + "') ";
		// sql+=" AND T3.STATION_DESC='" + planRoute + "'";
		sql += " AND T.EXE_STATUS = '0' AND (T.IS_REPAIR_PLN IS NULL OR T.IS_REPAIR_PLN = '0')"
				+ " AND T.IS_PLAN_OK ='1' ";
		if (flag.equals("0")) {
			sql += "  AND T.GPREQ_ID IS NULL";
		} else {
			sql += " AND T.GPREQ_ID IS NOT NULL";
		}
		sql += " AND T.PLINE_CODE IN ('C008','C009','C010','C012','C017')";
		sql += ")ZG WHERE INSTR(ZG.GRADE_ALL, '" + gradCode + "') > 0";
		return this.getData(sql);

	}

	/**
	 * 查询轧管订单（根据管坯需求查询）
	 * 
	 * @return
	 */
	public CoreReturnObject doPlnZgQuery(String proPlanId) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelPlnZg.doPlnZgQuery");
		return this.getData(sql, new Object[] { proPlanId });
	}

	/**
	 * 查询铸造生产订单信息(新界面用)
	 * 
	 * @param plineCodeA
	 *            电炉
	 * @param pineCodeB
	 *            铸机
	 * @param gradeCode
	 *            钢种
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getOrderBInfoByContion(String cic,
			String planRoute, String gradCode, String diammterGp,
			String plineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.getOrderBInfo");
		sql += " AND T.GRADECODE='"
				+ gradCode
				+ "' AND T.DIAMETER_LZ='"
				+ diammterGp
				// + "' "
				// + "AND STATION_DESC='"
				// + planRoute
				+ "' AND T.PLINE_CODE='"
				+ plineCode
				+ "' AND T.EXE_STATUS IN ('0','1')  AND (T.IS_PLAN_OK='0' OR T.IS_PLAN_OK IS NULL) "
				+ "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";
		sql += "  order by TO_NUMBER(T.GX_PRO_SEQ) ASC";
		return this.getData(sql);
	}

	/**
	 * 查询炉次订单同一铸造产线最大炉号顺序号
	 * 
	 * @param con
	 * @param time
	 * @return
	 * @throws SQLException
	 */
	static int getMaxCcmSeqno(Connection con, String plineCode, String furnNo)
			throws SQLException {
		int furnSeqno = 1;
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanChange.getMaxCcmSeqno");
		sql += " AND T.FURNACENO=? AND (T.SURPLUS_TYPE  IS NULL OR  T.SURPLUS_TYPE IN ('1','6'))";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, plineCode);
		ps.setObject(2, furnNo);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			furnSeqno = rs.getInt("CCM_SEQ") + 1;
		}
		rs.close();
		ps.close();
		return furnSeqno;
	}

	/**
	 * 利计划
	 * 
	 * @param list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doLibrary(ArrayList<String> jsonList,
			String furnaceno, String sequenceno, String name, String ciclc,
			String falg, String seleTab) 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;
			// 获取数据库当前时间
			// String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
			// SimpleDateFormat df = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			double toWeightM = 0;
			int toNumM = 0;
			int cutNumGp = 0;// 倍尺数
			// 查询炉次订单余材信息
			String sqlfurn = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlfurn += " AND T.SEQUENCENO=?";
			ps = conn.prepareStatement(sqlfurn);
			ps.setObject(1, furnaceno);
			ps.setObject(2, sequenceno);
			rs = ps.executeQuery();
			List<PlnSteelforOrdEntity> steelordList = EntityTool
					.getEntitysByRs(rs, PlnSteelforOrdEntity.class);
			rs.close();
			ps.close();
			if (steelordList == null || steelordList.size() == 0) {
				cro.setV_errMsg("无炉次余材订单信息,请刷新!");
				return cro;
			}
			PlnSteelforOrdEntity entity = steelordList.get(0);
			toWeightM = Double.parseDouble(entity.getTotWeightM());
			toNumM = Integer.parseInt(entity.getTotMumM());
			cutNumGp = Integer.parseInt(entity.getCutNumGp());
			if (!entity.getStatus().equals("00")
					&& !entity.getStatus().equals("10")) {
				cro.setV_errMsg("炉次订单已不是编制中/下发状态!");
				return cro;
			}
			// for (int i = 0; i < jsonList.size(); i++) {
			// ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
			String proPlanId = jsonList.get(0);
			String gxPlanNo = jsonList.get(1);
			int cutNum = Integer.parseInt(jsonList.get(2));// 倍尺数
			double reallWt = Double.parseDouble(jsonList.get(3));// 轧管冶炼量
			int reallNum = Integer.parseInt(jsonList.get(4));// 轧管冶炼支
			double legSingGp = Double.parseDouble(jsonList.get(5));// 轧管单倍坯长
			String gpreqId = jsonList.get(6);
			String cic = jsonList.get(7);
			// String ifMonitorLg = "";

			String craftSeq = "";
			String indexSeq = "";
			String ordLnDlyPk = "";
			String cicGroupGp = "";
			// 查询轧管排产计划
			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryPlnOrderZgS");
			ps = conn.prepareStatement(sql);
			ps.setObject(1, proPlanId);
			ps.setObject(2, gxPlanNo);
			rs = ps.executeQuery();
			if (rs.next()) {
				if (!rs.getString("EXE_STATUS").equals("0")) {
					cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
							+ "不是计划状态,不能利轧管计划!");
					return cro;
				}
				// if (matchWt == 0) {// 轧管可利库吨
				// cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
				// + ",需坯吨为0或已利计划!");
				// return cro;
				// }
				craftSeq = rs.getString("CRAFT_SEQ");
				indexSeq = rs.getString("INDEX_SEQ");
				ordLnDlyPk = rs.getString("ORD_LN_DLY_PK");
				cicGroupGp = rs.getString("CIC_GROUP_GP");
				if (rs.getString("IS_PLAN_OK") == null
						|| rs.getString("IS_PLAN_OK").equals("0")) {
					cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
							+ ",未轧管确认,不能利轧管计划!!");
					return cro;
				}
				if (seleTab.equals("0")) {
					if (rs.getString("GPREQ_ID") != null) {
						cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
								+ ",已生成管坯需求,不能利轧管计划!");
						return cro;
					}
				}
				entity.setOrderNo(rs.getString("ORDER_NO"));
				entity.setSteelcode(rs.getString("STEELCODE"));
				entity.setSteelname(rs.getString("STEELNAME"));
				entity.setProduccode(rs.getString("PRODUCCODE"));
				entity.setProducname(rs.getString("PRODUCNAME"));
				entity.setFinalUserDesc(rs.getString("FINAL_USER_DESC"));
				entity.setGowhereCode(rs.getString("PLINE_CODE"));
				entity.setGowhereName(rs.getString("PLINE_NAME"));

				if (rs.getString("IF_MONITOR_LG").equals("0")) {
					entity.setIfMonitorLg("/");
				} else {
					entity.setIfMonitorLg("是");
					entity.setPrdcrNo(rs.getString("PRDCR_NO"));
				}
				//
				// if (ifMonitorLg.equals("1")) {
				// entity.setPrdcrNo(rs.getString("PRDCR_NO"));
				// }
				// entity.setCic(rs.getString("CIC_GP"));

			} else {
				cro.setV_errMsg("轧管订单排产数据发生变化,请刷新");
				return cro;
			}
			rs.close();
			ps.close();
//			// 查询钢种对应索引码
//			String sqlCic = CoreXmlSqlParsersFactory
//					.getSql("FrmSteelPlnZg.QueryZgCic");
//			ps = conn.prepareStatement(sqlCic);
//			ps.setObject(1, craftSeq);
//			ps.setObject(2, ordLnDlyPk);
//			ps.setObject(3, indexSeq);
//			ps.setObject(4, entity.getGradecode());
//			rs = ps.executeQuery();
//			while (rs.next()) {
//				if (cicGroupGp.contains(rs.getString("CIC"))) {
//					entity.setCic(rs.getString("CIC"));
//					continue;
//				}
//			}
//			rs.close();
//			ps.close();
			entity.setCic(cic);
			if (!ciclc.contains(entity.getCic())) {
				ciclc = ciclc + "," + entity.getCic();
				// String[] strArray = ciclc.split(',').Distinct().ToArray();
				// Array.Sort(strArray);
				// ciclc = string.Join(",", strArray);
			}

			double lkWt = 0;// 利库吨
			int lkNum = 0;
			double dimater = Double.parseDouble(entity.getDiameter());
			double mSingleWeight = (7.8 * Pi / 4 * dimater * dimater) / 1000 / 1000;
			// 倍尺坯长
			double lenLong = legSingGp * cutNum;
			// 倍尺坯单支重=坯米单重*倍尺坯长/1000
			double weightM = mSingleWeight * (lenLong / 1000);
			// 单倍坯重
			double weightGpOne = mSingleWeight
					* (Double.parseDouble(entity.getLenGpSingle()) / 1000);
			// 如果余材量与轧管待冶炼量比较余材比冶炼量小
			// if (toWeightM - reallWt < 0.0000002) {
			lkWt = toWeightM;
			toNumM = (int) Math.ceil(toWeightM / weightM);
			if (toNumM == 0) {
				toNumM = 1;
			}
			lkNum = toNumM;
			lkWt = lkNum * weightM;
			// }
			// else {
			// lkWt = reallWt - toWeightM;
			// toNumM = (int) Math.ceil(lkWt / weightM);
			// if (toNumM == 0) {
			// toNumM = 1;
			// }
			// lkNum = toNumM;
			// lkWt = lkNum * weightM;
			// }
			if (lkNum == 0) {
				lkNum = 1;
			}
			double wt = 0;// 余材剩余量
			int num = 0;// 余材剩余支
			num = Integer.parseInt(entity.getTotMumM()) - lkNum;
			wt = num * weightM;
			// num = (int) Math.ceil(wt /
			// Double.parseDouble(entity.getWeightM()));
			entity.setCutNumGp(String.valueOf(cutNum));
			entity.setWeightGpOne(String.valueOf(weightGpOne));
			entity.setLenGpSingle(String.valueOf(legSingGp));
			entity.setActWeightM(String.valueOf(lkWt));
			entity.setTotMumM(String.valueOf(lkNum));
			entity.setWeightM(String.valueOf(weightM));
			entity.setLengthM(String.valueOf(lenLong));
			entity.setProPlanId(proPlanId);
			entity.setGxPlanNo(gxPlanNo);
			// 修改轧管订单利库量
			String sqlupdateZg = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.updarePlnOrderZgS");
			ps = conn.prepareStatement(sqlupdateZg);
			ps.setObject(1, lkWt);
			ps.setObject(2, lkNum * cutNum);
			ps.setObject(3, "1");
			ps.setObject(4, proPlanId);
			ps.setObject(5, gxPlanNo);
			ps.executeUpdate();
			ps.close();

			// 新增利库记录表
			String sqlAdd = "INSERT INTO PLN_STEELFOR_ORD_LK (FURNACENO, PRO_PLAN_ID, GX_PLAN_NO, CREATE_TIME, MATCH_WT_IN, MATCH_NUM_IN, TOT_MUM_M, TOT_WEIGHT_M,CIC) "
					+ "VALUES  (?, ?, ?, SYSDATE, ?, ?, ?, ?,?)";
			ps = conn.prepareStatement(sqlAdd);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			ps.setObject(4, lkWt);
			ps.setObject(5, lkNum);
			ps.setObject(6, num);
			ps.setObject(7, wt);
			ps.setObject(8, entity.getCic());
			ps.executeUpdate();
			ps.close();

			// 如果全部余材量利库
			if (wt <= 0) {
				// 修改炉次订单余材状态
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET SURPLUSFLAG='0',SURPLUS_TYPE='', STATE_LK='1',TOT_MUM_M=?,TOT_WEIGHT_M=?,"
						+ "PRO_PLAN_ID='#PRO_PLAN_ID#',GX_PLAN_NO='#GX_PLAN_NO#',ORDER_NO='#ORDER_NO#',FINAL_USER_DESC='#FINAL_USER_DESC#',STEELCODE='#STEELCODE#',"
						+ "STEELNAME='#STEELNAME#',PRODUCCODE='#PRODUCCODE#',PRODUCNAME='#PRODUCNAME#',GOWHERE_CODE='#GOWHERE_CODE#',GOWHERE_NAME='#GOWHERE_NAME#',"
						+ "CIC='#CIC#',LEN_GP_SINGLE='#LEN_GP_SINGLE#',CUT_NUM_GP='#CUT_NUM_GP#',LENGTH_M='#LENGTH_M#',WEIGHT_GP_ONE='#WEIGHT_GP_ONE#',WEIGHT_M='#WEIGHT_M#',"
						+ " IF_MONITOR_LG='#IF_MONITOR_LG#',PRDCR_NO='#PRDCR_NO#'"
						+ " WHERE FURNACENO='#FURNACENO#' AND SEQUENCENO='#SEQUENCENO#'";
				String update = EntityTool.fillSqlByEntity(sqlupdatef, entity);
				ps = conn.prepareStatement(update);
				ps.setObject(1, lkNum);
				ps.setObject(2, lkWt);
				ps.executeUpdate();
				ps.close();
			} else {
				int sequenceno1 = FrmSteelMerge.getMaxSequenceno(conn,
						furnaceno);// 查询最大炉次内顺序号
				int cutNumno = Integer.parseInt(entity.getCutNum());// 查询炉次内最大分切
				int ccmSeq = Integer.parseInt(entity.getCcmSeq());
				String judgeStoveNo = entity.getJudgeStoveNo();
				String judgeStoveNoSeq = entity.getJudgeStoveNoSeq();
				String flagStoveNo = entity.getFlagStoveNo();
				if (!entity.getStatus().equals("00")) {
					if (cutNumno == 1) {
						String JudgeStoveNo = new StoveNoGenerate()
								.GetNewJudgeStove(entity.getEfPlineCode(),
										entity.getStoveNo(),
										Long.parseLong(String
												.valueOf(cutNumno + 1)), entity
												.getProMonth());
						judgeStoveNo = JudgeStoveNo;
						judgeStoveNoSeq = JudgeStoveNo + "-01";
						flagStoveNo = ("C001".endsWith(entity.getEfPlineCode())
								&& cutNumno == 1 ? "0" : cutNumno)
								+ entity.getStoveNo().substring(
										entity.getStoveNo().length() - 6);
					}
				}
				// 修改余材量
				String update = "UPDATE PLN_STEELFOR_ORD T SET T.TOT_MUM_M= TO_NUMBER(?), "
						+ " T.TOT_WEIGHT_M = TO_NUMBER(?),T.JUDGE_STOVE_NO=?,T.JUDGE_STOVE_NO_SEQ=?,T.FLAG_STOVE_NO=?"
						+ " WHERE T.FURNACENO = ? AND T.SEQUENCENO = ?";
				ps = conn.prepareStatement(update);
				ps.setObject(1, num);
				ps.setObject(2, wt);
				ps.setObject(3, judgeStoveNo);
				ps.setObject(4, judgeStoveNoSeq);
				ps.setObject(5, flagStoveNo);
				ps.setObject(6, furnaceno);
				ps.setObject(7, sequenceno);
				ps.executeUpdate();
				ps.close();

				// 更新序號
				FrmSteeSerialPublic.seqIncreaseOrdDeleteSeq(conn, steelordList
						.get(0).getPlineCode(), 1, cutNumno, furnaceno);
				FrmSteeSerialPublic.seqIncreaseOrd(conn, entity.getPlineCode(),
						ccmSeq, 1, -1);
				entity.setMakeman(name);
				// entity.setProMonth(dFormat.format(df.parse(dateTime)));
				entity.setTotMumM(String.valueOf(lkNum));
				entity.setTotWeightM(String.valueOf(lkWt));
				entity.setCcmSeq(String.valueOf(ccmSeq));
				entity.setSequenceno(String.valueOf(sequenceno1));
				entity.setCutNum(String.valueOf(cutNumno));
				entity.setSurplusflag("0");
				entity.setSurplusType("");
				if (!entity.getStatus().equals("00")) {
					String JudgeStoveNo = new StoveNoGenerate()
							.GetNewJudgeStove(entity.getEfPlineCode(),
									entity.getStoveNo(),
									Long.parseLong(String.valueOf(cutNumno)),
									entity.getProMonth());
					entity.setJudgeStoveNo(JudgeStoveNo);
					entity.setJudgeStoveNoSeq(JudgeStoveNo + "-01");
					entity.setFlagStoveNo(("C001".endsWith(entity
							.getEfPlineCode()) && cutNumno == 1 ? "0"
							: cutNumno)
							+ entity.getStoveNo().substring(
									entity.getStoveNo().length() - 6));
				}
				// 新增炉次订单量
				String sqlupdatef = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("FrmSteelPlnZg.AddFurnOrd"), entity);
				ps = conn.prepareStatement(sqlupdatef);
				ps.executeUpdate();
				ps.close();
			}
			if (entity.getIfConfirm().equals("1")) {
				String mess = ComPlanFurnace.addPlnSteelOrd(conn,
						entity.getFurnaceno(), entity.getSequenceno(), name);
				if (!mess.equals("")) {
					cro.setV_errMsg(mess);
					return cro;
				}
			}
			// if (falg.equals("1")) {
			// 修改爐次cic
			String updatef = "UPDATE PLN_STEELFORFURNACE T SET T.CIC='"
					+ ciclc
					+ "',T.QUANTITY=(SELECT SUM(TOT_MUM_M)  FROM PLN_STEELFOR_ORD WHERE FURNACENO='"
					+ furnaceno + "') WHERE T.FURNACENO='" + furnaceno + "'";
			ps = conn.prepareStatement(updatef);
			ps.executeUpdate();
			ps.close();
			// 修改浇次
			String updatecast = "UPDATE PLN_STEELFORCAST T SET T.TOT_NUM=(SELECT SUM(QUANTITY) FROM PLN_STEELFORFURNACE WHERE CAST_NO='"
					+ entity.getCastNo()
					+ "') WHERE T.CAST_NO='"
					+ entity.getCastNo() + "'";
			ps = conn.prepareStatement(updatecast);
			ps.executeUpdate();
			ps.close();

			// }
			if (seleTab.equals("2")) {
				double castWt = 0;
				int castNum = 0;
				String queryZz = "SELECT T.PRO_PLAN_ID,T.GX_PLAN_NO,TO_NUMBER(T.PLAN_WT_S) - TO_NUMBER(NVL(T.PLANED_WT, 0))-TO_NUMBER(NVL(T.PLAN_WT_SOLD, '0')) CAST_WT,"
						+ " TO_NUMBER(T.PLAN_NUM_S) - TO_NUMBER(NVL(T.PLANED_NUM, 0))-TO_NUMBER(NVL(T.PLAN_NUM_SOLD, '0')) CAST_NUM FROM PLN_ORDER_CAST_S T WHERE "
						+ " T.PRO_PLAN_ID=? AND TO_NUMBER(T.PLAN_WT_S)-TO_NUMBER(NVL(T.PLANED_WT,0))>0 "
						+ " ORDER BY T.PLAN_WT_S ASC";
				ps = conn.prepareStatement(queryZz);
				ps.setObject(1, gpreqId);
				rs = ps.executeQuery();
				while (rs.next()) {
					if (lkWt > rs.getDouble("CAST_WT")) {
						castWt = rs.getDouble("CAST_WT");
						castNum = rs.getInt("CAST_NUM");
					} else if (lkWt < rs.getDouble("CAST_WT")) {
						castWt = lkWt;
						castNum = lkNum;
					}
					if (lkWt != 0) {
						// 修改铸造订单待冶炼量
						String updatcastS = "UPDATE PLN_ORDER_CAST_S T SET T.PLAN_WT_SOLD=TO_NUMBER(NVL(T.PLAN_WT_SOLD,0))+TO_NUMBER(?),"
								+ "T.PLAN_NUM_SOLD =TO_NUMBER(NVL(T.PLAN_NUM_SOLD,0))+TO_NUMBER(?) WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
						ps = conn.prepareStatement(updatcastS);
						ps.setObject(1, castWt);
						ps.setObject(2, castNum);
						ps.setObject(3, gpreqId);
						ps.setObject(4, rs.getString("GX_PLAN_NO"));
						ps.executeUpdate();
						ps.close();
						lkWt = lkWt - castWt;
						lkNum = lkNum - castNum;
					} else {
						continue;
					}
				}
				rs.close();
				ps.close();

			}
			// 更新目标钢水量
			FrmSteelMerge.updatePlanOrder(conn, entity.getCastNo());
			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 list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doAddCast(ArrayList<String> jsonList,
			String furnaceno, String sequenceno, String name, String ciclc,
			String falg) 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;
			// 获取数据库当前时间
			// String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
			// SimpleDateFormat df = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			double toWeightM = 0;
			int toNumM = 0;
			int cutNumGp = 0;// 倍尺数
			// 查询炉次订单余材信息
			String sqlfurn = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlfurn += " AND T.SEQUENCENO=?";
			ps = conn.prepareStatement(sqlfurn);
			ps.setObject(1, furnaceno);
			ps.setObject(2, sequenceno);
			rs = ps.executeQuery();
			List<PlnSteelforOrdEntity> steelordList = EntityTool
					.getEntitysByRs(rs, PlnSteelforOrdEntity.class);
			rs.close();
			ps.close();
			if (steelordList == null || steelordList.size() == 0) {
				cro.setV_errMsg("无炉次余材订单信息,请刷新!");
				return cro;
			}
			PlnSteelforOrdEntity entity = steelordList.get(0);
			toWeightM = Double.parseDouble(entity.getTotWeightM());
			toNumM = Integer.parseInt(entity.getTotMumM());
			cutNumGp = Integer.parseInt(entity.getCutNumGp());
			if (!entity.getStatus().equals("00")
					&& !entity.getStatus().equals("10")) {
				cro.setV_errMsg("炉次订单已不是编制中/下发状态!");
				return cro;
			}

			String proPlanId = jsonList.get(0);
			String gxPlanNo = jsonList.get(1);

			int matchNum = 0;// 冶炼支
			double matchWt = 0;// 冶炼量

			PlnOrderCastSEntity entity1 = ControlOrderPlan.getOrderCastById(
					conn, proPlanId, gxPlanNo);
			if (entity1 == null) {
				cro.setV_errMsg("铸造数据异常,请刷新数据!");
				return cro;
			}
			if (Double.parseDouble(entity1.getCanWgt()) <= 0) {
				cro.setV_errMsg("可组炉重量为0,请刷新数据!");
				return cro;
			}
			if (Integer.parseInt(entity1.getExeStatus()) > 1) {
				cro.setV_errMsg("铸造订单(" + entity1.getProPlanId() + "/"
						+ entity1.getGxPlanNo() + "),不是计划和生产中的状态!");
				return cro;
			}

			matchWt = Double.parseDouble(entity1.getCanWgt());
			if (matchWt == 0) {// 轧管可利库吨
				cro.setV_errMsg("铸造订单号:" + proPlanId + "/" + gxPlanNo
						+ ",待冶炼量为0或已组浇!");
				return cro;
			}
			String[] pram = FrmSteelMakingPlanChange
					.getOrderUser(conn, entity1);
			entity.setLenGpSingle(entity1.getLenGpSingle());
			entity.setCutNumGp(entity1.getCutNumGp());
			entity.setLengthM(entity1.getLengthLz());
			entity.setWeightM(entity1.getWtCastOne());
			entity.setCic(entity1.getCic());
			entity.setSurplusflag("1");
			entity.setMemo("");
			entity.setProPlanId(entity1.getProPlanId());
			entity.setGxPlanNo(entity1.getGxPlanNo());
			entity.setOrderNo(pram[0]);
			entity.setFinalUserDesc(pram[1]);
			entity.setSteelcode(pram[4]);
			entity.setSteelname(pram[5]);
			entity.setProduccode(pram[6]);
			entity.setProducname(pram[7]);
			entity.setGowhereCode(pram[2]);
			entity.setGowhereName(pram[3]);
			if (entity1.getIfMonitorLg().equals("0")) {
				entity.setIfMonitorLg("/");
			} else {
				entity.setIfMonitorLg("是");
			}
			entity.setPrdcrNo(entity1.getPrdcrNo());
			double weightM1 = 0;
			double weightM = 0;
			if (entity.getGptype().equals("1")) {
				double dimater1 = Double.parseDouble(entity1.getDiameterLz());
				double mSingleWeight1 = (7.8 * Pi / 4 * dimater1 * dimater1) / 1000 / 1000;
				// 倍尺坯单支重=坯米单重*倍尺坯长/1000
				weightM1 = mSingleWeight1
						* (Double.parseDouble(entity1.getLengthLz()) / 1000);
				double dimater = Double.parseDouble(entity.getDiameter());
				double mSingleWeight = (7.8 * Pi / 4 * dimater * dimater) / 1000 / 1000;
				// 倍尺坯单支重=坯米单重*倍尺坯长/1000
				weightM = mSingleWeight
						* (Double.parseDouble(entity.getLengthM()) / 1000);
			} else {
				weightM1 = Double.parseDouble(entity1.getWtCastOne());
				weightM = Double.parseDouble(entity.getWeightM());
			}
			int gpreqNum = 0;// 可组炉支
			double gpreqWeight = 0;// 可组炉吨
			matchNum = Integer.parseInt(entity1.getCanNum());
			double wt = 0;// 余材剩余量
			int num = 0;// 余材剩余支
			toNumM = (int) Math.ceil(toWeightM / weightM1);
			if (toNumM == 0) {
				toNumM = 1;
			}
			// 如果余材量小于冶炼吨
			if (toWeightM - matchWt < 0.000002) {
				gpreqWeight = toWeightM;
				// 可组炉支=余材吨/利库铸造倍尺坯重
				gpreqNum = toNumM;
				gpreqWeight = weightM1 * toNumM;
				if (toNumM == matchNum) {// 如果利库支等于余材支
					gpreqWeight = matchWt;
				}
				if (gpreqWeight > matchWt) {
					gpreqWeight = matchWt;
					gpreqNum = matchNum;
				}
			} else {
				gpreqWeight = matchWt;
				gpreqNum = matchNum;
				// gpreqWeight = gpreqNum * weightM;
				// if(matchWt-gpreqWeight<0.00002){
				//
				// }
			}
			if (gpreqNum == 0) {
				gpreqNum = 1;
			}
			wt = toWeightM - gpreqWeight;
			// num = toNumM - gpreqNum;
			num = (int) Math.ceil(wt / weightM);
			wt = num * weightM;
			// 修改铸造订单已组炉量
			String updatcastS = "UPDATE PLN_ORDER_CAST_S T SET T.PLAN_WT_SOLD=TO_NUMBER(NVL(T.PLAN_WT_SOLD,0))+TO_NUMBER(?),"
					+ " T.PLAN_NUM_SOLD =TO_NUMBER(NVL(T.PLAN_NUM_SOLD,0))+TO_NUMBER(?) WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
			ps = conn.prepareStatement(updatcastS);
			ps.setObject(1, gpreqWeight);
			ps.setObject(2, gpreqNum);
			ps.setObject(3, proPlanId);
			ps.setObject(4, gxPlanNo);
			ps.executeUpdate();
			ps.close();

			// 新增利库记录表
			String sqlAdd = "INSERT INTO PLN_STEELFOR_ORD_LK (FURNACENO, PRO_PLAN_ID, GX_PLAN_NO, CREATE_TIME, MATCH_WT_IN, MATCH_NUM_IN, TOT_MUM_M, TOT_WEIGHT_M,CIC) "
					+ "VALUES  (?, ?, ?, SYSDATE, ?, ?, ?, ?,?)";
			ps = conn.prepareStatement(sqlAdd);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			ps.setObject(4, gpreqWeight);
			ps.setObject(5, gpreqNum);
			ps.setObject(6, num);
			ps.setObject(7, wt);
			ps.setObject(8, entity.getCic());
			ps.executeUpdate();
			ps.close();
			entity.setTotMumM(String.valueOf(gpreqNum));
			// 如果全部余材量利库
			if (wt <= 0) {
				// 修改炉次订单余材状态
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET SURPLUSFLAG='0',SURPLUS_TYPE='', STATE_LK='1',TOT_MUM_M=?,TOT_WEIGHT_M=?,"
						+ "PRO_PLAN_ID='#PRO_PLAN_ID#',GX_PLAN_NO='#GX_PLAN_NO#',ORDER_NO='#ORDER_NO#',FINAL_USER_DESC='#FINAL_USER_DESC#',STEELCODE='#STEELCODE#',"
						+ "STEELNAME='#STEELNAME#',PRODUCCODE='#PRODUCCODE#',PRODUCNAME='#PRODUCNAME#',GOWHERE_CODE='#GOWHERE_CODE#',GOWHERE_NAME='#GOWHERE_NAME#',"
						+ "CIC='#CIC#',LEN_GP_SINGLE='#LEN_GP_SINGLE#',CUT_NUM_GP='#CUT_NUM_GP#',LENGTH_M='#LENGTH_M#',WEIGHT_GP_ONE='#WEIGHT_GP_ONE#',WEIGHT_M='#WEIGHT_M#' "
						+ "WHERE FURNACENO='#FURNACENO#' AND SEQUENCENO='#SEQUENCENO#'";
				String update = EntityTool.fillSqlByEntity(sqlupdatef, entity);
				ps = conn.prepareStatement(update);
				ps.setObject(1, gpreqNum);
				ps.setObject(2, gpreqWeight);
				ps.executeUpdate();
				ps.close();
			} else {
				int sequenceno1 = FrmSteelMerge.getMaxSequenceno(conn,
						furnaceno);// 查询最大炉次内顺序号
				int cutNumno = Integer.parseInt(entity.getCutNum());// 查询炉次内最大分切
				int ccmSeq = Integer.parseInt(entity.getCcmSeq());
				String judgeStoveNo = entity.getJudgeStoveNo();
				String judgeStoveNoSeq = entity.getJudgeStoveNoSeq();
				String flagStoveNo = entity.getFlagStoveNo();
				if (!entity.getStatus().equals("00")) {
					if (cutNumno == 1) {
						String JudgeStoveNo = new StoveNoGenerate()
								.GetNewJudgeStove(entity.getEfPlineCode(),
										entity.getStoveNo(),
										Long.parseLong(String
												.valueOf(cutNumno + 1)), entity
												.getProMonth());
						judgeStoveNo = JudgeStoveNo;
						judgeStoveNoSeq = JudgeStoveNo + "-01";
						flagStoveNo = ("C001".endsWith(entity.getEfPlineCode())
								&& cutNumno == 1 ? "0" : cutNumno)
								+ entity.getStoveNo().substring(
										entity.getStoveNo().length() - 6);
					}
				}
				// 修改余材量
				String update = "UPDATE PLN_STEELFOR_ORD T SET T.TOT_MUM_M= TO_NUMBER(?), "
						+ " T.TOT_WEIGHT_M = TO_NUMBER(?),T.JUDGE_STOVE_NO=?,T.JUDGE_STOVE_NO_SEQ=?,T.FLAG_STOVE_NO=?"
						+ " WHERE T.FURNACENO = ? AND T.SEQUENCENO = ?";
				ps = conn.prepareStatement(update);
				ps.setObject(1, num);
				ps.setObject(2, wt);
				ps.setObject(3, judgeStoveNo);
				ps.setObject(4, judgeStoveNoSeq);
				ps.setObject(5, flagStoveNo);
				ps.setObject(6, furnaceno);
				ps.setObject(7, sequenceno);
				ps.executeUpdate();
				ps.close();

				// 更新序號
				FrmSteeSerialPublic.seqIncreaseOrdDeleteSeq(conn, steelordList
						.get(0).getPlineCode(), 1, cutNumno, furnaceno);
				FrmSteeSerialPublic.seqIncreaseOrd(conn, entity.getPlineCode(),
						ccmSeq, 1, -1);
				entity.setMakeman(name);
				// entity.setProMonth(dFormat.format(df.parse(dateTime)));
				entity.setTotMumM(String.valueOf(gpreqNum));
				entity.setTotWeightM(String.valueOf(gpreqWeight));
				entity.setCcmSeq(String.valueOf(ccmSeq));
				entity.setSequenceno(String.valueOf(sequenceno1));
				entity.setProPlanId(proPlanId);
				entity.setGxPlanNo(gxPlanNo);
				entity.setSurplusflag("0");
				entity.setSurplusType("");
				entity.setCutNum(String.valueOf(cutNumno));
				if (!entity.getStatus().equals("00")) {
					String JudgeStoveNo = new StoveNoGenerate()
							.GetNewJudgeStove(entity.getEfPlineCode(),
									entity.getStoveNo(),
									Long.parseLong(String.valueOf(cutNumno)),
									entity.getProMonth());
					entity.setJudgeStoveNo(JudgeStoveNo);
					entity.setJudgeStoveNoSeq(JudgeStoveNo + "-01");
					entity.setFlagStoveNo(("C001".endsWith(entity
							.getEfPlineCode()) && cutNumno == 1 ? "0"
							: cutNumno)
							+ entity.getStoveNo().substring(
									entity.getStoveNo().length() - 6));
				}
				// 新增炉次订单量
				String sqlupdatef = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("FrmSteelPlnZg.AddFurnOrd"), entity);
				ps = conn.prepareStatement(sqlupdatef);
				ps.executeUpdate();
				ps.close();

			}
			if (entity.getIfConfirm().equals("1")) {
				String mess = ComPlanFurnace.addPlnSteelOrd(conn,
						entity.getFurnaceno(), entity.getSequenceno(), name);
				if (!mess.equals("")) {
					cro.setV_errMsg(mess);
					return cro;
				}
			}
			// 修改爐次cic
			String updatef = "UPDATE PLN_STEELFORFURNACE T SET T.CIC='"
					+ ciclc
					+ "',T.QUANTITY=(SELECT SUM(TOT_MUM_M)  FROM PLN_STEELFOR_ORD WHERE FURNACENO='"
					+ furnaceno + "') WHERE T.FURNACENO='" + furnaceno + "'";
			ps = conn.prepareStatement(updatef);
			ps.executeUpdate();
			ps.close();
			// 修改浇次
			String updatecast = "UPDATE PLN_STEELFORCAST T SET T.TOT_NUM=(SELECT SUM(QUANTITY) FROM PLN_STEELFORFURNACE WHERE CAST_NO='"
					+ entity.getCastNo()
					+ "') WHERE T.CAST_NO='"
					+ entity.getCastNo() + "'";
			ps = conn.prepareStatement(updatecast);
			ps.executeUpdate();
			ps.close();
			// 更新目标钢水量
			FrmSteelMerge.updatePlanOrder(conn, entity.getCastNo());
			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 list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doDeleteLibrary(ArrayList<String> jsonList)
			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;
			// 获取数据库当前时间
			// String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
			// SimpleDateFormat df = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			String furnaceno = jsonList.get(0);
			String sequenceno = jsonList.get(1);
			String proPlanId = jsonList.get(2);
			String gxPlanNo = jsonList.get(3);
			int cutNumGp = 0;// 倍尺数
			// 查询炉次订单信息
			String sqlfurn = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlfurn += " AND T.SEQUENCENO=?";
			ps = conn.prepareStatement(sqlfurn);
			ps.setObject(1, furnaceno);
			ps.setObject(2, sequenceno);
			rs = ps.executeQuery();
			List<PlnSteelforOrdEntity> steelordList = EntityTool
					.getEntitysByRs(rs, PlnSteelforOrdEntity.class);
			rs.close();
			ps.close();
			if (steelordList == null || steelordList.size() == 0) {
				cro.setV_errMsg("无炉次订单信息,请刷新!");
				return cro;
			}
			PlnSteelforOrdEntity entity = steelordList.get(0);
			if (!entity.getStatus().equals("00")
					&& !entity.getStatus().equals("10")) {
				cro.setV_errMsg("炉次订单不是编制中/下发状态!");
				return cro;
			}
			cutNumGp = Integer.parseInt(entity.getCutNumGp());
			// int matchNum1 = 0;// 轧管利库支
			double matchWt2 = 0;// 轧管利库吨
			String start = "";
			String gperdId = "";
			// 查询轧管排产计划
			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryPlnOrderZgS");
			ps = conn.prepareStatement(sql);
			ps.setObject(1, proPlanId);
			ps.setObject(2, gxPlanNo);
			rs = ps.executeQuery();
			if (rs.next()) {

				if (!rs.getString("EXE_STATUS").equals("0")) {
					cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
							+ "不是计划状态,不能撤销利轧管计划!");
					return cro;
				}
				// if (rs.getString("IS_PLAN_OK") == null
				// || rs.getString("IS_PLAN_OK").equals("0")) {
				// cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
				// + ",未轧管确认,不能撤销利轧管计划!!");
				// return cro;
				// }
				if (rs.getString("GPREQ_ID") != null) {
					gperdId = rs.getString("GPREQ_ID");
					// cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
					// + ",已生成管坯需求,不能撤销利轧管计划!");
					// return cro;
				}
				// matchNum1 = rs.getInt("MATCH_NUM_IN");
				matchWt2 = rs.getDouble("MATCH_WT_IN");
				start = rs.getString("STATE_SINGLE");
			} else {
				cro.setV_errMsg("轧管订单排产数据发生变化,请刷新");
				return cro;
			}
			rs.close();
			ps.close();

			double toWeightM = 0;
			int toNumM = 0;//
			int matchNum = 0;
			double matchWt = 0;

			String cic = "";

			// 根据炉次，订单号，排产序号查询利库记录
			String sqlQuery = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryLk");
			ps = conn.prepareStatement(sqlQuery);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			rs = ps.executeQuery();
			if (rs.next()) {
				matchNum = rs.getInt("MATCH_NUM_IN");
				matchWt = rs.getDouble("MATCH_WT_IN");
				toNumM = rs.getInt("TOT_MUM_M");
				toWeightM = rs.getDouble("TOT_WEIGHT_M");
				cic = rs.getString("CIC");
			}
			rs.close();
			ps.close();
			double lkcastWt = matchWt;
			int lkcastNum = matchNum;
			String ifgperdId = "";
			// 查询是否利的已生成管坯需求轧管订单
			String sqlQueryZg = "SELECT T.PRO_PLAN_ID, T.GX_PLAN_NO,TO_NUMBER(T.PLAN_WT_S) - TO_NUMBER(NVL(T.PLANED_WT, 0))-TO_NUMBER(NVL(T.PLAN_WT_SOLD, '0')) CAST_WT, "
					+ "TO_NUMBER(T.PLAN_NUM_S) - TO_NUMBER(NVL(T.PLANED_NUM, 0))-TO_NUMBER(NVL(T.PLAN_NUM_SOLD, '0')) CAST_NUM,T.PLAN_WT_SOLD,T.PLAN_NUM_SOLD "
					+ "FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID = ? "
					+ "AND T.PLAN_WT_SOLD IS NOT NULL AND T.PLAN_WT_SOLD > 0 ORDER BY T.PLAN_WT_SOLD ASC";
			ps = conn.prepareStatement(sqlQueryZg);
			ps.setObject(1, gperdId);
			rs = ps.executeQuery();
			while (rs.next()) {
				ifgperdId = "1";
				double castWt = 0;
				int castNum = 0;
				if (lkcastWt - rs.getDouble("PLAN_WT_SOLD") > 0) {
					castWt = rs.getDouble("PLAN_WT_SOLD");
					castNum = rs.getInt("PLAN_NUM_SOLD");
				} else if (lkcastWt - rs.getDouble("PLAN_WT_SOLD") <= 0) {
					castWt = lkcastWt;
					castNum = lkcastNum;
				}
				if (lkcastWt != 0) {
					// 修改铸造订单待冶炼量
					String updatcastS = "UPDATE PLN_ORDER_CAST_S T SET  T.PLAN_WT_SOLD=TO_NUMBER(NVL(T.PLAN_WT_SOLD,0))-TO_NUMBER(?),"
							+ " T.PLAN_NUM_SOLD =TO_NUMBER(NVL(T.PLAN_NUM_SOLD,0))-TO_NUMBER(?) WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
					ps = conn.prepareStatement(updatcastS);
					ps.setObject(1, castWt);
					ps.setObject(2, castNum);
					ps.setObject(3, gperdId);
					ps.setObject(4, rs.getString("GX_PLAN_NO"));
					ps.executeUpdate();
					ps.close();
					lkcastWt = lkcastWt - castWt;
					lkcastNum = lkcastNum - castNum;
				} else {
					continue;
				}
			}
			rs.close();
			ps.close();
			if (ifgperdId.equals("") && !gperdId.equals("")) {
				// cro.setV_errMsg("轧管订单号:" + proPlanId + "/" + gxPlanNo
				// + ",已生成管坯需求,不能撤销利轧管计划!");
				// return cro;
			}
			// 判断是否有利计划剩余
			double matchWtSy = matchWt2 - matchWt;
			if (matchWtSy == 0) {
				start = "0";
			}
			// 修改轧管订单利库量
			String sqlupdateZg = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.updarePlnOrderZgS");
			ps = conn.prepareStatement(sqlupdateZg);
			ps.setObject(1, -matchWt);
			ps.setObject(2, -matchNum * cutNumGp);
			ps.setObject(3, start);
			ps.setObject(4, proPlanId);
			ps.setObject(5, gxPlanNo);
			ps.executeUpdate();
			ps.close();

			// 删除利库记录表
			String sqldelete = "DELETE PLN_STEELFOR_ORD_LK WHERE FURNACENO = ? AND PRO_PLAN_ID = ? AND GX_PLAN_NO = ?";
			ps = conn.prepareStatement(sqldelete);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			ps.executeUpdate();
			ps.close();

			if (entity.getIfConfirm().equals("1")) {
				String mess = ComPlanFurnace.deleteSteelOrd(conn,
						entity.getFurnaceno(), entity.getSequenceno());
				if (!mess.equals("")) {
					cro.setV_errMsg(mess);
					return cro;
				}
			}
			// 查询是否存在同CIC,钢种的余材信息
			String sqlyc = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlyc += " AND T.SURPLUS_TYPE='1' AND T.CIC='" + entity.getCic()
					+ "' AND T.GRADECODE ='" + entity.getGradecode() + "'";
			PreparedStatement psyc = conn.prepareStatement(sqlyc);
			psyc.setObject(1, furnaceno);
			ResultSet rsyc = psyc.executeQuery();
			if (rsyc.next()) {
				// 存在
				// 修改余材量
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET TOT_MUM_M=TO_NUMBER(NVL(TOT_MUM_M,0))+TO_NUMBER(?) ,TOT_WEIGHT_M=TO_NUMBER(NVL(TOT_WEIGHT_M,0))+TO_NUMBER(?)"
						+ "WHERE FURNACENO=? AND SEQUENCENO=?";
				ps = conn.prepareStatement(sqlupdatef);
				ps.setObject(1, matchNum);
				ps.setObject(2, matchWt);
				ps.setObject(3, rsyc.getString("FURNACENO"));
				ps.setObject(4, rsyc.getString("SEQUENCENO"));
				ps.executeUpdate();
				ps.close();
				// 删除撤销利库炉次订单
				String sqlDelete = "DELETE PLN_STEELFOR_ORD  WHERE FURNACENO = ? AND SEQUENCENO = ?";
				ps = conn.prepareStatement(sqlDelete);
				ps.setObject(1, furnaceno);
				ps.setObject(2, sequenceno);
				ps.executeUpdate();
				ps.close();
				FrmSteeSerialPublic.seqIncreaseOrd(conn, entity.getPlineCode(),
						Integer.parseInt(entity.getCcmSeq()), -1, 1);
				FrmSteeSerialPublic.seqIncreaseOrdDeleteSeq(conn, steelordList
						.get(0).getPlineCode(), -1, Integer.parseInt(entity
						.getCutNum()), furnaceno);

			} else {
				// 修改炉次订单余材状态
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET SURPLUSFLAG='1',SURPLUS_TYPE='1', STATE_LK='0',"
						+ "ORDER_NO='',FINAL_USER_DESC='备料',STEELCODE='',"
						+ "STEELNAME='',PRODUCCODE='',PRODUCNAME='',GOWHERE_CODE='',GOWHERE_NAME='离线库',CIC='"
						+ cic + "'" + "WHERE FURNACENO=? AND SEQUENCENO=?";
				ps = conn.prepareStatement(sqlupdatef);
				ps.setObject(1, furnaceno);
				ps.setObject(2, sequenceno);
				ps.executeUpdate();
				ps.close();
			}
			rsyc.close();
			psyc.close();
			String ciclc = "";
			// 查詢是否一個索引碼
			sqlQuery = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryCicALLFurnOed");
			ps = conn.prepareStatement(sqlQuery);
			ps.setObject(1, furnaceno);
			rs = ps.executeQuery();
			if (rs.next()) {
				ciclc = rs.getString("CIC");
			}
			rs.close();
			ps.close();

			// 修改爐次cic
			String updatef = "UPDATE PLN_STEELFORFURNACE T SET T.CIC='"
					+ ciclc
					+ "',T.QUANTITY=(SELECT SUM(TOT_MUM_M)  FROM PLN_STEELFOR_ORD WHERE FURNACENO='"
					+ furnaceno + "') WHERE T.FURNACENO='" + furnaceno + "'";
			ps = conn.prepareStatement(updatef);
			ps.executeUpdate();
			ps.close();
			// 修改浇次
			String updatecast = "UPDATE PLN_STEELFORCAST T SET T.TOT_NUM=(SELECT SUM(QUANTITY) FROM PLN_STEELFORFURNACE WHERE CAST_NO='"
					+ entity.getCastNo()
					+ "') WHERE T.CAST_NO='"
					+ entity.getCastNo() + "'";
			ps = conn.prepareStatement(updatecast);
			ps.executeUpdate();
			ps.close();
			// 更新目标钢水量
			FrmSteelMerge.updatePlanOrder(conn, entity.getCastNo());
			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 list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doDeleteCast(ArrayList<String> jsonList)
			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;
			// 获取数据库当前时间
			String furnaceno = jsonList.get(0);
			String sequenceno = jsonList.get(1);
			String proPlanId = jsonList.get(2);
			String gxPlanNo = jsonList.get(3);
			// 查询炉次订单信息
			String sqlfurn = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlfurn += " AND T.SEQUENCENO=?";
			ps = conn.prepareStatement(sqlfurn);
			ps.setObject(1, furnaceno);
			ps.setObject(2, sequenceno);
			rs = ps.executeQuery();
			List<PlnSteelforOrdEntity> steelordList = EntityTool
					.getEntitysByRs(rs, PlnSteelforOrdEntity.class);
			rs.close();
			ps.close();
			if (steelordList == null || steelordList.size() == 0) {
				cro.setV_errMsg("无炉次订单信息,请刷新!");
				return cro;
			}
			PlnSteelforOrdEntity entity = steelordList.get(0);
			if (!entity.getStatus().equals("00")
					&& !entity.getStatus().equals("10")) {
				cro.setV_errMsg("炉次订单不是编制中/下发状态!");
				return cro;
			}
			// int matchNum1 = 0;// 轧管利库支
			double matchWt2 = 0;// 轧管利库吨
			String start = "";
			PlnOrderCastSEntity entity1 = ControlOrderPlan.getOrderCastById(
					conn, proPlanId, gxPlanNo);
			if (entity1 == null) {
				cro.setV_errMsg("铸造数据异常,请刷新数据!");
				return cro;
			}
			if (Integer.parseInt(entity1.getExeStatus()) > 1) {
				cro.setV_errMsg("铸造订单(" + entity1.getProPlanId() + "/"
						+ entity1.getGxPlanNo() + "),不是计划和生产中的状态!");
				return cro;
			}
			double toWeightM = 0;
			int toNumM = 0;//
			int matchNum = 0;
			double matchWt = 0;

			String cic = "";
			// 根据炉次，订单号，排产序号查询利库记录
			String sqlQuery = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryLk");
			ps = conn.prepareStatement(sqlQuery);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			rs = ps.executeQuery();
			if (rs.next()) {
				matchNum = rs.getInt("MATCH_NUM_IN");
				matchWt = rs.getDouble("MATCH_WT_IN");
				toNumM = rs.getInt("TOT_MUM_M");
				toWeightM = rs.getDouble("TOT_WEIGHT_M");
				cic = rs.getString("CIC");
			}
			rs.close();
			ps.close();

			// 判断是否有利计划剩余
			double matchWtSy = matchWt2 - matchWt;
			if (matchWtSy == 0) {
				start = "0";
			}
			// 修改铸造订单已组炉量
			String updatcastS = "UPDATE PLN_ORDER_CAST_S T SET  T.PLAN_WT_SOLD=TO_NUMBER(NVL(T.PLAN_WT_SOLD,0))-TO_NUMBER(?),"
					+ " T.PLAN_NUM_SOLD =TO_NUMBER(NVL(T.PLAN_NUM_SOLD,0))-TO_NUMBER(?) WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
			ps = conn.prepareStatement(updatcastS);
			ps.setObject(1, matchWt);
			ps.setObject(2, matchNum);
			ps.setObject(3, proPlanId);
			ps.setObject(4, gxPlanNo);
			ps.executeUpdate();
			ps.close();

			// 删除利库记录表
			String sqldelete = "DELETE PLN_STEELFOR_ORD_LK WHERE FURNACENO = ? AND PRO_PLAN_ID = ? AND GX_PLAN_NO = ?";
			ps = conn.prepareStatement(sqldelete);
			ps.setObject(1, furnaceno);
			ps.setObject(2, proPlanId);
			ps.setObject(3, gxPlanNo);
			ps.executeUpdate();
			ps.close();
			if (entity.getIfConfirm().equals("1")) {
				String mess = ComPlanFurnace.deleteSteelOrd(conn,
						entity.getFurnaceno(), entity.getSequenceno());
				if (!mess.equals("")) {
					cro.setV_errMsg(mess);
					return cro;
				}
			}
			// 查询是否存在同CIC,钢种的余材信息
			String sqlyc = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryFurnacaen");
			sqlyc += " AND T.SURPLUS_TYPE='1' AND T.CIC='" + entity.getCic()
					+ "' AND T.GRADECODE ='" + entity.getGradecode() + "'";
			PreparedStatement psyc = conn.prepareStatement(sqlyc);
			psyc.setObject(1, furnaceno);
			ResultSet rsyc = psyc.executeQuery();
			if (rsyc.next()) {
				// 存在
				// 修改余材量
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET TOT_MUM_M=TO_NUMBER(NVL(TOT_MUM_M,0))+TO_NUMBER(?) ,TOT_WEIGHT_M=TO_NUMBER(NVL(TOT_WEIGHT_M,0))+TO_NUMBER(?)"
						+ "WHERE FURNACENO=? AND SEQUENCENO=?";
				ps = conn.prepareStatement(sqlupdatef);
				ps.setObject(1, matchNum);
				ps.setObject(2, matchWt);
				ps.setObject(3, rsyc.getString("FURNACENO"));
				ps.setObject(4, rsyc.getString("SEQUENCENO"));
				ps.executeUpdate();
				ps.close();

				// 删除撤销利库炉次订单
				String sqlDelete = "DELETE PLN_STEELFOR_ORD  WHERE FURNACENO = ? AND SEQUENCENO = ?";
				ps = conn.prepareStatement(sqlDelete);
				ps.setObject(1, furnaceno);
				ps.setObject(2, sequenceno);
				ps.executeUpdate();
				ps.close();
				FrmSteeSerialPublic.seqIncreaseOrd(conn, entity.getPlineCode(),
						Integer.parseInt(entity.getCcmSeq()), -1, 1);
				FrmSteeSerialPublic.seqIncreaseOrdDeleteSeq(conn, steelordList
						.get(0).getPlineCode(), -1, Integer.parseInt(entity
						.getCutNum()), furnaceno);
			} else {
				// 修改炉次订单余材状态
				String sqlupdatef = "UPDATE PLN_STEELFOR_ORD SET SURPLUSFLAG='1',SURPLUS_TYPE='1', STATE_LK='0',"
						+ "ORDER_NO='',FINAL_USER_DESC='备料',STEELCODE='',"
						+ "STEELNAME='',PRODUCCODE='',PRODUCNAME='',GOWHERE_CODE='',GOWHERE_NAME='离线库',CIC='"
						+ cic + "'" + "WHERE FURNACENO=? AND SEQUENCENO=?";
				ps = conn.prepareStatement(sqlupdatef);
				ps.setObject(1, furnaceno);
				ps.setObject(2, sequenceno);
				ps.executeUpdate();
				ps.close();
			}
			rsyc.close();
			psyc.close();
			String ciclc = "";
			// 查詢是否一個索引碼
			sqlQuery = CoreXmlSqlParsersFactory
					.getSql("FrmSteelPlnZg.QueryCicALLFurnOed");
			ps = conn.prepareStatement(sqlQuery);
			ps.setObject(1, furnaceno);
			rs = ps.executeQuery();
			if (rs.next()) {
				ciclc = rs.getString("CIC");
			}
			rs.close();
			ps.close();

			// 修改爐次cic
			String updatef = "UPDATE PLN_STEELFORFURNACE T SET T.CIC='"
					+ ciclc
					+ "',T.QUANTITY=(SELECT SUM(TOT_MUM_M)  FROM PLN_STEELFOR_ORD WHERE FURNACENO='"
					+ furnaceno + "') WHERE T.FURNACENO='" + furnaceno + "'";
			ps = conn.prepareStatement(updatef);
			ps.executeUpdate();
			ps.close();
			// 修改浇次
			String updatecast = "UPDATE PLN_STEELFORCAST T SET T.TOT_NUM=(SELECT SUM(QUANTITY) FROM PLN_STEELFORFURNACE WHERE CAST_NO='"
					+ entity.getCastNo()
					+ "') WHERE T.CAST_NO='"
					+ entity.getCastNo() + "'";
			ps = conn.prepareStatement(updatecast);
			ps.executeUpdate();
			ps.close();
			// 更新目标钢水量
			FrmSteelMerge.updatePlanOrder(conn, entity.getCastNo());
			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 jsonStr
	 * @param processCode
	 * @return
	 */
	public CoreReturnObject setPlanFinish(ArrayList<String> jsonStr,
			String userName, String processCode) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			String message = setPlanFinish(con, jsonStr, userName, processCode);
			if (message.length() > 0) {
				core.setV_errMsg(message);
				return core;
			}
			core.setResult(true);
			core.setV_errMsg("设置铸造订单关闭成功!");
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null) {
					con.rollback();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 设置铸造订单关闭
	 * 
	 * @param con
	 * @param jsonStrList
	 * @param userName
	 * @param processCode
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 */
	public String setPlanFinish(Connection con, ArrayList<String> jsonStrList,
			String userName, String processCode) throws SQLException,
			ParseException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		String planTimeB = "2016-01-01 00:00:00";
		Date nowTime = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String timeStr = sf.format(nowTime);
		String memo = "手动设置铸造订单关闭  操作人:[" + userName + "] 操作时间:[ " + timeStr
				+ "]";
		ProducHelperBean helperBean = new ProducHelperBean();
		if (processCode.equals("B")) {
			List<PlnOrderCastSEntity> entityList = PlnHelper.jsonsToEntityList(
					PlnOrderCastSEntity.class, jsonStrList);

			int seq = 0;// 最小生产顺序
			String planTimeE = "";
			String plineCode = "";
			for (PlnOrderCastSEntity entity1 : entityList) {
				PlnOrderCastSEntity entity = ControlOrderPlan.getOrderCastById(
						con, entity1.getProPlanId(), entity1.getGxPlanNo());
				if (entity == null) {
					return "数据发生变化,请刷新数据!";
				}
				if (entity.getIsRepairPln().equals("1")) {
					return "检修计划不能设置关闭!";
				}
				if (Integer.parseInt(entity.getExeStatus()) > 2) {
					return "铸造订单(" + entity1.getProPlanId() + "/"
							+ entity1.getGxPlanNo() + ")已关闭!";
				}
				int gxProSeq = Integer.parseInt(entity.getGxProSeq());
				int zgExtrat = 0;
				// 查询轧管排产最小状态
				String sql = CoreXmlSqlParsersFactory
						.getSql("FrmSteelPlnZg.doPlnZgQueryStrat");
				ps = con.prepareStatement(sql);
				ps.setObject(1, entity1.getProPlanId());
				rs = ps.executeQuery();
				if (rs.next()) {
					zgExtrat = rs.getInt("COUNT");
					if (rs.getInt("EXE_STATUS") < 2) {
						// if (zgExtrat < 2) {
						return "管坯需求(" + entity1.getProPlanId()
								+ ")对应轧管订单信息有未生产完成数据!";
						// }
					}
				}
				rs.close();
				ps.close();

				if (seq == 0) {
					seq = gxProSeq;
				}
				if (seq > gxProSeq) {
					seq = gxProSeq;
					planTimeE = entity.getPlanTimeB();
					plineCode = entity.getPlineCode();
				}
				entity.setGxProSeq("-2");
				entity.setExeStatus("3");
				if (entity.getMemo() != null && !entity.getMemo().equals("")) {
					memo = "," + memo;
				}
				entity.setMemo(entity.getMemo() + memo);
				PlnHelper.deleteOrUpdateByEntity(con,
						"FrmSteelPlnZg.updatePlnOrderCast", entity);
				// 生产顺序调整
				helperBean.seqIncrease(con, entity.getPlineCode(), gxProSeq,
						-1, -1, processCode);

				// 修改管坯需求状态
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmSteelMakingPlanChange.updateReqinfGp");
				ps = con.prepareStatement(sql);
				ps.setObject(1, "3");
				ps.setObject(2, entity.getProPlanId());
				ps.executeUpdate();
				ps.close();
			}
			// 时间调整
			// helperBean
			// .timeIncrease(con, seq, plineCode, planTimeE, processCode);
		}
		return "";
	}
}
