package com.steering.pss.plnsaleord.planStove;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.planStove.entity.MatBcTrackEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.entity.*;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

/**
 * 镦拔扩利库
 * 
 * @author teng 2017.11.21
 */
public class FrmRollTubeLibraryDbk extends DBCommon {

	/**
	 * 查询虚拟炉计划
	 * 
	 * @param proPlanId
	 * @param gxPlanNo
	 * @return
	 */
	public CoreReturnObject queryPlanStoveD(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryPlanStoveD");
		List<String> param = new ArrayList<String>();
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID=?";
			param.add(proPlanId);
		}
		if (!gxPlanNo.equals("")) {
			sql += " AND T.GX_PLAN_NO =?";
			param.add(gxPlanNo);
		}
		sql += " ORDER BY T.GX_PRO_SEQ ASC ";
		return this.getData(sql, param.toArray());
	}

	/**
	 * 查询实际炉计划
	 * 
	 * @param proPlanId
	 * @param heatId
	 * @return
	 */
	public CoreReturnObject queryPlanStoveDc(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryPlanStoveDc");
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID='" + proPlanId + "'";
			sql += " AND T.GX_PLAN_NO ='" + gxPlanNo + "'";
		}
		sql += " ORDER BY T.HEAT_PLAN_SQE ASC";
		return this.getData(sql);
	}

	/**
	 * 查询排产(界面展示)
	 * 
	 * @param plineCode
	 *            产线
	 * @param proPlanId
	 *            　订单编号
	 * @param orderNo
	 *            　合同号
	 * @param statusArray
	 *            　生产状态
	 * @return CoreReturnObject
	 */
	public CoreReturnObject queryPlanOrderD(String[] plineCode,
			String proPlanId, String orderNo, String[] statusArray,
			String proMonth, String comPlineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryPlanOrderD");
		List<String> params = new ArrayList<String>();
		if (!comPlineCode.equals("")) {
			params.add(comPlineCode);
			sql += " AND T.PLINE_CODE=? ";
		} else {
			sql += CoreConverter
					.toSqlConditionString("T.PLINE_CODE", plineCode);
		}
		if (!proPlanId.equals("")) {
			params.add(proPlanId);
			sql += " AND T.PRO_PLAN_ID LIKE '%'||?||'%'";
		}
		if (!orderNo.equals("")) {
			params.add(orderNo);
			sql += " AND T.ORDER_NO||'/'||T.ORDER_SEQ LIKE '%'||?||'%'";
		}

		if (!proMonth.equals("")) {
			params.add(proMonth);
			sql += " AND T.PRO_MONTH=?";
		}
		if (statusArray.length > 0) {
			sql += CoreConverter.toSqlConditionString("T.EXE_STATUS",
					statusArray);
		}
		// sql +=" and T.GPREQ_ID IS NULL";
		sql += "  ORDER BY  T.PLINE_CODE,TO_NUMBER(T.GX_PRO_SEQ))DBK";
		return this.getData(sql, params.toArray());
	}

	/**
	 * 查询
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getPlnOrderDbk(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryPlanOrderD");
		sql += " AND T.PRO_PLAN_ID ='" + proPlanId + "'";
		sql += " AND T.GX_PLAN_NO ='" + gxPlanNo + "')DBK";
		return this.getData(sql);
	}

	/**
	 * 查询产线环形炉最小
	 * 
	 * @param plineCode
	 * @return
	 */
	public CoreReturnObject queryPline(String plineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryPline");
		return this.getData(sql, new Object[] { plineCode });
	}

	/**
	 * 查询成分元素
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getStlChemicalStd(String cic, String desginKey,
			String mscPline) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.getStlChemicalStd");
		return this.getData(sql, new Object[] { cic, desginKey, mscPline });
	}

	/**
	 * 查询
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getPlnOrderZg(String proPlanId, String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.getPlnOrderZg");
		return this.getData(sql, new Object[] { proPlanId, gxPlanNo });
	}

	/**
	 * 查询判定成分元素
	 * 
	 * @param gxPlanNo
	 *            　订单编号
	 * @param gxPlanNo
	 *            　排产序号
	 * @return CoreReturnObject
	 */
	public CoreReturnObject getStlChemicalData(String judgeStoveNo,
			String chemJudgeId) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.getStlChemicalData");
		return this.getData(sql, new Object[] { judgeStoveNo, chemJudgeId });
	}

	/**
	 * 查询镦拔扩坯子库存信息
	 * 
	 * @param con
	 * @param matStatus
	 *            材料状态
	 * @param judgeStoveNo
	 *            判定炉号
	 * @param storageNo
	 *            仓库号
	 * @param locationNo
	 *            库位号
	 * @throws SQLException
	 */
	public static List<MatBcMEntityPln> getQureyMatGpM(Connection con,
			PlnZyDbkCEntity plnZyC, int plnNumGp,String heatPlanNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.getPlnMatBcDbk");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, plnZyC.getFeedHeatNo());
		ps.setObject(2, plnZyC.getBatchNo());
		ps.setObject(3, plnZyC.getBatchGroudNo());
		// ps.setObject(4, plnZyC.getProPlanId());
		// ps.setObject(5, plnZyC.getGxPlanNo());
		// ps.setObject(6, "E");
		ps.setObject(4, plnZyC.getJugdeApplyCode());
		ps.setObject(5, heatPlanNo);
		ps.setObject(6, plnNumGp);
		ResultSet rs = ps.executeQuery();
		List<MatBcMEntityPln> list = EntityTool.getEntitysByRs(rs,
				MatBcMEntityPln.class);
		ps.close();
		rs.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (MatBcMEntityPln listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 查询脱单利库记录
	 * 
	 * @param proPlanId
	 * @param gxPlanNo
	 * @return
	 */
	public CoreReturnObject queryMatGpTrack(String styeSj, String judgeNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmRollTubeLibraryDbk.queryMatGpTrack");
		return this.getData(sql, new Object[] { styeSj, judgeNo });
	}

	/**
	 * 查询实际炉计划
	 */
	public static <T> ArrayList<T> getQureyZyC(Connection con,
			String heatPlanNo, String processCode, Class<T> cls)
			throws SQLException {
		String sql = "";
		if (processCode.equals("E")) {
			sql = "SELECT T.* FROM PLN_ZY_DBK_C T WHERE 1=1";
		} else if (processCode.equals("F")) {
			sql = "SELECT T.* FROM PLN_ZY_RCL_C T WHERE 1=1";
		} else if (processCode.equals("G")) {
			sql = "SELECT T.* FROM PLN_ZY_JGX_C T WHERE 1=1";
		}
		sql += "  AND T.HEAT_PLAN_NO ='" + heatPlanNo + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		ArrayList<T> t = EntityTool.getEntitysByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 炉计划撤销
	 * 
	 * @param jslist
	 * @param userName
	 *            操作人
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject doDelete(ArrayList<ArrayList<String>> jslist,
			String userName) 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;
			// 获取数据库当前时间
			String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			DecimalFormat df = new DecimalFormat("0000000000");
			// 循环库存信息
			int seq = 1;
			for (int i = 0; i < jslist.size(); i++) {

				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String heatPlanNo = list.get(0);
				PlnZyDbkMEntity plnzgM = FrmPlanStoveE.getQureyZyM(conn,
						heatPlanNo, "E", PlnZyDbkMEntity.class);
				if (plnzgM == null) {
					cro.setV_errMsg("炉计划数据已发生改变,请刷新!");
					return cro;
				}
				List<PlnZyDbkCEntity> plnzyC = getQureyZyC(conn, heatPlanNo,
						"E", PlnZyDbkCEntity.class);
				int plnNum = 0;
				double plnWt = 0;
				String proPlanId = "";
				String gxPlanNo = "";
				String ifMatchOdd = "";
				proPlanId = plnzgM.getProPlanId();
				gxPlanNo = plnzgM.getGxPlanNo();
				ifMatchOdd = plnzgM.getIfMatchOdd();
				plnNum = Integer.parseInt(plnzgM.getPlnInsingleNum());// 单倍支数
				plnWt = Double.parseDouble(plnzgM.getPlnInsingleWt());
				if (!plnzgM.getPlanstatus().equals("计划")) {
					cro.setV_errMsg("炉计划状态不是计划状态!,请确认!");
					return cro;
				}

				if (plnzyC.size()>0) {
					for (PlnZyDbkCEntity plnC : plnzyC) {
						int plnNumGp = Integer.parseInt(plnC
								.getPlanIndoubleNum());
						List<MatBcMEntityPln> matGpMlist = getQureyMatGpM(conn,
								plnC, plnNumGp,heatPlanNo);
						if (matGpMlist == null) {
							cro.setV_errMsg("管坯物料已发生改变,请刷新!");
							return cro;
						}
						String proPlanIdNo = plnC.getProPlanId() + "/"
								+ plnC.getGxPlanNo();
						MatBcTrackEntity matTrack = FrmPlanMaterialDbk
								.getQureyMatTrack(conn, plnC.getFeedHeatNo(),
										plnC.getBatchNo(), plnC
												.getBatchGroudNo(), plnNumGp,
										"1", proPlanIdNo,
										MatBcTrackEntity.class,"delete","","");
						int matCount = 0;
						for (MatBcMEntityPln matGpM : matGpMlist) {
							if (!matGpM.getMatStatus().equals("80150103")) {
								cro.setV_errMsg("判定炉号为:"
										+ matGpM.getJudgeStoveNo()
										+ ",不是材料已编计划状态,不能删除炉计划!");
								return cro;
							}
							matCount += Integer.parseInt(matGpM.getActCount());
							
							String matStatus="80150102";
							if(matGpM.getJudgeResultCode()==null||matGpM.getJudgeResultCode().equals("")){
								matStatus="80150101";
							}
							// 修改坯子库存信息
							String sqlUpdateMat = CoreXmlSqlParsersFactory
									.getSql("FrmPlanMaterialDbk.UpdateMatGp");
							ps = conn.prepareStatement(sqlUpdateMat);
							ps.setObject(1, matStatus);
							ps.setObject(2, "");
							ps.setObject(3, "");
							ps.setObject(4, "0");
							ps.setObject(5, "0");
							ps.setObject(6, "");
							ps.setObject(7, "");
							ps.setObject(8, matGpM.getMatNo());
							ps.executeUpdate();
							ps.close();
						}
						String resumeSeq = dateFormat.format(now)
								+ df.format(seq);
						// 生成利库日志
						matTrack.setResumeSeq(resumeSeq);
						matTrack.setEventId("900101");
						matTrack.setEventDesc("脱单");
						matTrack
								.setFormName("com.steering.pss.plnsaleord.planStove.FrmRollTubeLibraryDbk");
						matTrack.setCallFuncCoding("doDelete");
						matTrack
								.setKeyvalue1("List<MatBcMEntityPln> matGpMlist");
						matTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
						matTrack.setKeyvalue2("String userName");
						matTrack.setKeyvalue2Desc2("操作人");
						matTrack.setKeyvalue3("doDelete");
						matTrack.setKeyvalue3Desc3("删除炉计划");
						matTrack.setProcessCdoe("E");
						matTrack.setMemo("");
						matTrack.setCreateName(userName);
						matTrack.setCreateTime(dateTime);
						seq++;
						String sqlAddTrack = EntityTool
								.fillSqlByEntity(
										CoreXmlSqlParsersFactory
												.getSql("FrmPlanMaterialDbk.addMatBcTrack"),
										matTrack);
						ps = conn.prepareStatement(sqlAddTrack);
						ps.executeUpdate();
						ps.close();

						if (matCount != plnNumGp) {
							cro.setV_errMsg("库存支数与实际炉计划支数不符,请确认!");
							return cro;
						}
						// 删除实际炉计划
						String deleteZgC = "DELETE PLN_ZY_DBK_C WHERE HEAT_PLAN_NO = ? AND HEAT_PLAN_SQE=?";
						ps = conn.prepareStatement(deleteZgC);
						ps.setObject(1, heatPlanNo);
						ps.setObject(2, plnC.getHeatPlanSqe());
						ps.executeUpdate();
						ps.close();
					}
				} else {
					// 修改库存订单号
					String updateMat = "UPDATE MAT_BC_M T SET T.PRO_PLAN_ID_NEXT='', T.GX_PLAN_NO_NEXT='',T.NEXT_PROCESS_CDOE='',T.NEXT_PROCESS_DESC='',T.HEAT_PLAN_NO_NEXT=''"
							+ " WHERE T.JUDGE_STOVE_NO=? AND T.HEAT_PLAN_NO_NEXT=?  AND T.HANGING_FLAG='0'";
					ps = conn.prepareStatement(updateMat);
					ps.setObject(1, plnzgM.getFeedHeatNo());
					ps.setObject(2, heatPlanNo);
					ps.executeUpdate();
					ps.close();
				}
				// 删除虚拟炉计划
				String deleteZgM = "DELETE PLN_ZY_DBK_M WHERE HEAT_PLAN_NO = ?";
				ps = conn.prepareStatement(deleteZgM);
				ps.setObject(1, heatPlanNo);
				ps.executeUpdate();
				ps.close();

				// 修改利库信息
				// String sqlUpdateZgS = "UPDATE PLN_ORDER_DBK_S T  SET "
				// +
				// "T.BATCHED_WT  = TO_NUMBER(NVL(T.BATCHED_WT, 0)) - TO_NUMBER('"
				// + plnWt
				// + "'),"
				// +
				// "T.BATCHED_NUM = TO_NUMBER(NVL(T.BATCHED_NUM, 0)) - TO_NUMBER('"
				// + plnNum + "')";
				// sqlUpdateZgS += " WHERE T.PRO_PLAN_ID = '" + proPlanId
				// + "' AND T.GX_PLAN_NO = '" + gxPlanNo + "' ";
				// ps = conn.prepareStatement(sqlUpdateZgS);
				// 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;
	}
}
