package com.steering.pss.plnsaleord.jggxpln;

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.Arrays;
import java.util.Date;
import java.util.List;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import IceInternal.Ex;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.jggxpln.model.PlnZyJgWorkbillEntity;
import com.steering.pss.plnsaleord.order.model.PlnGxJgPropCEntity;
import com.steering.pss.plnsaleord.processOrder.base.BaseHelper;
import com.steering.pss.plnsaleord.processOrder.entity.PlnGxJgPropSEntity;
import com.steering.pss.plnsaleord.processOrder.tmsDemand.writeDemand;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.entity.PlnZyJgCEntity;
import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader;

/**
 * 接箍合同利库
 * 
 * @author 2018.06.24 tjg
 * 
 */
public class FrmPlnZyJgWorkBill extends DBCommon {

	/**
	 * 查询接箍炉计划
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnZyJg(String heatPlanNo, String judgeNo,
			String plineCode, String[] plineC, String[] pcStart, String codeBl,
			String str, String proPlanId, String timeB, String timeE,
			String cpJg, String flag) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryPlanStoveReadyH");
		if (flag.equals("0")) {

			if (cpJg.equals("0")) {
				sql += ",(SELECT JGS.PRO_PLAN_ID||'/'||JGS.GX_PLAN_NO PRO_PLAN_ID_GX FROM PLN_GX_JG_PROP_S JGS,PLN_GX_JG_PROP_C JGC,"
						+ " (SELECT JS.PLAN_TIME_B, T1.KEY FROM PLN_SALEORD_PROC S, PLN_ORDER_JG J,PLN_ORDER_JGX_S  JS,PLN_GX_JG_PROP_C T1 "
						+ " WHERE S.ORD_LN_DLY_PK = J.ORD_LN_DLY_PK AND JS.ORD_LN_DLY_PK = S.ORD_LN_DLY_PK "
						+ " AND JS.PLN_DIVIDE_ID = S.PLN_DIVIDE_ID AND JS.EXE_STATUS = '0' AND J.KEY = T1.KEY "
						+ " AND JS.PLAN_TIME_B BETWEEN TO_DATE('"
						+ timeB
						+ "', 'YYYY-MM-DD HH24:MI:SS') AND "
						+ " TO_DATE('"
						+ timeE
						+ "', 'YYYY-MM-DD HH24:MI:SS') GROUP BY T1.KEY, JS.PLAN_TIME_B) T2  "
						+ " WHERE JGS.PRO_PLAN_ID = JGC.PRO_PLAN_ID AND (JGS.IS_REPAIR_PLN IS NULL OR JGS.IS_REPAIR_PLN = '0')  "
						+ " AND T2.KEY = JGC.KEY  ORDER BY T2.PLAN_TIME_B ASC) T2";
			} else {
				sql += " ,(SELECT JGS.PRO_PLAN_ID || '/' || JGS.GX_PLAN_NO PRO_PLAN_ID_GX FROM PLN_GX_JG_PROP_S JGS,  PLN_GX_JG_PROP_C JGC,"
						+ " (SELECT J.KEY FROM PLN_SALEORD_PROC S, PLN_ORDER_JG     J, PLN_GX_JG_PROP_C JGC,  PLN_SALEORD S1  "
						+ " WHERE S.ORD_LN_DLY_PK = J.ORD_LN_DLY_PK  AND S1.ORD_LN_DLY_PK = S.ORD_LN_DLY_PK  AND J.KEY = JGC.KEY "
						+ " AND S.PROCESS_SEQ = 'H' GROUP BY J.KEY) T1 WHERE JGS.PRO_PLAN_ID = JGC.PRO_PLAN_ID  "
						+ " AND JGC.KEY = T1.KEY ORDER BY TO_NUMBER(JGS.GX_PRO_SEQ) ASC) T2";
			}
		}
		sql += " WHERE T.HEAT_PLAN_NO = T1.HEAT_PLAN_NO(+) AND T.PRO_PLAN_ID = S.PRO_PLAN_ID AND T.GX_PLAN_NO = S.GX_PLAN_NO ";
		if (flag.equals("0")) {
			sql += " AND T.PRO_PLAN_ID||'/'||T.GX_PLAN_NO=T2.PRO_PLAN_ID_GX";
		}
		if (!heatPlanNo.equals("")) {
			sql += " AND T.HEAT_PLAN_NO LIKE '%" + heatPlanNo + "%'";
		}
		if (!judgeNo.equals("")) {
			sql += " AND T.JUDGE_STOVE_NO LIKE '%" + judgeNo + "%'";
		}
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE='" + plineCode + "'";
		} else {
			sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineC);
		}
		if (pcStart.length > 0) {
			sql += CoreConverter.toSqlConditionString("S.EXE_STATUS", pcStart);
		}
		if (!codeBl.equals("")) {
			sql += " AND T.CODE_JG_BL='" + codeBl + "'";
		}
		if (str.equals("1")) {
			sql += " AND (NVL(T1.USE_BL_NUM, 0)-NVL(T1.REAL_INDOUBLE_NUM, 0)>0 OR NVL(T1.USE_BL_NUM, 0)=0)";
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID||'/'||T.GX_PLAN_NO ='" + proPlanId + "'";
		}
		sql += "  ORDER BY T.HEAT_PLAN_NO ASC,T1.HEAT_PLAN_SQE ASC ) JG";
		sql += "  GROUP BY HEAT_PLAN_NO,PRO_PLAN_ID,JG_GROUP_ID, GX_PLAN_NO,FEED_HEAT_NO,JUDGE_STOVE_NO,PLINE_CODE, PLINE_NAME,CODE_JG_BL, BL_WL_ID, BL_WL_DESC,STEELCODE, STEELNAME, GRADECODE,"
				+ " GRADENAME, MIN_D, MIN_H, AIMLENGTH_BL,AIM_CUT_LEN,LENGTH_MIN, LENGTH_MAX,TAPER,CODE_JG, MODEL_CODE,MODEL_DESC,OUTDIAMETER,WALLTHICK,SPEC_JG, SPEC_JG_DESC, "
				+ " STYLE_JG, DIAMETER,CHECK_J_VAL,AIMLENGTH, SINGLEWEIGHT,COAT_TYPE,PLAN_JG_NUM,PLAN_BL_NUM,PLAN_BL_WT,MONITORDEMAND,IF_MONITOR_JG,PRDCR_NO,CUT_MACH_GRP_NO, "
				+ " CUT_MACH_GRP_NM,DEMAND_COPPER,LATHE_GRP_NO,LATHE_GRP_NM,PLANSTATUS,MEMO, CREATE_NAME,CREATE_TIME,UPDATE_NAME,UPDATE_TIME,CUST_ALPHA_NO, ORDER_SPECIAL_DESC, "
				+ " ALPHA_CODE,CRAFT_FILE_NO,CRAFT_SEQ,ORD_LN_DLY_PK,SINGLE_CUT_NUN, IF_MATCH_ODD,IF_DO_HEAT_PLAN,OUTWL_ID, OUTWL_DESC, STOVE_NO,FLAG_STOVE_NO,GX_PRO_SEQ, PRO_DAY, "
				+ " BAL_YEAR_MONTH, PROD_STANDARD, OUTPUT_STANDARD,UPPER_HEATPLAN_ID, PLANSTATUS_GX, UPPER_PROCESS_CODE, HEAT_PLAN_SQE,JUGDE_APPLY_CODE, OUT_JG_NUM, USE_BL_NUM,"
				+ " USE_BL_WT, REAL_INDOUBLE_NUM,REAL_INDOUBLE_WT,STD_CODE, STD_NAME, STD_STYLE, STD_STYLE_DESC, PRODUCCODE_JG,PRODUCCODE_JG_DESC, BATCH_NO, BATCH_GROUD_NO, "
				+ " EXE_STATUS,  WASTE_RATE,EXE_STATUS_DD,EXE_STATUS, WASTE_RATE, EXE_STATUS";
		return this.getData(sql);
	}

	/**
	 * 查询车丝机床
	 * 
	 * @param plineC
	 * @return
	 */
	public CoreReturnObject queryMach(String[] plineC, String proessCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryMach");
		sql += CoreConverter.toSqlConditionString("T.PLINE_NO", plineC);
		// sql += " AND T.PROCESS_NO='" + proessCode + "'";
		sql += "ORDER BY T.MACHINE_NO ASC";
		return this.getData(sql);
	}

