package com.steering.pss.plnsaleord.jggxpln;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.jggxpln.model.PlnGxJgPropEntity;
import com.steering.pss.plnsaleord.jggxpln.model.PlnOrdJgMEditEntity;
import com.steering.pss.plnsaleord.order.CorePlnOrdJgDjDeal;
import com.steering.pss.plnsaleord.order.baseMethod.CoreOrdBase;
import com.steering.pss.plnsaleord.order.model.PlnJgAndBlEntity;
import com.steering.pss.plnsaleord.order.model.PlnPorderBlReqEntity;

/**
 * 接箍订单组料
 * 
 * @author xiaohai
 * 
 */
public class CoreJgMBlOrd extends DBCommon {

	/**
	 * 接箍订单原交货行记录
	 * 
	 * @param proPlanId
	 * @return
	 */
	public CoreReturnObject querySaleOrder(String proPlanId) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreJgMBlOrd.querySaleOrder",
				new Object[] { proPlanId });
		return cro;
	}

	/**
	 * 查询工序订单订单号
	 * 
	 * @return
	 */
	public CoreReturnObject queryJgGxMNo() {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreJgMBlOrd.queryJgGxMNo");
		return cro;
	}

	/**
	 * 查询备料需求号
	 * 
	 * @return
	 */
	public CoreReturnObject queryJglRelNo() {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreJgMBlOrd.queryJglRelNo");
		return cro;
	}

	/**
	 * 查询订单
	 * 
	 * @param strJgDdNo
	 * @return
	 */
	public CoreReturnObject queryGxJgM(String strJgDdNo, String inFinished) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory.getSql("CoreJgMBlOrd.queryGxJgM");
		if (!inFinished.trim().equals("1")) {
			sql += " AND T.IFBUYPLAN != '1' AND SIGN(NVL(T.PLAN_NUM, 0)"
					+ " - NVL(T.MATCHNUM, 0) - NVL(T.JGWT_BLREQ, 0)) = 1";
		}
		cro = this.getData(sql, new Object[] { strJgDdNo });
		return cro;
	}

	/**
	 * 查询订单配料
	 * 
	 * @param strJgDdNo
	 * @return
	 */
	public CoreReturnObject queryJgDealedit(String strJgDdNo, String inFinished) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreJgMBlOrd.queryJgDealedit");
		if (!inFinished.trim().equals("1")) {
			sql += " AND T.IFBUYPLAN != '1' AND SIGN(NVL(T.PLAN_NUM, 0)"
					+ " - NVL(T.MATCHNUM, 0) - NVL(T.JGWT_BLREQ, 0)) = 1";
		}
		cro = this.getData(sql, new Object[] { strJgDdNo });
		return cro;
	}

	/**
	 * 查询接箍备料需求信息
	 * 
	 * @return object
	 */
	public CoreReturnObject queryJgBlNeed(String reqBlId) {
		CoreReturnObject cro = null;
		cro = this.getDataBySqlID("CoreJgMBlOrd.queryJgBlNeed",
				new Object[] { reqBlId });
		return cro;
	}

	/**
	 * 查询接箍及备料关系
	 * 
	 * @param str
	 *            备料需求编号
	 * @return object
	 */
	public CoreReturnObject queryRelation(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreJgMBlOrd.queryRelation",
				new Object[] { str });
		return cro;
	}

	/**
	 * 新增接箍料需求
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject addJgBlReq(ArrayList<PlnOrdJgMEditEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			PreparedStatement ps = null;
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			String sqla = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.addJgAndBlRelation");
			String sqlb = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.addPlnOrdJglReq");
			String sqlc = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateBlreq");
			ArrayList<String> blCodeList = new ArrayList<String>();

			for (PlnOrdJgMEditEntity editEntity : list) {
				if (!blCodeList.contains(editEntity.getCodeJgBl() + ","
						+ editEntity.getPrdcrNo())) {
					blCodeList.add(editEntity.getCodeJgBl() + ","
							+ editEntity.getPrdcrNo());
				}
			}
			for (String codeBlPr : blCodeList) {
				String codeBl = codeBlPr.substring(0, codeBlPr.indexOf(","));
				String blReqId = "";
				double aimLenBl = 0;// 备料管目标长度（m）
				double wtOfmiBl = 0;// 备料米单重（t/m）
				double sinWtBlg = 0;// 备料管单重
				double sinBlLen = 0;// 备料需求长度（m）
				String msc = "";
				PlnPorderBlReqEntity blReqEntity = new PlnPorderBlReqEntity();
				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.queryJgReqblid"));
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getString("REQ_BL_ID") != null) {
						blReqId = rs.getString("REQ_BL_ID");
					}
				}
				rs.close();
				ps.close();

				if (blReqId.equals("")) {
					conn.rollback();
					cro.setV_errCode(-1);
					cro.setV_errMsg("生成备料需求编号错误！");
					return cro;
				}

				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.queryBlList"));
				ps.setObject(1, codeBl);
				rs = ps.executeQuery();
				if (rs.next()) {
					double minD = rs.getDouble("MIN_D");
					double minH = rs.getDouble("MIN_H");
					double minL = rs.getDouble("MIN_L");
					double maxL = rs.getDouble("MAX_L");
					if (rs.getString("MSC") != null) {
						msc = rs.getString("MSC");
					}
					aimLenBl = (minL + maxL) / 2;
					wtOfmiBl = CoreOrdBase.WeightOfMi(minD, minH);
					sinWtBlg = aimLenBl * wtOfmiBl;
				}
				rs.close();
				ps.close();

				for (PlnOrdJgMEditEntity editEntity : list) {
					String sql = "";
					String plinCode = "";
					String plinName = "";
					String blWlId = "";
					String blWlDesc = "";
					String[] blMaterial = null;
					PreparedStatement pst = null;
					ResultSet rst = null;

					PlnJgAndBlEntity jgAndBl = new PlnJgAndBlEntity();

					String strJgBlPrdcr = editEntity.getCodeJgBl() + ","
							+ editEntity.getPrdcrNo();
					if (!strJgBlPrdcr.equals(codeBlPr)) {
						// 过滤掉不是同一备料码的记录
						continue;
					}
					double wtJg = Double.parseDouble(editEntity.getWeightJg());
					double wtJglReq = Double.parseDouble(editEntity
							.getJgblReqWeight());
					if (wtJg <= 0 || wtJglReq <= 0) {
						continue;
					}
					double getrate = 100 * wtJg / wtJglReq;
					jgAndBl.setProPlanId(editEntity.getProPlanId());
					jgAndBl.setReqBlId(blReqId);
					jgAndBl.setCodeJg(editEntity.getCodeJg());
					jgAndBl.setCodeJgBl(editEntity.getCodeJgBl());
					jgAndBl.setNumJg(editEntity.getNumJg());
					jgAndBl.setWeightJg(editEntity.getWeightJg());
					jgAndBl.setJgblReqNum(editEntity.getNumJgbl());
					jgAndBl.setJgblReqWeight(editEntity.getJgblReqWeight());
					jgAndBl.setSingleweight2(String.valueOf(sinWtBlg));
					jgAndBl.setAimlengthBl(String.valueOf(aimLenBl));
					jgAndBl.setGetrate(String.valueOf(getrate));
					jgAndBl.setSingleAddlen(editEntity.getSingleAddlen());
					jgAndBl.setCreateName(editEntity.getCreateName());

					String sqlAdd = EntityTool.fillSqlByEntity(sqla, jgAndBl);
					ps = conn.prepareStatement(sqlAdd);
					ps.executeUpdate();
					ps.close();

					// 更新接箍合同已做备料接箍个数
					ps = conn.prepareStatement(sqlc);
					ps.setObject(1, editEntity.getNumJg());
					ps.setObject(2, editEntity.getProPlanId());
					ps.executeUpdate();
					ps.close();

					sql = CoreXmlSqlParsersFactory
							.getSql("CoreJgMBlOrd.selectJgMaterialPl");
					sql += " ORDER BY T.PRD_RATE DESC, T.WASTE_RATE ASC";
					pst = conn.prepareStatement(sql);
					pst.setObject(1, codeBl);
					pst.setObject(2, editEntity.getCodeJg());
					rst = pst.executeQuery();
					if (rst.next()) {
						plinCode = rst.getString("PLINE_CODE");
						plinName = rst.getString("PLINE_NAME");
					}
					rst.close();
					pst.close();

					blMaterial = CorePlnOrdJgDjDeal.getBlMaterial(conn, codeBl);
					if (blMaterial != null) {
						blWlId = blMaterial[0];
						blWlDesc = blMaterial[1];
					}
					sql = CoreXmlSqlParsersFactory
							.getSql("CoreJgMBlOrd.updateJgMBlPl");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, editEntity.getCodeJgBl());
					ps.setObject(2, blWlId);
					ps.setObject(3, blWlDesc);
					ps.setObject(4, plinCode);
					ps.setObject(5, plinName);
					ps.setObject(6, editEntity.getProPlanId());
					ps.executeUpdate();
					ps.close();

					// 接箍订单属性明细表回写备料码
					updateJgMPropBl(conn, editEntity.getCodeJgBl(), editEntity
							.getProPlanId());

					sinBlLen += Double
							.parseDouble(editEntity.getJgblSumlenth());
				}

				double wtBlOrd = sinBlLen * wtOfmiBl;
				int blNumOrd = 0;
				if (Math.abs(sinBlLen % aimLenBl) < 0.0000001) {
					blNumOrd = (int) (sinBlLen / aimLenBl);
				} else {
					blNumOrd = (int) (sinBlLen / aimLenBl) + 1;
				}

				blReqEntity.setReqBlId(blReqId);
				blReqEntity.setCodeJgBl(codeBl);
				blReqEntity.setJgblReqNum(String.valueOf(blNumOrd));
				blReqEntity.setJgblReqWeight(String.valueOf(wtBlOrd));
				blReqEntity.setAimlength(String.valueOf(aimLenBl));
				blReqEntity.setSingleweight(String.valueOf(sinWtBlg));
				blReqEntity.setMsc(msc);
				blReqEntity.setCreateName(list.get(0).getCreateName());
				String sqlNew = EntityTool.fillSqlByEntity(sqlb, blReqEntity);
				ps = conn.prepareStatement(sqlNew);
				ps.executeUpdate();
				ps.close();
			}
			conn.commit();
			cro.setResult("操作成功！");
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 新增接箍备料对应需求
	 * 
	 * @param list
	 * @param blReqNo
	 * @return
	 */
	public CoreReturnObject addJgAndBl(ArrayList<PlnOrdJgMEditEntity> list,
			String blReqId) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			PreparedStatement ps = null;
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			String sqla = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.addJgAndBlRelation");
			String sqlb = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateRelation");
			String sqlc = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateBlreq");
			String sqld = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateJglneed");
			ArrayList<String> param = new ArrayList<String>();
			PlnPorderBlReqEntity blReqEntity = new PlnPorderBlReqEntity();

			double aimLenBl = 0;// 备料管目标长度（m）
			double wtOfmiBl = 0;// 备料米单重（t/m）
			double sinWtBlg = 0;// 备料管单重
			double sinBlLen = 0;// 备料需求长度（m）

			ps = conn.prepareStatement(CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.queryRelation"));
			ps.setObject(1, blReqId);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				if (rs.getString("PRO_PLAN_ID") == null) {
					conn.rollback();
					cro.setV_errCode(-1);
					cro.setV_errMsg("数据异常！");
					return cro;
				}
				param.add(rs.getString("PRO_PLAN_ID"));
			}
			rs.close();
			ps.close();

			ps = conn.prepareStatement(CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.queryBlList"));
			ps.setObject(1, list.get(0).getCodeJgBl());
			rs = ps.executeQuery();
			if (rs.next()) {
				double minD = rs.getDouble("MIN_D");
				double minH = rs.getDouble("MIN_H");
				double minL = rs.getDouble("MIN_L");
				double maxL = rs.getDouble("MAX_L");
				aimLenBl = (minL + maxL) / 2;
				wtOfmiBl = CoreOrdBase.WeightOfMi(minD, minH);
				sinWtBlg = aimLenBl * wtOfmiBl;
			}
			rs.close();
			ps.close();

			for (PlnOrdJgMEditEntity editEntity : list) {
				String sql = "";
				String plinCode = "";
				String plinName = "";
				String blWlId = "";
				String blWlDesc = "";
				String[] blMaterial = null;
				PreparedStatement pst = null;
				ResultSet rst = null;

				boolean fl = false;// 否（新增），是更新
				PlnJgAndBlEntity jgAndBl = new PlnJgAndBlEntity();
				if (param.contains(editEntity.getProPlanId())) {
					fl = true;
				}
				if (fl) {
					// 更新原关系记录
					jgAndBl.setProPlanId(editEntity.getProPlanId());
					jgAndBl.setReqBlId(blReqId);
					jgAndBl.setNumJg(editEntity.getNumJg());
					jgAndBl.setWeightJg(editEntity.getWeightJg());
					jgAndBl.setJgblReqNum(editEntity.getNumJgbl());
					jgAndBl.setJgblReqWeight(editEntity.getJgblReqWeight());
					jgAndBl.setUpdateName(editEntity.getCreateName());

					String sqlAdd = EntityTool.fillSqlByEntity(sqlb, jgAndBl);
					ps = conn.prepareStatement(sqlAdd);
					ps.executeUpdate();
					ps.close();
				} else {
					// 新增关系记录
					double wtJg = Double.parseDouble(editEntity.getWeightJg());
					double wtJglReq = Double.parseDouble(editEntity
							.getJgblReqWeight());
					if (wtJg <= 0 || wtJglReq <= 0) {
						continue;
					}
					double getrate = 100 * wtJg / wtJglReq;
					jgAndBl.setProPlanId(editEntity.getProPlanId());
					jgAndBl.setReqBlId(blReqId);
					jgAndBl.setCodeJg(editEntity.getCodeJg());
					jgAndBl.setCodeJgBl(editEntity.getCodeJgBl());
					jgAndBl.setNumJg(editEntity.getNumJg());
					jgAndBl.setWeightJg(editEntity.getWeightJg());
					jgAndBl.setJgblReqNum(editEntity.getNumJgbl());
					jgAndBl.setJgblReqWeight(editEntity.getJgblReqWeight());
					jgAndBl.setSingleweight2(String.valueOf(sinWtBlg));
					jgAndBl.setAimlengthBl(String.valueOf(aimLenBl));
					jgAndBl.setGetrate(String.valueOf(getrate));
					jgAndBl.setSingleAddlen(editEntity.getSingleAddlen());
					jgAndBl.setCreateName(editEntity.getCreateName());

					String sqlAdd = EntityTool.fillSqlByEntity(sqla, jgAndBl);
					ps = conn.prepareStatement(sqlAdd);
					ps.executeUpdate();
					ps.close();
				}

				// 更新接箍合同已做备料接箍个数
				ps = conn.prepareStatement(sqlc);
				ps.setObject(1, editEntity.getNumJg());
				ps.setObject(2, editEntity.getProPlanId());
				ps.executeUpdate();
				ps.close();

				sql = CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.selectJgMaterialPl");
				sql += " ORDER BY T.PRD_RATE DESC, T.WASTE_RATE ASC";
				pst = conn.prepareStatement(sql);
				pst.setObject(1, editEntity.getCodeJgBl());
				pst.setObject(2, editEntity.getCodeJg());
				rst = pst.executeQuery();
				if (rst.next()) {
					plinCode = rst.getString("PLINE_CODE");
					plinName = rst.getString("PLINE_NAME");
				}
				rst.close();
				pst.close();

				blMaterial = CorePlnOrdJgDjDeal.getBlMaterial(conn, editEntity
						.getCodeJgBl());
				if (blMaterial != null) {
					blWlId = blMaterial[0];
					blWlDesc = blMaterial[1];
				}
				sql = CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.updateJgMBlPl");
				ps = conn.prepareStatement(sql);
				ps.setObject(1, editEntity.getCodeJgBl());
				ps.setObject(2, blWlId);
				ps.setObject(3, blWlDesc);
				ps.setObject(4, plinCode);
				ps.setObject(5, plinName);
				ps.setObject(6, editEntity.getProPlanId());
				ps.executeUpdate();
				ps.close();

				// 接箍订单属性明细表回写备料码
				updateJgMPropBl(conn, editEntity.getCodeJgBl(), editEntity
						.getProPlanId());

				sinBlLen += Double.parseDouble(editEntity.getJgblSumlenth());
			}

			// 更新备料需求
			double wtBlOrd = sinBlLen * wtOfmiBl;
			int blNumOrd = 0;
			if (Math.abs(sinBlLen % aimLenBl) < 0.0000001) {
				blNumOrd = (int) (sinBlLen / aimLenBl);
			} else {
				blNumOrd = (int) (sinBlLen / aimLenBl) + 1;
			}
			blReqEntity.setReqBlId(blReqId);
			blReqEntity.setJgblReqNum(String.valueOf(blNumOrd));
			blReqEntity.setJgblReqWeight(String.valueOf(wtBlOrd));
			blReqEntity.setUpdateName(list.get(0).getCreateName());
			String sqlNew = EntityTool.fillSqlByEntity(sqld, blReqEntity);
			ps = conn.prepareStatement(sqlNew);
			ps.executeUpdate();
			ps.close();

			conn.commit();
			cro.setResult("操作成功！");
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除备料需求
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject deleteReq(ArrayList<String> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			ArrayList<String> message = new ArrayList<String>();
			PreparedStatement ps = null;
			String sqla = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.deleteBlneed");
			String sqlb = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.deleteRelation");
			String sqlc = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateBlreq");
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			for (String blReqId : list) {
				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.selectBlReqStatus"));
				ps.setObject(1, blReqId);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getString("PLANSTATUS") != null
							&& !rs.getString("PLANSTATUS").trim().equals("0")) {
						message.add("备料需求" + blReqId + "已经确认。");
						continue;
					}
				}
				rs.close();
				ps.close();

				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.queryRelation"));
				ps.setObject(1, blReqId);
				rs = ps.executeQuery();
				while (rs.next()) {
					if (rs.getString("PRO_PLAN_ID") == null) {
						conn.rollback();
						cro.setV_errCode(-1);
						cro.setV_errMsg("数据异常！");
						return cro;
					}
					String proPlanId = rs.getString("PRO_PLAN_ID");
					int numJg = rs.getInt("NUM_JG");// 接箍个数

					PreparedStatement psta = conn.prepareStatement(sqlb);
					psta.setObject(1, proPlanId);
					psta.setObject(2, blReqId);
					psta.executeUpdate();
					psta.close();

					// 更新接箍合同已做备料接箍个数
					psta = conn.prepareStatement(sqlc);
					psta.setObject(1, -numJg);
					psta.setObject(2, proPlanId);
					psta.executeUpdate();
					psta.close();
				}
				rs.close();
				ps.close();

				// 删除备料需求
				ps = conn.prepareStatement(sqla);
				ps.setObject(1, blReqId);
				ps.executeUpdate();
				ps.close();
			}
			conn.commit();
			if (message.size() > 0) {
				cro.setResult(message.size() + "条操作失败。\n" + message.get(0));
			} else {
				cro.setResult("操作成功！");
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除备料需求对应接箍合同
	 * 
	 * @param list
	 * @param blReqId
	 * @param udpateName
	 * @return
	 */
	public CoreReturnObject deleteRelation(ArrayList<String> list,
			String blReqId, String udpateName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			PreparedStatement ps = null;
			ArrayList<String> message = new ArrayList<String>();
			String sqla = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateJglneed");
			String sqlb = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.deleteRelation");
			String sqlc = CoreXmlSqlParsersFactory
					.getSql("CoreJgMBlOrd.updateBlreq");
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			double aimLenBl = 0;// 备料管目标长度（m）
			double wtOfmiBl = 0;// 备料米单重（t/m）
			double sinBlLen = 0;// 备料需求长度（m）

			for (String proPlanId : list) {
				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.selectBlReqStatus"));
				ps.setObject(1, blReqId);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getString("PLANSTATUS") != null
							&& !rs.getString("PLANSTATUS").trim().equals("0")) {
						message.add("备料需求" + blReqId + "已经确认。");
						continue;
					}
				}
				rs.close();
				ps.close();

				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.getJgBlRelation"));
				ps.setObject(1, proPlanId);
				ps.setObject(2, blReqId);
				rs = ps.executeQuery();
				if (rs.next()) {
					double minD = rs.getDouble("MIN_D");
					double minH = rs.getDouble("MIN_H");
					double minL = rs.getDouble("MIN_L");
					double maxL = rs.getDouble("MAX_L");
					int numJg = rs.getInt("NUM_JG");
					double lenJg = rs.getDouble("LENGTH_JG");
					double addJg = rs.getDouble("SINGLE_ADDLEN");
					aimLenBl = (minL + maxL) / 2;
					wtOfmiBl = CoreOrdBase.WeightOfMi(minD, minH);
					sinBlLen += (lenJg + addJg) * numJg / 1000;
					if (wtOfmiBl <= 0 || aimLenBl <= 0) {
						conn.rollback();
						cro.setV_errCode(-1);
						cro.setV_errMsg("备料码数据异常！");
						return cro;
					}
					if (lenJg <= 0) {
						conn.rollback();
						cro.setV_errCode(-1);
						cro.setV_errMsg("接箍码数据异常！");
						return cro;
					}

					PreparedStatement psta = conn.prepareStatement(sqlb);
					psta.setObject(1, proPlanId);
					psta.setObject(2, blReqId);
					psta.executeUpdate();
					psta.close();

					// 更新接箍合同已做备料接箍个数
					psta = conn.prepareStatement(sqlc);
					psta.setObject(1, -numJg);
					psta.setObject(2, proPlanId);
					psta.executeUpdate();
					psta.close();
				}
				rs.close();
				ps.close();
			}

			// 更新备料需求
			PlnPorderBlReqEntity blReqEntity = new PlnPorderBlReqEntity();
			double wtBlOrd = sinBlLen * wtOfmiBl;
			int blNumOrd = 0;
			if (Math.abs(sinBlLen % aimLenBl) < 0.0000001) {
				blNumOrd = (int) (sinBlLen / aimLenBl);
			} else {
				blNumOrd = (int) (sinBlLen / aimLenBl) + 1;
			}
			blReqEntity.setReqBlId(blReqId);
			blReqEntity.setJgblReqNum(String.valueOf(-blNumOrd));
			blReqEntity.setJgblReqWeight(String.valueOf(-wtBlOrd));
			blReqEntity.setUpdateName(udpateName);
			String sqlNew = EntityTool.fillSqlByEntity(sqla, blReqEntity);
			ps = conn.prepareStatement(sqlNew);
			ps.executeUpdate();
			ps.close();

			conn.commit();
			if (message.size() > 0) {
				cro.setResult(message.size() + "条操作失败。\n" + message.get(0));
			} else {
				cro.setResult("操作成功！");
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 更新接箍订单属性备料码
	 * 
	 * @param conn
	 * @param codeBl
	 * @param proPlanId
	 * @return
	 * @throws SQLException
	 */
	public static boolean updateJgMPropBl(Connection conn, String codeBl,
			String proPlanId) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<PlnGxJgPropEntity> propEntiyS = null;
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreJgMBlOrd.selectJgMProP");
		ps = conn.prepareStatement(sql);
		ps.setObject(1, proPlanId);
		rs = ps.executeQuery();
		propEntiyS = EntityTool.getEntitysByRs(rs, PlnGxJgPropEntity.class);

		if (propEntiyS != null) {
			for (PlnGxJgPropEntity propEntiy : propEntiyS) {
				// if (!propEntiy.getCodeJgBl().equals(codeBl)) {
				PreparedStatement psta = null;
				String sqlUpProp = CoreXmlSqlParsersFactory
						.getSql("CoreJgMBlOrd.updateJgMProPBl");
				String sqlUp = "";
				String codeJg = propEntiy.getCodeJg();
				propEntiy.setCodeJgBl(codeBl);
				CorePlnJgOrdToDd.getSinBlToJgNum(conn, codeJg, propEntiy);
				sqlUp = EntityTool.fillSqlByEntity(sqlUpProp, propEntiy);
				psta = conn.prepareStatement(sqlUp);
				psta.executeUpdate();
				psta.close();
				// }
			}
		} else {
			return false;
		}
		rs.close();
		ps.close();
		return true;
	}

	/**
	 * 是否完成接箍料编制
	 * 
	 * @param conn
	 * @param jgOrderNum
	 *            接箍合同号
	 * @throws SQLException
	 */
	/*
	 * public void isFinishedJgl(Connection conn, String jgOrderNum) throws
	 * SQLException { PreparedStatement ps = null; boolean isFinished = true;
	 * String sql = CoreXmlSqlParsersFactory
	 * .getSql("CorePlnJgBlDeal.queryJgbyOrderno"); ps =
	 * conn.prepareStatement(sql); ps.setString(1, jgOrderNum); ResultSet result
	 * = ps.executeQuery(); while (result.next()) { String ordLnDlyPk = ""; if
	 * (result.getString("ORD_LN_DLY_PK") != null) { ordLnDlyPk =
	 * result.getString("ORD_LN_DLY_PK"); } else { return; } //
	 * 查询接箍合同信息,判断是否完成接箍料编制 sql = CoreXmlSqlParsersFactory
	 * .getSql("CorePlnJgBlDeal.haveJgOrder"); PreparedStatement psta =
	 * conn.prepareStatement(sql); psta.setString(1, ordLnDlyPk); ResultSet rs =
	 * psta.executeQuery(); while (rs.next()) { if (rs.getString("IFBUYPLAN") !=
	 * null && !rs.getString("IFBUYPLAN").equals("1")) { if
	 * (rs.getInt("ORDERNUM") > rs.getInt("JGWT_BLREQ") + rs.getInt("MATCHNUM"))
	 * { isFinished = false; } } } rs.close(); psta.close();
	 * 
	 * // 如果完成，更新销售合同接箍料需求是否制订 if (isFinished) { sql = CoreXmlSqlParsersFactory
	 * .getSql("CorePlnJgBlDeal.isFinishedJgOrder"); psta =
	 * conn.prepareStatement(sql); psta.setObject(1, "1"); psta.setObject(2,
	 * jgOrderNum); psta.executeUpdate(); psta.close();
	 * 
	 * sql = CoreXmlSqlParsersFactory .getSql("CorePlnJgBlDeal.isFinishedJgl");
	 * psta = conn.prepareStatement(sql); psta.setObject(1, "1");
	 * psta.setObject(2, ordLnDlyPk); psta.executeUpdate(); psta.close(); } else
	 * { sql = CoreXmlSqlParsersFactory
	 * .getSql("CorePlnJgBlDeal.isFinishedJgOrder"); psta =
	 * conn.prepareStatement(sql); psta.setObject(1, "0"); psta.setObject(2,
	 * jgOrderNum); psta.executeUpdate(); psta.close();
	 * 
	 * sql = CoreXmlSqlParsersFactory .getSql("CorePlnJgBlDeal.isFinishedJgl");
	 * psta = conn.prepareStatement(sql); psta.setObject(1, "0");
	 * psta.setObject(2, ordLnDlyPk); psta.executeUpdate(); psta.close(); } }
	 * result.close(); ps.close(); }
	 */

	/**
	 * 修改接箍订单个数
	 */
	public CoreReturnObject updatePlanGxJgM(String proPlanId)
			throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;

			// 查询接箍订单个数
			int planNum = 0;
			int jgwtBlreq = 0;
			String plineCode = "";
			String inMaterialNo = "";
			String outMaterialNo = "";
			String sqlQuery = "SELECT T.PRO_PLAN_ID, NVL(T.PLAN_NUM,0) PLAN_NUM, NVL(T.JGWT_BLREQ, 0) JGWT_BLREQ,T.PLINE_CODE,T.BL_WL_ID,T.CODE_JG FROM PLN_GX_JG_M T WHERE T.PRO_PLAN_ID = ?";
			ps = conn.prepareStatement(sqlQuery);
			ps.setObject(1, proPlanId);
			rs = ps.executeQuery();
			if (rs.next()) {
				planNum = rs.getInt("PLAN_NUM");
				jgwtBlreq = rs.getInt("JGWT_BLREQ");
				plineCode = rs.getString("PLINE_CODE");
				inMaterialNo = rs.getString("BL_WL_ID");
				outMaterialNo = rs.getString("CODE_JG");
			}
			rs.close();
			ps.close();
			if (jgwtBlreq != 0) {
				return cro;
			}
			// 查询投入产出物料对应小时能力表万只废品数
			double wasteRate = 0;
			String sqldesc = "SELECT NVL(T.WASTE_RATE,0) WASTE_RATE  FROM SLM_BASE_MATERIAL_H_PL T  WHERE T.IN_MATERIAL_NO=? AND T.OUT_MATERIAL_NO=? AND T.PLINE_CODE=?";
			ps = conn.prepareStatement(sqldesc);
			ps.setObject(1, inMaterialNo);
			ps.setObject(2, outMaterialNo);
			ps.setObject(3, plineCode);
			rs = ps.executeQuery();
			if (rs.next()) {
				wasteRate = rs.getDouble("WASTE_RATE") / 10000;
			}
			rs.close();
			ps.close();
			// 求原始接箍个数
			int oldplanNum = 0;
			String sqlOldNum = "SELECT NVL(SUM(T.GROUP_NUM),0) GROUP_NUM FROM PLN_GX_JG_PROP T WHERE T.PRO_PLAN_ID=?";
			ps = conn.prepareStatement(sqlOldNum);
			ps.setObject(1, proPlanId);
			rs = ps.executeQuery();
			if (rs.next()) {
				oldplanNum=rs.getInt("GROUP_NUM");
			}
			rs.close();
			ps.close();
			planNum = (int) Math.ceil(oldplanNum / (1 - wasteRate));
			// 修改接箍订单接箍个数
			String sqlgXJgM = "UPDATE PLN_GX_JG_M SET PLAN_NUM=? WHERE PRO_PLAN_ID=?";
			ps = conn.prepareStatement(sqlgXJgM);
			ps.setObject(1, planNum);
			ps.setObject(2, proPlanId);
			ps.executeUpdate();
			ps.close();
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

}