package com.steering.pss.plnsaleord.steelMarkingPlan;

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.steelMarkingPlan.entity.*;

/**
 * @author tjg 2018.04.11
 */
public class FrmLgAmount extends DBCommon {
	/**
	 * 查询排产信息
	 * 
	 * @param ordLnDlyPk
	 * @param plnDivideId
	 * @return object
	 */
	public CoreReturnObject query(String[] plineCode, String proPlanId,
			String[] statusArray, String comPlineCode) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmLgAmount.query");
		if (!comPlineCode.equals("")) {
			sql += " AND T.PLINE_CODE='" + comPlineCode + "' ";
		} else {
			sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plineCode);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID LIKE '%'||'" + proPlanId + "'||'%'";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		sql += " AND T.IF_AMOUNT ='0'";
		sql += "  ORDER BY T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ)) H "
				+ " where H.EXE_STATUS_ZG='计划'";
		return this.getData(sql);
	}

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

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

	/**
	 * 新增补量
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject addAmount(ArrayList<ArrayList<String>> list,
			String userName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			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<PlnOrderCastSEntityAmount> plnAmount = null;
			for (int i = 0; i < list.size(); i++) {
				double amountWet = Double.parseDouble(list.get(i).get(1));// 补量需求吨
				int amountNum = Integer.parseInt(list.get(i).get(0));// 补量需求支
				String proPlanId = list.get(i).get(2);// 订单编号
				String gxPlanNo = list.get(i).get(3);// 排产序号

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

				if (plnAmount == null || plnAmount.size() == 0) {
					cro.setV_errMsg("铸造订单信息发生改变,请重新获取数据!");
					return cro;
				}
				String statusCoun = "";
				// 查询订单是否存在计划状态
				String sqlSratus = "SELECT MIN(T.EXE_STATUS) EXE_STATUS FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=?";
				psc = conn.prepareStatement(sqlSratus);
				psc.setObject(1, proPlanId);
				rs = psc.executeQuery();
				if (rs.next()) {
					statusCoun = rs.getString("EXE_STATUS");
				}
				rs.close();
				psc.close();

				if (!statusCoun.equals("") && !statusCoun.equals("2")) {
					cro.setV_errMsg("铸造订单(" + proPlanId + "),还存在不是已生产状态,不能补量!");
					return cro;
				}
				// 根据管坯需求号产线轧管订单状态
				int countZg = 0;
				String sqlQueryZg = "SELECT COUNT(*)  COUNT FROM PLN_ORDER_ZG_S T WHERE T.GPREQ_ID=? AND T.EXE_STATUS='0'";
				psta = conn.prepareStatement(sqlQueryZg);
				psta.setString(1, proPlanId);
				rsta = psta.executeQuery();
				if (rsta.next()) {
					countZg = rsta.getInt("COUNT");
				}
				rsta.close();
				psta.close();
				if (countZg == 0) {
					cro.setV_errMsg("铸造订单对应的轧管订单信息没有计划状态,不能补量!");
					return cro;
				}
				// 查询铸造订单总冶炼量Min
				double allWt = 0;
				double allWtMin = 0;
				double allWtLk = 0;
				String sqlQuery = "SELECT NVL(SUM(T.PLAN_WT_MIN),0) PLAN_WT_MIN,NVL(SUM(T.PLAN_WT_S),0) PLAN_WT_S,NVL(SUM(PLAN_WT_SOLD),0) PLAN_WT_SOLD   FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=?";
				psta = conn.prepareStatement(sqlQuery);
				psta.setObject(1, proPlanId);
				rsta = psta.executeQuery();
				if (rsta.next()) {
					allWt = rsta.getDouble("PLAN_WT_S");
					allWtMin = rsta.getDouble("PLAN_WT_MIN");
					allWtLk = rsta.getDouble("PLAN_WT_SOLD");
				}
				rsta.close();
				psta.close();
				// 铸造订单已做炼钢炉计划量(订单)
				double spitWgtall = 0;
				String sqlProNum = CoreXmlSqlParsersFactory
						.getSql("ControlOrderPlan.getCastProPlanIdNumAll");
				PreparedStatement ps = conn.prepareStatement(sqlProNum);
				ps.setObject(1, proPlanId);
				rs = ps.executeQuery();
				if (rs.next()) {
					spitWgtall = rs.getDouble("TOT_WEIGHT_M");
				}
				rs.close();
				ps.close();
				double plnInsingleWt = 0;
				// 查询铸造订单对应轧管订单炉计划量(炼钢利库，有管坯需求轧管利库)
				String sqlProPlanZg = CoreXmlSqlParsersFactory
						.getSql("ControlOrderPlan.getCastProPlanIdZg");
				ps = conn.prepareStatement(sqlProPlanZg);
				ps.setObject(1, proPlanId);
				rs = ps.executeQuery();
				if (rs.next()) {
					plnInsingleWt = rs.getDouble("PLN_INSINGLE_WT");
				}
				rs.close();
				ps.close();
				// 验证重量（冶炼量min-已组浇量-后轧管利库-炼钢利库<=0）
				if (allWtMin > 0) {
//					if (allWtMin - spitWgtall - plnInsingleWt - allWtLk <= 1) {
//						cro
//								.setV_errMsg("订单号(" + proPlanId
//										+ ")已满足最小冶炼,不能新增补量!");
//						return cro;
//					}
				} else {
					if (allWt - spitWgtall - plnInsingleWt - allWtLk <= 1) {
						cro.setV_errMsg("订单号(" + proPlanId + ")已满足冶炼,不能新增补量!");
						return cro;
					}
				}
				// 产线铸造订单对应
				for (PlnOrderCastSEntityAmount proEntity : plnAmount) {
					proEntity.setProMonth(df1.format(time));// 赋值当前年月
					if (!proEntity.getExeStatus().equals("2")) {
						cro.setV_errMsg("订单号(" + proPlanId + "/" + gxPlanNo
								+ ")不是已生成状态,不能新增补量!");
						return cro;
					}

					ProducHelperBean helperBean = new ProducHelperBean();
					// 1.2验证产线能力
					double[] capacity = helperBean.getPlineCapacity(conn,
							proEntity.getWlidIn(), proEntity.getMaterialNo(),
							proEntity.getPlineCode(), "B");
					if (capacity[0] <= 0) {
						cro.setV_errMsg("订单号(" + proEntity.getProPlanId()
								+ "/)" + proEntity.getGxPlanNo() + "),产线("
								+ proEntity.getPlineName() + ")没有维护产线能力!");
						return cro;
					}
					double weigthSMin = Double.parseDouble(proEntity
							.getPlanWtMin())
							/ Double.parseDouble(proEntity.getPlanWtS())
							* amountWet;
					// 排产序号
					String gxPlanNo1 = helperBean.getMaxGxPlanNo(conn,
							proEntity.getProPlanId(), "B");
					// 生产顺序
					int gxProSeq = helperBean.getMaxGxProSeq(conn, proEntity
							.getPlineCode(), "B", proEntity.getProMonth());
					// 3.1计划开始时间(这个时间应该从数据库里查)
					String planTimeB = helperBean.getMaxPlanTimeE(conn,
							proEntity.getPlineCode(), "B", 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, "B");
					// 3.2新增新记录
					proEntity.setGxPlanNo(gxPlanNo1);
					proEntity.setGxProSeq(String.valueOf(gxProSeq));
					proEntity.setPlanWtS(String.valueOf(amountWet));
					proEntity.setPlanNumS(String.valueOf(amountNum));
					proEntity.setPlanTimeB(planTimeB);
					proEntity.setPlanTimeE(planTimeE);
					proEntity.setPlanUsetime(planUserTime);
					proEntity.setPlanWtMin(String.valueOf(weigthSMin));
					proEntity.setCreateName(userName);
					proEntity.setCreateTime(nowTime);
					proEntity.setIfAmount("1");
					proEntity.setIsRepairPln("0");
					proEntity.setCastNoAll("");
					proEntity.setRepairType("");
					proEntity.setExeStatus("0");
					// 新增铸造排产补量
					String sqlUpAddPln = EntityTool.fillSqlByEntity(
							CoreXmlSqlParsersFactory
									.getSql("FrmLgAmount.queryAddAmount"),
							proEntity);
					psta = conn.prepareStatement(sqlUpAddPln);
					psta.executeUpdate();
					psta.close();
					// 时间自动调整
					helperBean.timeIncrease(conn, Integer.parseInt(proEntity
							.getGxProSeq()), proEntity.getPlineCode(),
							planTimeE, "B");
				}
			}
			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>> jsonList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement psta = null;
			List<PlnOrderCastSEntityAmount> plnAmount = null;
			for (int i = 0; i < jsonList.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jsonList.get(i);
				String proPlanId = list.get(0);// 订单编号
				String gxPlanNo = list.get(1);// 排产序号

				// 查询铸造订单状态
				String sql = CoreXmlSqlParsersFactory
						.getSql("FrmLgAmount.queryAddPlnOrderZgSStrat");
				PreparedStatement psc = conn.prepareStatement(sql);
				psc.setString(1, proPlanId);
				psc.setString(2, gxPlanNo);
				ResultSet rs = psc.executeQuery();
				plnAmount = EntityTool.getEntitysByRs(rs,
						PlnOrderCastSEntityAmount.class);
				rs.close();
				psc.close();

				if (plnAmount == null || plnAmount.size() == 0) {
					cro.setV_errMsg("排产补量信息发生改变,请重新获取数据!");
					return cro;
				}
				for (PlnOrderCastSEntityAmount proEntity : plnAmount) {
					if (Integer.parseInt(proEntity.getPlanedNum()) > 0) {
						cro.setV_errMsg("订单号(" + proEntity.getProPlanId()
								+ "/)" + proEntity.getGxPlanNo()
								+ "),已组浇,不能删除!");
						return cro;
					}
					if (proEntity.getExeStatus().equals("2")) {
						cro.setV_errMsg("订单号(" + proEntity.getProPlanId()
								+ "/)" + proEntity.getGxPlanNo()
								+ "),已生产完成,不能删除!");
						return cro;
					}
					if (proEntity.getExeStatus().equals("3")) {
						cro.setV_errMsg("订单号(" + proEntity.getProPlanId()
								+ "/)" + proEntity.getGxPlanNo()
								+ "),已关闭,不能删除!");
						return cro;
					}
					ProducHelperBean helperBean = new ProducHelperBean();

					// // 1.2验证产线能力
					// double[] capacity = helperBean.getPlineCapacity(conn,
					// proEntity.getWlidIn(), proEntity.getMaterialNo(),
					// proEntity.getPlineCode(), "B");
					// if (capacity[0] <= 0) {
					// cro.setV_errMsg("合同号(" + proEntity.getProPlanId() + "/)"
					// + proEntity.getGxPlanNo() + "),产线("
					// + proEntity.getPlineName() + ")没有维护产线能力!");
					// return cro;
					// }
					String planTimeB = proEntity.getPlanTimeB();
					// 删除排产补量
					String sqlUpDelete = CoreXmlSqlParsersFactory
							.getSql("FrmLgAmount.DeleteAmount");
					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,
							"B");
					// 时间自动调整
					helperBean.timeIncrease(conn, Integer.parseInt(proEntity
							.getGxProSeq()) - 1, proEntity.getPlineCode(),
							planTimeB, "B");
				}
			}
			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;
	}
}