	/**
	 * 查询切管机床
	 * 
	 * @param plineC
	 * @return
	 */
	public CoreReturnObject queryMachC(String[] plineC, String proessCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryMachC");
		sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineC);
		// sql += " AND T.PROCESS_NO='" + proessCode + "'";
		sql += "ORDER BY T.MACHINE_NO ASC";
		return this.getData(sql);
	}

	/**
	 * 根据炉计划查接箍成品合同
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnZyJgOrder(String proPlanId, String timeB,
			String timeE, String cpJg, String[] pcStart) {
		String sql = "";
		if (cpJg.equals("0")) {
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmPlnZyJgWorkBill.queryOrderPlnJg");
			sql += " AND JS.PLAN_TIME_B BETWEEN TO_DATE('" + timeB
					+ "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('" + timeE
					+ "', 'YYYY-MM-DD HH24:MI:SS')";
			sql += "GROUP BY T1.KEY,JS.PLAN_TIME_B, JS.PRO_PLAN_ID,JS.GX_PLAN_NO,JS.PLINE_NAME,JS.ORDER_NO,JS.ORDER_SEQ,JS.NUM_S,JS.FINAL_USER_DESC,J.JG_ORDERNO"
					+ " ,S1.PRODUCNAME) T2  WHERE JGS.PRO_PLAN_ID = JGC.PRO_PLAN_ID "
					+ " AND (JGS.IS_REPAIR_PLN IS NULL OR JGS.IS_REPAIR_PLN = '0') AND T2.KEY = JGC.KEY  AND JGC.KEY = C1.KEY(+)";
			if (!proPlanId.equals("")) {
				sql += " AND JGS.PRO_PLAN_ID||'/'||JGS.GX_PLAN_NO ='"
						+ proPlanId + "'";
			}
			if (pcStart.length > 0) {
				sql += CoreConverter.toSqlConditionString("JGS.EXE_STATUS", pcStart);
			}
			sql += " ORDER BY T2.PLAN_TIME_B ASC";
		} else {
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmPlnZyJgWorkBill.queryOrderPlnJgCp");
			if (!proPlanId.equals("")) {
				sql += " AND JGS.PRO_PLAN_ID||'/'||JGS.GX_PLAN_NO ='"
						+ proPlanId + "'";
			}
			if (pcStart.length > 0) {
				sql += CoreConverter.toSqlConditionString("JGS.EXE_STATUS", pcStart);
			}
			sql += " ORDER BY TO_NUMBER(JGS.GX_PRO_SEQ) ASC";
		}
		return this.getData(sql);
	}

	/**
	 * 根据炉计划查询工单
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnZyWorkBill(String heatPlanNo,
			String heatPlanSqe) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryPlnZyWorkBill");
		sql += " AND T.HEAT_PLAN_NO='" + heatPlanNo + "'";
		sql += " AND T.HEAT_PLAN_SQE='" + heatPlanSqe + "'";
		sql += " ORDER BY T.GX_PRO_SEQ ASC";
		return this.getData(sql);
	}

	/**
	 * 查询工单
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnZyWorkBillPln(String workBill,
			String judgeNoBill, String plineCode, String[] plineC,
			String[] pcStart,String date,
			String endDate) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryPlnZyWorkBill");
		if (!workBill.equals("")) {
			sql += " AND T.WO_ID='" + workBill + "'";
		}
		if (!judgeNoBill.equals("")) {
			sql += " AND T.JUDGE_STOVE_NO='" + judgeNoBill + "'";
		}
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE='" + plineCode + "'";
		} else {
			sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineC);
		}
		if (pcStart.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.ZY_BILL_STATUS",
					pcStart);
		}
		if (!date.equals("")) {
			sql+= " AND T.CREATE_TIME BETWEEN TO_DATE('" + date
					+ "' ,'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('" + endDate
					+ "' ,'YYYY-MM-DD HH24:MI:SS') ";
		}
		sql += " ORDER BY T.GX_PRO_SEQ ASC";
		return this.getData(sql);
	}

	/**
	 * 获取工单号Max
	 * 
	 * @param con
	 * @return
	 * @throws SQLException
	 */
	public static String getPlnJgWork(Connection con, String heatPlanSeq)
			throws SQLException {
		String workID = "0001";
		String sql = "SELECT ?|| LPAD(SUBSTR(NVL(MAX(T.WO_ID),'00'),-2,2) + 1, 2, '0')  AS WO_ID FROM PLN_ZY_JG_WORKBILL T WHERE T.HEAT_PLAN_SQE=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, heatPlanSeq);
		ps.setObject(2, heatPlanSeq);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			workID = rs.getString("WO_ID");
		}
		rs.close();
		ps.close();
		return workID;
	}

	/**
	 * 根据工单ID查询工单
	 */
	public static <T> T getQureyWoId(Connection con, String woId, Class<T> cls)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.QueryworkBill");
		sql += "  AND T.WO_ID='" + woId + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 序号自增减
	 * 
	 * @param con
	 * @param
	 * @param gxProSeqB
	 * @param gxProSeqE
	 *            (如果没有上限，请设为负数)
	 * @param num
	 * @param
	 * @throws SQLException
	 */
	public void seqIncrease(Connection con, int gxProSeqB, int gxProSeqE,
			int num) throws SQLException {
		String sql = "UPDATE PLN_ZY_JG_WORKBILL T SET T.GX_PRO_SEQ = TO_NUMBER(T.GX_PRO_SEQ) + TO_NUMBER(?) WHERE TO_NUMBER(T.GX_PRO_SEQ) >= TO_NUMBER(?)";
		if (gxProSeqE > 0) {
			sql += "  AND TO_NUMBER(T.GX_PRO_SEQ) < TO_NUMBER(?) ";
		}
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, num);
		ps.setObject(2, gxProSeqB);
		if (gxProSeqE > 0) {
			ps.setObject(3, gxProSeqE);
		}
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 查询实际炉计划
	 */
	public static <T> T getQureyPlnZyC(Connection con, String heatPlanNo,
			String heatPlanSeq, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.queryPlnZyC");
		sql += "  AND T.HEAT_PLAN_NO='" + heatPlanNo + "' ";
		sql += "  AND T.HEAT_PLAN_SQE='" + heatPlanSeq + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 查询接箍排产订单7+4
	 */
	public static <T> T getQureyPropC(Connection con, String key,
			String proPlanId, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.getQureyPropC");
		sql += "  AND T.KEY ='" + key + "' ";
		sql += "  AND T.PRO_PLAN_ID ='" + proPlanId + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 查询接箍排产订单7+1
	 */
	public static <T> T getQureyPropS(Connection con, String proPlanId,
			String gxPlanNo, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.getQureyPropS");
		sql += "  AND T.PRO_PLAN_ID ='" + proPlanId + "' ";
		sql += "  AND T.GX_PLAN_NO ='" + gxPlanNo + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 下发
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doIssued(ArrayList<ArrayList<String>> jslist,
			String userName, String flag) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		//Connection tmsCon =null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			//tmsCon = this.getDao("TmsDao").getConnection(); 注释生产物流  2024/4/24 肖沅累
			conn.setAutoCommit(false);
			//tmsCon.setAutoCommit(false);
			PreparedStatement ps = null;
			String msg = "";
			// ResultSet rs = null;
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// 循环接箍工单信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String woId = list.get(0);
				// 查询工单
				PlnZyJgWorkbillEntity workBill = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (workBill == null) {
					cro.setV_errMsg("无工单信息!");
					return cro;
				}

				if (flag.equals("0")) {// 下发
					if (!workBill.getZyBillStatus().equals("0")) {
						cro.setV_errMsg("工单号:" + workBill.getWoId()
								+ "不是计划状态,不能下发!");
						return cro;
					}
					// 修改工单状态
					String updateBill = "UPDATE PLN_ZY_JG_WORKBILL T SET T.ZY_BILL_STATUS='1',T.UPDATE_NAME=? ,T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') WHERE T.WO_ID=?";
					ps = conn.prepareStatement(updateBill);
					ps.setObject(1, userName);
					ps.setObject(2, dateTime);
					ps.setObject(3, woId);
					ps.executeUpdate();
					ps.close();



				} else {
					if (!workBill.getZyBillStatus().equals("1")) {
						cro.setV_errMsg("工单号:" + workBill.getWoId()
								+ "不是下发状态,不能取消下发!");
						return cro;
					}
					// 修改工单状态
					String updateBill = "UPDATE PLN_ZY_JG_WORKBILL T SET T.ZY_BILL_STATUS='0',T.UPDATE_NAME=? ,T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') WHERE T.WO_ID=?";
					ps = conn.prepareStatement(updateBill);
					ps.setObject(1, userName);
					ps.setObject(2, dateTime);
					ps.setObject(3, woId);
					ps.executeUpdate();
					ps.close();

				}
			}
           // 循环接箍工单信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);

				if(flag.equals("0"))
				{
					//msg = writeDemand.writeDemandPln(list,"H",userName,tmsCon,conn);
					if(!msg.equals(""))
					{
						cro.setV_errMsg("生成运输需求出错!");
						return  cro;
					}
				}
//				else
//				{
//					msg = writeDemand.cancelWriteDemandPln(list,"H",userName,tmsCon,conn);
//					if(!msg.equals(""))
//					{
//						cro.setV_errMsg("删除运输需求出错!");
//						return  cro;
//					}
//				}
			}

			cro.setV_errMsg("成功!");
			conn.commit();
			//tmsCon.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null /*|| tmsCon !=null*/) {
					conn.rollback();
					//tmsCon.rollback();;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
				/*if (tmsCon != null && !tmsCon.isClosed()) {
					tmsCon.close();
				}*/
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 工单委外
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doOutsourc(ArrayList<ArrayList<String>> jslist,
			String userName, String flag) {
		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);
			// 循环炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String woId = list.get(0);
				// 查询工单
				PlnZyJgWorkbillEntity workBill = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (workBill == null) {
					cro.setV_errMsg("无工单信息!");
					return cro;
				}

				if (flag.equals("0")) {// 下发
					if (!workBill.getZyBillStatus().equals("0")) {
						cro.setV_errMsg("工单号:" + workBill.getWoId()
								+ "不是计划状态,不能委外!");
						return cro;
					}
					// 修改工单状态
					String updateBill = "UPDATE PLN_ZY_JG_WORKBILL T SET T.IF_ALL_OUT_WORK='1' WHERE T.WO_ID=?";
					ps = conn.prepareStatement(updateBill);
					ps.setObject(1, woId);
					ps.executeUpdate();
					ps.close();
				} else {
					if (!workBill.getZyBillStatus().equals("0")) {
						cro.setV_errMsg("工单号:" + workBill.getWoId()
								+ "不是计划状态,不能取消委外!");
						return cro;
					}
					// 修改工单状态
					String updateBill = "UPDATE PLN_ZY_JG_WORKBILL T SET T.IF_ALL_OUT_WORK='0' WHERE T.WO_ID=?";
					ps = conn.prepareStatement(updateBill);
					ps.setObject(1, woId);
					ps.executeUpdate();
					ps.close();
				}
			}
			cro.setV_errMsg("成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除工单
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doDelete(ArrayList<ArrayList<String>> jslist,
			String userName) {
		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);
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String woId = list.get(0);
				// 查询工单
				PlnZyJgWorkbillEntity workBill = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (workBill == null) {
					cro.setV_errMsg("无工单信息!");
					return cro;
				}
				if (!workBill.getZyBillStatus().equals("0")) {
					cro.setV_errMsg("工单号:" + workBill.getWoId()
							+ "不是计划状态,不能删除!");
					return cro;
				}
				int gxProSeq = Integer.parseInt(workBill.getGxProSeq());
				// 删除工单
				String updateBill = "DELETE PLN_ZY_JG_WORKBILL WHERE WO_ID = ?";
				ps = conn.prepareStatement(updateBill);
				ps.setObject(1, woId);
				ps.executeUpdate();
				ps.close();
				// 顺序修改
				seqIncrease(conn, gxProSeq, -1, -1);
				// 修改炉计划减量
				String updatePlnZyC = "UPDATE PLN_ZY_JG_C T SET T.REAL_INDOUBLE_NUM=TO_NUMBER(NVL(T.REAL_INDOUBLE_NUM,0))-TO_NUMBER(?),"
						+ "T.REAL_INDOUBLE_WT=TO_NUMBER(NVL(T.REAL_INDOUBLE_WT,0))-TO_NUMBER(?) WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
				ps = conn.prepareStatement(updatePlnZyC);
				ps.setObject(1, workBill.getPlanBlNum());
				ps.setObject(2, workBill.getPlanBlWt());
				ps.setObject(3, workBill.getHeatPlanNo());
				ps.setObject(4, workBill.getHeatPlanSqe());
				ps.executeUpdate();
				ps.close();

				int count = 0;
				// 查询炉计划下工单是否全部删除
				String query = "SELECT COUNT(*) COUNT FROM PLN_ZY_JG_WORKBILL T WHERE T.HEAT_PLAN_NO=?";
				ps = conn.prepareStatement(query);
				ps.setObject(1, workBill.getHeatPlanNo());
				rs = ps.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
				}
				rs.close();
				ps.close();
				// 修改接箍合同工单号
				String updateOrder = " UPDATE PLN_ORDER_JG T SET T.WO_ID='' WHERE T.WO_ID=?";
				ps = conn.prepareStatement(updateOrder);
				ps.setObject(1, workBill.getWoId());
				// ps.setObject(2, plnJg.getJgOrderno());
				// ps.setObject(3, gxJpS.getProPlanId());
				ps.executeUpdate();
				ps.close();
				if (count == 0) {
					// 修改炉计划状态及减量
					String updatePlnZyM = "UPDATE PLN_ZY_JG_M T SET T.PLANSTATUS='10' WHERE T.HEAT_PLAN_NO=?";
					ps = conn.prepareStatement(updatePlnZyM);
					ps.setObject(1, workBill.getHeatPlanNo());
					ps.executeUpdate();
					ps.close();
				}
			}
			cro.setV_errMsg("删除成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询工单最大顺序号
	 * 
	 * @param con
	 * @return
	 * @throws SQLException
	 */
	public int getMaxGxProSeq(Connection con) throws SQLException {
		String sql = "SELECT NVL(MAX(TO_NUMBER(T.GX_PRO_SEQ)), 0) + 1 GX_PRO_SEQ FROM PLN_ZY_JG_WORKBILL T WHERE 1=1";
		PreparedStatement ps = con.prepareStatement(sql);
		// ps.setObject(1, proPlanId);
		ResultSet rs = ps.executeQuery();
		int gxPlanNo = 1;
		if (rs.next()) {
			gxPlanNo = rs.getInt("GX_PRO_SEQ");
		}
		rs.close();
		ps.close();
		return gxPlanNo;
	}

	/**
	 * 新增工单
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doAdd(ArrayList<ArrayList<String>> jslist,
			String userName, String heatPlanNo, String heatPlanSeq,
			String latheGrpNo, String latheGrpName, String latheCutName,
			String memo, String decision, String numKGd) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			PlnZyJgWorkbillEntity workBill = new PlnZyJgWorkbillEntity();
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			// 查询实际炉计划
			PlnZyJgCEntity jgC = getQureyPlnZyC(conn, heatPlanNo, heatPlanSeq,
					PlnZyJgCEntity.class);
			if (jgC == null) {
				cro.setV_errMsg("无实际炉计划信息!");
				return cro;
			}
			if (!jgC.getPlanstatus().equals("00")
					&& !jgC.getPlanstatus().equals("10")
					&& !jgC.getPlanstatus().equals("20")) {
				cro.setV_errMsg("判定炉号:" + jgC.getJudgeStoveNo()
						+ "不是下发和生产中的状态,不能新增工单!");
				return cro;
			}
			// 查询接箍排产订单7+1(主)
			PlnGxJgPropSEntity propS = getQureyPropS(conn, jgC.getProPlanId(),
					jgC.getGxPlanNo(), PlnGxJgPropSEntity.class);
			if (propS == null) {
				cro.setV_errMsg("无接箍排产订单7+1信息!");
				return cro;
			}
			// 炉计划剩余未做工的支吨
			int useblNum = Integer.parseInt(jgC.getUseBlNum())
					- Integer.parseInt(jgC.getRealIndoubleNum());
			double useBlWt = Double.parseDouble(jgC.getUseBlWt())
					- Double.parseDouble(jgC.getRealIndoubleWt());
			double wt = Double.parseDouble(jgC.getUseBlWt())
					/ Integer.parseInt(jgC.getUseBlNum());
			int gdNum = 0;// 工单支
			double gdWt = 0;// 工单吨
			int numK = Integer.parseInt(numKGd);
			// int counNum = 0;
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String key = list.get(0);
				String workId = "";
				// int numK = Integer.parseInt(list.get(3));
				int singLenCutNum = Integer.parseInt(list.get(4));
				int workNum = Integer.parseInt(list.get(2));// 可做工单个

				int xqJgNumAll = Integer.parseInt(list.get(5));// 接箍需求总个

				int numGd = 0;//workNum / singLenCutNum;
				
//				if (numGd == 0) {
//					numGd = numK;
//				}
//				if (useblNum - numGd < 0) {
//					numGd = useblNum;
//				}
//				if (numGd < numK) {
//					numGd=numK;
//				}
				if(numK!=0){
					numGd=numK;
				}
				if(numK==0){
					cro.setV_errMsg("可做工单不能为零!");
					return cro;
				}
				// counNum += numGd;

				int xqJgNum = 0;
				if (xqJgNumAll != 0) {
					if (workNum != 0) {
						xqJgNum = (int) Math.ceil((xqJgNumAll / workNum)
								* numGd)
								* singLenCutNum;
					}
				}

				// 查询接箍订单从表信息
				PlnGxJgPropCEntity propC = getQureyPropC(conn, key,
						jgC.getProPlanId(), PlnGxJgPropCEntity.class);
				if (propC == null) {
					cro.setV_errMsg("无接箍排产订单7+4信息!");
					return cro;
				}
				int count = 0;
				String order = "";// 成品合同
				String buyerId = "";
				String buyerName = "";
				String jgOrderNoAll = "";
				// 查询是否存工单
				String sqlQuery = "SELECT T.WO_ID,T.ORDER_NO,T.BUYER_ID,T.BUYER_NAME,T.JG_ORDERNO_ALL FROM PLN_ZY_JG_WORKBILL T WHERE T.ZY_BILL_STATUS IN ('0','1','2') AND T.HEAT_PLAN_SQE=? AND T.KEY=?";
				ps = conn.prepareStatement(sqlQuery);
				ps.setObject(1, heatPlanSeq);
				ps.setObject(2, key);
				rs = ps.executeQuery();
				if (rs.next()) {
					count = 1;
					workId = rs.getString("WO_ID");
					order = rs.getString("ORDER_NO");
					buyerId = rs.getString("BUYER_ID");
					buyerName = rs.getString("BUYER_NAME");
					jgOrderNoAll = rs.getString("JG_ORDERNO_ALL");
				}
				rs.close();
				ps.close();
				// if (useblNum == 0) {
				// cro.setV_errMsg("选中的炉计划已全部生成工单,请重新选择炉计划!");
				// return cro;
				// }
				if (numGd == 0) {
					cro.setV_errMsg("可做工单支数为0,不能新增。请重新选择炉计划!");
					return cro;
				}
				// if (useblNum - Integer.parseInt(propC.getPlanNum()) > 0) {
				// gdNum = Integer.parseInt(propC.getPlanNum());
				// gdWt = Double.parseDouble(propC.getPlanWt());
				// } else {
				// gdNum = useblNum;
				// gdWt = useBlWt;
				// }
				gdNum = numGd;
				gdWt = wt * numGd;
				// String latheGrpNm = "";
				// String latheGrpNo = "";
				// // 查询车丝机床组
				// String sqlCs =
				// "SELECT T.MACHINE_GROUP,T.MACHINE_NAME FROM COUPLING_MACHINE_USER T WHERE T.PLINE_NO=? AND T.PROCESS_NO='700305'";
				// ps = conn.prepareStatement(sqlCs);
				// ps.setObject(1, jgC.getPlineCode());
				// rs = ps.executeQuery();
				// if (rs.next()) {
				// latheGrpNm = rs.getString("MACHINE_GROUP");
				// latheGrpNo = rs.getString("MACHINE_NAME");
				// }
				// rs.close();
				// ps.close();
				// 查询最大顺序号
				int gxProSeq = getMaxGxProSeq(conn);
				workBill.setHeatPlanNo(heatPlanNo);
				workBill.setHeatPlanSqe(heatPlanSeq);
				workBill.setJudgeStoveNo(jgC.getJudgeStoveNo());
				workBill.setBatchNo(jgC.getBatchNo());
				workBill.setBatchGroudNo(jgC.getBatchGroudNo());
				workBill.setPlineCode(jgC.getPlineCode());
				workBill.setPlineName(jgC.getPlineName());
				workBill.setDemandBlast(propC.getDemandBlast());
				workBill.setDemandBonderizing(propC.getDemandBonderizing());
				if (propC.getDemandBonderizing().equals("")) {
					workBill.setCoatType("0");
				} else if (propC.getDemandBonderizing().equals("40840201")) {
					workBill.setCoatType("2");
				} else if (propC.getDemandBonderizing().equals("40840202")) {
					workBill.setCoatType("1");
				}
				workBill.setDemandCopper(propC.getDemandCopper());
				workBill.setDemandDetection(propC.getDemandDetection());
				workBill.setCreateName(userName);
				workBill.setCreateTime(dateTime);
				workBill.setLatheCutNm(latheCutName);
				workBill.setLatheGrpNm(latheGrpName);
				workBill.setLatheGrpNo(latheGrpNo);
				workBill.setStoveNo(jgC.getStoveNo());
				workBill.setFlagStoveNo(jgC.getFlagStoveNo());
				workBill.setSteelcode(propS.getSteelcode());
				workBill.setSteelname(propS.getSteelname());
				workBill.setGradecode(jgC.getGradecode());
				workBill.setGradename(jgC.getGradename());
				workBill.setSpecJg(propS.getSpecJg());
				workBill.setSpecJgDesc(propS.getSpecJgDesc());
				workBill.setStdCode(propS.getStdCode());
				workBill.setStdName(propS.getStdName());
				workBill.setStdStyle(propS.getStdStyle());
				workBill.setStdStyleDesc(propS.getStdStyleDesc());
				workBill.setStyleJg(propS.getStyleJg());
				workBill.setModelCode(propS.getModelCode());
				workBill.setModelDesc(propS.getModelDesc());
				workBill.setIfMonitorJg(propS.getIfMonitorJg());
				workBill.setPrdcrNo(propS.getPrdcrNo());
				workBill.setProduccodeJg(propS.getProduccodeJg());
				workBill.setProduccodeJgDesc(propS.getProduccodeJgDesc());
				workBill.setCodeJg(propS.getCodeJg());
				workBill.setCodeJgBl(propS.getCodeJgBl());
				workBill.setCodeBlAll(propS.getCodeBlAll());
				workBill.setPlanBlNum(String.valueOf(gdNum));
				workBill.setPlanBlWt(String.valueOf(gdWt));
				workBill.setKey(key);
				workBill.setBlWlDesc(propS.getBlWlDesc());
				workBill.setBlWlId(propS.getBlWlId());
				workBill.setOutwlId(propS.getOutwlId());
				workBill.setOutwlDesc(propS.getOutwlDesc());
				workBill.setAimlengthBl(propS.getAimlengthBl());
				workBill.setAimCutLen(propS.getAimCutLen());
				workBill.setSingleCutNun(String.valueOf(singLenCutNum));
				workBill.setSingleweight(jgC.getSingleweight());
				workBill.setPlanJgNum(String.valueOf(singLenCutNum * gdNum));
				workBill.setJgOrdernoAll(propC.getJgOrderno());
				workBill.setCraftNoJg2(propC.getCraftNoJg2());
				workBill.setCraftSeq2(propC.getCraftSeq2());
				workBill.setCraftPath(propC.getCraftPath());

				workBill.setOrderNo(propC.getOrderNo() + "/"
						+ propC.getOrderSeq() + "/" + propC.getDeliveryNo());
				// workBill.setOrderSeq();
				// workBill.setDeliveryNo();

				workBill.setOrdLnDlyPk(propS.getOrdLnDlyPk());
				workBill.setMemo(memo);
				workBill.setXqJgNum(String.valueOf(xqJgNum));
				workBill.setDecision(propS.getDecision());
				workBill.setIndexSeq(propS.getIndexSeq());
				workBill.setCraftSeq(propS.getCraftSeq());
				workBill.setCraftFileNo(propS.getCraftFileNo());
				workBill.setGxProSeq(String.valueOf(gxProSeq));
				workBill.setBuyerId(propS.getBuyerId());
				workBill.setBuyerName(propS.getBuyerName());
				workBill.setMinD(propS.getMinD());
				workBill.setMinH(propS.getMinH());
				workBill.setMonitorPoint(propS.getMonitorPoint());
				workBill.setMonitordemand(jgC.getMonitordemand());
				if (count == 0) {
					// 新增
					workId = getPlnJgWork(conn, heatPlanSeq);
					workBill.setWoId(workId);
					String addBill = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("FrmPlnZyJgWorkBill.AddWork"),
							workBill);
					ps = conn.prepareStatement(addBill);
					ps.executeUpdate();
					ps.close();
				} else {
					workBill.setWoId(workId);
					String orderC = propC.getOrderNo() + "/"
							+ propC.getOrderSeq() + "/" + propC.getDeliveryNo();
					String buyerIdC = propS.getBuyerId();
					String buyerNameC = propS.getBuyerName();
					if (!order.contains(orderC)) {
						workBill.setOrderNo(order + "," + orderC);
					}
					if (!buyerId.contains(buyerIdC)) {
						workBill.setBuyerId(buyerId + "," + buyerIdC);
						workBill.setBuyerName(buyerName + "," + buyerNameC);
					}
					if (jgOrderNoAll != null
							&& !jgOrderNoAll.contains(propC.getJgOrderno())) {
						workBill.setJgOrdernoAll(jgOrderNoAll + ","
								+ propC.getJgOrderno());
					}
					// 修改
					String updateBill = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("FrmPlnZyJgWorkBill.updateWork"),
							workBill);
					ps = conn.prepareStatement(updateBill);
					ps.executeUpdate();
					ps.close();
				}

				// 修改炉计划减量
				String updatePlnZyC = "UPDATE PLN_ZY_JG_C T SET T.REAL_INDOUBLE_NUM=TO_NUMBER(NVL(T.REAL_INDOUBLE_NUM,0))+TO_NUMBER(?),"
						+ "T.REAL_INDOUBLE_WT=TO_NUMBER(NVL(T.REAL_INDOUBLE_WT,0))+TO_NUMBER(?) WHERE T.HEAT_PLAN_NO=? AND T.HEAT_PLAN_SQE=?";
				ps = conn.prepareStatement(updatePlnZyC);
				ps.setObject(1, gdNum);
				ps.setObject(2, gdWt);
				ps.setObject(3, heatPlanNo);
				ps.setObject(4, heatPlanSeq);
				ps.executeUpdate();
				ps.close();

				useblNum = useblNum - gdNum;
				useBlWt = useBlWt - gdWt;
			}

			// 修改炉计划状态
			String updatePlnZyM = "UPDATE PLN_ZY_JG_M T SET T.PLANSTATUS='20' WHERE T.HEAT_PLAN_NO=?";
			ps = conn.prepareStatement(updatePlnZyM);
			ps.setObject(1, heatPlanNo);
			ps.executeUpdate();
			ps.close();

			cro.setV_errMsg("新增成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 工单拆分
	 */
	public CoreReturnObject doBreakUp(ArrayList<ArrayList<String>> jslist,
			String userName,String spitWgt,String spitNum) throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// 循环炉计划信息
			String heatPlanNoAdd = "";
//			String heatPlanSeqNoAdd = "";
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String woId = list.get(0);

				int reaNum = 0;// 上料支
				int plnNum = 0;// 装炉支
				// 查询炉计信息
				PlnZyJgWorkbillEntity listM = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (listM == null) {
					cro.setV_errMsg("工单已发生变化,请重新查询!");
					return cro;
				}
//				if (listM.getZyBillStatus().equals("0")
//						|| listM.getZyBillStatus().equals("1")) {
//					cro.setV_errMsg("选择的工单是计划/下发状态,不能拆分!");
//					return cro;
//				}
				if (listM.getRealBlNum() != null
						&& !listM.getRealBlNum().equals("")) {
					reaNum = Integer.parseInt(listM.getRealBlNum());
				}
				if (listM.getPlanBlNum() != null
						&& !listM.getPlanBlNum().equals("")) {
					plnNum = Integer.parseInt(listM.getPlanBlNum());
				}
//				if (reaNum == 0) {
//					cro.setV_errMsg("选中的工单无上料支,不能拆分!");
//					return cro;
//				}
				if (plnNum - reaNum <= 0) {
					cro.setV_errMsg("选中的炉计划已全部上料,不能拆分!");
					return cro;
				}
				int addPlnNum =Integer.parseInt(spitNum);
						//plnNum - reaNum;// 拆分支
				// 查询库存拆分吨
				double addPlnWt = queryMatWt(conn, listM.getJudgeStoveNo(),
						listM.getBatchNo(), listM.getBatchGroudNo(),
						listM.getHeatPlanSqe(), listM.getHeatPlanNo(),
						addPlnNum);
				if (addPlnWt == 0) {
					cro.setV_errMsg("无库存信息,请确认!");
					return cro;
				}
				int planJgNum = Integer.parseInt(listM.getPlanJgNum());
				int xqJgNum = Integer.parseInt(listM.getXqJgNum());
				// 拆分接箍计划个
				int plnJgSy = (planJgNum / plnNum) * addPlnNum;
				int xqJgSy = (xqJgNum / plnNum) * addPlnNum;
				// 修改原实际工单支吨
				String updateOldC = " UPDATE PLN_ZY_JG_WORKBILL T SET T.PLAN_JG_NUM=TO_NUMBER(T.PLAN_JG_NUM)-TO_NUMBER(?),"
						+ " T.XQ_JG_NUM=TO_NUMBER(T.XQ_JG_NUM)-TO_NUMBER(?),T.PLAN_BL_NUM=TO_NUMBER(T.PLAN_BL_NUM)-TO_NUMBER(?),"
						+ " T.PLAN_BL_WT=TO_NUMBER(T.PLAN_BL_WT)-TO_NUMBER(?) WHERE T.WO_ID=?";
				ps = conn.prepareStatement(updateOldC);
				ps.setObject(1, plnJgSy);
				ps.setObject(2, plnJgSy);
				ps.setObject(3, addPlnNum);
				ps.setObject(4, addPlnWt);
				ps.setObject(5, woId);
				ps.executeUpdate();
				ps.close();

				// if(listM.getHeatPlanNoOld().equals("")){
				// listM.setHeatPlanNoOld(heatPlanNo);
				// }
				int gxProSeq = Integer.parseInt(listM.getGxProSeq());
				// 查询炉计划ID
				heatPlanNoAdd = getPlnJgWork(conn, listM.getHeatPlanSqe());
				listM.setWoId(heatPlanNoAdd);
				listM.setPlanBlNum(String.valueOf(addPlnNum));
				listM.setPlanBlWt(String.valueOf(addPlnWt));
				listM.setRealBlNum("");
				listM.setRealBlWt("");
				listM.setOutNum("");
				listM.setOutWt("");
				listM.setPlanJgNum(String.valueOf(plnJgSy));
				listM.setCsJgNum("");
				listM.setXqJgNum(String.valueOf(xqJgSy));
				listM.setGxProSeq(String.valueOf(gxProSeq + 1));
				// 顺序修改
				seqIncrease(conn, gxProSeq+1, -1, 1);
				// 新增新工单
				String addC = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("FrmPlnZyJgWorkBill.AddWork"), listM);
				ps = conn.prepareStatement(addC);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("拆分成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改计划支吨
	 */
	public CoreReturnObject doUpdateOrder(ArrayList<ArrayList<String>> jslist,
			String userName) throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// 循环炉计划信息
			// String heatPlanNoAdd = "";
			// String heatPlanSeqNoAdd = "";
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);

				int numPln = Integer.parseInt(list.get(0));
				double wtPln = Double.parseDouble(list.get(1));
				String woId = list.get(2);

				// 查询炉计信息
				PlnZyJgWorkbillEntity listM = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (listM == null) {
					cro.setV_errMsg("工单已发生变化,请重新查询!");
					return cro;
				}
				if (listM.getZyBillStatus().equals("4")) {
					cro.setV_errMsg("选择的工单已关闭,不能修改!");
					return cro;
				}

				// int planJgNum=
				// Integer.parseInt(listM.getSingleCutNun())*numPln;
				int planJgNum = Integer.parseInt(listM.getPlanJgNum());
				int xqJgNum = Integer.parseInt(listM.getXqJgNum());
				int plnNum = Integer.parseInt(listM.getPlanBlNum());
				// 拆分接箍计划个
				int plnJgSy = (planJgNum / plnNum) * numPln;
				int xqJgSy = (xqJgNum / plnNum) * numPln;
				// 修改原实际工单支吨
				String updateOldC = " UPDATE PLN_ZY_JG_WORKBILL T SET T.PLAN_JG_NUM=?,"
						+ " T.XQ_JG_NUM=?,T.PLAN_BL_NUM=?,"
						+ " T.PLAN_BL_WT=? WHERE T.WO_ID=?";
				ps = conn.prepareStatement(updateOldC);
				ps.setObject(1, plnJgSy);
				ps.setObject(2, xqJgSy);
				ps.setObject(3, numPln);
				ps.setObject(4, wtPln);
				ps.setObject(5, woId);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询库存可拆分吨
	 * 
	 * @param con
	 * @throws SQLException
	 */
	public static double queryMatWt(Connection con, String judgeStoveNo,
			String batchNo, String batchGroudNo, String heatPlanNoSeq,
			String heatPlanNo, int num) throws SQLException {
		double wt = 0;
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlnZyJgWorkBill.QueryMatWt");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		ps.setObject(2, batchNo);
		ps.setObject(3, batchGroudNo);
		ps.setObject(4, heatPlanNo);
		ps.setObject(5, heatPlanNoSeq);
		ps.setObject(6, heatPlanNo);
		ps.setObject(7, num);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			wt = rs.getDouble("ACT_WEIGHT");
		}
		rs.close();
		ps.close();
		return wt;
	}

	/**
	 * 排序
	 * 
	 * @param jsonstrList
	 * @param
	 * @param
	 * @return
	 */
	public CoreReturnObject sortPlanOrder(ArrayList<String> jsonstrList,
			String jsonStrM) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// 移动行
			List<PlnZyJgWorkbillEntity> entityList = new ArrayList<PlnZyJgWorkbillEntity>();
			for (String jsonStr : jsonstrList) {
				PlnZyJgWorkbillEntity proEntity = BaseHelper.jsonToEntity(
						PlnZyJgWorkbillEntity.class, jsonStr);
				entityList.add(proEntity);
			}
			// 定位行
			PlnZyJgWorkbillEntity entityM = BaseHelper.jsonToEntity(
					PlnZyJgWorkbillEntity.class, jsonStrM);
			if (entityM == null) {
				return core;
			}
			// String plineCode = entityM.getPlineCode();// 用于生产批次号
			// 查询炉计信息
			PlnZyJgWorkbillEntity listM = getQureyWoId(con, entityM.getWoId(),
					PlnZyJgWorkbillEntity.class);
			if (listM == null) {
				return core;
			}
			/**
			 * 1.判断数据
			 */
			// 1.1定位行数据状态
			if (listM.getZyBillStatus().equals("3")
					|| listM.getZyBillStatus().equals("4")) {
				return core;
			}
			int gxProSeqM = Integer.parseInt(entityM.getGxProSeq()); // 移至行序号
			int[] intArray = new int[entityList.size()];
			// 1.2移动行数据
			for (int i = 0; i < entityList.size(); i++) {
				PlnZyJgWorkbillEntity entity = entityList.get(i);
				if (entity == null) {
					return core;
				}
				PlnZyJgWorkbillEntity listM1 = getQureyWoId(con,
						entity.getWoId(), PlnZyJgWorkbillEntity.class);
				if (listM.getZyBillStatus().equals("3")
						|| listM.getZyBillStatus().equals("4")
						|| !entity.getGxProSeq().equals(listM1.getGxProSeq())) {
					return core;
				}
				intArray[i] = Integer.parseInt(entity.getGxProSeq());
			}
			// 1.3必须是在调整行的序号中间
			if (gxProSeqM >= intArray[0]
					&& gxProSeqM <= intArray[entityList.size() - 1]) {
				return core;
			}
			Arrays.sort(intArray);
			// 调整行操作
			/**
			 * 2. 前移(需要操作步骤:1.)
			 */
			if (gxProSeqM < intArray[0]) {
				for (int i = 0; i < entityList.size(); i++) {
					// 2.1序号自动调整
					PlnZyJgWorkbillEntity entity = entityList.get(i);
					seqIncrease(con, gxProSeqM,
							Integer.parseInt(entity.getGxProSeq()), 1);
					entity.setGxProSeq(String.valueOf(gxProSeqM));
					// 2.2修改移动数据
					String update = "UPDATE PLN_ZY_JG_WORKBILL T SET T.GX_PRO_SEQ =? WHERE T.WO_ID=?";
					ps = con.prepareStatement(update);
					ps.setObject(1, String.valueOf(gxProSeqM));
					ps.setObject(2, entity.getWoId());
					ps.executeUpdate();
					ps.close();
					gxProSeqM = gxProSeqM + 1;
				}
			} else {
				/**
				 * 3.后移
				 */
				// 如果不是小于最小序号,那么肯定是大于最大序号,前面加以限制
				int differNum = 0;
				for (int i = 0; i < entityList.size(); i++) {
					PlnZyJgWorkbillEntity entity = entityList.get(i);
					// 3.1序号自动调整
					seqIncrease(con, Integer.parseInt(entity.getGxProSeq())
							- differNum, gxProSeqM + 1, -1);

					entity.setGxProSeq(String.valueOf(gxProSeqM));
					// 3.2 修改数据
					String update = "UPDATE PLN_ZY_JG_WORKBILL T SET T.GX_PRO_SEQ =? WHERE T.WO_ID=?";
					ps = con.prepareStatement(update);
					ps.setObject(1, String.valueOf(gxProSeqM));
					ps.setObject(2, entity.getWoId());
					ps.executeUpdate();
					ps.close();
					differNum++;
				}
			}
			core.setResult(true);
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null) {
					con.rollback();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null && !con.isClosed())
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 修改计划支吨
	 */
	public CoreReturnObject doUpdateMach(ArrayList<ArrayList<String>> jslist,
			String userName) throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// 循环炉计划信息
			// String heatPlanNoAdd = "";
			// String heatPlanSeqNoAdd = "";
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);

				String latheGrpNo = list.get(0);
				String latheGrpNm = list.get(1);
				String latheCutNm = list.get(2);
				String woId = list.get(3);

				// 查询炉计信息
				PlnZyJgWorkbillEntity listM = getQureyWoId(conn, woId,
						PlnZyJgWorkbillEntity.class);
				if (listM == null) {
					cro.setV_errMsg("工单已发生变化,请重新查询!");
					return cro;
				}
				if (listM.getZyBillStatus().equals("4")) {
					cro.setV_errMsg("选择的工单已关闭,不能修改!");
					return cro;
				}
				// 修改原实际工单支吨
				String updateOldC = " UPDATE PLN_ZY_JG_WORKBILL T SET T.LATHE_GRP_NO=?,"
						+ " T.LATHE_GRP_NM=?,T.LATHE_CUT_NM=? WHERE T.WO_ID=?";
				ps = conn.prepareStatement(updateOldC);
				ps.setObject(1, latheGrpNo);
				ps.setObject(2, latheGrpNm);
				ps.setObject(3, latheCutNm);
				ps.setObject(4, woId);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 炉计划下发
	 * 
	 * @param jslist
	 * @param userName
	 *            操作人
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doFurnacePlan(ArrayList<ArrayList<String>> jslist,
			String userName, String flag) 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);
			// 循环虚拟炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String heatPlanNo = list.get(0);
				String planstatus = "";
				String sql = "SELECT T.PLANSTATUS,T.HEAT_PLAN_NO,T.JUDGE_STOVE_NO FROM PLN_ZY_JG_M T WHERE T.HEAT_PLAN_NO=?";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, heatPlanNo);
				rs = ps.executeQuery();
				if (rs.next()) {
					String judgeStoveNo = rs.getString("JUDGE_STOVE_NO");
					heatPlanNo = rs.getString("HEAT_PLAN_NO");
					if (flag.equals("1")) {// 撤销下发
						if (rs.getString("PLANSTATUS").equals("20")) {
							cro.setV_errMsg("判定炉号(" + judgeStoveNo
									+ ")已是生产中,不能撤销下发!");
							return cro;
						}
						if (rs.getString("PLANSTATUS").equals("30")) {
							cro.setV_errMsg("判定炉号(" + judgeStoveNo
									+ ")已是生产完成,不能撤销下发!");
							return cro;
						}
						if (rs.getString("PLANSTATUS").equals("40")) {
							cro.setV_errMsg("判定炉号(" + judgeStoveNo
									+ ")已是关闭,不能撤销下发!");
							return cro;
						}
						planstatus = "00";
					} else {
						planstatus = "10";
					}
				}
				rs.close();
				ps.close();
				// 修改接箍实际炉计划
				String updateM = "UPDATE PLN_ZY_JG_M T SET T.PLANSTATUS=?,T.UPDATE_NAME=?,T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') WHERE T.HEAT_PLAN_NO=?";
				ps = conn.prepareStatement(updateM);
				ps.setObject(1, planstatus);
				ps.setObject(2, userName);
				ps.setObject(3, dateTime);
				ps.setObject(4, heatPlanNo);
				ps.executeUpdate();
				ps.close();
			}
			if (flag.equals("1")) {
				cro.setV_errMsg("撤销成功!");
			} else {
				cro.setV_errMsg("下发成功!");
			}
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					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 parmList
	 * @return
	 */
	public CoreReturnObject updateStatus(ArrayList<String> parmList)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for (String str : parmList)
			{
				PlnZyJgWorkbillEntity plnEntity = EntityTool.getEntityByJSONStr(str,PlnZyJgWorkbillEntity.class);
				String updateBillSql = CoreXmlSqlParsersFactory.getSql("FrmPlnZyJgWorkBill.updateStatus");
				updateBillSql = EntityTool.fillSqlByEntity(updateBillSql,plnEntity);
				sqllist.add(updateBillSql);
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("设置完成成功!");
			}
		} 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;
	}
}