package com.steering.mes.mcp.coup;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.QualityDesignTool;
import com.steering.comm.db.DBCommon;
import com.steering.common.EntityTool;
import com.steering.mes.mcp.common.PlanService;
import com.steering.mes.mcp.entity.CouplingOfflineResultEntity;
import com.steering.mes.mcp.entity.CouplingOutsourcResultEntity;
import com.steering.mes.mcp.entity.MatBcMEntity;
import com.steering.mes.mcp.entity.PhosphateResult;
import com.steering.mes.mcp.entity.MchEntity.PlnZyJgWorkbillEntity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class FrmDownLineManage extends DBCommon {

	/**
	 * 查询工序点
	 * 
	 * @param list
	 * @param startTim
	 * @param endTim
	 * @return
	 */
	public CoreReturnObject doQuery(String sortCode) {

		String sql = "";
		sql = CoreXmlSqlParsersFactory.getSql("FrmDownLineManage.doQuery");
		return this.getData(sql, new Object[] { sortCode });
	}

	/***
	 * 查询返线
	 * 
	 * @return
	 */
	public CoreReturnObject doQueryReturnLine(ArrayList<String> list,
			String[] plineCode) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.doQueryReturnLine");
		if (!list.get(0).equals("")) {
			sql += "  AND T.RE_TIME BETWEEN TO_DATE('" + list.get(0)
					+ "','YYYY-MM-DD HH24:MI:SS') " + " AND TO_DATE('"
					+ list.get(1) + "','YYYY-MM-DD HH24:MI:SS')";
		}
		if (!list.get(2).equals("")) {
			sql += " AND T.JUDGE_STOVE_NO ='" + list.get(2) + "'";
		}
		if (!list.get(3).equals("")) {
			sql += " AND T.WO_ID || '&' LIKE '%' || '" + list.get(3)
					+ "' || '%'";
		}
		// sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineCode);
		if (!list.get(4).equals("")) {
			sql += " AND T.STATION_CODE ='" + list.get(4) + "'";
		}
		return this.getData(sql);
	}

	/***
	 * 查询离线
	 * 
	 * @return
	 */
	public CoreReturnObject doQueryOffLine(ArrayList<String> list,
			String[] plineCode) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.doQueryOffLine");
		if (!list.get(0).equals("")) {
			sql += "  AND T.CREATE_TIME BETWEEN TO_DATE('" + list.get(0)
					+ "','YYYY-MM-DD HH24:MI:SS') " + " AND TO_DATE('"
					+ list.get(1) + "','YYYY-MM-DD HH24:MI:SS')";
		}
		if (!list.get(2).equals("")) {
			sql += " AND T.JUDGE_STOVE_NO ='" + list.get(2) + "'";
		}
		if (!list.get(3).equals("")) {
			sql += " AND T.WO_ID || '&' LIKE '%' || '" + list.get(3)
					+ "' || '%'";
		}
		// sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineCode);
		if (!list.get(4).equals("")) {
			sql += " AND T.STATION_CODE ='" + list.get(4) + "'";
		}
		return this.getData(sql);
	}

	/***
	 * 查询委外
	 * 
	 * @return
	 */
	public CoreReturnObject doQueryOutSourc(ArrayList<String> list,
			String[] plineCode) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.doQueryOutSourc");
		if (!list.get(0).equals("")) {
			sql += "  AND T.CREATE_TIME BETWEEN TO_DATE('" + list.get(0)
					+ "','YYYY-MM-DD HH24:MI:SS') " + " AND TO_DATE('"
					+ list.get(1) + "','YYYY-MM-DD HH24:MI:SS')";
		}
		if (!list.get(2).equals("")) {
			sql += " AND T.JUDGE_STOVE_NO ='" + list.get(2) + "'";
		}
		if (!list.get(3).equals("")) {
			sql += " AND T.WO_ID || '&' LIKE '%' || '" + list.get(3)
					+ "' || '%'";
		}
		// sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineCode);
		if (!list.get(4).equals("")) {
			sql += " AND T.ENTRUSTED_LOG ='" + list.get(4) + "'";
		}
		return this.getData(sql);
	}

	/**
	 * 根据工单ID查询工单
	 */
	public static <T> T getQureyWoId(Connection con, String woId, Class<T> cls)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.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
	 * @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("FrmDownLineManage.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 con
	 * @param plineCode
	 * @param gxProSeqB
	 * @param gxProSeqE
	 *            (如果没有上限，请设为负数)
	 * @param num
	 * @param processCode
	 * @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();
	}

	/**
	 * 获取工单号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;
	}

	/**
	 * 工单拆分
	 */
	public CoreReturnObject doBreakUp(ArrayList<ArrayList<String>> jslist,
			String userName, String spitWgt, String spitNum) {
		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);
				String result = list.get(1);

				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;
				}
				String resultNo = "";
				String sqlloading = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.queryLoadRESULT");// 查询最大实绩编号
				ps = conn.prepareStatement(sqlloading);
				ps.setObject(1, listM.getPlineCode());
				ps.setObject(2, "01");
				ps.setObject(3, listM.getPlineCode() + "01");
				ResultSet rs1 = ps.executeQuery();
				if (rs1.next()) {
					resultNo = rs1.getString("RESULT_NO");
				}
				rs1.close();
				ps.close();
				// if (plnNum - reaNum <= 0) {
				// cro.setV_errMsg("选中的炉计划已全部上料,不能拆分!");
				// return cro;
				// }
				int addPlnNum = Integer.parseInt(spitNum);
				double addspWt = Double.parseDouble(spitWgt);
				double singWt = Double.parseDouble(spitWgt)
						/ Integer.parseInt(spitNum);
				int gxProSeq = Integer.parseInt(listM.getGxProSeq());
				// 查询炉计划ID
				heatPlanNoAdd = getPlnJgWork(conn, listM.getHeatPlanSqe());
				// 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;
				int count = 0;
				ArrayList<String> list1 = new ArrayList<String>();
				ArrayList<String> list2 = new ArrayList<String>();
				int num = 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.REAL_BL_NUM=TO_NUMBER(T.REAL_BL_NUM)-TO_NUMBER(?),T.REAL_BL_WT=TO_NUMBER(T.REAL_BL_WT)-TO_NUMBER(?),"
						+ " T.PLAN_BL_WT=TO_NUMBER(T.PLAN_BL_WT)-TO_NUMBER(?),T.IFSPLIT ='1' WHERE T.WO_ID=?";
				ps = conn.prepareStatement(updateOldC);
				ps.setObject(1, plnJgSy);
				ps.setObject(2, xqJgSy);
				ps.setObject(3, addPlnNum);
				ps.setObject(4, addPlnNum);
				ps.setObject(5, addspWt);
				ps.setObject(6, addspWt);
				ps.setObject(7, woId);
				ps.executeUpdate();
				ps.close();

				// 查询上料实绩条数
				String queryCount = " SELECT count(*) count FROM COUPLING_LOADING_RESULT T WHERE T.WO_ID = ?";
				ps = conn.prepareStatement(queryCount);
				ps.setObject(1, woId);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					count = Integer.parseInt(rs.getString("count"));
				}
				rs.close();
				ps.close();

				String queryLoad = " SELECT t.result_no,t.load_pieces,t.load_weight FROM COUPLING_LOADING_RESULT T WHERE T.WO_ID = ? group by t.result_no,t.load_pieces,t.load_weight order by t.result_no";
				ps = conn.prepareStatement(queryLoad);
				ps.setObject(1, woId);
				rs = ps.executeQuery();
				while (rs.next()) {
					list1.add(rs.getString("result_no"));
					list2.add(rs.getString("load_pieces"));
				}
				rs.close();
				ps.close();

				if (count > 0) {
					for (int j = 0; j < list1.size(); j++) {
						if (num >= Integer.parseInt(list2.get(j))) {
							// 修改上料实绩工单号
							String updateLoad = " UPDATE COUPLING_LOADING_RESULT T SET T.WO_ID = ? WHERE T.RESULT_NO = ?";
							ps = conn.prepareStatement(updateLoad);
							ps.setObject(1, heatPlanNoAdd);
							ps.setObject(2, list1.get(j));
							ps.executeUpdate();
							ps.close();
							num = num - Integer.parseInt(list2.get(j));
						} else {
							// 拆分上料实绩工单号
							String updateLoad = " UPDATE COUPLING_LOADING_RESULT T SET T.LOAD_PIECES=TO_NUMBER(T.LOAD_PIECES)-TO_NUMBER(?),"
									+ " T.LOAD_WEIGHT=TO_NUMBER(T.LOAD_WEIGHT)-TO_NUMBER(?) WHERE T.RESULT_NO=?";
							ps = conn.prepareStatement(updateLoad);
							ps.setObject(1, num);
							ps.setObject(2, num * singWt);
							ps.setObject(3, list1.get(j));
							ps.executeUpdate();
							ps.close();
							// 新增上料实绩
							String update = CoreXmlSqlParsersFactory
									.getSql("FrmDownLineManage.AddLoad");
							ps = conn.prepareStatement(update);
							ps.setObject(1, resultNo);
							ps.setObject(2, heatPlanNoAdd);
							ps.setObject(3, num);
							ps.setObject(4, num * singWt);
							ps.setObject(5, list1.get(j));
							ps.executeUpdate();
							ps.close();
							break;
						}
					}
					// for(int j=0;j<count;j++)
					// {
					//						
					// }
				} else {
					cro.setV_errMsg("没查询到上料支数!");
					return cro;
				}

				// if(listM.getHeatPlanNoOld().equals("")){
				// listM.setHeatPlanNoOld(heatPlanNo);
				// }

				// 新增离线实绩
				String update = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.AddOffline");
				ps = conn.prepareStatement(update);
				ps.setObject(1, resultNo);
				ps.setObject(2, heatPlanNoAdd);
				ps.setObject(3, addPlnNum);
				ps.setObject(4, addspWt);
				ps.setObject(5, woId);
				ps.executeUpdate();
				ps.close();

				// 减去离线实绩
				String updateOff = " UPDATE COUPLING_OFFLINE_RESULT T SET T.OFFLINE_NUM=TO_NUMBER(T.OFFLINE_NUM)-TO_NUMBER(?),"
						+ " T.OFFLINE_WT=TO_NUMBER(T.OFFLINE_WT)-TO_NUMBER(?) WHERE T.RESULT_NO=?";
				ps = conn.prepareStatement(updateOff);
				ps.setObject(1, addPlnNum);
				ps.setObject(2, addspWt);
				ps.setObject(3, result);
				ps.executeUpdate();
				ps.close();

				listM.setWoId(heatPlanNoAdd);
				listM.setPlanBlNum(String.valueOf(addPlnNum));
				listM.setPlanBlWt(String.valueOf(addspWt));
				listM.setRealBlNum(String.valueOf(addPlnNum));
				listM.setRealBlWt(String.valueOf(addspWt));
				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("FrmDownLineManage.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;
	}

	/**
	 * 返线
	 * 
	 * @param con
	 * @param cor
	 * @param parm
	 * @param parm1
	 * @throws SQLException
	 */
	public static CoreReturnObject doReturnLine(Connection con,
			CoreReturnObject cor, ArrayList<String> parm,
			ArrayList<String> parm1) throws SQLException {
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String systime = dateFormat.format(now);
		String updateOff = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.UpdateOff");// 修改离线表返线支数
		PreparedStatement pstaupdateOff = con.prepareStatement(updateOff);

		String addMatBc = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.deleteMatBc");
		PreparedStatement pastDeletMatBc = con.prepareStatement(addMatBc);// 删除材料号

		String addButt = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.deleteMatBut");
		PreparedStatement pstaDeletButt = con.prepareStatement(addButt);// 删除位置表
		String plineCode = parm1.get(0);
		String name = parm1.get(1);
		String bz = parm1.get(2);
		String bc = parm1.get(3);
		String turnLinGx = parm1.get(4);// 返线工序点
		String storageNo = parm1.get(5);// 仓库
		String turnLinName = parm1.get(8);// 返线工序点

		for (String str : parm) {
			CouplingOfflineResultEntity jgOffline = EntityTool
					.getEntityByJSONStr(str.toString(),
							CouplingOfflineResultEntity.class);
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmDownLineManage.doQueryOffLine2");//
			psta = con.prepareStatement(sql);
			psta.setString(1, jgOffline.getResultNo());
			psta.setString(2, jgOffline.getOffXh());
			rs = psta.executeQuery();
			String OfflineNumBj = jgOffline.getOfflineNumBj();
			String stationCode = jgOffline.getStationCode();
			List<CouplingOfflineResultEntity> data = EntityTool.getEntitysByRs(
					rs, CouplingOfflineResultEntity.class);
			psta.close();
			rs.close();
			if (data.size() <= 0) {
				cor.setV_errMsg("离线数据不存在,请刷新数据!");
				return cor;
			}

			DecimalFormat df = new DecimalFormat("0.000");
			double offwt = 0;
			if (jgOffline.getOfflineWt() != null
					&& !jgOffline.getOfflineWt().equals("")) {
				offwt = Double.parseDouble(jgOffline.getOfflineWt());
			}
			double weight = (offwt / Integer
					.parseInt(jgOffline.getOfflineNum()))
					* Integer.parseInt(OfflineNumBj);
			String weight1 = df.format(weight);
			int remCount = 0;// 返线支数
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmDownLineManage.QueryOffLineReNum");// 查询可返线个
			psta = con.prepareStatement(sql);
			psta.setString(1, jgOffline.getJudgeStoveNo());
			psta.setString(2, jgOffline.getBatchNo());
			psta.setString(3, jgOffline.getResultNo());
			psta.setString(4, jgOffline.getOffXh());
			psta.setString(5, jgOffline.getWoId());
			rs = psta.executeQuery();
			if (rs.next()) {
				remCount = Integer.parseInt(rs.getString("RE_NUM"));
			}
			rs.close();
			psta.close();
			if (remCount == 0) {
				cor.setV_errMsg("此炉已返线!");
				return cor;
			}
			String cutNum = "";
			String sqlloadingOff = CoreXmlSqlParsersFactory
					.getSql("FrmInLibrary.QueryOffCut");// 查询委外返线个数
			psta = con.prepareStatement(sqlloadingOff);
			psta.setObject(1, jgOffline.getWoId());
			rs = psta.executeQuery();
			while (rs.next()) {
				cutNum = rs.getString("INCISION_NUM");
			}
			rs.close();
			psta.close();
			if (Integer.parseInt(cutNum) > 0) {
				// 修改工单拆分状态
				String updateOldC = " UPDATE PLN_ZY_JG_WORKBILL T SET T.IFSPLIT ='1' WHERE T.WO_ID=?";
				psta = con.prepareStatement(updateOldC);
				psta.setObject(1, jgOffline.getWoId());
				psta.executeUpdate();
				psta.close();
			}

			String woId = jgOffline.getWoId();
			PlnZyJgWorkbillEntity pln = getSendJgCInfo(con, woId);

			if (pln == null) {
				cor.setV_errMsg("无工单数据,不允许此操作！");
				return cor;
			}

			if (stationCode.equals("700301")) {
				// 上料点离线
				List<String> matNo = new ArrayList<String>();
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.QueryOffMatNo");// 查询半成品材料表离线支
				psta = con.prepareStatement(sql);
				psta.setString(1, jgOffline.getJudgeStoveNo());
				psta.setString(2, jgOffline.getBatchNo());
				psta.setString(3, jgOffline.getBatchGroudNo());
				psta.setObject(4, Integer.parseInt(OfflineNumBj) + 1);
				rs = psta.executeQuery();
				while (rs.next()) {
					matNo.add(rs.getString("MAT_NO"));
				}
				rs.close();
				psta.close();

				for (int i = 0; i < matNo.size(); i++) {
					String matNo1 = matNo.get(i);
					// 删除材料表
					pastDeletMatBc.setObject(1, matNo1);
					pastDeletMatBc.addBatch();
					// 删除位置表
					pstaDeletButt.setObject(1, matNo1);
					pstaDeletButt.addBatch();
				}
				pastDeletMatBc.executeBatch();
				pstaDeletButt.executeBatch();
				pastDeletMatBc.close();
				pstaDeletButt.close();
			} else {
				String matNo = "";
				int proNum = 0;
				// double proWt = 0;
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.QueryOffCoupMat");// 查询接箍库存材料表离线个
				psta = con.prepareStatement(sql);
				psta.setString(1, jgOffline.getJudgeStoveNo());
				psta.setString(2, jgOffline.getBatchNo());
				psta.setString(3, jgOffline.getWoId());
				rs = psta.executeQuery();
				if (rs.next()) {
					matNo = rs.getString("MAT_NO");
					proNum = rs.getInt("PRO_NUM");
					// proWt = rs.getDouble("PRO_WT");
				}
				rs.close();
				psta.close();

				if (matNo.equals("")) {
					cor.setV_errMsg("无对应的离线接箍库存数据!");
					return cor;
				}
				// 判断返线个是否与接箍库存离线个相等
				if (proNum - Integer.parseInt(OfflineNumBj) <= 0) {
					// 删除接箍材料表
					String deleteMat = " DELETE COUPLING_MAT_M WHERE MAT_NO = ?";
					psta = con.prepareStatement(deleteMat);
					psta.setObject(1, matNo);
					psta.executeUpdate();
					psta.close();
					// 删除接箍位置表
					String deleteMatBut = " DELETE COUPLING_MAT_BUTTRESS WHERE MAT_NO = ?";
					psta = con.prepareStatement(deleteMatBut);
					psta.setObject(1, matNo);
					psta.executeUpdate();
					psta.close();
				} else {
					// 修改接箍库存表
					String updateMat = "UPDATE COUPLING_MAT_M T SET T.PRO_NUM=TO_NUMBER(T.PRO_NUM)-TO_NUMBER(?),T.PRO_WT=TO_NUMBER(T.PRO_WT)-TO_NUMBER(?) WHERE T.MAT_NO=?";
					psta = con.prepareStatement(updateMat);
					psta.setObject(1, OfflineNumBj);
					psta.setObject(2, weight1);
					psta.setObject(3, matNo);
					psta.executeUpdate();
					psta.close();
					// 修改接箍位置表
					String updateMatBut = " UPDATE COUPLING_MAT_BUTTRESS T SET T.PIECES=TO_NUMBER(T.PIECES)-TO_NUMBER(?),T.WEIGHT=TO_NUMBER(T.WEIGHT)-TO_NUMBER(?) WHERE T.MAT_NO=?";
					psta = con.prepareStatement(updateMatBut);
					psta.setObject(1, OfflineNumBj);
					psta.setObject(2, weight1);
					psta.setObject(3, matNo);
					psta.executeUpdate();
					psta.close();
				}
			}
			// 修改离线实绩返线个数
			pstaupdateOff.setObject(1, OfflineNumBj);
			pstaupdateOff.setObject(2, weight1);
			pstaupdateOff.setObject(3, turnLinGx);
			pstaupdateOff.setObject(4, systime);
			pstaupdateOff.setObject(5, name);
			pstaupdateOff.setObject(6, jgOffline.getResultNo());
			pstaupdateOff.setObject(7, jgOffline.getOffXh());
			pstaupdateOff.addBatch();
			pstaupdateOff.executeBatch();
			pstaupdateOff.close();
		}
		return cor;
	}

	/**
	 * 返线
	 * 
	 * @param result
	 * @return
	 */
	public CoreReturnObject doReturnLine(ArrayList<String> parm,
			ArrayList<String> parm1) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		try {
			con.setAutoCommit(false); // 取消自动提交事务
			cor = doReturnLine(con, cor, parm, parm1);
			if (cor.getV_errMsg().equals("")) {
				cor.setV_errMsg("返线成功！");
				con.commit();
			} else {
				return cor;
			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 返线交库（返线并保存）
	 * 
	 * @param parm
	 * @param parm1
	 * @return
	 */
	public CoreReturnObject doReturnLineAddPhosphateResult(
			ArrayList<String> parm, ArrayList<String> parm1) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PhosphateResultService pho = new PhosphateResultService();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String systime = dateFormat.format(now);
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		String isCpjg = "0"; //是否有成品加工项目
		String proNum = ""; //磷化个数
		try {
			con.setAutoCommit(false); // 取消自动提交事务
			cor = doReturnLine(con, cor, parm, parm1);// 返线
			if (!cor.getV_errMsg().equals("")) {
				return cor;
			}

			String[] array = {"0","0","1"};
			ArrayList<Object> list1 = new ArrayList<Object>();
			ArrayList<Object> resultList= new ArrayList<Object>(Arrays.asList(array));
			Collections.addAll(resultList,array);
			for (String str : parm) {
				CouplingOfflineResultEntity jgOffline = EntityTool
						.getEntityByJSONStr(str.toString(),
								CouplingOfflineResultEntity.class);
				PhosphateResult result = new PhosphateResult();

				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.QueryHttEntrustResult");// 查询委托实绩
				psta = con.prepareStatement(sql);
				psta.setString(1, jgOffline.getSubcontractNo());
				rs = psta.executeQuery();
				if (rs.next()) {
					isCpjg = rs.getString("isCpjg");
					proNum = rs.getString("PRO_NUM");
				}
				rs.close();
				psta.close();
				if (isCpjg.equals("0")) {
					cor.setV_errMsg("此炉没有成口加工项目，不能返线交库!");
					return cor;
				}
				result.setWoId(jgOffline.getWoId());
				result.setPlineCode(jgOffline.getPlineCode());
				result.setColUser(parm1.get(1));
				result.setColShft(parm1.get(2));
				result.setColGroup(parm1.get(3));
				result.setColCount(proNum);// 磷化个数
				result.setCreateTime(systime);
				result.setRemark("返线交库");
				cor = pho.addPhosphateResult(con, cor, result, list1, "700310",
						"700311", resultList, "0", jgOffline.getWoId(), "0"); // 新增磷化检测实绩交库
				if (!cor.getV_errMsg().equals("")) {
					return cor;
				}
			}

			cor.setV_errMsg("返线交库成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 撤销返线
	 * 
	 * @param result
	 * @return
	 */
	public CoreReturnObject doCancelReturnLine(ArrayList<String> parm,
			ArrayList<String> parm1) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String systime = dateFormat.format(now);
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		try {
			con.setAutoCommit(false); // 取消自动提交事务
			String updateOff = CoreXmlSqlParsersFactory
					.getSql("FrmDownLineManage.UpdateOff");// 修改离线表返线支数
			PreparedStatement pstaupdateOff = con.prepareStatement(updateOff);
			// String updatePort = CoreXmlSqlParsersFactory
			// .getSql("FrmDownLineManage.UpdatePortVrpReturn");// 修改管号队列表
			// PreparedStatement pstaUpdatePort =
			// con.prepareStatement(updatePort);
			// String addMatBc = CoreXmlSqlParsersFactory
			// .getSql("FrmDownLineManage.AddJgOfflineMat");// 新增材料表
			// PreparedStatement pastaddMatBc = con.prepareStatement(addMatBc);
			// String addButt = CoreXmlSqlParsersFactory
			// .getSql("FrmDownLineManage.AddJgBut");// 新增位置表
			// PreparedStatement pstaAddButt = con.prepareStatement(addButt);
			String name = parm1.get(1);
			String storageNo = parm1.get(4);// 仓库

			for (String str : parm) {
				CouplingOfflineResultEntity jgOffline = EntityTool
						.getEntityByJSONStr(str.toString(),
								CouplingOfflineResultEntity.class);

				List<String> matNo = new ArrayList<String>();

				String woId = jgOffline.getWoId();
				PlnZyJgWorkbillEntity pln = getSendJgCInfo(con, woId);

				if (pln == null) {
					cor.setV_errMsg("无工单数据,不允许此操作！");
					return cor;
				}
				if (pln.getZyBillStatus().equals("3")) {
					cor.setV_errMsg("该炉对应的工单已生产完成,不允许次操作！");
					return cor;
				}
				if (pln.getZyBillStatus().equals("4")) {
					cor.setV_errMsg("该炉对应的工单已关闭,不允许次操作！");
					return cor;
				}
				String OfflineNumBj = jgOffline.getReNum();
				String stationCode = jgOffline.getStationCode();
				String JudgeNo = jgOffline.getJudgeStoveNo();
				String BatchNo = jgOffline.getBatchNo();
				String groupNo = jgOffline.getBatchGroudNo();
				String Woid = jgOffline.getWoId();
				String UserName = jgOffline.getColUser();
				String latGx = jgOffline.getStationCode();
				String reultNo = jgOffline.getResultNo();
				// 查询工单信息
				PlnZyJgWorkbillEntity work = CoupLoadingService.getPlanWoId(
						con, Woid, PlnZyJgWorkbillEntity.class);
				if (work == null) {
					cor.setV_errMsg("未查询到工单信息,请确认!");
					return cor;
				}
				if (!work.getZyBillStatus().equals("2")) {
					cor.setV_errMsg("工单状态不是生产中,不允许此操作!");
					return cor;
				}
				if (stationCode.equals("700301")) {
					List<MatBcMEntity> listMat = getQureyPortJg(con, JudgeNo,
							BatchNo, groupNo, Integer.parseInt(OfflineNumBj));
					//
					for (MatBcMEntity lvMat : listMat) {
						// 新增材料表
						if (!OfflineNumBj.equals("")
								&& !OfflineNumBj.equals("0")) {

							PlanService.AddJgMatBcM(con, "H", UserName, "11",
									lvMat.getMatNo(), latGx, Woid, "", work
											.getJudgeStoveNo());
						}
					}
				} else {
					// 新增材料表
					if (!OfflineNumBj.equals("") && !OfflineNumBj.equals("0")) {
						// 判断是否存在该工单已经离线
						String CouplingMatNo = "";
						double SINGLEWEIGHT = 0;
						String sqlloading = CoreXmlSqlParsersFactory
								.getSql("PlanService.selectOfflineCount");
						psta = con.prepareStatement(sqlloading);
						psta.setObject(1, JudgeNo);
						psta.setObject(2, BatchNo);
						psta.setObject(3, Woid);
						ResultSet rs1 = psta.executeQuery();
						if (rs1.next()) {
							CouplingMatNo = rs1.getString("Mat_No");
							SINGLEWEIGHT = rs1.getDouble("SINGLEWEIGHT");
						}
						rs1.close();
						psta.close();
						if (CouplingMatNo == null || CouplingMatNo.equals("")) {
							// 获取材料号
							String matNo1 = doAddMatNo(JudgeNo, Woid, con);

							PlanService.AddJgCoupMatNo(con, "H", UserName,
									"11", matNo1, latGx, Woid, "",
									OfflineNumBj, reultNo, work, systime);
						} else {
							// 修改接箍库存表
							String updateMat = "UPDATE COUPLING_MAT_M T SET T.PRO_NUM=TO_NUMBER(T.PRO_NUM)+TO_NUMBER(?),T.PRO_WT=TO_NUMBER(T.PRO_WT)+TO_NUMBER(?) WHERE T.MAT_NO=?";
							psta = con.prepareStatement(updateMat);
							psta.setObject(1, OfflineNumBj);
							psta.setObject(2, (SINGLEWEIGHT / 1000)
									* Integer.parseInt(OfflineNumBj));
							psta.setObject(3, CouplingMatNo);
							psta.executeUpdate();
							psta.close();
							// 修改接箍位置表
							String updateMatBut = " UPDATE COUPLING_MAT_BUTTRESS T SET T.PIECES=TO_NUMBER(T.PIECES)+TO_NUMBER(?),T.WEIGHT=TO_NUMBER(T.WEIGHT)+TO_NUMBER(?) WHERE T.MAT_NO=?";
							psta = con.prepareStatement(updateMatBut);
							psta.setObject(1, OfflineNumBj);
							psta.setObject(2, (SINGLEWEIGHT / 1000)
									* Integer.parseInt(OfflineNumBj));
							psta.setObject(3, CouplingMatNo);
							psta.executeUpdate();
							psta.close();
						}

					}

				}

				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.QueryReturnMatNo");// 查询管号队列返线材料号
				psta = con.prepareStatement(sql);
				psta.setString(1, jgOffline.getWoId());
				psta.setString(2, jgOffline.getReturnProcess());
				psta.setObject(3, Integer.parseInt(jgOffline.getReNum()) + 1);
				rs = psta.executeQuery();
				while (rs.next()) {
					matNo.add(rs.getString("MAT_NO"));
				}
				rs.close();
				psta.close();

				// if (matNo.size() == 0) {
				// cor.setV_errMsg("物料已发生改变,不允许撤销!");
				// return cor;
				// }
				// for (int i = 0; i < matNo.size(); i++) {
				//
				// String QcmStatus = "11";
				// pastaddMatBc.setObject(1, "");
				// pastaddMatBc.setObject(2, name);
				// pastaddMatBc.setObject(3, QcmStatus);
				// pastaddMatBc.setObject(4, QcmStatus.equals("22") ? "000000"
				// : "");
				// pastaddMatBc.setObject(5, "");
				// pastaddMatBc.setObject(6, matNo.get(i));
				// pastaddMatBc.setObject(7, "");
				// pastaddMatBc.setObject(8,
				// QcmStatus.equals("22") ? "40740705" : "");
				// pastaddMatBc.setObject(9, jgOffline.getWoId());
				//
				// pastaddMatBc.addBatch();
				//
				// pstaAddButt.setObject(1, name);
				// pstaAddButt.setObject(2, jgOffline.getWoId());
				// pstaAddButt.setObject(3, matNo.get(i));
				// pstaAddButt.addBatch();
				//
				// }
				// pastaddMatBc.executeBatch();
				// pstaAddButt.executeBatch();
				// pstaAddButt.close();
				// pastaddMatBc.close();
				// 修改离线表返线支数
				pstaupdateOff.setObject(1, "-" + jgOffline.getReNum());
				pstaupdateOff.setObject(2, "-" + jgOffline.getReWt());
				pstaupdateOff.setObject(3, "");
				pstaupdateOff.setObject(4, "");
				pstaupdateOff.setObject(5, "");
				pstaupdateOff.setObject(6, jgOffline.getResultNo());
				pstaupdateOff.setObject(7, jgOffline.getOffXh());
				pstaupdateOff.addBatch();

			}
			pstaupdateOff.executeBatch();
			pstaupdateOff.close();

			cor.setV_errMsg("撤销返线成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 查询接箍对列表材料号
	 * 
	 * @param con
	 * @param matStatus
	 *            材料状态
	 * @param judgeStoveNo
	 *            判定炉号
	 * @throws SQLException
	 */
	public static List<MatBcMEntity> getQureyPortJg(Connection con,
			String judgeStoveNo, String batchNo, String batchGroupBy,
			int takeCount) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoupCutService.QueryMatGp");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, judgeStoveNo);
		ps.setObject(2, batchNo);
		ps.setObject(3, batchGroupBy);
		// ps.setObject(4, proessCode);
		ps.setObject(4, takeCount);
		ps.setObject(5, judgeStoveNo);
		ps.setObject(6, batchNo);
		ps.setObject(7, batchGroupBy);
		ResultSet rs = ps.executeQuery();
		List<MatBcMEntity> list = EntityTool.getEntitysByRs(rs,
				MatBcMEntity.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (MatBcMEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/***
	 * 生产材料号
	 * 
	 * @param plineCode
	 * @param zygNo
	 * @param connection
	 * @return
	 */
	public String doAddMatNo(String judNo, String woId, Connection connection) {
		String MatNo = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		// SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd");
		String sqlloading = CoreXmlSqlParsersFactory
				.getSql("CoupCutService.queryMaxMatNo");// 查询最大材料号

		try {
			psta = connection.prepareStatement(sqlloading);
			psta.setObject(1, judNo);
			psta.setObject(2, judNo);
			ResultSet rs1 = psta.executeQuery();
			if (rs1.next()) {
				MatNo = rs1.getString("MAT_NO");
			}
			rs1.close();
			psta.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return MatNo;
	}

	/***
	 * 查询工单信息
	 * 
	 * @param con
	 * @param woId
	 * @return
	 * @throws SQLException
	 */
	public static PlnZyJgWorkbillEntity getSendJgCInfo(Connection con,
			String woId) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.QueryWoIdJg");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, woId);
		ResultSet rs = ps.executeQuery();
		List<PlnZyJgWorkbillEntity> sendPlanCEntitys = EntityTool
				.getEntitysByRs(rs, PlnZyJgWorkbillEntity.class);
		rs.close();
		ps.close();
		if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
			return null;
		} else {
			for (PlnZyJgWorkbillEntity sendPlanCEntity : sendPlanCEntitys) {
				QualityDesignTool.nullConverNullString(sendPlanCEntity);
			}
			return sendPlanCEntitys.get(0);
		}
	}

	/**
	 * 获取最大委外编号
	 * 
	 * @param conn
	 *            c
	 * @throws Exception
	 *             异常处理
	 */
	public static String queryEntrustrMax(Connection conn) throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd");
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.queryEntrustrMax");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, matter1.format(dt));
		psta.setString(2, matter.format(dt));
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("ENTRUSTED_NO");
		}
		rs.close();
		psta.close();
		return seq;
	}

	/**
	 * 委外加工
	 * 
	 * @param result
	 * @return
	 */
	public CoreReturnObject doOutSourc(ArrayList<String> parm,
			ArrayList<String> parm1) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String systime = dateFormat.format(now);
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		try {
			con.setAutoCommit(false); // 取消自动提交事务

			String memo = parm1.get(0);// 委托说明
			String harshType = parm1.get(1);// 粗加工类型
			String stationUnitCode = parm1.get(2);// 委托说明
			String stationUnitDesc = parm1.get(3);// 粗加工类型
			// String plineCode = parm1.get(4);
			String name = parm1.get(5);
			String bc = parm1.get(7);
			String bz = parm1.get(6);

			String entrusNo = queryEntrustrMax(con);
			String coatingType = "";
			for (String str : parm) {
				CouplingOfflineResultEntity jgOffline = EntityTool
						.getEntityByJSONStr(str.toString(),
								CouplingOfflineResultEntity.class);
				String woId = jgOffline.getWoId();
				PlnZyJgWorkbillEntity pln = getSendJgCInfo(con, woId);

				if (pln == null) {
					cor.setV_errMsg("无工单数据,,不允许此操作！");
					return cor;
				}
				if (pln.getZyBillStatus().equals("3")) {
					cor.setV_errMsg("该炉对应的工单已生产完成,不允许次操作！");
					return cor;
				}
				if (pln.getZyBillStatus().equals("4")) {
					cor.setV_errMsg("该炉对应的工单已关闭,不允许次操作！");
					return cor;
				}
				double offWt = 0;
				coatingType = pln.getCoatType();
				int remCount = 0;// 委外支数
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.QueryOffLineReNum");// 查询可委外
				psta = con.prepareStatement(sql);
				psta.setString(1, jgOffline.getJudgeStoveNo());
				psta.setString(2, jgOffline.getBatchNo());
				psta.setString(3, jgOffline.getResultNo());
				psta.setString(4, jgOffline.getOffXh());
				psta.setString(5, jgOffline.getWoId());
				rs = psta.executeQuery();
				if (rs.next()) {
					remCount = Integer
							.parseInt(rs.getString("SUBCONTRACT_NUM"));
					offWt = rs.getDouble("OFFLINE_WT");
				}
				rs.close();
				psta.close();
				double offWtBj = 0;
				if (offWt == 0) {
					offWtBj = (offWt / Integer.parseInt(jgOffline
							.getOfflineNum()))
							* Integer.parseInt(jgOffline.getOfflineNumBj());
				}

				if (remCount == 0) {
					cor.setV_errMsg("选择的炉号已委外加工,不允许此操作!");
					return cor;
				}
				CouplingOutsourcResultEntity outEntity = new CouplingOutsourcResultEntity();
				// 新增委外加工表
				outEntity.setEntrustedNo(entrusNo);
				outEntity.setPlineCode(jgOffline.getPlineCode());
				outEntity.setPlineName(jgOffline.getPlineName());
				outEntity.setWoId(jgOffline.getWoId());
				outEntity.setJudgeStoveNo(jgOffline.getJudgeStoveNo());
				outEntity.setBatchNo(jgOffline.getBatchNo());
				outEntity.setEntrustedLog("1");
				outEntity.setEntrustedNum1(jgOffline.getOfflineNumBj());
				outEntity.setEntrustedWt1(String.valueOf(offWtBj));
				outEntity.setHarshType(harshType);
				outEntity.setCoatingType(coatingType);
				outEntity.setColMode("1");
				outEntity.setColUser(name);
				outEntity.setColShift(bc);
				outEntity.setColGroup(bz);
				outEntity.setCreateTime(systime);
				outEntity.setStationCode(jgOffline.getStationCode());
				outEntity.setStationDesc(jgOffline.getStationDesc());
				outEntity.setMemo(memo);
				outEntity.setResultNo(jgOffline.getResultNo());
				outEntity.setOffXh(jgOffline.getOffXh());
				outEntity.setStationUnitCode(stationUnitCode);
				outEntity.setStationUnitDesc(stationUnitDesc);
				String addOff = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("FrmHttDownLineManage.AddOutSourc"),
						outEntity);
				psta = con.prepareStatement(addOff);
				psta.executeUpdate();
				psta.close();

				// 修改离线表返线支数
				String updateOff = CoreXmlSqlParsersFactory
						.getSql("FrmHttDownLineManage.UpdateOffOutSourc");// 修改离线表委外支数
				psta = con.prepareStatement(updateOff);
				psta.setObject(1, entrusNo);
				psta.setObject(2, jgOffline.getOfflineNumBj());
				psta.setObject(3, offWtBj);
				psta.setObject(4, systime);
				psta.setObject(5, name);
				psta.setObject(6, jgOffline.getResultNo());
				psta.setObject(7, jgOffline.getOffXh());
				psta.executeUpdate();
				psta.close();
			}

			cor.setV_errMsg("委外加工成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/***
	 * 查询委外信息
	 * 
	 * @throws SQLException
	 */
	public static CouplingOutsourcResultEntity getSendOut(Connection con,
			String entrustedNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDownLineManage.doQueryOutResult");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, entrustedNo);
		ResultSet rs = ps.executeQuery();
		List<CouplingOutsourcResultEntity> sendPlanCEntitys = EntityTool
				.getEntitysByRs(rs, CouplingOutsourcResultEntity.class);
		rs.close();
		ps.close();
		if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
			return null;
		} else {
			for (CouplingOutsourcResultEntity sendPlanCEntity : sendPlanCEntitys) {
				QualityDesignTool.nullConverNullString(sendPlanCEntity);
			}
			return sendPlanCEntitys.get(0);
		}
	}

	/**
	 * 撤销委外加工
	 * 
	 * @param result
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CoreReturnObject doCancelOutSourc(ArrayList<Object> parm) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		// ResultSet rs = null;
		try {
			con.setAutoCommit(false); // 取消自动提交事务

			for (int i = 0; i < parm.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) parm.get(i);
				String entrustedNo = list.get(0);// 委托单序号

				CouplingOutsourcResultEntity outEntity = getSendOut(con,
						entrustedNo);

				if (outEntity == null) {
					cor.setV_errMsg("选择委外信息已撤销,不允许此操作!");
					return cor;
				}
				if (!outEntity.getEntrustedLog().equals("1")) {
					cor.setV_errMsg("选择委外信息不是未申请状态,不允许此操作!");
					return cor;
				}
				// 删除委外加工表
				String deleteOff = "DELETE COUPLING_OUTSOURC_RESULT WHERE ENTRUSTED_NO = ?";// 删除委外加工表
				psta = con.prepareStatement(deleteOff);
				psta.setObject(1, entrustedNo);
				psta.executeUpdate();
				psta.close();

				// 修改离线表返线支数
				String updateOff = CoreXmlSqlParsersFactory
						.getSql("FrmHttDownLineManage.UpdateOffOutSourc");// 修改离线表委外支数
				psta = con.prepareStatement(updateOff);
				psta.setObject(1, "");
				psta.setObject(2, "-" + outEntity.getEntrustedNum1());
				psta.setObject(3, "-" + outEntity.getEntrustedWt1());
				psta.setObject(4, "");
				psta.setObject(5, "");
				psta.setObject(6, outEntity.getResultNo());
				psta.setObject(7, outEntity.getOffXh());
				psta.executeUpdate();
				psta.close();
			}

			cor.setV_errMsg("撤销委外加工成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 撤销委外加工
	 * 
	 * @param result
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CoreReturnObject DoOutApply(ArrayList<Object> parm) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		try {
			con.setAutoCommit(false); // 取消自动提交事务

			for (int i = 0; i < parm.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) parm.get(i);
				String entrustedNo = list.get(0);// 委托单序号

				CouplingOutsourcResultEntity outEntity = getSendOut(con,
						entrustedNo);

				if (outEntity == null) {
					cor.setV_errMsg("选择委外信息撤銷,不允许此操作!");
					return cor;
				}
				if (!outEntity.getEntrustedLog().equals("1")) {
					cor.setV_errMsg("选择委外信息不是未申请状态,不允许此操作!");
					return cor;
				}
				// 修改委外加工表
				String deleteOff = "UPDATE COUPLING_OUTSOURC_RESULT T SET T.ENTRUSTED_LOG='2' WHERE ENTRUSTED_NO = ?";// 修改委外標準
				psta = con.prepareStatement(deleteOff);
				psta.setObject(1, entrustedNo);
				psta.executeUpdate();
				psta.close();

			}

			cor.setV_errMsg("申请成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 撤销委外加工
	 * 
	 * @param result
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CoreReturnObject DoOutApplyUn(ArrayList<Object> parm) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		try {
			con.setAutoCommit(false); // 取消自动提交事务

			for (int i = 0; i < parm.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) parm.get(i);
				String entrustedNo = list.get(0);// 委托单序号

				CouplingOutsourcResultEntity outEntity = getSendOut(con,
						entrustedNo);

				if (outEntity == null) {
					cor.setV_errMsg("选择委外信息撤銷,不允许此操作!");
					return cor;
				}
				if (!outEntity.getEntrustedLog().equals("2")) {
					cor.setV_errMsg("选择委外信息不是已申请状态,不允许此操作!");
					return cor;
				}
				// 修改委外加工表
				String deleteOff = "UPDATE COUPLING_OUTSOURC_RESULT T SET T.ENTRUSTED_LOG='1' WHERE ENTRUSTED_NO = ?";// 修改委外標準
				psta = con.prepareStatement(deleteOff);
				psta.setObject(1, entrustedNo);
				psta.executeUpdate();
				psta.close();

			}

			cor.setV_errMsg("撤销申请成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

	/**
	 * 委内更换产线
	 * 
	 * @param HeatPlanIDs
	 *            需要委外的数据
	 * @param PlineCode
	 *            要更换产线的产线代码
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CoreReturnObject DoInterDelegation(ArrayList<String> HeatPlanIDs,
			String PlineCode, String PlineName) {
		CoreReturnObject cor = new CoreReturnObject();
		Connection con = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();

		try {
			con.setAutoCommit(false); // 取消自动提交事务

			String sql = "";

			for (String HeatPlanID : HeatPlanIDs) {

				// 修改离线表产线
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.updateJgOffLine");
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, PlineCode);
				ps.setObject(2, PlineName);
				ps.setObject(3, HeatPlanID);
				ps.executeUpdate();
				ps.close();

				// 修改队列表产线
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.updateJgPort");
				ps = con.prepareStatement(sql);
				ps.setObject(1, PlineCode);
				ps.setObject(2, PlineName);
				ps.setObject(3, HeatPlanID);
				ps.executeUpdate();
				ps.close();

				// 修改工单表产线
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmDownLineManage.updateJGMPlan");
				ps = con.prepareStatement(sql);
				ps.setObject(1, PlineCode);
				ps.setObject(2, PlineCode);
				ps.setObject(3, PlineName);
				ps.setObject(4, PlineName);
				ps.setObject(5, HeatPlanID);
				ps.executeUpdate();
				ps.close();

			}

			cor.setV_errMsg("委内成功！");
			con.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (con != null) {
				try {
					cor.setV_errMsg(e.getMessage());
					con.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (Exception e2) {
			}
		}
		return cor;
	}

}
