package com.steering.pss.plnsaleord.steelMarkingPlan;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
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.steelMarkingPlan.entity.PlnOrderCastSEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnSteelforOrdEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnSteelforcastEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.entity.PlnSteelforfurnaceEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;

/**
 * 浇次控件类
 * 
 * @author Administrator
 */
public class ControlCastPlan extends DBCommon {

	/**
	 * 按条件查询浇次信息
	 * 
	 * @param bmakeTime
	 *            制定开始时间
	 * @param emakeTime
	 *            制定结束时间
	 * @param castNo
	 *            浇次号
	 * @param furnacenogetCastByCondition
	 *            炉次号
	 * @return
	 */
	public CoreReturnObject getCastByCondition(String bmakeTime,
			String emakeTime, String castNo, String furnaceno, String[] status,
			String[] plineCode, String num) {
		List<String> param = new ArrayList<String>();
		String sql = CoreXmlSqlParsersFactory.getSql("ControlCastPlan.getCast");
		if (!bmakeTime.equals("") && !emakeTime.equals("")) {
			sql += " and t.MAKETIME between to_date(?,'yyyy-mm-dd hh24:mi:ss') and to_date(?,'yyyy-mm-dd hh24:mi:ss')";
			param.add(bmakeTime);
			param.add(emakeTime);
		}
		if (!castNo.equals("")) {
			sql += " and t.CAST_NO like '%'||?||'%'";
			param.add(castNo);
		}
		if (!furnaceno.equals("")) {
			sql += " and t.CAST_NO in (select t1.CAST_NO from PLN_STEELFORFURNACE t1 where t1.FURNACENO like '%'||?||'%' )";
			param.add(furnaceno);
		}
		// if (!status.equals("")) {
		sql += CoreConverter.toSqlConditionString("t.status", status);
		// }
		if (plineCode != null) {
			sql += CoreConverter
					.toSqlConditionString("T.PLINE_CODE", plineCode);
		}
		if (num.equals("0")) {
			sql += " order by t.MAKETIME desc,t.CAST_NO desc,t.CAST_SEQ DESC";
		} else {
			sql += " order by t.PLINE_CODE asc ,t.CAST_SEQ asc, CAST_NO asc";
		}

		return this.getData(sql, param.toArray());
	}

