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 CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
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.stove.entity.MatBcMEntityPln;
import com.steering.pss.plnsaleord.stove.entity.PlnZyJgCEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyJgMEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.entity.PlnZyRclMEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;

/**
 * 接箍炉计划
 * 
 * @author peng
 */
public class FrmPlanStoveH extends DBCommon {

	/**
	 * 查询虚拟炉计划
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlanStoveYzH(String timeBegin, String timeEnd,
			String plineCode, String orderNo, String proPlanId, String heatId,
			String[] statusArr, String judgeNo, String feedNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanStoveH.queryPlanStoveMH");
		List<String> param = new ArrayList<String>();
		if (!timeBegin.equals("") && !timeEnd.equals("")) {
			sql += " AND TO_DATE(T.PRO_DAY, 'YYYY-MM-DD') BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')";
			param.add(timeBegin);
			param.add(timeEnd);
		}
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE=? ";
			param.add(plineCode);
		}
		if (!orderNo.equals("")) {
			sql += " AND T.ORD_LN_DLY_PK LIKE '%'||?||'%'";
			param.add(orderNo);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID=?";
			param.add(proPlanId);
		}
		if (!heatId.equals("")) {
			sql += " AND T.HEAT_PLAN_NO LIKE '%'||?||'%'";
			param.add(heatId);
		}
		if (!judgeNo.equals("")) {
			sql += " AND T.JUDGE_STOVE_NO=?";
			param.add(judgeNo);
		}
		// if (!feedNo.equals("")) {
		// sql += " AND T.FEED_HEAT_NO=?";
		// param.add(feedNo);
		// }
		sql += CoreConverter.toSqlConditionString("T.PLANSTATUS", statusArr);
		sql += " ORDER BY T.GX_PRO_SEQ,T.HEAT_PLAN_NO  ASC";
		return this.getData(sql, param.toArray());
	}

	/**
	 * 查询接箍实际炉计划
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnZyDbkReadyById(String timeBegin,
			String timeEnd, String plineCode, String orderNo, String proPlanId,
			String heatId, String[] statusArr, String judgeNo, String feedNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanStoveH.queryPlanStoveReadyH");
		List<String> param = new ArrayList<String>();
		if (!timeBegin.equals("") && !timeEnd.equals("")) {
			sql += " AND TO_DATE(T.PRO_DAY, 'YYYY-MM-DD') BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')";
			param.add(timeBegin);
			param.add(timeEnd);
		}
		if (!plineCode.equals("")) {
			sql += " AND T.PLINE_CODE=? ";
			param.add(plineCode);
		}
		if (!orderNo.equals("")) {
			sql += " AND T.ORD_LN_DLY_PK LIKE '%'||?||'%'";
			param.add(orderNo);
		}
		if (!proPlanId.equals("")) {
			sql += " AND T.PRO_PLAN_ID=?";
			param.add(proPlanId);
		}
		if (!heatId.equals("")) {
			sql += " AND T.HEAT_PLAN_NO LIKE '%'||?||'%'";
			param.add(heatId);
		}
		if (!judgeNo.equals("")) {
			sql += " AND T.JUDGE_STOVE_NO=?";
			param.add(judgeNo);
		}
		// if (!feedNo.equals("")) {
		// sql += " AND T.FEED_HEAT_NO=?";
		// param.add(feedNo);
		// }
		sql += CoreConverter.toSqlConditionString("T.PLANSTATUS", statusArr);
		sql += " ORDER BY T.GX_PRO_SEQ,T.HEAT_PLAN_NO ASC";
		return this.getData(sql, param.toArray());
	}

	/**
	 * 根据炉计划号查询实际炉计划
	 * 
	 * @param heatPlanNo
	 * @return
	 */
	public CoreReturnObject queryPlanStoveRow(String heatPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanStoveH.queryPlanStoveReadyH");
		sql += "  AND T.HEAT_PLAN_NO ='" + heatPlanNo + "' ";
		sql += " ORDER BY T.GX_PRO_SEQ,T.HEAT_PLAN_NO ASC";
		return this.getData(sql);
	}

	/**
	 * 根据订单号，排产序号查询炉计划
	 * 
	 * @param heatPlanNo
	 * @return
	 */
	public CoreReturnObject queryPlanStovePlanId(String proPlanId,
			String gxPlanNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanStoveH.queryPlanStoveReadyH");
		sql += "  AND T.PRO_PLAN_ID ='" + proPlanId + "' AND T.GX_PLAN_NO='"
				+ gxPlanNo + "' ";
		sql += " ORDER BY T.GX_PRO_SEQ,T.HEAT_PLAN_NO ASC";
		return this.getData(sql);
	}

