package com.steering.pss.plnsaleord.order;

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

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.processOrder.entity.TimeEntity;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.order.model.PlnOrdInfo;
import com.steering.pss.plnsaleord.order.model.PlnOrderZgSEntity;
import com.steering.pss.plnsaleord.order.model.PlnOrderZgSEntityAmount;

/**
 * @author tjg 2017.05.27
 */
public class FrmProdSchAmount extends DBCommon {
	/**
	 * 查询排产信息
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return object
	 */
	public CoreReturnObject query(String[] plineCode, String proPlanId,
			String orderNo, String[] statusArray, String comPlineCode) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmProdSchAmount.query");
		if (!comPlineCode.equals("")) {
			sql += " AND T.PLINE_CODE='" + comPlineCode + "' ";
		} else {
			sql += CoreConverter.toSqlConditionString("PLINE_CODE", plineCode);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID LIKE '%'||'" + proPlanId + "'||'%'";
		}
		if (!orderNo.equals("")) {
			sql += " AND T.ORDER_NO||'/'||T.ORDER_SEQ LIKE '%'||'" + orderNo
					+ "'||'%'";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		sql += " AND T.ORDER_SOURCE IN ('销售合同','补量需求','备料需求')";
		sql += "  ORDER BY  T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ)";
		return this.getData(sql);
	}

	/**
	 * 查询补量信息
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return object
	 */
	public CoreReturnObject queryBl(String[] plineCode, String proPlanId,
			String orderNo, String[] statusArray, String comPlineCode) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmProdSchAmount.query");
		if (!comPlineCode.equals("")) {
			sql += " AND T.PLINE_CODE='" + comPlineCode + "' ";
		} else {
			sql += CoreConverter.toSqlConditionString("PLINE_CODE", plineCode);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID LIKE '%'||'" + proPlanId + "'||'%'";
		}
		if (!orderNo.equals("")) {
			sql += " AND T.ORDER_NO||'/'||T.ORDER_SEQ LIKE '%'||'" + orderNo
					+ "'||'%'";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		sql += " AND T.ORDER_SOURCE ='排产补量'";
		sql += "  ORDER BY  T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ)";
		return this.getData(sql);
	}