	/**
	 * 通过浇次号查询浇次
	 * 
	 * @param con
	 * @param castno
	 * @return
	 * @throws SQLException
	 */
	static PlnSteelforcastEntity getCastByCastno(Connection con, String castno)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlCastPlan.getCastByCastno");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, castno);
		ResultSet rs = ps.executeQuery();
		PlnSteelforcastEntity entity = EntityTool.getEntityByRs(rs,
				PlnSteelforcastEntity.class);
		rs.close();
		ps.close();
		return entity;
	}

	/**
	 * 通过浇次号炉次订单
	 * 
	 * @param con
	 * @param castno
	 * @return
	 * @throws SQLException
	 */
	static PlnSteelforOrdEntity getSteelOrdById(Connection con, String castno,
			String stateLk) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlCastPlan.getSteelOrdById");
		if (!stateLk.equals("")) {
			sql += " AND T.STATE_LK = '1'";
		}
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, castno);
		ResultSet rs = ps.executeQuery();
		PlnSteelforOrdEntity entity = EntityTool.getEntityByRs(rs,
				PlnSteelforOrdEntity.class);
		rs.close();
		ps.close();
		return entity;
	}

	/**
	 * 通过浇次号炉次信息
	 * 
	 * @param con
	 * @param castno
	 * @return
	 * @throws SQLException
	 */
	static List<PlnSteelforfurnaceEntity> getSteelFurnById(Connection con,
			String castno) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlCastPlan.getSteelFurnById");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, castno);
		ResultSet rs = ps.executeQuery();
		List<PlnSteelforfurnaceEntity> list = EntityTool.getEntitysByRs(rs,
				PlnSteelforfurnaceEntity.class);
		rs.close();
		ps.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			for (PlnSteelforfurnaceEntity listL : list) {
				QualityDesignTool.nullConverNullString(listL);
			}
			return list;
		}
	}

	/**
	 * 通过炉号，炉次顺序号查询炉次
	 * 
	 * @param con
	 * @param castno
	 * @return
	 * @throws SQLException
	 */
	static PlnSteelforfurnaceEntity getSteelFurnSeq(Connection con,
			String furnNo, String seq) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("ControlCastPlan.getSteelFurnSeq");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, furnNo);
		ps.setObject(2, seq);
		ResultSet rs = ps.executeQuery();
		PlnSteelforfurnaceEntity entity = EntityTool.getEntityByRs(rs,
				PlnSteelforfurnaceEntity.class);
		rs.close();
		ps.close();
		return entity;
	}

	/**
	 * 删除浇次
	 * 
	 * @param castnoList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public CoreReturnObject deleteCast(ArrayList<String> castnoList) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			for (String castno : castnoList) {
				PlnSteelforcastEntity entity = getCastByCastno(con, castno);
				if (entity == null) {
					core.setV_errMsg("浇次数据异常,请刷新数据!");
					return core;
				}
				if (Integer.parseInt(entity.getStatus()) >= 10) {
					core.setV_errMsg("浇次(" + entity.getCastNo()
							+ ")不是编制中的状态,不能删除浇次!");
					return core;
				}
				if (entity.getIfConfirm().equals("1")) {
					core.setV_errMsg("浇次(" + entity.getCastNo()
							+ "),已浇次确认,不能删除浇次!");
					return core;
				}
				// 查询是否有冲计划
				PlnSteelforOrdEntity entity1 = getSteelOrdById(con, castno, "1");
				if (entity1 != null) {
					if (entity1.getStateLk().equals("1")) {
						core.setV_errMsg("浇次(" + entity.getCastNo()
								+ ")向下的炉次订单(" + entity1.getFurnaceno() + "/"
								+ entity1.getSequenceno()
								+ ")是利轧管计划数据,不能删除浇次,请先撤销利计划!");
						return core;
					}
				}

				// 查询计划
				String queryOrdSql = "select t.pro_plan_id,t.gx_plan_no, sum(t.tot_weight_m) tot_weight_m,"
						+ "sum(t.tot_mum_m) tot_mum_m,T.MERGE_NO from pln_steelfor_ord t "
						+ "where t.surplusflag='0' AND T.STATE_LK='0' and t.cast_no=? group by t.pro_plan_id,t.gx_plan_no,T.MERGE_NO";
				ps = con.prepareStatement(queryOrdSql);
				ps.setObject(1, castno);
				rs = ps.executeQuery();
				List<PlnSteelforOrdEntity> ordList = EntityTool.getEntitysByRs(
						rs, PlnSteelforOrdEntity.class);
				rs.close();
				ps.close();
				// 修改计划已排产量
				String updateorderSql = "update pln_order_cast_s t"
						+ " set t.planed_wt  =( case when (t.planed_num - to_number(?))<0 then 0 when (t.planed_wt - to_number(?))<=0.002 then 0  else (t.planed_wt - to_number(?)) end), "
						+ " t.planed_num =( case when (t.planed_num - to_number(?))<0 then 0 when (t.planed_wt - to_number(?))<=0.002 then 0 else (t.planed_num - to_number(?)) end),"
						+ " t.CAST_NO_ALL=?  where t.pro_plan_id = ?  and t.gx_plan_no = ?";
				for (PlnSteelforOrdEntity ordEntity : ordList) {
					String castNoAll = "";
					// 合并编号为空
					if (ordEntity.getMergeNo().equals("")) {
						// 查询铸造订单状态
						queryOrdSql = "SELECT T.EXE_STATUS FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
						PreparedStatement psa = con
								.prepareStatement(queryOrdSql);
						psa.setObject(1, ordEntity.getProPlanId());
						psa.setObject(2, ordEntity.getGxPlanNo());
						ResultSet rs1 = psa.executeQuery();
						if (rs1.next()) {
							if (!rs1.getString("EXE_STATUS").equals("")
									&& rs1.getInt("EXE_STATUS") > 1) {
								// core.setV_errMsg("铸造订单("
								// + ordEntity.getProPlanId() + "/"
								// + ordEntity.getGxPlanNo()
								// + ")不是计划和生产中的状态,不能删除浇次!");
								// return core;
							}
						} else {
							core.setV_errMsg("铸造订单(" + ordEntity.getProPlanId()
									+ "/" + ordEntity.getGxPlanNo()
									+ ")不存在,不能删除浇次!");
							return core;
						}
						rs1.close();
						psa.close();
						// 查询铸造订单浇次号
						queryOrdSql = "SELECT LISTAGG(CAST_NO, ',') WITHIN GROUP(ORDER BY CAST_NO) CAST_NO  FROM (SELECT T.CAST_NO FROM PLN_STEELFOR_ORD T"
								+ "   WHERE T.PRO_PLAN_ID = ? AND T.GX_PLAN_NO = ?  AND T.CAST_NO != ? group by t.CAST_NO)";
						psa = con.prepareStatement(queryOrdSql);
						psa.setObject(1, ordEntity.getProPlanId());
						psa.setObject(2, ordEntity.getGxPlanNo());
						psa.setObject(3, castno);
						rs1 = psa.executeQuery();
						if (rs1.next()) {
							castNoAll = rs1.getString("CAST_NO");
						}
						rs1.close();
						psa.close();

						ps = con.prepareStatement(updateorderSql);
						ps.setObject(1, ordEntity.getTotMumM());
						ps.setObject(2, ordEntity.getTotWeightM());
						ps.setObject(3, ordEntity.getTotWeightM());
						ps.setObject(4, ordEntity.getTotMumM());
						ps.setObject(5, ordEntity.getTotWeightM());
						ps.setObject(6, ordEntity.getTotMumM());
						ps.setObject(7, castNoAll);
						ps.setObject(8, ordEntity.getProPlanId());
						ps.setObject(9, ordEntity.getGxPlanNo());
						ps.executeUpdate();
						ps.close();

						double planedWt = 0;
						// 查询铸造订单是否存在已组炉量
						queryOrdSql = "SELECT SUM(NVL(T.PLANED_WT,0)) PLANED_WT  FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=?";
						psa = con.prepareStatement(queryOrdSql);
						psa.setObject(1, ordEntity.getProPlanId());
						rs1 = psa.executeQuery();
						if (rs1.next()) {
							planedWt = rs1.getDouble("PLANED_WT");
						}
						rs1.close();
						psa.close();
						if (planedWt <= 0) {
							// 修改管坯需求状态
							String sqlupdaterR = CoreXmlSqlParsersFactory
									.getSql("FrmSteelMakingPlanChange.updateReqinfGp");
							psa = con.prepareStatement(sqlupdaterR);
							psa.setObject(1, "1");
							psa.setObject(2, ordEntity.getProPlanId());
							psa.executeUpdate();
							psa.close();
						}
					} else {
						// 查询合并记录信息
						String queryMegra = "SELECT SUM(T.TOT_MUM_M) TOT_MUM_M, SUM(T.TOT_WEIGHT_M) TOT_WEIGHT_M,"
								+ "T.PRO_PLAN_ID, T.GX_PLAN_NO,T.CUT_NUM_GP  FROM PLN_STEELFOR_MERGE T WHERE T.MERGE_NO=? "
								+ "GROUP BY T.PRO_PLAN_ID, T.GX_PLAN_NO,T.CUT_NUM_GP";
						ps = con.prepareStatement(queryMegra);
						ps.setObject(1, ordEntity.getMergeNo());
						rs = ps.executeQuery();
						while (rs.next()) {
							PreparedStatement psa = null;
							ResultSet rs1 = null;
							if (rs.getString("PRO_PLAN_ID").contains("ZG")) {
								// 查询轧管订单状态
								queryOrdSql = "SELECT T.EXE_STATUS, T.GPREQ_ID FROM PLN_ORDER_ZG_S T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
								psa = con.prepareStatement(queryOrdSql);
								psa.setObject(1, rs.getString("PRO_PLAN_ID"));
								psa.setObject(2, rs.getString("GX_PLAN_NO"));
								rs1 = psa.executeQuery();
								if (rs1.next()) {
									if (!rs1.getString("EXE_STATUS").equals("")
											&& rs1.getInt("EXE_STATUS") > 1) {
										core.setV_errMsg("轧管订单("
												+ rs.getString("PRO_PLAN_ID")
												+ "/"
												+ rs.getString("GX_PLAN_NO")
												+ ")不是计划和生产中的状态,不能删除浇次!");
										return core;
									}
									if (rs1.getString("GPREQ_ID") != null
											&& rs1.getString("GPREQ_ID") != "") {
										core.setV_errMsg("轧管订单号:"
												+ rs.getString("PRO_PLAN_ID")
												+ "/"
												+ rs.getString("GX_PLAN_NO")
												+ ",已生成管坯需求,不能删除浇次!");
										return core;
									}
								} else {
									core.setV_errMsg("轧管订单("
											+ rs.getString("PRO_PLAN_ID") + "/"
											+ rs.getString("GX_PLAN_NO")
											+ ")不存在,不能删除浇次!");
									return core;
								}
								rs1.close();
								psa.close();

								// 修改轧管利库支吨
								String zgUpdate = " UPDATE PLN_ORDER_ZG_S T SET T.MATCH_WT_IN  = TO_NUMBER(NVL(T.MATCH_WT_IN, 0))- TO_NUMBER(?),"
										+ " T.MATCH_NUM_IN = TO_NUMBER(NVL(T.MATCH_NUM_IN, 0))- TO_NUMBER(?), T.STATE_SINGLE = '0'"
										+ " WHERE T.PRO_PLAN_ID = ?   AND T.GX_PLAN_NO = ?";
								psa = con.prepareStatement(zgUpdate);
								psa.setObject(1, rs.getString("TOT_WEIGHT_M"));
								psa.setObject(2, rs.getInt("TOT_MUM_M")
										* rs.getInt("CUT_NUM_GP"));
								psa.setObject(3, rs.getString("PRO_PLAN_ID"));
								psa.setObject(4, rs.getString("GX_PLAN_NO"));
								psa.executeUpdate();
								psa.close();
							} else {
								// 查询铸造订单状态
								queryOrdSql = "SELECT T.EXE_STATUS FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
								psa = con.prepareStatement(queryOrdSql);
								psa.setObject(1, rs.getString("PRO_PLAN_ID"));
								psa.setObject(2, rs.getString("GX_PLAN_NO"));
								rs1 = psa.executeQuery();
								if (rs1.next()) {
									if (!rs1.getString("EXE_STATUS").equals("")
											&& rs1.getInt("EXE_STATUS") > 1) {
										// core.setV_errMsg("铸造订单("
										// + rs.getString("PRO_PLAN_ID") + "/"
										// + rs.getString("GX_PLAN_NO")
										// + ")不是计划和生产中的状态,不能删除浇次!");
										// return core;
									}
								} else {
									core.setV_errMsg("铸造订单("
											+ rs.getString("PRO_PLAN_ID") + "/"
											+ rs.getString("GX_PLAN_NO")
											+ ")不存在,不能删除浇次!");
									return core;
								}
								rs1.close();
								psa.close();

								// 查询铸造订单浇次号
								queryOrdSql = "SELECT LISTAGG(CAST_NO, ',') WITHIN GROUP(ORDER BY CAST_NO) CAST_NO  FROM (SELECT T.CAST_NO FROM PLN_STEELFOR_ORD T"
										+ "   WHERE T.PRO_PLAN_ID = ? AND T.GX_PLAN_NO = ?  AND T.CAST_NO != ? group by t.CAST_NO)";
								psa = con.prepareStatement(queryOrdSql);
								psa.setObject(1, rs.getString("PRO_PLAN_ID"));
								psa.setObject(2, rs.getString("GX_PLAN_NO"));
								psa.setObject(3, castno);
								rs1 = psa.executeQuery();
								if (rs1.next()) {
									castNoAll = rs1.getString("CAST_NO");
								}
								rs1.close();
								psa.close();

								PreparedStatement ps2 = con
										.prepareStatement(updateorderSql);
								ps2.setObject(1, rs.getString("TOT_MUM_M"));
								ps2.setObject(2, rs.getString("TOT_WEIGHT_M"));
								ps2.setObject(3, rs.getString("TOT_WEIGHT_M"));
								ps2.setObject(4, rs.getString("TOT_MUM_M"));
								ps2.setObject(5, rs.getString("TOT_WEIGHT_M"));
								ps2.setObject(6, rs.getString("TOT_MUM_M"));
								ps2.setObject(7, castNoAll);
								ps2.setObject(8, rs.getString("PRO_PLAN_ID"));
								ps2.setObject(9, rs.getString("GX_PLAN_NO"));
								ps2.executeUpdate();
								ps2.close();

								double planedWt = 0;
								// 查询铸造订单是否存在已组炉量
								queryOrdSql = "SELECT SUM(NVL(T.PLANED_WT,0)) PLANED_WT  FROM PLN_ORDER_CAST_S T WHERE T.PRO_PLAN_ID=?";
								ps2 = con.prepareStatement(queryOrdSql);
								ps2.setObject(1, rs.getString("PRO_PLAN_ID"));
								rs1 = ps2.executeQuery();
								if (rs1.next()) {
									planedWt = rs1.getDouble("PLANED_WT");
								}
								rs1.close();
								ps2.close();
								if (planedWt <= 0) {
									// 修改管坯需求状态
									String sqlupdaterR = CoreXmlSqlParsersFactory
											.getSql("FrmSteelMakingPlanChange.updateReqinfGp");
									ps2 = con.prepareStatement(sqlupdaterR);
									ps2.setObject(1, "1");
									ps2.setObject(2, rs
											.getString("PRO_PLAN_ID"));
									ps2.executeUpdate();
									ps2.close();
								}
							}
						}
						rs.close();
						ps.close();

						// 删除同定尺合并记录
						String deleteMege = "DELETE PLN_STEELFOR_MERGE WHERE MERGE_NO = ?";
						ps = con.prepareStatement(deleteMege);
						ps.setObject(1, ordEntity.getMergeNo());
						ps.executeUpdate();
						ps.close();
					}

				}
				int castSeq = Integer.parseInt(entity.getCastSeq());// 浇次顺序号
				// String castNo = entity.getCastNo();// 浇次号
				// String castStratTime = entity.getStarttime();// 浇次开始时间

				// 删除浇次
				String deleteCastSql = "delete from pln_steelforcast t where t.CAST_NO=?";
				ps = con.prepareStatement(deleteCastSql);
				ps.setObject(1, castno);
				ps.executeUpdate();
				ps.close();
				// 修改浇次顺序号
				FrmSteeSerialPublic.seqIncreaseCast(con, entity.getPlineCode(),
						castSeq, -1);

				ArrayList<Object> furnList = new ArrayList<Object>();
				// 查询浇次对应订单炉数，电炉产线
				String sql = CoreXmlSqlParsersFactory
						.getSql("ControlCastPlan.QueryFurnCastNo");
				ps = con.prepareStatement(sql);
				ps.setObject(1, castno);
				ps.setObject(2, castno);
				rs = ps.executeQuery();
				while (rs.next()) {
					ArrayList<String> list = new ArrayList<String>();
					list.add(rs.getString("COUNT"));
					list.add(rs.getString("PLINE_CODE"));
					list.add(rs.getString("PLINE_NAME"));
					list.add(rs.getString("FURNACENO_SEQ"));
					list.add(rs.getString("PLN_STARTTIME"));
					// 查询电炉产线，钢种对应投入产出小时能力
					double capacity = FrmSteeSerialPublic.seqCapacityFurn(con,
							rs.getString("EF_PLINE_CODE"), rs
									.getString("WLID_IN"), rs
									.getString("MATERIAL_NO"));
					// 查询铸造产线，钢种对应投入产出小时能力
					double capacityZz = FrmSteeSerialPublic.seqCapacityCast(
							con, rs.getString("PLINE_CODE"), rs
									.getString("MATERIAL_NO"), rs
									.getString("MATERIAL_NO_ZZ"));
					list.add(String.valueOf(capacity));
					list.add(String.valueOf(capacityZz));
					list.add(rs.getString("EF_PLINE_CODE"));
					furnList.add(list);
				}
				rs.close();
				ps.close();

				// 删除炉次
				String deleteFurnaceSql = " delete from PLN_STEELFORFURNACE t where t.cast_no=? ";
				ps = con.prepareStatement(deleteFurnaceSql);
				ps.setObject(1, castno);
				ps.executeUpdate();
				ps.close();
				for (int i = 0; i < furnList.size(); i++) {
					ArrayList<String> list = (ArrayList<String>) furnList
							.get(i);
					// 修改炉次顺序号
					FrmSteeSerialPublic.seqIncreaseFurn(con, list.get(1),
							Integer.parseInt(list.get(3)), -Integer
									.parseInt(list.get(0)), list.get(4), list
									.get(5), list.get(6), castSeq, 0, list
									.get(7), castno, "1");
				}
				int count = 0;
				int ccmSeq = 0;
				// 查询浇次下有多少炉次订单
				sql = "  SELECT COUNT(*) COUNT,MAX(T.CCM_SEQ) CCM_SEQ  FROM PLN_STEELFOR_ORD T WHERE T.CAST_NO = ?";
				ps = con.prepareStatement(sql);
				ps.setObject(1, castno);
				rs = ps.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
					ccmSeq = rs.getInt("CCM_SEQ");
				}
				rs.close();
				ps.close();
				// 删除炉次订单
				String deleteOrdSql = " delete from pln_steelfor_ord t where t.cast_no=?";
				ps = con.prepareStatement(deleteOrdSql);
				ps.setObject(1, castno);
				ps.executeUpdate();
				ps.close();
				// 修改炉次订单顺序号
				FrmSteeSerialPublic.seqIncreaseOrd(con, entity.getPlineCode(),
						ccmSeq, -count, 1);
			}
			// 查询浇次对应的炉次顺序号

			con.commit();
			core.setV_errMsg("删除成功!");
			core.setResult(true);
			return core;
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {

				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 炉次订单重量调整
	 * 
	 * @param jsonList
	 * @return
	 */
	public CoreReturnObject adjustSteeelord(ArrayList<String> jsonList,
			String username, String firstWt, String endWt, String resNum) {
		CoreReturnObject core = new CoreReturnObject();
		// 转json为实体类
		List<PlnSteelforOrdEntity> entityList = SteelHelper.jsonsToEntityList(
				PlnSteelforOrdEntity.class, jsonList);
		core.setResult(false);
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			String castNo = "";
			for (PlnSteelforOrdEntity entity : entityList) {
				PlnSteelforOrdEntity entity1 = ControlFurNacePlan
						.getSteelOrdById(con, entity.getFurnaceno(), entity
								.getSequenceno());
				if (entity1 == null) {
					core.setV_errMsg("数据异常,请刷新数据!");
					return core;
				}
				if (!entity1.getStatus().equals("编制中")) {
					core.setV_errMsg("不是编制中状态的炉次订单,不能调整重量!");
					return core;
				}
				if (!entity1.getSurplusflag().equals("订单材")) {
					core.setV_errMsg("不是订单材的炉次订单,不能调整重量!");
					return core;
				}
				if (entity1.getIfConfirm().equals("是")) {
					core.setV_errMsg("浇次已确认,不能调整炉次订单!");
					return core;
				}
				// 现在重量
				double nowWgt = Double.parseDouble(entity.getTotWeightM());
				// 现在重量
				int nowNum = Integer.parseInt(entity.getTotMumM());
				// 原始重量
				double oldWgt = Double.parseDouble(entity1.getTotWeightM());
				int oldNum = Integer.parseInt(entity1.getTotMumM());
				// 如果重量没有发生变化，则不执行
				if (Math.abs(nowWgt - oldWgt) <= 0.0001) {
					continue;
				}
				// 查询这个炉次订单对应的炉次,然后找对应电炉的出钢量上限与下限
				PlnSteelforfurnaceEntity furnaceEntity = ControlFurNacePlan
						.getFurnaceByFurnaceno(con, entity.getFurnaceno());
				double furnaceWgt = Double.parseDouble(furnaceEntity
						.getWeight()); // 炉总量
				int furnaceNum = Integer.parseInt(furnaceEntity.getQuantity());
				double[] lgParams = FrmSteelMakingPlanChange.getPlineLgParams(
						con, furnaceEntity.getEfPlineCode());
				// double standSteel = lgParams[0];// 标准出钢量
				// double minSteel = lgParams[1];// 出钢量下限
				// double maxSteel = lgParams[2];// 出钢量上限
				// 查询这个炉内计划的订单可组炉量
				PlnOrderCastSEntity orderEntity = ControlOrderPlan
						.getOrderCastById(con, entity.getProPlanId(), entity
								.getGxPlanNo());
				if (orderEntity == null) {
					core.setV_errMsg("订单" + entity.getProPlanId()
							+ "不存在,请刷新数据!");
					return core;
				}

				double planWgt = Double.parseDouble(orderEntity.getPlanWtS());// 排产重量
				int planNum = Integer.parseInt(orderEntity.getPlanNumS());// 排产支数
				double planedWgt = Double
						.parseDouble(orderEntity.getPlanedWt());// 已组炉重量
				int planedNum = Integer.parseInt(orderEntity.getPlanedNum());// 已组炉支数

				double excessWt = new BigDecimal(nowWgt - oldWgt).setScale(3,
						RoundingMode.HALF_UP).doubleValue();// 超量吨
				int excessNum = nowNum - oldNum;// 超量支
				// if (excessWt > 0) {
				// excessNum = (int) Math.ceil(excessWt / planWgt * planNum); //
				// 超量支
				// }
				// else {
				// excessNum = (int) Math.floor(excessWt / planWgt * planNum);
				// }

				double firstWt1 = 0;// 首炉加量
				double endWt1 = 0;// 尾炉加量
				if (!firstWt.equals("")) {
					firstWt1 = Double.parseDouble(firstWt);
				}
				if (!endWt.equals("")) {
					endWt1 = Double.parseDouble(endWt);
				}

				double moreWt = 0;
				double symoreWt = 0;
				if (!resNum.equals("")) {
					moreWt = Double.parseDouble(resNum);
					// // 余材量=总重量-原始订单材量
					// moreWt = new BigDecimal(furnaceWgt -resNum- oldWgt
					// - firstWt1 - endWt1).setScale(3,
					// RoundingMode.HALF_UP).doubleValue();

					if (moreWt != 0) {
						// 剩余余量
						symoreWt = moreWt - excessWt;
						if (symoreWt < 0) {
							symoreWt = 0;
						}
					}
				}

				// 不能小于最小出钢量
				// if (furnaceWgt - oldWgt + nowWgt < minSteel) {
				double wt = new BigDecimal((furnaceWgt - oldWgt - moreWt
						- firstWt1 - endWt1)
						+ nowWgt + symoreWt + firstWt1 + endWt1).setScale(3,
						RoundingMode.HALF_UP).doubleValue();
				int num = (int) Math.ceil(wt / furnaceWgt * furnaceNum); //
				// if (wt < minSteel) {
				// core.setV_errMsg("调整炉次号(" + entity.getFurnaceno()
				// + ")/炉内顺序号(" + entity.getSequenceno()
				// + ")的母坯重量,对应炉的重量将小于最小出钢量:" + minSteel);
				// return core;
				// }
				// 不能大于最大出钢量
				// if (furnaceWgt - oldWgt + nowWgt > maxSteel) {
				// if (wt > maxSteel) {
				// core.setV_errMsg("调整炉次号(" + entity.getFurnaceno()
				// + ")/炉内顺序号(" + entity.getSequenceno()
				// + ")的重量,对应炉的重量将大于最大出钢量:" + maxSteel);
				// return core;
				// }
				// double difWgt = new BigDecimal(oldWgt - nowWgt + moreWt)
				// .setScale(3, RoundingMode.HALF_UP).doubleValue();// 差量
				// int difNum = 0;
				// if (difWgt > 0) {
				// difNum = (int) Math.ceil(difWgt / planWgt * planNum); // 差支
				// }
				// else {
				// difNum = (int) Math.floor(difWgt / planWgt * planNum); // 差支
				// }
				// int nowNum = oldNum + excessNum; // 现在支数
				// int nowNum = furnaceNum-difNum;// 现在支数
				double nowplanedWgt = planedWgt + excessWt;// 订单新已组炉重量
				int nowplanedNum = planedNum + excessNum;
				// (int) Math.ceil(nowplanedWgt / planWgt
				// * planNum);// 订单新已组炉支数

				// 是否超量
				String superWtS = "";
				String superNumS = "";
				String nowplanedWgtS = "";
				String nowplanedNumS = "";
				if (planWgt - nowplanedWgt > 0) {
					superWtS = "";
					superNumS = "";
					nowplanedWgtS = String.valueOf(nowplanedWgt);
					nowplanedNumS = String.valueOf(nowplanedNum);
				} else {
					superWtS = String.valueOf(planWgt - nowplanedWgt);
					superNumS = String.valueOf(planNum - nowplanedNum);
					nowplanedWgtS = String.valueOf(planWgt);
					nowplanedNumS = String.valueOf(planNum);
				}
				// 修改炉次订单
				String updateOrdSql = " update pln_steelfor_ord t set t.TOT_WEIGHT_M=?,t.TOT_MUM_M=?,T.EXCESS_WT=TO_NUMBER(?),T.EXCESS_NUM=TO_NUMBER(?)  where t.FURNACENO=? and t.SEQUENCENO=?";
				ps = con.prepareStatement(updateOrdSql);
				ps.setObject(1, nowWgt);
				ps.setObject(2, nowNum);
				ps.setObject(3, superWtS);
				ps.setObject(4, superNumS);
				ps.setObject(5, entity.getFurnaceno());
				ps.setObject(6, entity.getSequenceno());
				ps.executeUpdate();
				ps.close();

				if (!resNum.equals("")) {

					// 判断剩余余量是否等于0
					if (symoreWt == 0) {
						// 删除炉次订单余材并且是开浇超量的数据
						String deteOrdSql = "  DELETE pln_steelfor_ord where FURNACENO=? AND SURPLUSFLAG='1' AND SURPLUS_TYPE='1'";
						ps = con.prepareStatement(deteOrdSql);
						ps.setObject(1, entity.getFurnaceno());
						ps.executeUpdate();
						ps.close();
					} else {
						// 修改炉次订单余材
						String updateOrdSql1 = " update pln_steelfor_ord t set t.TOT_WEIGHT_M=TO_NUMBER(NVL(t.TOT_WEIGHT_M,0))-TO_NUMBER(?),t.TOT_MUM_M=TO_NUMBER(NVL(t.TOT_MUM_M,0))-TO_NUMBER(?)  "
								+ "where t.FURNACENO=? AND T.SURPLUSFLAG='1' AND T.SURPLUS_TYPE='1'";
						ps = con.prepareStatement(updateOrdSql1);
						ps.setObject(1, excessWt);
						ps.setObject(2, excessNum);
						ps.setObject(3, entity.getFurnaceno());
						ps.executeUpdate();
						ps.close();
					}
				}
				if (Math.abs(excessWt) > moreWt) {
					// 修改铸造订单已组炉量
					String updateOrderSql = "update pln_order_cast_s t set  t.PLANED_WT=?,t.PLANED_NUM=? where t.PRO_PLAN_ID=? and t.GX_PLAN_NO=?";
					ps = con.prepareStatement(updateOrderSql);
					ps.setObject(1, nowplanedWgtS);
					ps.setObject(2, nowplanedNumS);
					ps.setObject(3, orderEntity.getProPlanId());
					ps.setObject(4, orderEntity.getGxPlanNo());
					ps.executeUpdate();
					ps.close();
					// if ((nowplanedWgt - planWgt) / planWgt > 0.05) {
					// core.setV_errMsg("调整炉次号(" + entity.getFurnaceno()
					// + ")/炉内顺序号(" + entity.getSequenceno()
					// + ")的重量,对应订单的已组炉重量将超出排产重量的5%");
					// return core;
					// }
				}
				// 修改炉次
				String updateFurnaceSql = " update pln_steelforfurnace t set t.WEIGHT=?,t.QUANTITY=? where t.FURNACENO=?";
				ps = con.prepareStatement(updateFurnaceSql);
				ps.setObject(1, wt);
				ps.setObject(2, num);
				ps.setObject(3, entity.getFurnaceno());
				ps.executeUpdate();
				ps.close();
				// 查询这个炉次订单对应的浇次
				PlnSteelforcastEntity castEntity = ControlCastPlan
						.getCastByCastno(con, entity.getCastNo());
				double castWgt = Double.parseDouble(castEntity.getTotWt());
				int castNum = Integer.parseInt(castEntity.getTotNum());
				// 修改浇次
				String udpateCastSql = " update pln_steelforcast t set t.TOT_WT=? ,t.TOT_NUM=? where t.cast_no=?";
				ps = con.prepareStatement(udpateCastSql);
				ps.setObject(1, castWgt - furnaceWgt + wt);
				ps.setObject(2, castNum - furnaceNum + num);
				ps.setObject(3, entity.getCastNo());
				ps.executeUpdate();
				ps.close();
				castNo = entity.getCastNo();
			}
			// 更新目标钢水量
			FrmSteelMerge.updatePlanOrder(con, castNo);
			con.commit();
			core.setV_errMsg("调整成功!");
			core.setResult(true);
			return core;
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {

				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 状态调整
	 * 
	 * @param jsonList
	 * @return
	 */
	public CoreReturnObject changeStatus(ArrayList<String> jsonList,
			String flag, String username) {
		CoreReturnObject core = new CoreReturnObject();
		// 转json为实体类
		List<PlnSteelforcastEntity> entityList = SteelHelper.jsonsToEntityList(
				PlnSteelforcastEntity.class, jsonList);
		core.setResult(false);
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			String castSql = "update pln_steelforcast t set t.status=?,t.MANFORTOL2=? ,t.TIMEFORTOL2=sysdate where t.cast_no=?";
			String furnaceSql = "update pln_steelforfurnace t set t.status=? where t.cast_no=?";
			String ordSql = "update pln_steelfor_ord  t set t.status=? where t.cast_no=?";
			for (PlnSteelforcastEntity entity : entityList) {
				PlnSteelforcastEntity entity1 = ControlCastPlan
						.getCastByCastno(con, entity.getCastNo());
				if (flag.equals("1")) {
					if (!entity1.getStatus().equals("1")) {
						core.setV_errMsg("浇次:" + entity.getCastNo()
								+ "不是编制中状态,不能下发!");
						return core;
					}
					ps = con.prepareStatement(castSql);
					ps.setObject(1, "2");
					ps.setObject(2, username);
					ps.setObject(3, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
					ps = con.prepareStatement(furnaceSql);
					ps.setObject(1, "2");
					ps.setObject(2, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
					ps = con.prepareStatement(ordSql);
					ps.setObject(1, "2");
					ps.setObject(2, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
				} else {
					if (!entity1.getStatus().equals("2")) {
						core.setV_errMsg("浇次:" + entity.getCastNo()
								+ "不是下发状态,不能取消下发!");
						return core;
					}
					ps = con.prepareStatement(castSql);
					ps.setObject(1, "1");
					ps.setObject(2, username);
					ps.setObject(3, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
					ps = con.prepareStatement(furnaceSql);
					ps.setObject(1, "1");
					ps.setObject(2, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
					ps = con.prepareStatement(ordSql);
					ps.setObject(1, "1");
					ps.setObject(2, entity.getCastNo());
					ps.executeUpdate();
					ps.close();
				}

			}
			con.commit();
			if (flag.equals("1")) {
				core.setV_errMsg("下发成功!");
			} else {
				core.setV_errMsg("取消下发成功!");
			}
			con.commit();
			core.setResult(true);
			return core;
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {

				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 删除炉次
	 * 
	 * @param castnoList
	 * @return
	 */
	public CoreReturnObject doDeleteSingle(ArrayList<String> castnoList,
			String castno, String castSeq) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			double wtj = 0;
			int numJ = 0;
			String plineCode = "";
			int countL = 0;

			String furnNo = castnoList.get(0);
			String castStoveSeq = castnoList.get(1);
			PlnSteelforfurnaceEntity entity = getSteelFurnSeq(con, furnNo,
					castStoveSeq);
			if (entity == null) {
				core.setV_errMsg("炉次数据异常,请刷新数据!");
				return core;
			}
			if (Integer.parseInt(entity.getStatus()) >= 10) {
				core.setV_errMsg("炉次(" + entity.getFurnaceno()
						+ ")不是编制中的状态,不能删除炉次!");
				return core;
			}
			// if (Integer.parseInt(entity.getToExcel())== 1) {
			// core.setV_errMsg("该浇次计划("+entity.getCastNo()+")已导出,不能删除!");
			// return core;
			// }
			plineCode = entity.getPlineCode();
			// 删除炉次重量，支数
			wtj += Double.parseDouble(entity.getWeight());
			numJ += Integer.parseInt(entity.getQuantity());
			countL++;

			// 删除炉次
			String deleteFurnaceSql = " delete from PLN_STEELFORFURNACE t where t.FURNACENO=? ";
			ps = con.prepareStatement(deleteFurnaceSql);
			ps.setObject(1, furnNo);
			ps.executeUpdate();
			ps.close();

			String materialNoZz = "";
			// 查询连铸产出物料
			String sql = "SELECT T.MATERIAL_NO,T.WLID_IN FROM PLN_STEELFOR_ORD T WHERE T.FURNACENO=?  AND T.SURPLUSFLAG='0' GROUP BY T.MATERIAL_NO,T.WLID_IN";
			ps = con.prepareStatement(sql);
			ps.setObject(1, furnNo);
			rs = ps.executeQuery();
			if (rs.next()) {
				materialNoZz = rs.getString("MATERIAL_NO");
			}
			rs.close();
			ps.close();
			// 查询电炉产线，钢种对应投入产出小时能力
			double capacity = FrmSteeSerialPublic.seqCapacityFurn(con, entity
					.getEfPlineCode(), entity.getWlidIn(), entity
					.getMaterialNo());
			// 查询铸造产线，钢种对应投入产出小时能力
			double capacityZz = FrmSteeSerialPublic.seqCapacityCast(con, entity
					.getPlineCode(), entity.getMaterialNo(), materialNoZz);
			// 修改炉次顺序号
			FrmSteeSerialPublic.seqIncreaseFurn(con, plineCode, Integer
					.parseInt(entity.getFurnacenoSeq()), -1, entity
					.getPlnStarttime(), String.valueOf(capacity), String
					.valueOf(capacityZz), Integer.parseInt(castSeq), -1, entity
					.getEfPlineCode(), entity.getCastNo(), "0");

			int count = 0;
			int ccmSeq = 0;
			// 查询炉次下有多少炉次订单
			sql = "SELECT COUNT(*) COUNT,MAX(T.CCM_SEQ) CCM_SEQ  FROM PLN_STEELFOR_ORD T WHERE T.FURNACENO = ?";
			ps = con.prepareStatement(sql);
			ps.setObject(1, furnNo);
			rs = ps.executeQuery();
			if (rs.next()) {
				count = rs.getInt("COUNT");
				ccmSeq = rs.getInt("CCM_SEQ");
			}
			rs.close();
			ps.close();
			// 删除炉次订单
			String deleteOrdSql = " delete from pln_steelfor_ord t where T.FURNACENO=?";
			ps = con.prepareStatement(deleteOrdSql);
			ps.setObject(1, furnNo);
			ps.executeUpdate();
			ps.close();
			// 修改炉次订单顺序号
			FrmSteeSerialPublic.seqIncreaseOrd(con, entity.getPlineCode(),
					ccmSeq, -count, 1);

			// 查询浇次向下炉次是否全部删除
			List<PlnSteelforfurnaceEntity> entitylc = getSteelFurnById(con,
					castno);
			if (entitylc == null) {
				// 删除浇次
				String deleteCastSql = "delete from pln_steelforcast t where t.CAST_NO=?";
				ps = con.prepareStatement(deleteCastSql);
				ps.setObject(1, castno);
				ps.executeUpdate();
				ps.close();
				// 修改浇次顺序号
				FrmSteeSerialPublic.seqIncreaseCast(con, plineCode, Integer
						.parseInt(castSeq), -1);
			} else {
				// 修改浇次
				String updateCastSql = "UPDATE PLN_STEELFORCAST T SET T.TOT_WT=TO_NUMBER(T.TOT_WT)-TO_NUMBER(?),"
						+ "T.TOT_NUM=TO_NUMBER(T.TOT_NUM)-TO_NUMBER(?),"
						+ "T.FURNACENUMBER=TO_NUMBER(T.FURNACENUMBER)-TO_NUMBER(?) WHERE T.CAST_NO=?";
				ps = con.prepareStatement(updateCastSql);
				ps.setObject(1, wtj);
				ps.setObject(2, numJ);
				ps.setObject(3, countL);
				ps.setObject(4, castno);
				ps.executeUpdate();
				ps.close();
			}

			con.commit();
			core.setV_errMsg("删除成功!");
			core.setResult(true);
			return core;
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {

				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (con != null && !con.isClosed()) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}
}