	/**
	 * 选择炉计划下发，撤销下发
	 */
	public CoreReturnObject doFurnacePlan(ArrayList<ArrayList<String>> jslist,
			String userName, String flag) 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);
			// 循环虚拟炉计划信息
			String heatPlanNo1 = "";
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String heatPlanNo = list.get(0);
				if (heatPlanNo1.equals(heatPlanNo)) {
					continue;
				}
				if (heatPlanNo1.equals("") || !heatPlanNo1.equals(heatPlanNo)) {
					heatPlanNo1 = heatPlanNo;
				}
				// 查询炉计划信息
				PlnZyJgMEntity listM = FrmPlanStoveE.getQureyZyM(conn,
						heatPlanNo, "H", PlnZyJgMEntity.class);
				if (listM == null) {
					cro.setV_errMsg("炉计划已发生变化,请重新查询!");
					return cro;
				}
				// String proPlanId = listM.getProPlanId();
				// String gxPlanNo = listM.getGxPlanNo();
				// String plnDivideId = listM.getPlnDivideId();
				if (flag.equals("0") && !listM.getPlanstatus().equals("计划")) {
					cro.setV_errMsg("选择的炉计划状态不是计划状态,不能下发!");
					return cro;
				}
				if (flag.equals("1") && !listM.getPlanstatus().equals("下发")) {
					cro.setV_errMsg("选择的炉计划不是下发状态,不能撤销下发!");
					return cro;
				}
				String zyBatchId = "";
				String planstatus = "";
				if (flag.equals("1")) {// 撤销下发
					planstatus = "00";
					// zyBatchId = "";
				} else {
					planstatus = "10";
					// zyBatchId = listM.getZyBatchId();
				}
				// 修改虚拟炉计划
				String deleteZgM = "UPDATE PLN_ZY_JG_M T SET T.PLANSTATUS=?,T.DOWNMAN=?,T.DOWNTIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') WHERE T.HEAT_PLAN_NO=?";
				ps = conn.prepareStatement(deleteZgM);
				ps.setObject(1, planstatus);
				ps.setObject(2, userName);
				ps.setObject(3, dateTime);
				ps.setObject(4, heatPlanNo);
				ps.executeUpdate();
				ps.close();

				// 修改实际炉计划
				// deleteZgM =
				// "UPDATE PLN_ZY_JG_C T SET T.ZY_BATCH_ID=? WHERE T.HEAT_PLAN_NO=?";
				// ps = conn.prepareStatement(deleteZgM);
				// ps.setObject(1, zyBatchId);
				// ps.setObject(2, heatPlanNo);
				// ps.executeUpdate();
				// ps.close();
			}
			if (flag.equals("1")) {
				cro.setV_errMsg("撤销成功!");
			} else {
				cro.setV_errMsg("下发成功!");
			}
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					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 con
	 * @param matStatus
	 *            材料状态
	 * @param judgeStoveNo
	 *            判定炉号
	 * @param storageNo
	 *            仓库号
	 * @param locationNo
	 *            库位号
	 * @throws SQLException
	 */
	public static List<MatBcMEntityPln> getQureyMatGpM(Connection con,
			PlnZyJgCEntity plnZyC, int plnNumGp,String heatPlanNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmPlanStoveH.getPlnMatBcJg");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, plnZyC.getJudgeStoveNo());
		ps.setObject(2, plnZyC.getBatchNo());
		ps.setObject(3, plnZyC.getBatchGroudNo());
		// ps.setObject(4, plnZyC.getProPlanId());
		// ps.setObject(5, plnZyC.getGxPlanNo());
		// ps.setObject(6, "F");
		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;
		}
	}

	/**
	 * 选择炉计划删除
	 */
	public CoreReturnObject doDeleteLu(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);
				String heatPlanSeqNo = list.get(1);
				// 查询炉计信息

				PlnZyJgMEntity listM = FrmPlanStoveE.getQureyZyM(conn,
						heatPlanNo, "H", PlnZyJgMEntity.class);
				if (listM == null) {
					cro.setV_errMsg("炉计划已发生变化,请重新查询!");
					return cro;
				}
				if (!listM.getPlanstatus().equals("计划")) {
					cro.setV_errMsg("选择的接箍炉计划状态不是计划状态,不能删除!");
					return cro;
				}

				if (!heatPlanSeqNo.equals("")) {// 删除实际炉计划
					PlnZyJgCEntity listC = FrmPlanStoveE.getQureyZyC(conn,
							heatPlanNo, heatPlanSeqNo, PlnZyJgCEntity.class,
							"H");
					if (listC == null) {
						cro.setV_errMsg("炉计划已发生变化,请重新查询!");
						return cro;
					}

					int plnNumGp = Integer.parseInt(listC.getUseBlNum());
					List<MatBcMEntityPln> matGpMlist = getQureyMatGpM(conn,
							listC, plnNumGp,heatPlanNo);
					// if (matGpMlist == null) {
					// cro.setV_errMsg("管坯物料已发生改变,请刷新!");
					// return cro;
					// }
					if (matGpMlist != null) {
						String proPlanIdNo = listC.getProPlanId() + "/"
								+ listC.getGxPlanNo();
						MatBcTrackEntity matTrack = FrmPlanMaterialDbk
								.getQureyMatTrack(conn,
										listC.getJudgeStoveNo(),
										listC.getBatchNo(),
										listC.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;
							}
							String matStatus = "80150102";
							if (matGpM.getJudgeResultCode() == null
									|| matGpM.getJudgeResultCode().equals("")) {
								matStatus = "80150101";
							}
							matCount += Integer.parseInt(matGpM.getActCount());
							// 修改坯子库存信息
							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);
						// 生成利库日志
						if(matTrack != null)
						{

						}else
						{
							matTrack = new MatBcTrackEntity();
						}
						matTrack.setResumeSeq(resumeSeq);
						matTrack.setEventId("900101");
						matTrack.setEventDesc("脱单");
						matTrack.setFormName("com.steering.pss.plnsaleord.planStove.FrmPlanStoveH");
						matTrack.setCallFuncCoding("doDeleteLu");
						matTrack.setKeyvalue1("List<MatBcMEntityPln> matGpMlist");
						matTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
						matTrack.setKeyvalue2("String userName");
						matTrack.setKeyvalue2Desc2("操作人");
						matTrack.setKeyvalue3("doDeleteLu");
						matTrack.setKeyvalue3Desc3("删除炉计划");
						matTrack.setProcessCdoe("H");
						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_JG_C WHERE HEAT_PLAN_NO = ? AND HEAT_PLAN_SQE=?";
					ps = conn.prepareStatement(deleteZgC);
					ps.setObject(1, heatPlanNo);
					ps.setObject(2, heatPlanSeqNo);
					ps.executeUpdate();
					ps.close();

					// 查询实际炉计划是否全部删除
					int count = 0;
					String sql = "SELECT COUNT(*) COUNT FROM PLN_ZY_JG_C T WHERE T.HEAT_PLAN_NO=?";
					ps = conn.prepareStatement(sql);
					ps.setObject(1, heatPlanNo);
					rs = ps.executeQuery();
					if (rs.next()) {
						count = rs.getInt("COUNT");
					}
					if (count == 0) {
						// 删除虚拟炉计划
						String deleteZgM = "DELETE PLN_ZY_JG_M WHERE HEAT_PLAN_NO = ?";
						ps = conn.prepareStatement(deleteZgM);
						ps.setObject(1, heatPlanNo);
						ps.executeUpdate();
						ps.close();
					}
				} else {
					// 删除虚拟炉计划
					String deleteZgM = "DELETE PLN_ZY_JG_M WHERE HEAT_PLAN_NO = ?";
					ps = conn.prepareStatement(deleteZgM);
					ps.setObject(1, heatPlanNo);
					ps.executeUpdate();
					ps.close();

					// 修改库存订单号
					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, listM.getJgGroupId());
					ps.setObject(2, heatPlanNo);
					ps.executeUpdate();
					ps.close();
					// // 删除实际炉计划
					// String deleteZgC =
					// "DELETE PLN_ZY_JGX_C WHERE HEAT_PLAN_NO = ?";
					// ps = conn.prepareStatement(deleteZgC);
					// ps.setObject(1, heatPlanNo);
					// ps.executeUpdate();
					// ps.close();
				}

			}
			cro.setV_errMsg("删除成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					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 parmList
	 * @return
	 */
	public CoreReturnObject updateLoadFlag(ArrayList<String> parmList) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for (String str : parmList) {
				PlnZyJgMEntity plnZyZgEntity = EntityTool.getEntityByJSONStr(str, PlnZyJgMEntity.class);
				if(plnZyZgEntity.getIsLoadFlag().equals("是"))
				{
					plnZyZgEntity.setIsLoadFlag("0");
				}else
				{
					plnZyZgEntity.setIsLoadFlag("1");
				}
				String updateGoWhereSql = CoreXmlSqlParsersFactory.getSql("FrmPlanStoveH.updateLoadFlag");
				updateGoWhereSql = EntityTool.fillSqlByEntity(updateGoWhereSql, plnZyZgEntity);
				sqllist.add(updateGoWhereSql);
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if (cro.getV_errMsg().equals("")) {
				cro.setV_errMsg("修改成功!");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}

}
