package com.steering.pss.plnsaleord.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.order.model.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 合同工艺变更确认
 * 
 * @author xiaohai
 */
public class CoreConfirmCraft extends DBCommon {
	/**
	 * 查询
	 * 
	 * @param list
	 * @param isConfirm
	 * @return
	 */
	public CoreReturnObject querySaleOrder(ArrayList<Object> list,
			String strFinish, Boolean isConfirm) {
		return querySaleOrder(list,strFinish,isConfirm,"");
	}

	public CoreReturnObject querySaleOrder(ArrayList<Object> list,
										   String strFinish, Boolean isConfirm,String supp) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.querySaleOrder");
		if (isConfirm) {
			sql = sql + " AND DECODE(E.CRAFT_SEQ,"
					+ " NVL((SELECT MAX(T1.CRAFT_SEQ)"
					+ " FROM CRAFT_ORD_DESIGN T1"
					+ " WHERE T1.ORD_LN_PK = T.ORD_LN_PK"
					+ " AND T1.VALIDFLAG = '1'), E.CRAFT_SEQ),"
					+ " E.CRAFT_RENEW_ST, '1') = '1'"
					+ " AND E.PLANSTATUS IN ('1', '2', '3')";
		}
		if (strFinish.equals("0")) {
			sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3') OR "
					+ "(E.PLANSTATUS IN ('4', '5') AND "
					+ "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		} else if (strFinish.equals("1")) {
			sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3', '4') OR "
					+ "(E.PLANSTATUS = '5' AND "
					+ "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		}
		/*if (!StringUtils.isEmpty(supp)) {
			sql += " and T.SUPPLY_UNIT_CODE = '"+ supp+"'";
		}*/
		cro = this.getData(sql, list.toArray());
		return cro;
	}