	/**
	 * 查询排产补量信息
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return object
	 */
	public CoreReturnObject queryPlnBl(String proPlanId) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmProdSchAmount.query");
		sql += " AND T.PRO_PLAN_ID ='" + proPlanId + "'";
		sql += " AND T.ORDER_SOURCE ='排产补量'";
		sql += "  ORDER BY  T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ)";
		return this.getData(sql);
	}

	/**
	 * 判断后工序是否生成完成
	 * 
	 * @param conn
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return
	 * @throws SQLException
	 */
	public static String canAfterProcess(Connection conn, String ordLnDlyPk,
			String plnDivideId, String processCode, String wholeBacklogDesc,
			String orderNoSeq) throws SQLException {
		String reason = "";
		PreparedStatement ps = null;
		ResultSet rs = null;
		if (processCode.equals("D")) {
			if (wholeBacklogDesc.contains("镦拔扩")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_DBK_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序镦拔扩排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			} else if (wholeBacklogDesc.contains("热处理")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_RCL_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序热处理排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			} else if (wholeBacklogDesc.contains("加工")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_JGX_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序加工线排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			}
		} else if (processCode.equals("E")) {
			if (wholeBacklogDesc.contains("热处理")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_RCL_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序热处理排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			} else if (wholeBacklogDesc.contains("加工")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_JGX_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序加工线排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			}
		} else if (processCode.equals("F")) {
			if (wholeBacklogDesc.contains("加工")) {
				String sqlDbk = "SELECT  NVL(MIN(T.EXE_STATUS),0) EXE_STATUS FROM PLN_ORDER_JGX_S T WHERE T.ORD_LN_DLY_PK=? AND T.PLN_DIVIDE_ID=?";
				ps = conn.prepareStatement(sqlDbk);
				ps.setObject(1, ordLnDlyPk);
				ps.setObject(2, plnDivideId);
				rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getInt("EXE_STATUS") >= 2) {
						reason = "合同：" + orderNoSeq + "后工序加工线排产订单已生成完成。";
						return reason;
					}
				}
				rs.close();
				ps.close();
			}
		}
		return reason;
	}

	/**
	 * 新增补量
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject addAmount(ArrayList<ArrayList<String>> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			int failNum = 0;
			PreparedStatement psta = null;
			ResultSet rsta = null;
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			DateFormat df1 = new SimpleDateFormat("yyyy-MM");
			Date time = new Date();
			String nowTime = df.format(time);
			List<PlnOrderZgSEntityAmount> plnAmount = null;
			for (int i = 0; i < list.size(); i++) {
				String amountName = list.get(i).get(0);
				double amountWet = Double.parseDouble(list.get(i).get(2));// 补量需求吨
				int amountNum = Integer.parseInt(list.get(i).get(1));// 补量需求支
				String proPlanId = list.get(i).get(3);// 订单编号
				String gxPlanNo = list.get(i).get(4);// 排产序号
				String billWeight = list.get(i).get(5);// 单倍坯重

				PlnOrdInfo ordInfo = new PlnOrdInfo();
				String sql = CoreXmlSqlParsersFactory
						.getSql("FrmProdSchAmount.queryAddPlnOrderZgSStrat");
				PreparedStatement psc = conn.prepareStatement(sql);
				psc.setString(1, proPlanId);
				psc.setString(2, gxPlanNo);
				ResultSet rs = psc.executeQuery();
				plnAmount = EntityTool.getEntitysByRs(rs,
						PlnOrderZgSEntityAmount.class);
				rs.close();
				psc.close();

				if (plnAmount == null || plnAmount.size() == 0) {
					cro.setV_errMsg("轧管信息发生改变,请重新获取数据!");
					return cro;
				}

				for (PlnOrderZgSEntityAmount proEntity : plnAmount) {
					proEntity.setProMonth(df1.format(time));// 赋值当前年月
					//&& !proEntity.getExeStatus().equals("3")
					if (!proEntity.getExeStatus().equals("2")
							) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq()
								+ ")不是生产完成状态,不能新增补量!");
						return cro;
					}
					String mess = canAfterProcess(
							conn,
							proEntity.getOrdLnDlyPk(),
							proEntity.getPlnDivideId(),
							"D",
							proEntity.getWholeBacklogDesc(),
							proEntity.getOrderNo() + "/"
									+ proEntity.getOrderSeq());
					if (!mess.equals("")) {
						cro.setV_errMsg(mess);
						return cro;
					}
					ProducHelperBean helperBean = new ProducHelperBean();
					// 1.2验证产线能力
					double[] capacity = helperBean.getPlineCapacity(conn,
							proEntity.getInwlId(), proEntity.getOutwlId(),
							proEntity.getPlineCode(), "D");
					if (capacity[0] <= 0) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq() + "),产线("
								+ proEntity.getPlineName() + ")没有维护产线能力!");
						return cro;
					}
					double orglWgt = 0;
					int orglNum = 0;

					double weigthSMin = 0;// 排产剩余重量MIN
					double weigthS = 0;// 排产重量
					int numS = 0;// 排产支数
					int plnNum = 0;// 计划总产出支数
					double wastRate = 0;// 万只废品
					int addNum = 0;
					double addWt = 0;
					double gpreqWeightMin = 0;
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnProcessOrd.queryBaseMaterialDPl");
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.setString(1, proEntity.getInwlId());
					ps.setString(2, proEntity.getOutwlId());
					ps.setString(3, proEntity.getPlineCode());
					rs = ps.executeQuery();
					if (rs.next()) {
						wastRate = rs.getInt("WASTE_RATE") / 10000;
					}
					rs.close();
					ps.close();
					// 查询合同信息
					sql = CoreXmlSqlParsersFactory
							.getSql("CorePlnProcessOrd.querySaleProcStatus");
					psta = conn.prepareStatement(sql);
					psta.setString(1, proEntity.getOrdLnDlyPk());
					psta.setString(2, proEntity.getPlnDivideId());
					rs = psta.executeQuery();
					if (rs.next()) {
						ordInfo.setOrdLnPk(rs.getString("ORD_LN_PK"));
						ordInfo.setDesginKey(rs.getString("DESGIN_KEY"));
						ordInfo.setBom(rs.getString("BOM"));
						if (rs.getString("OUTS_STL_PIPE_FL") != null) {
							ordInfo.setOutsStlPipeFl(rs
									.getString("OUTS_STL_PIPE_FL"));
						}
					} else {
						cro.setV_errMsg("未找到合同信息。");
						return cro;
					}
					rs.close();
					psta.close();
					// 获取最新工艺 CIC
					// 2.3查找工艺
					String[] craftInfo = PlnHelper.getArray(conn,
							"CorePlnSaleOrder.queryOrdCraftOrdDesign",
							" AND T.VALIDFLAG = '1'",
							new String[] { ordInfo.getOrdLnPk() },
							new String[] { "CRAFT_SEQ", "DESGIN_KEY",
									"CRAFT_NAME", "CRAFT_NO", "CRAFT_NO_V" });
					if (craftInfo == null || craftInfo.length == 0) {
						cro.setV_errMsg("合同行：" + proEntity.getOrderNo() + "/"
								+ proEntity.getOrderSeq() + "未找到有效的工艺评审！");
						return cro;
					}

					proEntity.setCraftSeq(craftInfo[0]);
					proEntity.setCraftFileMan(craftInfo[2]);
					proEntity.setCraftFileNo(craftInfo[3]);
					String sqlZgCic = CoreXmlSqlParsersFactory
							.getSql("CorePlnOrdProUseTime.queryZgPineHrCapcty");
					ps = conn.prepareStatement(sqlZgCic);
					ps.setObject(1, proPlanId);
					rs = ps.executeQuery();
					if (rs.next()) {
						if (rs.getString("CIC") != null) {
							proEntity.setCic(rs.getString("CIC"));
						}
						if (rs.getString("PIC") != null) {
							proEntity.setPic(rs.getString("PIC"));
						}
						if (rs.getString("SIC") != null) {
							proEntity.setSic(rs.getString("SIC"));
						}
						if (rs.getString("DIC") != null) {
							proEntity.setDic(rs.getString("DIC"));
						}
						if (rs.getString("WIC") != null) {
							proEntity.setWic(rs.getString("WIC"));
						}
						if (rs.getString("GIC") != null) {
							proEntity.setGic(rs.getString("GIC"));
						}
						if (rs.getString("STATION_ROAD") != null) {
							proEntity.setStationRoad(rs
									.getString("STATION_ROAD"));
						}
					}
					rs.close();
					ps.close();

					String groupCic = "";
					String gradeCode = proEntity.getGradecode();
					String groupWic = "";// 水压
					String groupPic = "";// 材质
					String groupSic = "";// 公差
					String groupDic = "";// 探伤
					String groupGic = "";// 加工
					String progyMemo = "";// 工艺备注
					sql = CoreXmlSqlParsersFactory
							.getSql("FrmProdSchAmount.selectGpIcList");
					ps = conn.prepareStatement(sql);
					ps.setObject(1, proPlanId);
					rs = ps.executeQuery();
					while (rs.next()) {
						if (rs.getString("CIC") != null) {
							if (!rs.getString("CIC").equals("")) {
								groupCic += rs.getString("CIC") + ",";
							}
						}
						// if (rs.getString("GRADECODE") != null) {
						// gradeCode = rs.getString("GRADECODE");
						// }
						if (rs.getString("PIC") != null) {
							if (!rs.getString("PIC").equals("")) {
								groupPic += rs.getString("PIC") + ",";
							}
						}
						if (rs.getString("SIC") != null) {
							if (!rs.getString("SIC").equals("")) {
								groupSic += rs.getString("SIC") + ",";
							}
						}
						if (rs.getString("DIC") != null) {
							if (!rs.getString("DIC").equals("")) {
								groupDic += rs.getString("DIC") + ",";

							}
						}
						if (rs.getString("WIC") != null) {
							if (!rs.getString("WIC").equals("")) {
								groupWic += rs.getString("WIC") + ",";
							}
						}
						if (rs.getString("GIC") != null) {
							if (!rs.getString("GIC").equals("")) {
								groupGic += rs.getString("GIC") + ",";
							}
						}
						progyMemo = rs.getString("PROGY_MEMO");
					}
					rs.close();
					ps.close();
					proEntity.setProgyMemo(progyMemo);//工艺备注
					if (!groupDic.equals("") && groupDic.contains(",")) {
						groupDic = groupDic.substring(0, groupDic.length() - 1);
					}
					proEntity.setDicGroupGp(groupDic);
					proEntity.setDicGp(groupDic.split(",")[0]);

					if (!groupPic.equals("") && groupPic.contains(",")) {
						groupPic = groupPic.substring(0, groupPic.length() - 1);
					}
					proEntity.setPicGroupGp(groupPic);
					proEntity.setPicGp(groupPic.split(",")[0]);

					if (!groupSic.equals("") && groupSic.contains(",")) {
						groupSic = groupSic.substring(0, groupSic.length() - 1);
					}
					proEntity.setSicGroupGp(groupSic);
					proEntity.setSicGp(groupSic.split(",")[0]);

					if (!groupWic.equals("") && groupWic.contains(",")) {
						groupWic = groupWic.substring(0, groupWic.length() - 1);
					}
					proEntity.setWicGroupGp(groupWic);
					proEntity.setWicGp(groupWic.split(",")[0]);
					if (!groupGic.equals("") && groupGic.contains(",")) {
						groupGic = groupGic.substring(0, groupGic.length() - 1);
					}
					proEntity.setGicGroupGp(groupGic);
					proEntity.setGicGp(groupGic.split(",")[0]);

					if (!groupCic.equals("") && groupCic.contains(",")) {
						groupCic = groupCic.substring(0, groupCic.length() - 1);
					}
					String[] groupCic1 = groupCic.split(",");
					proEntity.setCicGroupGp(groupCic);
					// 去除数组中的空格
					List<String> tmp = new ArrayList<String>();
					for (String str : groupCic1) {
						if (str != null && str.length() != 0) {
							tmp.add(str.trim());
						}
					}
					groupCic1 = tmp.toArray(new String[0]);

					String cicGroup = "";
					if (groupCic1 != null && groupCic1.length > 0) {
						// String sqlc = CoreXmlSqlParsersFactory
						// .getSql("CorePlnZgMStoGp.screenCicByGrade");
						String sqlc = CoreXmlSqlParsersFactory
								.getSql("FrmBomConfirm.getQueryGrade");
						sqlc += " AND INSTR(T.GRADECODE,'" + gradeCode
								+ "') > 0";
						sqlc += CoreConverter.toSqlConditionString("T.CIC",
								groupCic1);
						sqlc += " AND T1.PURCHASE_STD='"
								+ proEntity.getOutsBilletFl() + "' ";
						PreparedStatement pst = conn.prepareStatement(sqlc);
						// pst.setObject(1, gradeCode);
						ResultSet rst = pst.executeQuery();
						if (rst.next()) {
							if (rst.getString("CIC") != null) {
								cicGroup += rst.getString("CIC") + ",";
							}
							// if (rst.getString("STD_NAME_NK") != null) {
							// stdNameNk += rst.getString("STD_NAME_NK")+ ",";
							// }
						} else {
							if (ordInfo.getOutsStlPipeFl().equals("")
									|| ordInfo.getOutsStlPipeFl().equals(
											"121901")) {
								if (proEntity.getOutsBilletFl().equals("1")) {
									cro.setV_errMsg("无外购钢种索引码,请联系工艺人员。");
									return cro;
								} else {
									cro.setV_errMsg("无自炼钢种索引码,请联系工艺人员。");
									return cro;
								}
							}
						}
						rst.close();
						pst.close();
						if (!cicGroup.equals("") && cicGroup.contains(",")) {
							cicGroup = cicGroup.substring(0,
									cicGroup.length() - 1);
						}
						proEntity.setCicGp(cicGroup.split(",")[0]);
					}

					String gradCodeArr = "";
					String gradNameArr = "";
					String cicGroupLk = "";
					String[] gradArr = PlnHelper.getArray(
							conn,
							"CorePlnProcessOrd.queryDesginPl",
							new String[] { ordInfo.getDesginKey(),
									ordInfo.getDesginKey(),
									ordInfo.getDesginKey() }, new String[] {
									"GRADECODE", "GRADENAME" });
					if (gradArr == null || gradArr[0] == null
							|| gradArr[0].length() == 0) {

					} else {
						gradCodeArr = gradArr[0];
						gradNameArr = gradArr[1];
						String[] gradCode = gradCodeArr.split(",");
						sql = CoreXmlSqlParsersFactory
								.getSql("CorePlnOrdProUseTime.selectGpIcListlk");
						sql += CoreConverter.toSqlConditionString(
								"D.GRADECODE", gradCode);
						sql += ")";
						ps = conn.prepareStatement(sql);
						ps.setObject(1, proPlanId);
						rs = ps.executeQuery();
						if (rs.next()) {
							cicGroupLk = rs.getString("CIC");
						}
						rs.close();
						ps.close();
					}

					proEntity.setGradecodeLk(gradCodeArr);
					proEntity.setGradenameLk(gradNameArr);
					proEntity.setCicGroupLk(cicGroupLk);
					if (proEntity.getGpreqNum().equals("0")) {
						// orglWgt = amountWet;// 原需坯重量
						// orglNum = amountNum;// 原需坯支数
						weigthSMin = 0;
						plnNum = 0;
						plnNum = (int) Math
								.ceil((amountNum
										* Integer.parseInt(proEntity
												.getOutnumCut()) * (1 - wastRate)));
						// 排产重量
						weigthS = amountWet * (1 - wastRate);
						// 排产支数
						numS = plnNum;
						addNum = (int) Math.ceil(wastRate * plnNum
								/ Integer.parseInt(proEntity.getOutnumCut()));
						addWt = wastRate * weigthS;
					} else {
						orglWgt = Double
								.parseDouble(proEntity.getGpreqWeight());// 原需坯重量
						orglNum = Integer.parseInt(proEntity.getGpreqNum());// 原需坯支数

						// 排产重量
						weigthS = amountWet
								* Double.parseDouble(proEntity.getWeigthS())
								/ orglWgt;
						// 产出重量MIN
						weigthSMin = amountWet
								* Double.parseDouble(proEntity.getWeigthSMin())
								/ orglWgt;
						// 排产支数
						numS = (amountNum)
								* Integer.parseInt(proEntity.getNumS())
								/ orglNum;
						// 计划产出支
						plnNum = (amountNum)
								* Integer.parseInt(proEntity.getPlansNum())
								/ orglNum;
						addNum = (amountNum)
								* Integer.parseInt(proEntity.getAddNumIn())
								/ orglNum;
						addWt = amountWet
								* Double.parseDouble(proEntity.getAddWtIn())
								/ orglWgt;
						gpreqWeightMin = amountWet
								* Double.parseDouble(proEntity
										.getGpreqWeightMin()) / orglWgt;
					}

					// 排产序号
					String gxPlanNo1 = helperBean.getMaxGxPlanNo(conn,
							proEntity.getProPlanId(), "D");
					// 生产顺序
					int gxProSeq = helperBean.getMaxGxProSeq(conn,
							proEntity.getPlineCode(), "D",
							proEntity.getProMonth());
					// 3.1计划开始时间(这个时间应该从数据库里查)
					String planTimeB = helperBean.getMaxPlanTimeE(conn,
							proEntity.getPlineCode(), "D",
							proEntity.getProMonth(), gxProSeq);
					if (planTimeB.equals("")) {
						cro.setV_errMsg("计划开始时间为空,补量失败!");
						return cro;

					}
					TimeEntity TimeEntiy = helperBean.calculateTime(amountNum,
							capacity[0], planTimeB);
					// 计划结束时间
					String planTimeE = TimeEntiy.getEndTime();
					String planUserTime = TimeEntiy.getUserTime();

					helperBean.seqIncrease(conn, proEntity.getPlineCode(),
							gxProSeq, -1, 1, "D");
					// // 修改轧管信息状态
					// String sqlUpPrc = CoreXmlSqlParsersFactory
					// .getSql("FrmProdSchAmount.UpdatePlnOrderZgS");
					// psta = conn.prepareStatement(sqlUpPrc);
					// psta.setObject(1, "2");
					// psta.setObject(2, "");
					// psta.executeUpdate();
					// psta.close();
					// 3.2新增新记录
					proEntity.setGxPlanNo(gxPlanNo1);
					proEntity.setGxProSeq(String.valueOf(gxProSeq));
					proEntity.setWeigthS(String.valueOf(weigthS));
					proEntity.setNumS(String.valueOf(numS));
					proEntity.setPlanTimeB(planTimeB);
					proEntity.setPlanTimeE(planTimeE);
					proEntity.setPlanUsetime(planUserTime);
					proEntity.setWeigthSMin(String.valueOf(weigthSMin));
					proEntity.setGpreqNum(String.valueOf(amountNum));
					proEntity.setGpreqWeight(String.valueOf(amountWet));//
					proEntity.setPlansNum(String.valueOf(plnNum));
					proEntity.setAddNumIn(String.valueOf(addNum));
					proEntity.setAddWtIn(String.valueOf(addWt));
					proEntity.setCreateTime(nowTime);
					proEntity.setOrderSource("排产补量");
					proEntity.setZyBatchId("");
					proEntity.setGpreqWeightMin(String.valueOf(gpreqWeightMin));
					proEntity.setProgyMemo(progyMemo);
					// 新增轧管排产补量
					String sqlUpAddPln = EntityTool
							.fillSqlByEntity(
									CoreXmlSqlParsersFactory
											.getSql("FrmProdSchAmount.queryAddPlnOrderZgSAmount"),
									proEntity);
					psta = conn.prepareStatement(sqlUpAddPln);
					psta.executeUpdate();
					psta.close();

					// 时间自动调整
					helperBean.timeIncrease(conn,
							Integer.parseInt(proEntity.getGxProSeq()),
							proEntity.getPlineCode(), planTimeE, "D");
					// helperBean.generateZyBatchId(conn,
					// proEntity.getPlineCode(), "D");
				}
			}
			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());
		} 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) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 删除补量
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject deleteAmount(ArrayList<ArrayList<String>> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement psta = null;
			ResultSet rsta = null;
			List<PlnOrderZgSEntityAmount> plnAmount = null;
			for (int i = 0; i < list.size(); i++) {
				String amountName = list.get(i).get(0);
				double amountWet = Double.parseDouble(list.get(i).get(2));// 补量需求吨
				int amountNum = Integer.parseInt(list.get(i).get(1));// 补量需求支
				String proPlanId = list.get(i).get(3);// 订单编号
				String gxPlanNo = list.get(i).get(4);// 排产序号

				String sql = CoreXmlSqlParsersFactory
						.getSql("FrmProdSchAmount.queryAddPlnOrderZgSStrat");
				PreparedStatement psc = conn.prepareStatement(sql);
				psc.setString(1, proPlanId);
				psc.setString(2, gxPlanNo);
				ResultSet rs = psc.executeQuery();
				plnAmount = EntityTool.getEntitysByRs(rs,
						PlnOrderZgSEntityAmount.class);
				rs.close();
				psc.close();

				if (plnAmount == null || plnAmount.size() == 0) {
					cro.setV_errMsg("排产补量信息发生改变,请重新获取数据!");
					return cro;
				}
				for (PlnOrderZgSEntityAmount proEntity : plnAmount) {

					if (proEntity.getExeStatus().equals("2")) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq() + "),已生产完成,不能删除!");
						return cro;
					}
					if (proEntity.getExeStatus().equals("3")) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq() + "),已关闭,不能删除!");
						return cro;
					}
					if (proEntity.getGpreqId() != null
							&& !proEntity.getGpreqId().equals("")) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq()
								+ "),已生成管坯需求,请先撤销管坯需求!");
						return cro;
					}
					ProducHelperBean helperBean = new ProducHelperBean();

					// 1.2验证产线能力
					double[] capacity = helperBean.getPlineCapacity(conn,
							proEntity.getInwlId(), proEntity.getOutwlId(),
							proEntity.getPlineCode(), "D");
					if (capacity[0] <= 0) {
						cro.setV_errMsg("合同号(" + proEntity.getOrderNo() + "/)"
								+ proEntity.getOrderSeq() + "),产线("
								+ proEntity.getPlineName() + ")没有维护产线能力!");
						return cro;
					}
					String planTimeB = proEntity.getPlanTimeB();
					// 删除轧管排产补量
					String sqlUpDelete = CoreXmlSqlParsersFactory
							.getSql("FrmProdSchAmount.DeletePlnOrderZgSAmount");
					psta = conn.prepareStatement(sqlUpDelete);
					psta.setObject(1, proEntity.getProPlanId());
					psta.setObject(2, proEntity.getGxPlanNo());
					psta.executeUpdate();
					psta.close();
					helperBean.seqIncrease(conn, proEntity.getPlineCode(),
							Integer.parseInt(proEntity.getGxProSeq()), -1, -1,
							"D");
					// 时间自动调整
					helperBean.timeIncrease(conn,
							Integer.parseInt(proEntity.getGxProSeq()) - 1,
							proEntity.getPlineCode(), planTimeB, "D");
				}
			}
			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());
		} 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) {
				e.printStackTrace();
			}
		}
		return cro;
	}
}