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.List;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;

import com.steering.pss.plnsaleord.order.baseMethod.CoreOrdBase;
import com.steering.pss.plnsaleord.processOrder.base.ProducEntity;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.processOrder.entity.TimeEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnOrderCastSEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnSteelforcastEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnSteelforfurnaceEntity;
import com.steering.pss.plnsaleord.stove.ComPlanFurnace;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

/**
 * 生产订单类
 * 
 * @author Administrator
 */
public class ControlOrderPlan extends DBCommon {
	/**
	 * 查询铸造生产订单信息
	 * 
	 * @param plineCode
	 * @param year
	 * @param proPlanId
	 * @return
	 */
	public CoreReturnObject getOrderBInfo(String plineCode, String year,
			String proPlanId) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.getOrderBInfo");
		List<String> list = new ArrayList<String>();
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE=?";
			list.add(plineCode);
		}
		if (!year.equals("")) {
			sql += " AND T.PRO_MONTH=?";
			list.add(year);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID LIKE  '%'||?||'%' ";
			list.add(proPlanId);
		}
		return this.getData(sql, list.toArray());
	}

	/**
	 * 查询铸造生产订单信息(新界面用)
	 * 
	 * @param plineCodeA
	 *            电炉
	 * @param pineCodeB
	 *            铸机
	 * @param gradeCode
	 *            钢种
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getOrderBInfoByContion(String[] plineCodeA,
			String[] pineCodeB, String gradeCode, String proPlanId,
			String fiterStatus, String isRepairPln, String[] statusArray,
			String[] plineB, String gongy) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.getOrderBInfo");
		List<String> list = new ArrayList<String>();
		if (plineCodeA.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.PLINE_CODE_A",
					plineCodeA);
		}

		if (plineB.length <= 0) {
			sql += CoreConverter
					.toSqlConditionString("T.PLINE_CODE", pineCodeB);
		} else {
			sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineB);
		}
		if (!gradeCode.equals("")) {
			sql += " AND T.GRADECODE=?";
			list.add(gradeCode);
		}
		if (!proPlanId.equals("")) {
			sql += " and t.pro_plan_id like '%'||?||'%'";
			list.add(proPlanId);
		}
		// if (fiterStatus.equals("1")) {
		// if (isRepairPln.equals("0")) {
		// sql +=
		// " and TO_NUMBER(NVL(T.PLAN_WT_S,'0'))-TO_NUMBER(NVL(T.PLANED_WT,'0'))>0 ";
		// } else {
		// sql +=
		// "  and (TO_NUMBER(NVL(T.PLAN_WT_S, '0')) - TO_NUMBER(NVL(T.PLANED_WT, '0')) > 0 OR T.IS_REPAIR_PLN='1') ";
		// }
		// }
		if (isRepairPln.equals("0")) {
			sql += " AND (T.IS_REPAIR_PLN != '1' OR T.IS_REPAIR_PLN IS NULL)";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		if (gongy.equals("1")) {
			sql += " AND T.IS_PLAN_OK='1'";
		} else if (gongy.equals("0")) {
			sql += " AND (T.IS_PLAN_OK='0' OR T.IS_PLAN_OK IS NULL)";
		}
		sql += "  order by TO_NUMBER(T.GX_PRO_SEQ) ASC";
		return this.getData(sql, list.toArray());
	}

	/**
	 * 查询生产订单
	 * 
	 * @param con
	 * @param proPlanId
	 * @param gxPlanNo
	 * @return PlnOrderCastSEntity
	 * @throws SQLException
	 */
	public static PlnOrderCastSEntity getOrderCastById(Connection con,
			String proPlanId, String gxPlanNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.getOrderCastById");
		sql += "AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
		// sql+=" ORDER BY TO_NUMBER(NVL(T.PLAN_WT_S,0))-TO_NUMBER(NVL(T.PLANED_WT,0))";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, proPlanId);
		ps.setObject(2, gxPlanNo);
		ResultSet rs = ps.executeQuery();
		List<PlnOrderCastSEntity> list = EntityTool.getEntitysByRs(rs,
				PlnOrderCastSEntity.class);
		rs.close();
		ps.close();
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 根据断面查询铸造产线
	 * 
	 * @param plineCode
	 * @param year
	 * @param proPlanId
	 * @return
	 */
	public CoreReturnObject queryPlineCode(String diameter, String castingtype) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.queryPlineCode");
		if (castingtype.equals("连铸")) {
			diameter = diameter + ".00";
		}
		sql += " AND C.SPEC_NAME ='" + diameter + "'";
		sql += " GROUP BY C.PLINE_CODE, C.PLINE_NAME";
		sql += ") ORDER BY PLINE_CODE ASC";
		return this.getData(sql);
	}

	/**
	 * 铸造排产拆分
	 * 
	 * @param jsonStr
	 * @param spitWgt
	 *            拆分重量
	 * @param spitNum
	 *            拆分支数
	 * @param processCode
	 *            工序
	 * @return
	 */
	public CoreReturnObject spitPlanOrder(String jsonStr, String spitWgtStr,
			String spitNumStr, String processCode, String maxNumstr) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		try {
			double spitWgt = Double.parseDouble(spitWgtStr);
			int spitNum = Integer.parseInt(spitNumStr);
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			ProducHelperBean helperBean = new ProducHelperBean();
			ProducEntity proEntity = helperBean.genertionProEntity(con,
					jsonStr, processCode);
			/**
			 * 1.验证数据
			 */
			if (proEntity == null) {
				core.setV_errMsg("数据异常,请刷新数据!");
				return core;
			}
			// if (!processCode.equals("D")) {
			// if (proEntity.getIfStoveIssued().equals("1")) {
			// core.setV_errMsg("订单编号(" + proEntity.getProPlanId()
			// + ") 炉计划已经下发!");
			// return core;
			// }
			// }
			if (!proEntity.getExeStatus().equals("0")
					&& !proEntity.getExeStatus().equals("1")) {
				core.setV_errMsg("订单编号(" + proEntity.getProPlanId()
						+ ")/不是 (计划/生产中)执行状态!");
				return core;
			}
			// 1.2验证产线能力
			double[] capacity = helperBean.getPlineCapacity(con, proEntity
					.getInwlId(), proEntity.getOutwlId(), proEntity
					.getPlineCode(), processCode);

			if (capacity[0] <= 0) {
				if (!processCode.equals("B")) {
					core
							.setV_errMsg("订单编号(" + proEntity.getProPlanId()
									+ ")/产线(" + proEntity.getPlineName()
									+ ")没有维护产线能力!");
					return core;
				} else {
					capacity[0] = 0;
				}
			}
			double orglWgt = 0;// 剩余重量
			int orglNum = 0;// 剩余支数
			int numS1 = 0;// 产出剩余支数
			double weigthS1 = 0;// 产出剩余重量
			double weigthS = 0;// 总产出重量
			int numS = 0;// 总产出支数
			double weigthSMin = 0;
			double weigthSMin1 = 0;
			double inWegths = 0;
			int inNums = 0;
			weigthS = proEntity.getWeigthS();// 总投入重量
			numS = proEntity.getNumS();// 总投入支数
			// 1.1验证重量
			if (weigthS <= spitWgt) {
				core.setV_errMsg("订单编号(" + proEntity.getProPlanId()
						+ ")总重量大于、等于分配重量!");
				return core;
			} // 待冶炼量
			inWegths = proEntity.getInWeightS();
			// 待冶炼支
			inNums = proEntity.getInNumS();
			weigthSMin1 = proEntity.getWeigthSMin();
			// 产出剩余重量MIN
			weigthSMin = (weigthS - spitWgt) * proEntity.getWeigthSMin()
					/ weigthS;
			// 待冶炼剩余重量
			weigthS1 = inWegths - spitWgt;
			// 待冶炼剩余支数
			numS1 = inNums - spitNum;
			double wtPln = weigthS - inWegths;// 已组炉量
			int numPln = numS - inNums;// 已组炉支
			int maxNum = Integer.parseInt(maxNumstr);

			// 原始序号
			String gxPlanNo1 = proEntity.getGxPlanNo();
			String exeStatus = proEntity.getExeStatus();
			int gxProSeq1 = proEntity.getGxProSeq();
			// 循环均分多少炉
			for (int i = 0; i < maxNum; i++) {

				/**
				 * 2. 原记录数据
				 */
				// 如果可拆分重量小于等于已待冶炼量
				if (weigthS <= inWegths) {

				}
				// 2.1 计算时间
				orglWgt = weigthS - spitWgt;// 产出剩余重量
				orglNum = numS - spitNum;// 产出剩余支数
				if (orglWgt - wtPln < 0) {
					orglWgt = wtPln;
					orglNum = numPln;
					spitWgt = weigthS - wtPln;
					spitNum = numS - numPln;
				}
				String orglplanTimeB = proEntity.getPlanTimeB(); // 计划开始时间
				TimeEntity orgltimeEntity = new TimeEntity();
				if (!processCode.equals("B")) {
					// 重算用时与结束时间
					orgltimeEntity = helperBean.calculateTime(orglNum,
							capacity[0], orglplanTimeB);
				} else {
					double[] steelArr = FrmSteelMakingPlanChange
							.getPlineLgParams(con, proEntity.getPlineCodeA());
					if (steelArr == null) {
						core.setV_errMsg("电炉(" + proEntity.getPlineNameA()
								+ ")没有排产基础数据!");
						return core;
					}
					double standSteel = steelArr[0];// 标准出钢量
					orgltimeEntity = helperBean.calculateTimeZz(orglWgt,
							capacity[0], orglplanTimeB, standSteel);
				}
				String orglplanTimeE = orgltimeEntity.getEndTime();// 计划结束时间
				String orglplanUserTime = orgltimeEntity.getUserTime(); // 计划用时

				// 2.2修改原始记录
				proEntity.setWeigthS(orglWgt);
				proEntity.setNumS(orglNum);
				proEntity.setPlanTimeB(orglplanTimeB);
				proEntity.setPlanTimeE(orglplanTimeE);
				proEntity.setPlanUserTime(orglplanUserTime);
				proEntity.setWeigthSMin(weigthSMin);
				updatePlanOrderZz(con, proEntity, processCode, proEntity
						.getProMonth(), gxProSeq1);
				// 2.3自动调整时间
				helperBean.timeIncrease(con, proEntity.getGxProSeq(), proEntity
						.getPlineCode(), orglplanTimeE, processCode);

				// if (orglWgt-spitWgt >0) {
				/**
				 * 3.新增记录
				 */
				// 排产序号
				String gxPlanNo = helperBean.getMaxGxPlanNo(con, proEntity
						.getProPlanId(), processCode);
				// 生产顺序
				int gxProSeq = proEntity.getGxProSeq() + 1;
				String planTimeB = orglplanTimeE;
				if (planTimeB.equals("")) {
					core.setV_errMsg("计划开始时间为空,拆分失败!");
					return core;

				}
				TimeEntity TimeEntiy = new TimeEntity();
				if (!processCode.equals("B")) {
					// 重算用时与结束时间
					TimeEntiy = helperBean.calculateTime(spitNum, capacity[0],
							planTimeB);
				} else {
					double[] steelArr = FrmSteelMakingPlanChange
							.getPlineLgParams(con, proEntity.getPlineCodeA());
					if (steelArr == null) {
						core.setV_errMsg("电炉(" + proEntity.getPlineNameA()
								+ ")没有排产基础数据!");
						return core;
					}
					double standSteel = steelArr[0];// 标准出钢量
					TimeEntiy = helperBean.calculateTimeZz(spitWgt,
							capacity[0], orglplanTimeB, standSteel);
				}
				// 计划结束时间
				String planTimeE = TimeEntiy.getEndTime();
				String planUserTime = TimeEntiy.getUserTime();
				// 3.2新增新记录
				proEntity.setGxPlanNo(gxPlanNo);
				proEntity.setGxProSeq(gxProSeq);
				proEntity.setWeigthS(spitWgt);
				proEntity.setNumS(spitNum);
				proEntity.setPlanTimeB(planTimeB);
				proEntity.setPlanTimeE(planTimeE);
				proEntity.setPlanUserTime(planUserTime);
				proEntity.setExeStatus("0");
				proEntity.setIsRepairPlan("0");
				proEntity.setIfStoveIssued("0");
				proEntity.setWeigthSMin(weigthSMin1 - weigthSMin);
				helperBean.seqIncrease(con, proEntity.getPlineCode(), gxProSeq,
						-1, 1, processCode);
				// 订单编号以及排产序号
				helperBean.addPlanOrder(con, proEntity, processCode, proEntity
						.getProMonth());
				// 时间自动调整
				helperBean.timeIncrease(con, proEntity.getGxProSeq(), proEntity
						.getPlineCode(), planTimeE, processCode);
				// }
				weigthS = orglWgt;
				numS = orglNum;
				proEntity.setGxPlanNo(gxPlanNo1);
				proEntity.setExeStatus(exeStatus);
			}
			core.setResult(true);
			core.setV_errMsg("拆分成功!");
			con.commit();
		} catch (Exception e) {
			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 entity
	 * @throws SQLException
	 */
	public void updatePlanOrderZz(Connection con, ProducEntity proEntity,
			String processCode, String proMonth, int gxProSeq1)
			throws SQLException {
		String sql = "";
		if (processCode.equals("B")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.updatePlanOrderB");
			com.steering.pss.plnsaleord.processOrder.entity.PlnOrderCastSEntity entity = (com.steering.pss.plnsaleord.processOrder.entity.PlnOrderCastSEntity) proEntity
					.getObjEntity();
			entity.setPlineCode(proEntity.getPlineCode());
			entity.setPlineName(proEntity.getPlineName());
			entity.setPlanNumS(String.valueOf(proEntity.getNumS()));
			entity.setPlanWtS(String.valueOf(proEntity.getWeigthS()));
			entity.setPlanUsetime(proEntity.getPlanUserTime());
			entity.setPlanTimeB(proEntity.getPlanTimeB());
			entity.setPlanTimeE(proEntity.getPlanTimeE());
			entity.setGxProSeq(String.valueOf(gxProSeq1));
			entity.setIsPlanOk(proEntity.getIsPlanOk());
			entity.setIsRepairPln(proEntity.getIsRepairPlan());
			entity.setRepairType(proEntity.getRepairType());
			entity.setMemo(proEntity.getMemo());
			entity.setProMonth(proMonth);
			entity.setPlineCodeA(proEntity.getPlineCodeA());
			entity.setPlineNameA(proEntity.getPlineNameA());
			entity.setGxPlanNo(proEntity.getGxPlanNo());
			entity.setExeStatus(proEntity.getExeStatus());
			entity.setPlanWtMin(String.valueOf(proEntity.getWeigthSMin()));
			sql = EntityTool.fillSqlByEntity(sql, entity);
		}
		PreparedStatement ps = con.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 修改倍尺数
	 * 
	 * @param jsonList
	 * @param falsg
	 * @return
	 */
	public CoreReturnObject doUpdateNumGp(ArrayList<ArrayList<String>> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			// List<PlnOrderCastSEntity> list = PlnHelper.jsonsToEntityList(
			// PlnOrderCastSEntity.class, jsonList);
			PreparedStatement ps = null;

			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				int cutNumGp = Integer.parseInt(list.get(0));
				String proPlanId = list.get(1);
				String gxPlanNo = list.get(2);
				PlnOrderCastSEntity entity = ControlOrderPlan.getOrderCastById(
						conn, proPlanId, gxPlanNo);
				if (entity == null) {
					cro.setV_errMsg("数据异常,请刷新数据!");
					return cro;
				}
				if (Integer.parseInt(entity.getExeStatus()) > 1) {
					cro.setV_errMsg("铸造订单(" + entity.getProPlanId() + "/"
							+ entity.getGxPlanNo() + "),不是计划和生产中的状态!");
					return cro;
				}
				if (Double.parseDouble(entity.getCanWgt()) < Double
						.parseDouble(entity.getPlanWtS())) {
					cro.setV_errMsg("存在组炉，请拆分数据后修改倍尺数!");
					return cro;
				}
				if (entity.getCastingtype().endsWith("2")) {
					cro.setV_errMsg("请选择连铸订单信息!");
					return cro;
				}
				double zgwtSingle = CoreOrdBase.GpweightOfmi(Double
						.parseDouble(entity.getDiameterLz())); // 坯米单重
				double planWtS = Double.parseDouble(entity.getPlanWtS());
				double lengthLz = Double.parseDouble(entity.getLenGpSingle())
						* cutNumGp;// 倍尺坯长
				double wtCastOne = zgwtSingle * (lengthLz / 1000);
				int planNumS = (int) Math.ceil(planWtS / wtCastOne);
				// 修改铸造倍尺数
				String updateSql = CoreXmlSqlParsersFactory
						.getSql("ControlOrderPlan.updatePlnOrdeCastCutNum");
				ps = conn.prepareStatement(updateSql);
				ps.setObject(1, cutNumGp);
				ps.setObject(2, lengthLz);
				ps.setObject(3, wtCastOne);
				ps.setObject(4, planNumS);
				ps.setObject(5, proPlanId);
				ps.setObject(6, gxPlanNo);
				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;
	}

	/**
	 * 浇次确认，取消确认
	 * 
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject updateCastConfirm(
			ArrayList<ArrayList<String>> jsonList, String flag, String userName)
			throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String castNo = list.get(0);
				PlnSteelforcastEntity entity1 = ControlCastPlan
						.getCastByCastno(conn, castNo);
				if (entity1 == null) {
					cro.setV_errMsg("浇次号:" + castNo + ",查询无数据!");
					return cro;
				}
				if (!entity1.getStatus().equals("00")) {
					cro.setV_errMsg("浇次号:" + castNo + ",不是计划状态,不能确认或取消确认!");
					return cro;
				}
				List<PlnSteelforfurnaceEntity> entitylc = ControlCastPlan
						.getSteelFurnById(conn, castNo);
				if (entitylc == null) {
					cro.setV_errMsg("浇次号:" + castNo + ",未找到炉次信息");
					return cro;
				}
				String furnaNo = "";
				for (PlnSteelforfurnaceEntity steel : entitylc) {
					furnaNo += steel.getFurnaceno() + ",";
				}
				String ifConfifm = "0";
				if (flag.equals("0")) {
					ifConfifm = "1";
					if (entity1.getIfConfirm().equals("1")) {
						cro.setV_errMsg("浇次号:" + castNo + ",已确认,不能重复确认!");
						return cro;
					}
					String[] furnaces = furnaNo.substring(0,
							furnaNo.length() - 1).split(",");
					// 生成下工序炉计划
					String mess = ComPlanFurnace.queryPlnSteelCast(furnaces,
							userName, conn);
					if (!mess.equals("")) {
						cro.setV_errMsg(mess);
						return cro;
					}
					// 自动拆分
					String messZz = spitPlanCast(castNo, "B", conn, userName);
					if (!messZz.equals("")) {
						cro.setV_errMsg(messZz);
						return cro;
					}
				} else {
					ifConfifm = "0";
					if (entity1.getIfConfirm().equals("0")) {
						cro.setV_errMsg("浇次号:" + castNo + ",未确认,不能取消确认!");
						return cro;
					}
					String[] furnaces = furnaNo.substring(0,
							furnaNo.length() - 1).split(",");
					// 删除下工序炉计划
					String mess = ComPlanFurnace.deletePlnSteelCast(furnaces,
							userName, conn);
					if (!mess.equals("")) {
						cro.setV_errMsg(mess);
						return cro;
					}
				}
				// 修改浇次确认标志
				String updateCast = "UPDATE PLN_STEELFORCAST T SET T.IF_CONFIRM=? WHERE T.CAST_NO=?";
				ps = conn.prepareStatement(updateCast);
				ps.setObject(1, ifConfifm);
				ps.setObject(2, castNo);
				ps.executeUpdate();
				ps.close();

			}

			if (flag.equals("0")) {
				cro.setV_errMsg("确认成功!");
			} else {
				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;
	}

	/**
	 * 浇次确认拆分
	 * 
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 */
	public static String spitPlanCast(String castNo, String processCode,
			Connection con, String userName) throws SQLException,
			ParseException {
		String mess = "";
		PreparedStatement ps = null;
		ResultSet rs = null;
		// 获取数据库当前时间
		String dateTime = FrmSteelMakingPlanChange.getSystemTime(con);
		ProducHelperBean helperBean = new ProducHelperBean();
		List<String> list = new ArrayList<String>();
		// 查询浇次向下有多少铸造订单
		String sqlProPlan = CoreXmlSqlParsersFactory
				.getSql("ControlOrderPlan.getCastProPlanId");
		ps = con.prepareStatement(sqlProPlan);
		ps.setObject(1, castNo);
		rs = ps.executeQuery();
		while (rs.next()) {
			list.add(rs.getString("PRO_PLAN_ID"));
		}
		rs.close();
		ps.close();

		for (int i = 0; i < list.size(); i++) {
			String proPlanId = list.get(i);// 铸造订单号+序号
			String proPlanId1 ="";
			String gxPlanNo ="";
			if(!proPlanId.contains("GP_")&&!proPlanId.contains("DP_")){
				 proPlanId1 = list.get(i).substring(0, 17);
				 gxPlanNo = list.get(i).substring(18, list.get(i).length());
			}else{
			 proPlanId1 = list.get(i).substring(0, 15);
			 gxPlanNo = list.get(i).substring(16, list.get(i).length());
			}
			// 铸造订单已做炼钢炉计划量(订单+序号)
			double spitWgt = 0;
			int spitNum = 0;
			String sqlProNum = CoreXmlSqlParsersFactory
					.getSql("ControlOrderPlan.getCastProPlanIdNum");
			ps = con.prepareStatement(sqlProNum);
			ps.setObject(1, proPlanId);
			rs = ps.executeQuery();
			if (rs.next()) {
				spitWgt = rs.getDouble("TOT_WEIGHT_M");
				spitNum = rs.getInt("TOT_MUM_M");
			}
			rs.close();
			ps.close();
			// 铸造订单已做炼钢炉计划量(订单)
			double spitWgtall = 0;
			sqlProNum = CoreXmlSqlParsersFactory
					.getSql("ControlOrderPlan.getCastProPlanIdNumAll");
			ps = con.prepareStatement(sqlProNum);
			ps.setObject(1, proPlanId1);
			rs = ps.executeQuery();
			if (rs.next()) {
				spitWgtall = rs.getDouble("TOT_WEIGHT_M");
			}
			rs.close();
			ps.close();
			// 查询铸造订单排产量，及最小排产量
			PlnOrderCastSEntity proEntity = ProducHelperBean.getPlanOrder(con,
					proPlanId1, gxPlanNo, processCode,
					PlnOrderCastSEntity.class);
			/**
			 * 1.验证数据
			 */
			if (proEntity == null) {
				mess = "数据异常,请刷新数据!";
				return mess;
			}
			if (!proEntity.getExeStatus().equals("0")
					&& !proEntity.getExeStatus().equals("1")) {
				mess = "订单编号(" + proEntity.getProPlanId()
						+ ")/不是 (计划/生产中)执行状态!";
				return mess;
			}
			double plnInsingleWt = 0;
			// 查询铸造订单对应轧管订单炉计划量(炼钢利库，有管坯需求轧管利库)
			String sqlProPlanZg = CoreXmlSqlParsersFactory
					.getSql("ControlOrderPlan.getCastProPlanIdZg");
			ps = con.prepareStatement(sqlProPlanZg);
			ps.setObject(1, proEntity.getProPlanId());
			rs = ps.executeQuery();
			if (rs.next()) {
				plnInsingleWt = rs.getDouble("PLN_INSINGLE_WT");
			}
			rs.close();
			ps.close();
			// 1.2验证产线能力
			double[] capacity = helperBean.getPlineCapacity(con, proEntity
					.getWlidIn(), proEntity.getMaterialNo(), proEntity
					.getPlineCode(), processCode);

			if (capacity[0] <= 0) {
				if (!processCode.equals("B")) {
					mess = "订单编号(" + proEntity.getProPlanId() + ")/产线("
							+ proEntity.getPlineName() + ")没有维护产线能力!";
					return mess;
				} else {
					capacity[0] = 0;
				}
			}
			double orglWgt = 0;// 剩余重量
			int orglNum = 0;// 剩余支数
			double planWtLk = Double.parseDouble(proEntity.getPlanWtSold());// 利库量
			int planWtNum = Integer.parseInt(proEntity.getPlanNumSold());// 利库支
			double weigthS = Double.parseDouble(proEntity.getPlanWtS());// 排产量
			int numS = Integer.parseInt(proEntity.getPlanNumS());// 排产支
			double planeWt = Double.parseDouble(proEntity.getPlanedWt());// 已组浇量
			int planeNum = Integer.parseInt(proEntity.getPlanedNum());// 已组浇支
			double weigthSMin1 = Double.parseDouble(proEntity.getPlanWtMin());// 排产量MIN
			double weigthSMin = (weigthS - planeWt-planWtLk) * weigthSMin1 / weigthS;// 剩余排产量MIN

			// 原始序号
			String exeStatus = proEntity.getExeStatus();
			int gxProSeq1 = Integer.parseInt(proEntity.getGxProSeq());

			// 查询铸造订单总冶炼量Min
			double allWt = 0;
			double allWtMin = 0;
			double allWtLk = 0;
			String sqlQuery = "SELECT NVL(SUM(T.PLAN_WT_MIN),0) PLAN_WT_MIN,NVL(SUM(T.PLAN_WT_S),0) PLAN_WT_S,NVL(SUM(PLAN_WT_SOLD),0) PLAN_WT_SOLD   FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=?";
			ps = con.prepareStatement(sqlQuery);
			ps.setObject(1, proEntity.getProPlanId());
			rs = ps.executeQuery();
			if (rs.next()) {
				allWt = rs.getDouble("PLAN_WT_S");
				allWtMin = rs.getDouble("PLAN_WT_MIN");
				allWtLk = rs.getDouble("PLAN_WT_SOLD");
			}
			rs.close();
			ps.close();

			/**
			 * 2. 原记录数据
			 */
			// 验证重量（冶炼量min-已组浇量-后轧管利库-炼钢利库<=0）
			if (allWtMin > 0) {
				if (allWtMin - spitWgtall - plnInsingleWt - allWtLk <= 1) {
					continue;
				}
			} else {
				if (allWt - spitWgtall - plnInsingleWt - allWtLk <= 1) {
					continue;
				}
			}
			if (weigthS - planeWt - planWtLk <= 1) {
				continue;
			}
			// 2.1 计算时间
			orglWgt = weigthS - planeWt-planWtLk;// 产出剩余重量
			orglNum = numS - planeNum-planWtNum;// 产出剩余支数
			if (orglWgt <= 0) {
				continue;
			}
			String orglplanTimeB = proEntity.getPlanTimeB(); // 计划开始时间
			TimeEntity orgltimeEntity = new TimeEntity();
			if (!processCode.equals("B")) {
				// 重算用时与结束时间
				orgltimeEntity = helperBean.calculateTime(spitNum, capacity[0],
						orglplanTimeB);
			} else {
				double[] steelArr = FrmSteelMakingPlanChange.getPlineLgParams(
						con, proEntity.getPlineCodeA());
				if (steelArr == null) {
					mess = "电炉(" + proEntity.getPlineNameA() + ")没有排产基础数据!";
					return mess;
				}
				double standSteel = steelArr[0];// 标准出钢量
				orgltimeEntity = helperBean.calculateTimeZz(spitWgt,
						capacity[0], orglplanTimeB, standSteel);
			}
			String orglplanTimeE = orgltimeEntity.getEndTime();// 计划结束时间
			String orglplanUserTime = orgltimeEntity.getUserTime(); // 计划用时

			// 2.2修改原始记录
			proEntity.setPlanWtS(String.valueOf(planeWt+planWtLk));
			proEntity.setPlanNumS(String.valueOf(planeNum+planWtNum));
			proEntity.setPlanTimeB(orglplanTimeB);
			proEntity.setPlanTimeE(orglplanTimeE);
			proEntity.setPlanUsetime(orglplanUserTime);
			proEntity.setPlanWtMin(String.valueOf(weigthSMin1 - weigthSMin));
			proEntity.setUpdateName(userName);
			proEntity.setUpdateTime(dateTime);
			// 更新铸造订单信息
			String sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
					.getSql("ControlOrderPlan.UpdatePlanCast"), proEntity);
			ps = con.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
			// 2.3自动调整时间
			helperBean.timeIncrease(con, gxProSeq1, proEntity.getPlineCode(),
					orglplanTimeE, processCode);

			// if (orglWgt-spitWgt >0) {
			/**
			 * 3.新增记录
			 */
			// 排产序号
			String gxPlanNo2 = helperBean.getMaxGxPlanNo(con, proEntity
					.getProPlanId(), processCode);
			// 生产顺序
			int gxProSeq = Integer.parseInt(proEntity.getGxProSeq()) + 1;
			String planTimeB = orglplanTimeE;
			if (planTimeB.equals("")) {
				mess = "计划开始时间为空,自动拆分失败!";
				return mess;

			}
			TimeEntity TimeEntiy = new TimeEntity();
			if (!processCode.equals("B")) {
				// 重算用时与结束时间
				TimeEntiy = helperBean.calculateTime(orglNum, capacity[0],
						planTimeB);
			} else {
				double[] steelArr = FrmSteelMakingPlanChange.getPlineLgParams(
						con, proEntity.getPlineCodeA());
				if (steelArr == null) {
					mess = "电炉(" + proEntity.getPlineNameA() + ")没有排产基础数据!";
					return mess;
				}
				double standSteel = steelArr[0];// 标准出钢量
				TimeEntiy = helperBean.calculateTimeZz(orglWgt, capacity[0],
						orglplanTimeB, standSteel);
			}
			// 计划结束时间
			String planTimeE = TimeEntiy.getEndTime();
			String planUserTime = TimeEntiy.getUserTime();
			// 3.2新增新记录
			proEntity.setGxPlanNo(gxPlanNo2);
			proEntity.setGxProSeq(String.valueOf(gxProSeq));
			proEntity.setPlanWtS(String.valueOf(orglWgt));
			proEntity.setPlanNumS(String.valueOf(orglNum));
			proEntity.setPlanTimeB(planTimeB);
			proEntity.setPlanTimeE(planTimeE);
			proEntity.setPlanUsetime(planUserTime);
			proEntity.setExeStatus("0");
			proEntity.setIsPlanOk("0");
			proEntity.setIsRepairPln("0");
			proEntity.setPlanWtMin(String.valueOf(weigthSMin));
			proEntity.setCreateName(userName);
			proEntity.setCreateTime(dateTime);
			proEntity.setPlanedNum("0");
			proEntity.setPlanedWt("0");
			proEntity.setIssuedMan("");
			proEntity.setIssuedTime("");
			proEntity.setLastUndownMan("");
			proEntity.setLastUndownTime("");
			helperBean.seqIncrease(con, proEntity.getPlineCode(), gxProSeq, -1,
					1, processCode);
			// 新增铸造订单信息
			String sqlAdd = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
					.getSql("ProducHelperBean.addPlanOrderB"), proEntity);
			ps = con.prepareStatement(sqlAdd);
			ps.executeUpdate();
			ps.close();
			// // 订单编号以及排产序号
			// helperBean.addPlanOrder(con, proEntity, processCode, proEntity
			// .getProMonth());
			// 时间自动调整
			helperBean.timeIncrease(con, gxProSeq, proEntity.getPlineCode(),
					planTimeE, processCode);
			// }
			weigthS = orglWgt;
			numS = orglNum;
			proEntity.setGxPlanNo(gxPlanNo2);
			proEntity.setExeStatus(exeStatus);

		}
		return mess;
	}
	
	/**
	 * 刷新工艺卡
	 * @param castNo
	 * @return
	 */
	public CoreReturnObject doLimitProcessAll(String castNo)
	{
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
			connection.setAutoCommit(false); // 取消自动提交事务
			String updateFlagSql = CoreXmlSqlParsersFactory.getSql("ControlOrderPlan.doLimitProcessAll");
			PreparedStatement updateFlagPsta = connection.prepareStatement(updateFlagSql);
			updateFlagPsta.setString(1, castNo);
			updateFlagPsta.addBatch();
			
			updateFlagPsta.executeBatch();
			cro.setV_errMsg("刷新工艺卡成功!");
			connection.commit();
        }
	   	catch (Exception e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                	cro.setV_errMsg(e.getMessage());
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
	}
}