	public CoreReturnObject querySaleOrder(String planStatus, String strFinish, String deleteTimeS, String deleteTimeE,Boolean checkMoth) {
		CoreReturnObject cro = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.querySaleOrder1");
		if (!StringUtils.isEmpty(planStatus)) {
			sql += " AND E.PLANSTATUS = '" + planStatus + "'";
		}
		if (!StringUtils.isEmpty(deleteTimeS) && !StringUtils.isEmpty(deleteTimeE)) {
			sql += " AND E.DELETE_TIME BETWEEN TO_DATE('" + deleteTimeS + "','YYYY-MM-DD') AND TO_DATE('" + deleteTimeE + "','YYYY-MM-DD')";
		}
		if(checkMoth){
			sql += "and E.CHECK_MOTH IS NOT NULL";
		}
		if (strFinish.equals("0")) {
			sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3') OR "
					+ "(E.PLANSTATUS IN ('4', '5') AND "
					+ "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		} else if (strFinish.equals("1")) {
			sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3', '4') OR "
					+ "(E.PLANSTATUS = '5' AND "
					+ "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		}
		cro = this.getData(sql);
		return cro;
	}

	/**
	 * 查询排产分解合同
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return
	 */
	public CoreReturnObject querySaleProcStatus(String ordLnDlyPk,
			String plnDivideId) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CoreConfirmCraft.querySaleProcStatus",
				new Object[] { ordLnDlyPk, plnDivideId });
		return cro;
	}

	/**
	 * 查询工艺信息
	 * 
	 * @param craftNo
	 * @param craftNoV
	 * @return
	 */
	public CoreReturnObject queryCraftDesign(String craftNo, String craftNoV) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CoreConfirmCraft.queryCraftDesign",
				new Object[] { craftNo, craftNoV });
		return cro;
	}

	/**
	 * 替换新版工艺
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject updateCraftVersion(
			ArrayList<PlnSaleordProcEntity> list,
			ArrayList<PlnSaleordCrfEditLogEntity> listLog) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement psta = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			String sqlW1 = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateCraftVersion");
			String sqlW2 = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateCraftVersionIndex");
			String sqlW3 = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateCraftVersionBom");
			String sqlW4 = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateCraftVersionBomPline");
			String sqlW5 = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateCraftVersionAmout");
			String sqlLog = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.insertCraftEditLog");

			for (int i = 0; i < list.size(); i++) {
				PlnSaleordProcEntity procEntity = list.get(i);
				String sqlUpe = EntityTool.fillSqlByEntity(sqlW1, procEntity);
				psta = conn.prepareStatement(sqlUpe);
				psta.executeUpdate();
				psta.close();

				sqlUpe = EntityTool.fillSqlByEntity(sqlLog, listLog.get(i));
				psta = conn.prepareStatement(sqlUpe);
				psta.executeUpdate();
				psta.close();
				if (!procEntity.getProcessSeq().equals("")) {
					String sqlUp = EntityTool
							.fillSqlByEntity(sqlW2, procEntity);
					psta = conn.prepareStatement(sqlUp);
					psta.executeUpdate();
					psta.close();
					CoreOrdLinePrdcrLst.updateOrdPrdcrproPk(conn, procEntity
							.getOrdLnDlyPk(), procEntity.getPlnDivideId());
				}
				if (!procEntity.getBom().equals("")) {
					String sqlUp = EntityTool
							.fillSqlByEntity(sqlW3, procEntity);
					psta = conn.prepareStatement(sqlUp);
					psta.executeUpdate();
					psta.close();
				}
				if (!procEntity.getGroupRoll().equals("")) {
					String sqlUp = EntityTool
							.fillSqlByEntity(sqlW4, procEntity);
					psta = conn.prepareStatement(sqlUp);
					psta.executeUpdate();
					psta.close();
				}
				// 判断是否需要更新合同量
				if (!procEntity.getPlanWtD().equals("")) {
					String sqlUp = EntityTool
							.fillSqlByEntity(sqlW5, procEntity);
					psta = conn.prepareStatement(sqlUp);
					psta.executeUpdate();
					psta.close();
				}
			}
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 查询排产行信息
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return
	 */
	public CoreReturnObject selectPlnOrderStatus(String ordLnDlyPk,
			String plnDivideId) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CoreConfirmCraft.selectPlnOrderStatus",
				new Object[] { ordLnDlyPk, plnDivideId });
		return cro;
	}

	/**
	 * 工艺制程
	 * 
	 * @param ordLnPk
	 * @param craftSeq
	 * @return
	 */
	public CoreReturnObject selectCraftDesgin(String ordLnPk, String craftSeq) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CoreConfirmCraft.selectCraftDesgin",
				new Object[] { ordLnPk, craftSeq });
		return cro;
	}

	/**
	 * 刷新工艺
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject updateRefresCraft(
			ArrayList<PlnSaleordProcEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement psta = null;
			String sql = CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateRefresCraft");
			for (PlnSaleordProcEntity procEntity : list) {
				String sqlUp = EntityTool.fillSqlByEntity(sql, procEntity);
				psta = conn.prepareStatement(sqlUp);
				psta.executeUpdate();
				psta.close();
			}
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 合同下发
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject iussedOrder(ArrayList<ArrayList<String>> list,
			String flag) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			int failNum = 0;
			if (list.size() < 0) {
				cro.setV_errCode(-1);
				cro.setV_errMsg("下发合同数为0。");
			}
			// 生成版次号
 			String versionNo = CorePlnGxOrdM.getSendVersionNo(conn);
			// 新增下发版次记录
			CorePlnGxOrdM.addIussedVersion(conn, versionNo, "0", list.get(0)
					.get(0));

			for (int i = 0; i < list.size(); i++) {
				PreparedStatement psta = null;
				ResultSet rsta = null;
				String iussedMan = list.get(i).get(0);
				String ordLnDlyPk = list.get(i).get(1);
				String plnDivideId = list.get(i).get(2);
				String orderUnit = list.get(i).get(3);// 合同订货单位
				double planWt = Double.parseDouble(list.get(i).get(4));
				int planNum = Integer.parseInt(list.get(i).get(5));
				String orderNoSeq = list.get(i).get(6);// 合同号
				String orderSource = list.get(i).get(7);// 排产分类
				// /
				String sqlUpProcess = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updateProcessOrderMt");
				String sqlUpPrc = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updateSaleOrdProcStatus");
				String sqlUp = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updatePlnSaleStatus");
				String sql = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.selectOrdBlReq");
				String sqlCrm = CoreXmlSqlParsersFactory.getSql("CoreConfirmCraft.insertCrmProduct");

				// 验证接箍备料
				if (!CoreConfirmCraft.checkJgBl(conn, ordLnDlyPk, plnDivideId,
						flag)) {
					cro.setV_errCode(-1);
					cro.setV_errMsg(message);
					return cro;
				}
				psta = conn.prepareStatement(sqlUpPrc);
				psta.setObject(1, "2");
				psta.setObject(2, iussedMan);
				psta.setObject(3, ordLnDlyPk);
				psta.setObject(4, plnDivideId);
				psta.executeUpdate();
				psta.close();

				psta = conn.prepareStatement(sqlUp);
				psta.setObject(1, "2");
				psta.setObject(2, ordLnDlyPk);
				psta.executeUpdate();
				psta.close();

				if (orderUnit.trim().equals("支")) {
					planWt = 0;
				}

				CorePlnProcessOrd prcOrder = new CorePlnProcessOrd();
				if (!prcOrder.addPrcOrder(conn, iussedMan, ordLnDlyPk,
						plnDivideId, versionNo, orderNoSeq, orderSource)) {
					try {
						conn.rollback();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					failNum++;
					Object[] readback = new Object[] { failNum,
							prcOrder.getErrMessage() };
					cro.setResult(readback);
					continue;
				}

				// 接箍合同制定
				String[] message = new String[1];
				// CorePlnOrdJgDjDeal.dealJgOrd(conn, ordLnDlyPk, iussedMan,
				// message);

				// 备料需求
				psta = conn.prepareStatement(sql);
				psta.setObject(1, ordLnDlyPk);
				rsta = psta.executeQuery();
				if (rsta.next()) {
					PreparedStatement ps = null;
					if (rsta.getString("PLANSTATUS") == null
							|| rsta.getString("PLANSTATUS").compareTo("2") < 0) {
					
						String sqlUpBl = CoreXmlSqlParsersFactory
								.getSql("CoreConfirmCraft.updateBlReqSatus");
						ps = conn.prepareStatement(sqlUpBl);
						ps.setObject(1, "2");
						ps.setObject(2, ordLnDlyPk);
						ps.executeUpdate();
						ps.close();
					}
					// 修改接箍合同排产下发状态
					String sqlUpdate = "UPDATE PLN_ORDER_JG T SET T.STATUS='1' WHERE T.PRO_PLAN_ID IN (SELECT T1.PRO_PLAN_ID FROM PLN_JG_AND_BL T1 WHERE T1.REQ_BL_ID = ?)";
					ps = conn.prepareStatement(sqlUpdate);
					ps.setObject(1, ordLnDlyPk);
					ps.executeUpdate();
					ps.close();
				} else {
					PreparedStatement ps = null;
					ps = conn.prepareStatement(sqlUpProcess);
					ps.setObject(1, planNum);
					ps.setObject(2, planWt);
					ps.setObject(3, ordLnDlyPk);
					ps.executeUpdate();
					ps.close();
				}
				rsta.close();
				psta.close();

				//新增CRM表
				String selectCrmSql = CoreXmlSqlParsersFactory.getSql("CoreConfirmCraft.selectCrmProduct");
				psta = conn.prepareStatement(selectCrmSql);
				psta.setString(1,ordLnDlyPk);
				rsta = psta.executeQuery();
				List<CrmOrderProduceEntity> crmOrderList = EntityTool.getEntitysByRs(rsta,CrmOrderProduceEntity.class);
				rsta.close();
				psta.close();

				if(crmOrderList.size()>0)
				{
					crmOrderList.get(0).setDataStatus("1");
					crmOrderList.get(0).setCreateName(list.get(i).get(0));
					sqlCrm = EntityTool.fillSqlByEntity(sqlCrm,crmOrderList.get(0));
					psta = conn.prepareStatement(sqlCrm);
					psta.executeUpdate();
					psta.close();
				}




				conn.commit();
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} catch (Exception e) {
			if (conn != null) {
				try {
					conn.rollback();
				} catch (SQLException sqle) {
					sqle.printStackTrace();
				}
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(e.getLocalizedMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 取消下发
	 * 
	 * @param list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject canCelIussed(ArrayList<ArrayList<String>> list,
			String username) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement psta = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			// 生成版次号
			// String versionNo = CorePlnGxOrdM.getSendVersionNo(conn);
			// 新增下发版次记录
			// CorePlnGxOrdM.addIussedVersion(conn, versionNo, "0", list.get(0)
			// .get(0));
			ArrayList<String> messageErr = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				String cancelMan = list.get(i).get(0);
				String ordLnDlyPk = list.get(i).get(1);
				String plnDivideId = list.get(i).get(2);
				String orderUnit = list.get(i).get(3);// 合同订货单位
				double planWt = Double.parseDouble(list.get(i).get(4));
				int planNum = Integer.parseInt(list.get(i).get(5));
				// 新增版次号从表
				PlnSaleordEntityA entityA = CorePlnProcessOrd
						.getPlnSaleordEntityById(conn, ordLnDlyPk, plnDivideId);
				String reason = canNotCancelIussed(conn, ordLnDlyPk,
						plnDivideId);
				if (!reason.trim().equals("")) {
					messageErr.add(reason);
					continue;
				}

				if (entityA != null) {
					if (!entityA.getVersionNo().equals("")) {
						PlnSaleordEntity saleordEntity = CorePlnProcessOrd
								.getPlnSaleordByPk(conn, ordLnDlyPk);
						String rollWellMonth = "";
						String acceptNo = "";
						String ifPassZg = "";
						String ifPassJgx = "";
						if (saleordEntity != null) {
							rollWellMonth = saleordEntity.getRollWellMonth();
							acceptNo = saleordEntity.getAcceptNo();
						}
						if (entityA.getDIsOk().equals("")
								|| entityA.getDIsOk().equals("2")) {
							ifPassZg = "0";
						} else {
							ifPassZg = "1";
						}
						if (entityA.getGIsOk().equals("")
								|| entityA.getGIsOk().equals("2")) {
							ifPassJgx = "0";
						} else {
							ifPassJgx = "1";
						}
						CorePlnProcessOrd.addPlnOrderDownLog(conn, entityA
								.getVersionNo(), ordLnDlyPk, plnDivideId, "1",
								entityA.getOrderSource(), entityA.getOrderNo(),
								entityA.getOrderSeq(), entityA.getDeliveryNo(),
								entityA.getRNumId(), entityA.getProcessSeq(),
								username, rollWellMonth, acceptNo, ifPassZg,
								ifPassJgx);
					}
				}
				String sql = "";
				if (orderUnit.trim().equals("支")) {
					planWt = 0;
				}
				// 修改版次号 2016/07/26
				// CorePlnProcessOrd.updatePlnSaleordProcVersionNo(conn,
				// ordLnDlyPk, plnDivideId, versionNo, username, "1");

				// 删除工序合同
				CorePlnProcessOrd prcOrder = new CorePlnProcessOrd();
				prcOrder.deletePlnOrderJgx(conn, ordLnDlyPk, plnDivideId,
						cancelMan);
				prcOrder.deletePlnOrderRcl(conn, ordLnDlyPk, plnDivideId,
						cancelMan);
				prcOrder.deletePlnOrderDbk(conn, ordLnDlyPk, plnDivideId,
						cancelMan);
				prcOrder.deletePlnOrderZg(conn, ordLnDlyPk, plnDivideId,
						cancelMan);
				//查询铸造订单状态
				String queryCast="SELECT NVL(MAX(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID =(SELECT  P.GPREQ_ID FROM PLN_SALEORD_PROC P WHERE P.ORD_LN_DLY_PK=? AND P.PLN_DIVIDE_ID=?)";
				psta = conn.prepareStatement(queryCast);
				psta.setObject(1, ordLnDlyPk);
				psta.setObject(2, plnDivideId);
				ResultSet rs1 = psta.executeQuery();
				if (rs1.next()) {
					if(!rs1.getString("EXE_STATUS").equals("0")){
					cro.setV_errMsg("铸造计划已不是计划状态,不能撤销下发！");
					return cro;	
					}
				}
				rs1.close();
				psta.close();
				//删除铸造工序订单
				String deteleM="DELETE PLN_GX_CAST_M T WHERE T.PRO_PLAN_ID =(SELECT  P.GPREQ_ID FROM PLN_SALEORD_PROC P WHERE P.ORD_LN_DLY_PK=? AND P.PLN_DIVIDE_ID=?)";
				psta = conn.prepareStatement(deteleM);
				psta.setObject(1, ordLnDlyPk);
				psta.setObject(2, plnDivideId);
				psta.executeUpdate();
				psta.close();
				//删除铸造工序订单
				String deteleS="DELETE PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID =(SELECT  P.GPREQ_ID FROM PLN_SALEORD_PROC P WHERE P.ORD_LN_DLY_PK=? AND P.PLN_DIVIDE_ID=?)";
				psta = conn.prepareStatement(deteleS);
				psta.setObject(1, ordLnDlyPk);
				psta.setObject(2, plnDivideId);
				psta.executeUpdate();
				psta.close();
				
				// 查询接箍排产订单
				String sqlQuery = "SELECT T.PRO_PLAN_ID FROM PLN_GX_JG_PROP_S T WHERE T.ORD_LN_DLY_PK = ? AND T.PLN_DIVIDE_ID = ?";
				psta = conn.prepareStatement(sqlQuery);
				psta.setObject(1, ordLnDlyPk);
				psta.setObject(2, plnDivideId);
				 rs1 = psta.executeQuery();
				if (rs1.next()) {
					// 删除接箍排产订单
					sql = "DELETE PLN_GX_JG_PROP_S  WHERE PRO_PLAN_ID = ?";
					PreparedStatement psta1 = conn.prepareStatement(sql);
					psta1.setObject(1, rs1.getString("PRO_PLAN_ID"));
					psta1.executeUpdate();
					psta1.close();
					// 删除接箍订单排产从表
					String deleteJgC = "DELETE PLN_GX_JG_PROP_C WHERE PRO_PLAN_ID = ?";
					psta1 = conn.prepareStatement(deleteJgC);
					psta1.setObject(1, rs1.getString("PRO_PLAN_ID"));
					psta1.executeUpdate();
					psta1.close();
					// 修改接箍合同订单号（从表订单）
					String updateOrder = " UPDATE PLN_ORDER_JG T SET T.KEY='' WHERE T.PRO_PLAN_ID_S=?";
					psta1 = conn.prepareStatement(updateOrder);
					psta1.setObject(1, rs1.getString("PRO_PLAN_ID"));
					psta1.executeUpdate();
					psta1.close();
				}
				rs1.close();
				psta.close();
				
				// 更新合同状态
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updateSaleOrdProcStatus");
				psta = conn.prepareStatement(sql);
				psta.setObject(1, "1");
				psta.setObject(2, cancelMan);
				psta.setObject(3, ordLnDlyPk);
				psta.setObject(4, plnDivideId);
				psta.executeUpdate();
				psta.close();

				// 备料需求
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.selectOrdBlReq");
				psta = conn.prepareStatement(sql);
				psta.setObject(1, ordLnDlyPk);
				ResultSet rsta = psta.executeQuery();
				if (rsta.next()) {
					PreparedStatement ps = null;
					if (rsta.getString("PLANSTATUS") == null
							|| rsta.getString("PLANSTATUS").compareTo("1") > 0) {
					
						String sqlUpBl = CoreXmlSqlParsersFactory
								.getSql("CoreConfirmCraft.updateBlReqSatus");
						ps = conn.prepareStatement(sqlUpBl);
						ps.setObject(1, "1");
						ps.setObject(2, ordLnDlyPk);
						ps.executeUpdate();
						ps.close();
					}
					// 修改接箍合同排产下发状态
					String sqlUpdate = "UPDATE PLN_ORDER_JG T SET T.STATUS='0' WHERE T.PRO_PLAN_ID IN (SELECT T1.PRO_PLAN_ID FROM PLN_JG_AND_BL T1 WHERE T1.REQ_BL_ID = ?)";
					ps = conn.prepareStatement(sqlUpdate);
					ps.setObject(1, ordLnDlyPk);
					ps.executeUpdate();
					ps.close();
				} else {
					PreparedStatement ps = null;
					sql = CoreXmlSqlParsersFactory
							.getSql("CoreConfirmCraft.updateProcessOrderMt");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, -planNum);
					ps.setObject(2, -planWt);
					ps.setObject(3, ordLnDlyPk);
					ps.executeUpdate();
					ps.close();
				}
				rsta.close();
				psta.close();

				sql = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.queryIsNotIussedOrd");
				psta = conn.prepareStatement(sql);
				psta.setString(1, ordLnDlyPk);
				ResultSet rs = psta.executeQuery();
				if (rs.next()) {
					if (rs.getInt("IUSSED_NUM") == 0) {
						String sqlUp = CoreXmlSqlParsersFactory
								.getSql("CoreConfirmCraft.updatePlnSaleStatus");
						PreparedStatement ps = conn.prepareStatement(sqlUp);
						ps.setObject(1, "1");
						ps.setObject(2, ordLnDlyPk);
						ps.executeUpdate();
						ps.close();
					}
				}
				rs.close();
				psta.close();

				//取消下发时删除CRM排产量
				sql = CoreXmlSqlParsersFactory.getSql("CoreConfirmCraft.selectCrmProduct");
				psta = conn.prepareStatement(sql);
				psta.setString(1,ordLnDlyPk);
				rs = psta.executeQuery();
				List<CrmOrderProduceEntity> crmList = EntityTool.getEntitysByRs(rs,CrmOrderProduceEntity.class);
				rs.close();
				psta.close();

				if(crmList.size()>0)
				{
					crmList.get(0).setCreateName(username);
					crmList.get(0).setDataStatus("1");
					sql = CoreXmlSqlParsersFactory.getSql("CoreConfirmCraft.insertCrmProduct");
					sql = EntityTool.fillSqlByEntity(sql,crmList.get(0));
					psta = conn.prepareStatement(sql);
					psta.executeUpdate();
					psta.close();
				}

				conn.commit();
			}
			cro.setResult(EntityTool.getGsonByEntity(messageErr));
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
			return cro;
		} catch (ParseException pe) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(pe.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 判断是否可以下发回退
	 * 
	 * @param conn
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return
	 * @throws SQLException
	 */
	public static String canNotCancelIussed(Connection conn, String ordLnDlyPk,
			String plnDivideId) throws SQLException {
		String reason = "";
		String proPlanId = "";
		String gxPlanNo = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.queryPlnOrderZg");
		PreparedStatement psta = conn.prepareStatement(sql);
		psta.setString(1, ordLnDlyPk);
		psta.setString(2, plnDivideId);
		ResultSet rs = psta.executeQuery();
		while (rs.next()) {
			if (rs.getString("ORDERSTATUS") != null
					&& rs.getString("ORDERSTATUS").compareTo("1") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的轧管工序已经排产。";
				return reason;
			}
			if (rs.getString("EXE_STATUS") != null
					&& rs.getString("EXE_STATUS").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的轧管订单已经排产。";
				return reason;
			}
			if (rs.getString("IF_STOVE_ISSUED") != null
					&& rs.getString("IF_STOVE_ISSUED").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的轧管订单已炉计划下发。";
				return reason;
			}
			if (rs.getString("GPREQ_ID") != null
					&& !rs.getString("GPREQ_ID").equals("")) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的轧管订单已组坯料需求。";
				return reason;
			}
			if (rs.getString("PRODUCTION_TH_FLAG") != null
					&& "123506".equals(rs.getString("PRODUCTION_TH_FLAG"))) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的轧管订单天淮已确认接收半成品。";
				return reason;
			}
			proPlanId = rs.getString("PRO_PLAN_ID");
			gxPlanNo = rs.getString("GX_PLAN_NO");

			if (proPlanId != null && !proPlanId.equals("")) {
				int count = 0;
				String sqlZy = "SELECT COUNT(*) COUNT FROM PLN_ZY_ZG_M T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
				PreparedStatement ps1 = conn.prepareStatement(sqlZy);
				ps1.setString(1, proPlanId);
				ps1.setString(2, gxPlanNo);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					count = rs1.getInt("COUNT");
				}
				rs1.close();
				ps1.close();
				if (count > 0) {
					reason = "合同：" + rs.getString("ORDER_NO_SEQ")
							+ "的轧管订单已生成炉计划，不能撤销下发。";
					return reason;
				}
			}
		}
		rs.close();
		psta.close();

		sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.queryPlnOrderDbk");
		psta = conn.prepareStatement(sql);
		psta.setString(1, ordLnDlyPk);
		psta.setString(2, plnDivideId);
		rs = psta.executeQuery();
		while (rs.next()) {
			if (rs.getString("ORDERSTATUS") != null
					&& rs.getString("ORDERSTATUS").compareTo("1") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的镦拔扩工序已经排产。";
				return reason;
			}

			if (rs.getString("EXE_STATUS") != null
					&& rs.getString("EXE_STATUS").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的镦拔扩订单已经排产。";
				return reason;
			}
			if (rs.getString("IF_STOVE_ISSUED") != null
					&& rs.getString("IF_STOVE_ISSUED").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的镦拔扩订单已炉计划下发。";
				return reason;
			}
			proPlanId = rs.getString("PRO_PLAN_ID");
			gxPlanNo = rs.getString("GX_PLAN_NO");

			if (proPlanId != null && !proPlanId.equals("")) {
				int count = 0;
				String sqlZy = "SELECT COUNT(*) COUNT FROM PLN_ZY_DBK_M T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
				PreparedStatement ps1 = conn.prepareStatement(sqlZy);
				ps1.setString(1, proPlanId);
				ps1.setString(2, gxPlanNo);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					count = rs1.getInt("COUNT");
				}
				rs1.close();
				ps1.close();
				if (count > 0) {
					reason = "合同：" + rs.getString("ORDER_NO_SEQ")
							+ "的镦拔扩订单已生成炉计划，不能撤销下发。";
					return reason;
				}
			}
		}
		rs.close();
		psta.close();

		sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.queryPlnOrderRcl");
		psta = conn.prepareStatement(sql);
		psta.setString(1, ordLnDlyPk);
		psta.setString(2, plnDivideId);
		rs = psta.executeQuery();
		while (rs.next()) {
			if (rs.getString("ORDERSTATUS") != null
					&& rs.getString("ORDERSTATUS").compareTo("1") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的热处理工序已经排产。";
				return reason;
			}
			if (rs.getString("IF_STOVE_ISSUED") != null
					&& rs.getString("IF_STOVE_ISSUED").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的热处理订单已炉计划下发。";
				return reason;
			}
			if (rs.getString("EXE_STATUS") != null
					&& rs.getString("EXE_STATUS").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的热处理订单已经排产。";
				return reason;
			}
			proPlanId = rs.getString("PRO_PLAN_ID");
			gxPlanNo = rs.getString("GX_PLAN_NO");

			if (proPlanId != null && !proPlanId.equals("")) {
				int count = 0;
				String sqlZy = "SELECT COUNT(*) COUNT FROM PLN_ZY_RCL_M T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
				PreparedStatement ps1 = conn.prepareStatement(sqlZy);
				ps1.setString(1, proPlanId);
				ps1.setString(2, gxPlanNo);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					count = rs1.getInt("COUNT");
				}
				rs1.close();
				ps1.close();
				if (count > 0) {
					reason = "合同：" + rs.getString("ORDER_NO_SEQ")
							+ "的热处理订单已生成炉计划，不能撤销下发。";
					return reason;
				}
			}
		}
		rs.close();
		psta.close();

		sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.queryPlnOrderJgx");
		psta = conn.prepareStatement(sql);
		psta.setString(1, ordLnDlyPk);
		psta.setString(2, plnDivideId);
		rs = psta.executeQuery();
		while (rs.next()) {
			if (rs.getString("ORDERSTATUS") != null
					&& rs.getString("ORDERSTATUS").compareTo("1") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的加工工序已经排产。";
				return reason;
			}
			if (rs.getString("IF_STOVE_ISSUED") != null
					&& rs.getString("IF_STOVE_ISSUED").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的加工订单已炉计划下发。";
				return reason;
			}
			if (rs.getString("EXE_STATUS") != null
					&& rs.getString("EXE_STATUS").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("ORDER_NO_SEQ") + "的加工订单已经排产。";
				return reason;
			}
			proPlanId = rs.getString("PRO_PLAN_ID");
			gxPlanNo = rs.getString("GX_PLAN_NO");

			if (proPlanId != null && !proPlanId.equals("")) {
				int count = 0;
				String sqlZy = "SELECT COUNT(*) COUNT FROM PLN_ZY_JGX_M T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
				PreparedStatement ps1 = conn.prepareStatement(sqlZy);
				ps1.setString(1, proPlanId);
				ps1.setString(2, gxPlanNo);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					count = rs1.getInt("COUNT");
				}
				rs1.close();
				ps1.close();
				if (count > 0) {
					reason = "合同：" + rs.getString("ORDER_NO_SEQ")
							+ "的加工订单已生成炉计划，不能撤销下发。";
					return reason;
				}
			}
		}
		rs.close();
		psta.close();

		// 查询接箍排产订单
		sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.queryPlnOrderJg");
		psta = conn.prepareStatement(sql);
		psta.setString(1, ordLnDlyPk);
		psta.setString(2, plnDivideId);
		rs = psta.executeQuery();
		while (rs.next()) {
			if (rs.getString("EXE_STATUS") != null
					&& rs.getString("EXE_STATUS").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("REQ_BL_ID") + "的接箍订单已经排产。";
				return reason;
			}
			if (rs.getString("IF_STOVE_ISSUED").compareTo("0") > 0) {
				reason = "合同：" + rs.getString("REQ_BL_ID") + "的接箍订单已炉计划下发。";
				return reason;
			}
			// proPlanId = rs.getString("PRO_PLAN_ID");
			// gxPlanNo = rs.getString("GX_PLAN_NO");
			//
			// if (proPlanId != null && !proPlanId.equals("")) {
			// int count = 0;
			// String sqlZy =
			// "SELECT COUNT(*) COUNT FROM PLN_ZY_JGX_M T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
			// PreparedStatement ps1 = conn.prepareStatement(sqlZy);
			// ps1.setString(1, proPlanId);
			// ps1.setString(2, gxPlanNo);
			// ResultSet rs1 = ps1.executeQuery();
			// if (rs1.next()) {
			// count = rs1.getInt("COUNT");
			// }
			// rs1.close();
			// ps1.close();
			// if (count > 0) {
			// reason = "合同：" + rs.getString("REQ_BL_ID")
			// + "的接箍订单已生成炉计划，不能撤销下发。";
			// return reason;
			// }
			// }
		}
		rs.close();
		psta.close();
		return reason;
	}

	private static String message = "";

	/**
	 * 验证接箍备料
	 * 
	 * @param con
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @param flag
	 * @return
	 * @throws SQLException
	 */
	public static boolean checkJgBl(Connection con, String ordLnDlyPk,
			String plnDivideId, String flag) throws SQLException {
		if (flag.equals("0")) {
			return true;
		}
		PlnSaleordEntityA entityA = CorePlnProcessOrd.getPlnSaleordEntityById(
				con, ordLnDlyPk, plnDivideId);
		if (entityA == null) {
			return true;
		}
		// 备料需要不作验证
		if (entityA.getOrderSource().equals("备料需求")) {
			return true;
		}
		// 1.销售提报表
		PlnSaleordEntity ordEntity = CorePlnProcessOrd.getPlnSaleordByPk(con,
				ordLnDlyPk);
		if (ordEntity == null) {
			message = "数据异常,请刷新数据!";
			return false;
		}
		String str = "合同号" + ordEntity.getOrderNo() + "/"
				+ ordEntity.getOrderSeq() + "/" + ordEntity.getDeliveryNo();
		if (ordEntity.getJgordIsOk().equals("0")) {
			/*message = str + "接箍合同没有形成!";
			return false;*/
		}
		if (ordEntity.getJgordIsOk().equals("1")) {
			// 2.接箍合同表
			PlnOrderJgEntity jgEntity = CorePlnProcessOrd.getPlnOrderJG(con,
					ordLnDlyPk);
			if (jgEntity == null) {
				message = str + "接箍合同未形成记录!";
				return false;
			}
			if (jgEntity.getProPlanId().equals("")) {
				message = str + "没有接箍工序订单编号!";
				return false;
			}
			// 3.接箍订单主表
			PlnGxJgMEntity gxJgMEntity = CorePlnProcessOrd.getPlnGxJgM(con,
					jgEntity.getProPlanId());
			if (gxJgMEntity == null) {
				message = str + "接箍工序订单未形成记录!";
				return false;
			}
			String ifBuyPlan = gxJgMEntity.getIfbuyplan();
			double planNum = 0;
			if (!gxJgMEntity.getPlanNum().equals("")) {
				planNum = Double.parseDouble(gxJgMEntity.getPlanNum());
			}
			double matchNum = 0;
			if (!gxJgMEntity.getMatchnum().equals("")) {
				matchNum = Double.parseDouble(gxJgMEntity.getMatchnum());
			}
			double jgwtBlreq = 0;
			if (!gxJgMEntity.getJgwtBlreq().equals("")) {
				jgwtBlreq = Double.parseDouble(gxJgMEntity.getJgwtBlreq());
			}
			if (ifBuyPlan.equals("0") && planNum - matchNum - jgwtBlreq > 0) {
				message = "接箍工序订单" + jgEntity.getProPlanId()
						+ "有外购计划,且订单总个数-利库个数-已做需求接箍个数 大于0!";
				return false;
			}
			// 4.接箍及备料关系表
			List<PlnJgAndBlEntity> blList = CorePlnProcessOrd
					.getPlnJgAndBlList(con, jgEntity.getProPlanId());
			if (blList == null || blList.size() == 0) {
				message = str + "备料关系不存在!";
				return false;
			}
			for (PlnJgAndBlEntity blEntity : blList) {
				PlnPorderBlReqEntity blReqEntity = CorePlnProcessOrd
						.getBlReqById(con, blEntity.getReqBlId());
				if (blReqEntity == null) {
					message = str + "接箍短节备料需求不存在!";
					return false;
				}
				if (blReqEntity.getPlanstatus().equals("0")
						|| blReqEntity.getPlanstatus().equals("1")) {
					message = str + "备料需求" + blEntity.getReqBlId() + "没有下发!";
					return false;
				}
			}
		}

		// 验证备料码
		if (ordEntity.getDjblReqIsOk().equals("0")) {
			message = str + "短节备料未制定";
			return false;
		}
		if (ordEntity.getDjblReqIsOk().equals("2")) {
			return true;
		}
		List<PlnPorderBlReqEntity> blList = CorePlnProcessOrd
				.getBlReqByOrdLnPk(con, ordLnDlyPk);
		if (blList == null) {
			message = str + "接箍短节备料需求不存在";
			return false;
		}
		for (PlnPorderBlReqEntity blReqEntity : blList) {
			if (blReqEntity.getPlanstatus().equals("0")
					|| blReqEntity.getPlanstatus().equals("1")) {
				message = str + "短节备料需求" + blReqEntity.getReqBlId() + "没有下发!";
				return false;
			}
		}
		return true;
	}

	/**
	 * 修改排产月
	 * 
	 * @param list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject updateMonth(ArrayList<ArrayList<String>> list,
			String username) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement psta = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			DateFormat df = new SimpleDateFormat("yyyy-MM");
			Calendar cal = Calendar.getInstance();
			cal.getTime();
			cal.add(cal.MONTH, 2);
			String nowTime = df.format(cal.getTime());
			for (int i = 0; i < list.size(); i++) {
				String ordLnDlyPk = list.get(i).get(0);
				String plnDivideId = list.get(i).get(1);
				String rollMonth = list.get(i).get(2);// 排产月份
				PlnSaleordEntityA entityA = CorePlnProcessOrd
						.getPlnSaleordEntityById(conn, ordLnDlyPk, plnDivideId);
				if (entityA != null) {
					if (!entityA.getPlanstatus().equals("1")) {
						cro.setV_errMsg("当前合同:" + entityA.getOrderNo() + "/"
								+ entityA.getOrderSeq() + ",不是已接收。不允许调整排产月份!");
						return cro;
					}
				}
				// 修改年月与系统年月比较
				if (df.parse(rollMonth).getTime() > df.parse(nowTime).getTime()) {
					cro.setV_errMsg("当前合同:" + entityA.getOrderNo() + "/"
							+ entityA.getOrderSeq() + ",调整年月不能大于当前月+2："
							+ nowTime + "。");
					return cro;
				}
				String sql = "";
				// 更新合同排产月份
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreConfirmCraft.updateRollMonth");
				psta = conn.prepareStatement(sql);
				psta.setObject(1, rollMonth);
				psta.setObject(2, ordLnDlyPk);
				psta.setObject(3, plnDivideId);
				psta.executeUpdate();
				psta.close();
			}
			cro.setV_errMsg("排产月份调整成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
			return cro;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	public static <T> T getQureySaleProc(Connection con, String ordLnDlyPk,
			String plnDivideId, Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreConfirmCraft.querySaleOrderProc");
		sql += "  AND T.ORD_LN_DLY_PK  ='" + ordLnDlyPk + "' ";
		sql += "  AND T.PLN_DIVIDE_ID  ='" + plnDivideId + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 拆分排产合同
	 * 
	 * @param list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doBreakUp(ArrayList<ArrayList<String>> list,
			String spitWgt, String spitNum, String username) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement psta = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			for (int i = 0; i < list.size(); i++) {
				String ordLnDlyPk = list.get(i).get(0);
				String plnDivideId = list.get(i).get(1);
				double ratio = Double.parseDouble(list.get(i).get(2));
				PlnSaleordEntityA entityA = getQureySaleProc(conn, ordLnDlyPk,
						plnDivideId, PlnSaleordEntityA.class);
				if (entityA == null) {
					cro.setV_errMsg("未勾选排产合同!");
					return cro;
				}
				if (!entityA.getPlanstatus().equals("1")) {
					cro.setV_errMsg("勾选的排产合同不是已接收状态,不能拆分!");
					return cro;
				}
				// 总支吨
				int num = Integer.parseInt(entityA.getPlanNumD());
				double wt = Double.parseDouble(entityA.getPlanWtD());
				// 最小管体总吨
				double wtMin = Double.parseDouble(entityA.getPlanPMainMin());
				// 管体总吨
				double planWt = Double.parseDouble(entityA.getPlanPMain());
				// 初始分配支吨总吨
				int beginNum = Integer.parseInt(entityA.getPlanNumBegin());
				double beginWt = Double.parseDouble(entityA.getPlanWtBegin());
				// 总米长
				double totLenD = Double.parseDouble(entityA.getPlanTotLenD());
				// 合同总量
				double orderWt = Double.parseDouble(entityA.getOrderQtyD());

				// 拆分支吨
				int spitNumD = Integer.parseInt(spitNum);
				double spitWtD = Double.parseDouble(spitWgt);
				// 拆分总米长
				double spitLenD = (totLenD / num) * spitNumD;
				// 拆分管体
				double spitplanWt = (planWt / num) * spitNumD;
				// 拆分管体mIN
				double spitwtMin = (wtMin / num) * spitNumD;

				// 拆分分配支吨总吨
				int spitbeginNum = (int) Math.ceil(beginNum * ratio);
				double spitbeginWt = 0;
				if (spitbeginNum != 0) {
					spitbeginWt = (beginWt / beginNum) * spitbeginNum;
				}
				// 拆分合同量
				double spitorderWt = (orderWt / num) * spitNumD;
				// 剩余支吨
				int remaNum = num - spitNumD;
				double remaWt = wt - spitWtD;
				double remaLenD = totLenD - spitLenD;
				// 剩余管体
				double remaplanWt = planWt - spitplanWt;
				// 剩余管体Min
				double remawtMin = wtMin - spitwtMin;
				// 剩余分配支吨总吨
				int remabeginNum = beginNum - spitbeginNum;
				double remabeginWt = beginWt - spitbeginWt;
				// 剩余合同量
				double remaOrderWt = orderWt - spitorderWt;

				entityA.setPlanNumD(String.valueOf(remaNum));
				entityA.setPlanWtD(String.valueOf(remaWt));
				entityA.setPlanNumBegin(String.valueOf(remabeginNum));
				entityA.setPlanWtBegin(String.valueOf(remabeginWt));
				entityA.setPlanTotLenD(String.valueOf(remaLenD));
				entityA.setPlanPMain(String.valueOf(remaplanWt));
				entityA.setPlanPMainMin(String.valueOf(remawtMin));
				entityA.setOrderQtyD(String.valueOf(remaOrderWt));

				// 修改原排产合同量
				String update = EntityTool.fillSqlByEntity(
						CoreXmlSqlParsersFactory
								.getSql("CoreConfirmCraft.updateOrdProc"),
						entityA);
				psta = conn.prepareStatement(update);
				psta.executeUpdate();
				psta.close();

				// 获取最大流水号
				String plnDivdeIdNo = getMaxPlnDivideId(conn, entityA
						.getOrdLnDlyPk());

				entityA.setPlanNumD(String.valueOf(spitNumD));
				entityA.setPlanWtD(String.valueOf(spitWtD));
				entityA.setPlanNumBegin(String.valueOf(spitbeginNum));
				entityA.setPlanWtBegin(String.valueOf(spitbeginWt));
				entityA.setPlanTotLenD(String.valueOf(spitLenD));
				entityA.setPlanPMain(String.valueOf(spitplanWt));
				entityA.setPlanPMainMin(String.valueOf(spitwtMin));
				entityA.setOrderQtyD(String.valueOf(spitorderWt));
				entityA.setPlnDivideId(plnDivdeIdNo);
				// 新增拆分行排产合同
				String sqlAdd = EntityTool
						.fillSqlByEntity(CoreXmlSqlParsersFactory
								.getSql("CoreConfirmCraft.ADDOrdProc"), entityA);
				psta = conn.prepareStatement(sqlAdd);
				psta.executeUpdate();
				psta.close();
			}
			cro.setV_errMsg("拆分成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
			return cro;
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 合并排产合同
	 * 
	 * @param list
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doMerge(ArrayList<ArrayList<String>> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement psta = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			String ordLnDlyPk1 = "";
			String orderSource1 = "";
			int plnDivideId1 = 0;
			// 总支吨
			int num = 0;
			double wt = 0;
			// 最小管体总吨
			double wtMin = 0;
			// 管体总吨
			double planWt = 0;
			// 初始分配支吨总吨
			int beginNum = 0;
			double beginWt = 0;
			// 总米长
			double totLenD = 0;
			// 合同总量
			double orderWt = 0;
			PlnSaleordEntityA entityA1 =null;
			for (int i = 0; i < list.size(); i++) {
				String ordLnDlyPk = list.get(i).get(0);
				String plnDivideId = list.get(i).get(1);
				PlnSaleordEntityA entityA = getQureySaleProc(conn, ordLnDlyPk,
						plnDivideId, PlnSaleordEntityA.class);
				if (entityA == null) {
					cro.setV_errMsg("未勾选排产合同!");
					return cro;
				}
				if (!entityA.getPlanstatus().equals("1")) {
					cro.setV_errMsg("勾选的排产合同不是已接收状态,不能合分!");
					return cro;
				}
				if (ordLnDlyPk1.equals("")) {
					ordLnDlyPk1 = ordLnDlyPk;
				}
				if (orderSource1.equals("")) {
					orderSource1 = entityA.getOrderSource();
				}
				if (!ordLnDlyPk.equals(ordLnDlyPk1)
						|| !entityA.getOrderSource().equals(orderSource1)) {
					cro.setV_errMsg("相同合同并且合同来源也相同才能合并!");
					return cro;
				}
				num += Integer.parseInt(entityA.getPlanNumD());
				wt += Double.parseDouble(entityA.getPlanWtD());
				// 最小管体总吨
				wtMin += Double.parseDouble(entityA.getPlanPMainMin());
				// 管体总吨
				planWt += Double.parseDouble(entityA.getPlanPMain());
				// 初始分配支吨总吨
				beginNum += Integer.parseInt(entityA.getPlanNumBegin());
				beginWt += Double.parseDouble(entityA.getPlanWtBegin());
				// 总米长
				totLenD += Double.parseDouble(entityA.getPlanTotLenD());
				// 合同总量
				orderWt += Double.parseDouble(entityA.getOrderQtyD());
				if (entityA1 == null) {
					plnDivideId1 = Integer.parseInt(plnDivideId);
					entityA1 = entityA;
				}
				// 找最小排产序号的排产行
				if (Integer.parseInt(plnDivideId) < plnDivideId1) {
					plnDivideId1 = Integer.parseInt(plnDivideId);
					entityA1 = entityA;
				}
			}

			entityA1.setPlanNumD(String.valueOf(num));
			entityA1.setPlanWtD(String.valueOf(wt));
			entityA1.setPlanNumBegin(String.valueOf(beginNum));
			entityA1.setPlanWtBegin(String.valueOf(beginWt));
			entityA1.setPlanTotLenD(String.valueOf(totLenD));
			entityA1.setPlanPMain(String.valueOf(planWt));
			entityA1.setPlanPMainMin(String.valueOf(wtMin));
			entityA1.setOrderQtyD(String.valueOf(orderWt));
			// 修改原排产合同量
			String update = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
					.getSql("CoreConfirmCraft.updateOrdProc"), entityA1);
			psta = conn.prepareStatement(update);
			psta.executeUpdate();
			psta.close();

			for (int i = 0; i < list.size(); i++) {
				String ordLnDlyPk = list.get(i).get(0);
				String plnDivideId = list.get(i).get(1);
				if (Integer.parseInt(plnDivideId) != plnDivideId1) {
					// 删除排产合同行
					String sqlAdd = "DELETE PLN_SALEORD_PROC WHERE ORD_LN_DLY_PK = ? AND PLN_DIVIDE_ID = ?";
					psta = conn.prepareStatement(sqlAdd);
					psta.setObject(1, ordLnDlyPk);
					psta.setObject(2, plnDivideId);
					psta.executeUpdate();
					psta.close();
				}
			}

			cro.setV_errMsg("合并成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
			return cro;
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
	/**
	 * 查最大流水号
	 * 
	 * @param con
	 * @param time
	 * @return
	 * @throws SQLException
	 */
	public static String getMaxPlnDivideId(Connection con, String ordLnDlyPk)
			throws SQLException {
		String gxPlnSeq = "01";
		String sql = "   SELECT TO_NUMBER(NVL(MAX(T.PLN_DIVIDE_ID),0))+1 AS PLN_DIVIDE_ID FROM PLN_SALEORD_PROC T where t.ORD_LN_DLY_PK=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, ordLnDlyPk);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {

			if (rs.getInt("PLN_DIVIDE_ID") >= 10) {
				gxPlnSeq = rs.getString("PLN_DIVIDE_ID");
			} else {
				gxPlnSeq = "0" + rs.getString("PLN_DIVIDE_ID");
			}
		}
		rs.close();
		ps.close();
		return gxPlnSeq;
	}
}