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.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import oracle.jdbc.proxy.annotation.Pre;

import org.apache.commons.beanutils.BeanUtils;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

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;

/**
 * 组炉/组浇计划
 * 
 * @author Administrator
 * 
 */
public class FrmSteelMakingPlanDesign extends DBCommon {
	/**
	 * 组炉
	 * 
	 * @param jsonlist1
	 *            订单信息
	 * @param jsonlist2
	 *            余材信息
	 * @param userName
	 *            操作人
	 * @param planWgt
	 *            计划重量
	 * @param allWgt
	 *            总重量
	 * @param allNum
	 *            总支数
	 * @param memo
	 *            计划备注
	 * @return
	 */
	public CoreReturnObject furnaceGroup(ArrayList<String> jsonlist1,
			ArrayList<String> jsonlist2, String userName, String planWgt,
			String allWgt, String allNum, String memo) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		// 转化json字符串为实体类(余材)
		List<PlnSteelforOrdEntity> ordEntityList = SteelHelper
				.jsonsToEntityList(PlnSteelforOrdEntity.class, jsonlist1);
		// 订单
		List<PlnOrderCastSEntity> castEntityList = SteelHelper
				.jsonsToEntityList(PlnOrderCastSEntity.class, jsonlist2);
		FrmSteelMakingPlanDesign frmSteelMakingPlanDesign = new FrmSteelMakingPlanDesign();
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// 炉信息
			PlnSteelforfurnaceEntity furnaceEntity = new PlnSteelforfurnaceEntity();
			furnaceEntity.setStatus("0");
			furnaceEntity.setAimSteelQty(planWgt);
			// 取第一条订单信息填充炉信息
			PlnOrderCastSEntity bentity = castEntityList.get(0);
			// 炉字段信息
			furnaceEntity.setCastingtype(bentity.getCastingtype());
			furnaceEntity.setMaterialNo(bentity.getMaterialNo());
			furnaceEntity.setMaterialName(bentity.getMaterialName());
			furnaceEntity.setWlidIn(bentity.getWlidIn());
			furnaceEntity.setWldescIn(bentity.getWldescIn());
			furnaceEntity.setGradecode(bentity.getGradecode());
			furnaceEntity.setGradename(bentity.getGradename());
			furnaceEntity.setQuantity(allNum);
			furnaceEntity.setWeight(allWgt);
			// 生成炉号
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
			String nowTime = sdf.format(new Date());
			// 查询最大炉号
			String furnaceno = frmSteelMakingPlanDesign.getMaxFurnaceNo(con,
					nowTime);
			furnaceEntity.setFurnaceno(furnaceno);
			// 新增炉
			frmSteelMakingPlanDesign.addFurnace(con, furnaceEntity);
			// 订单信息
			// 炉内顺序号
			int sequenceno = 0;
			for (PlnOrderCastSEntity entity : castEntityList) {
				sequenceno++;
				// 查询订单信息进行比较，是否能够组炉
				PlnOrderCastSEntity entityN = ControlOrderPlan
						.getOrderCastById(con, entity.getProPlanId(),
								entity.getGxPlanNo());
				// 先验证数据库是否还存在此记录
				if (entityN == null) {
					core.setV_errMsg("数据异常,请刷新数据!");
					return core;
				}
				// 排产支数
				String planNum = entityN.getPlanNumS();
				// 已组炉支数
				String planedNum = entityN.getPlanedNum();
				if (planedNum.equals("")) {
					planedNum = "0";
				}
				// 再验证重量与支数
				if (Integer.parseInt(entity.getCanNum()) > Integer
						.parseInt(planNum) - Integer.parseInt(planedNum)) {
					core.setV_errMsg("数据异常,请刷新数据!");
					return core;
				}
				PlnSteelforOrdEntity ordEntity = new PlnSteelforOrdEntity();
				BeanUtils.copyProperties(ordEntity, entity);
				ordEntity.setSequenceno(String.valueOf(sequenceno));
				ordEntity.setFurnaceno(furnaceno);
				ordEntity.setStatus("0");// 状态
				ordEntity.setSurplusflag("0");
				ordEntity.setIfSurplusAlloted("0");
				ordEntity.setLengthM(entity.getLengthLz());
				ordEntity.setTotMumM(entity.getCanNum());// 支数
				ordEntity.setTotWeightM(entity.getCanWgt());// 重量
				ordEntity.setDiameter(entity.getDiameterLz());// 管坯直径
				ordEntity.setMakeman(userName);
				ordEntity.setWeightM(entity.getWtCastOne());
				frmSteelMakingPlanDesign.addSteelForOrd(con, ordEntity);
				frmSteelMakingPlanDesign.updateOrderCastAdd(con,
						entity.getCanWgt(), entity.getCanNum(),
						entity.getProPlanId(), entity.getGxPlanNo());
			}
			// 余材信息
			if (ordEntityList != null) {
				for (PlnSteelforOrdEntity ordEntity : ordEntityList) {
					sequenceno++;
					ordEntity.setSequenceno(String.valueOf(sequenceno));
					ordEntity.setFurnaceno(furnaceno);
					ordEntity.setStatus("0");// 状态
					ordEntity.setSurplusflag("1");
					ordEntity.setIfSurplusAlloted("1");
					ordEntity.setMakeman(userName);
					frmSteelMakingPlanDesign.addSteelForOrd(con, ordEntity);
				}
			}
			core.setV_errMsg("组炉成功!");
			core.setResult(true);
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null)
					con.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 铸造订单转炉订单
	 * 
	 * @param entity
	 * @return
	 */
	static PlnSteelforOrdEntity orderToCastOrd(PlnOrderCastSEntity entity) {
		// 将排产订单信息转化为炉次订单信息
		PlnSteelforOrdEntity ordEntity = new PlnSteelforOrdEntity();
		ordEntity.setCastingtype(entity.getCastingtype());// 铸造类型（连铸、模铸）
		ordEntity.setCutNumGp(entity.getCutNumGp());// 倍尺数
		ordEntity.setCastNo("");
		ordEntity.setCic("");
		ordEntity.setDiameter(entity.getDiameterLz());// 管坯直径
		ordEntity.setDic("");
		ordEntity.setFurnaceno("");// 炉次号
		ordEntity.setGptype(entity.getGptype());
		ordEntity.setGradecode(entity.getGradecode());
		ordEntity.setGradename(entity.getGradename());
		ordEntity.setGxPlanNo(entity.getGxPlanNo());// 工序排产序号
		ordEntity.setIfSurplusAlloted("0");
		ordEntity.setLenGpSingle(entity.getLenGpSingle());
		ordEntity.setLengthM(entity.getLengthLz());
		ordEntity.setMakeman("");
		ordEntity.setMaketime("");
		ordEntity.setMaterialName(entity.getMaterialName());
		ordEntity.setMaterialNo(entity.getMaterialNo());
		ordEntity.setMemo("");
		ordEntity.setPic("");
		ordEntity.setProPlanId(entity.getProPlanId());// 铸造订单编号
		ordEntity.setSequenceno("");
		ordEntity.setSic("");
		ordEntity.setStatus("0");// 状态
		ordEntity.setSurplusflag("0");
		ordEntity.setSurplusType("");
		ordEntity.setTotMumM(entity.getCanNum());
		ordEntity.setTotWeightM(entity.getCanWgt());
		ordEntity.setWeightGpOne("");
		ordEntity.setWeightM(entity.getWtCastOne());
		return ordEntity;
	}

	/**
	 * 删除炉次计划
	 * 
	 * @param jsonlist
	 * @return
	 */
	public CoreReturnObject deleteFurnace(ArrayList<String> jsonlist) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		// 转化json字符串为实体类(余材)
		List<PlnSteelforfurnaceEntity> furEntityList = SteelHelper
				.jsonsToEntityList(PlnSteelforfurnaceEntity.class, jsonlist);
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			FrmSteelMakingPlanDesign frmSteelMakingPlanDesign = new FrmSteelMakingPlanDesign();
			for (PlnSteelforfurnaceEntity entity : furEntityList) {
				// 删除炉
				frmSteelMakingPlanDesign.deleteFurnace(con,
						entity.getFurnaceno());
				// 查询炉生产订单
				List<PlnSteelforOrdEntity> entityList = ControlFurNacePlan
						.getSteelOrdByFurnaceno(con, entity.getFurnaceno());
				if (entityList != null) {
					for (PlnSteelforOrdEntity castSEntity : entityList) {
						// 恢复铸造订单的组炉量
						if (castSEntity.getSurplusflag().equals("订单材")) {
							frmSteelMakingPlanDesign.updateOrderCastMove(con,
									castSEntity.getTotWeightM(),
									castSEntity.getTotMumM(),
									castSEntity.getProPlanId(),
									castSEntity.getGxPlanNo());
						}
					}
				}
				// 删除炉生产订单
				frmSteelMakingPlanDesign.deleteSteelOrd(con,
						entity.getFurnaceno());
			}
			core.setV_errMsg("删除炉成功!");
			core.setResult(true);
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null)
					con.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 组炉
	 * 
	 * @param jsonlist
	 * @return
	 */
	public CoreReturnObject castGroup(ArrayList<String> jsonlist,
			String userName) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		// 转化json字符串为实体类(余材)
		List<PlnSteelforfurnaceEntity> furEntityList = SteelHelper
				.jsonsToEntityList(PlnSteelforfurnaceEntity.class, jsonlist);
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			FrmSteelMakingPlanDesign frmSteelMakingPlanDesign = new FrmSteelMakingPlanDesign();
			// 生成浇次号
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
			String nowTime = sdf.format(new Date());
			String castno = frmSteelMakingPlanDesign.getMaxCastno(con, nowTime);
			double wgt = 0;
			double num = 0;
			// 浇次顺序号(暂自定义)
			int index = 0;
			String updateFurnaceSql = " update PLN_STEELFORFURNACE t set t.CAST_NO=?,t.status=? ,t.CAST_SEQ=? where t.FURNACENO=?";
			String updateSteelordSql = "update PLN_STEELFOR_ORD t set t.cast_no=? ,t.status=? ,t.SEQUENCEINCAST=?  where t.FURNACENO=?";
			PreparedStatement ps = null;
			for (PlnSteelforfurnaceEntity entity : furEntityList) {
				index++;
				PlnSteelforfurnaceEntity entityN = ControlFurNacePlan
						.getFurnaceByFurnaceno(con, entity.getFurnaceno());
				if (entityN == null) {
					core.setV_errMsg("数据异常,请重新刷新数据!");
					return core;
				}
				// 验证数据
				if (!entityN.getStatus().equals("编制中")) {
					core.setV_errMsg("数据异常,请重新刷新数据!!");
					return core;
				}
				wgt += Double.parseDouble(entity.getWeight());
				num += Integer.parseInt(entity.getQuantity());
				// 修改炉计划状态
				ps = con.prepareStatement(updateFurnaceSql);
				ps.setObject(1, castno);
				ps.setObject(2, "1");
				ps.setObject(3, index);
				ps.setObject(4, entity.getFurnaceno());
				ps.executeUpdate();
				ps.close();
				// 修改炉订单状态
				ps = con.prepareStatement(updateSteelordSql);
				ps.setObject(1, castno);
				ps.setObject(2, "1");
				ps.setObject(3, index);
				ps.setObject(4, entity.getFurnaceno());
				ps.executeUpdate();
				ps.close();

			}
			// 新增浇计划
			PlnSteelforcastEntity castEntity = new PlnSteelforcastEntity();
			castEntity.setCastNo(castno);
			castEntity.setStatus("1");
			castEntity.setFurnacenumber(String.valueOf(furEntityList.size()));
			castEntity.setTotWt(String.valueOf(wgt));
			castEntity.setTotNum(String.valueOf(num));
			castEntity.setMakeman(userName);
			String addCastSql = CoreXmlSqlParsersFactory
					.getSql("FrmSteelMakingPlanDesign.addCastno");
			addCastSql = EntityTool.fillSqlByEntity(addCastSql, castEntity);
			ps = con.prepareStatement(addCastSql);
			ps.executeUpdate();
			ps.close();
			core.setResult(true);
			con.commit();
			core.setV_errMsg("组烧成功!");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null)
					con.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	/**
	 * 删除浇次
	 * 
	 * @param jsonlist
	 * @return
	 */
	public CoreReturnObject deleteCast(ArrayList<String> jsonlist) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		// 转化json字符串为实体类(余材)
		List<PlnSteelforcastEntity> furEntityList = SteelHelper
				.jsonsToEntityList(PlnSteelforcastEntity.class, jsonlist);
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			String updateFurnaceSql = " update PLN_STEELFORFURNACE t set t.cast_no='',t.status=? ,t.cast_seq='' where t.cast_no=?";
			String updateSteelOrdSql = "update PLN_STEELFOR_ORD t set t.cast_no='' ,t.status=? ,t.SEQUENCEINCAST=''  where t.cast_no=?";
			String deleteCastSql = "delete from PLN_STEELFORCAST t where t.cast_no=?";
			PreparedStatement ps = null;
			for (PlnSteelforcastEntity entity : furEntityList) {
				// 删除炉计划里的浇次信息
				ps = con.prepareStatement(updateFurnaceSql);
				ps.setObject(1, "0");
				ps.setObject(2, entity.getCastNo());
				ps.executeUpdate();
				ps.close();
				// 删除炉订单里的浇次信息
				ps = con.prepareStatement(updateSteelOrdSql);
				ps.setObject(1, "0");
				ps.setObject(2, entity.getCastNo());
				ps.executeUpdate();
				ps.close();
				// 删除浇次信息
				ps = con.prepareStatement(deleteCastSql);
				ps.setObject(1, entity.getCastNo());
				ps.executeUpdate();
				ps.close();
			}
			core.setV_errMsg("删除浇成功!");
			core.setResult(true);
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (con != null)
					con.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return core;
	}

	// -----------------------------------------------数据库操作块
	/**
	 * 查询最大炉号
	 * 
	 * @param con
	 * @param time
	 * @return
	 * @throws SQLException
	 */
	String getMaxFurnaceNo(Connection con, String time) throws SQLException {
		String furnaceno = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.getMaxFurnaceNo");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, time);
		ps.setObject(2, time);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			furnaceno = rs.getString("FURNACENO");
		}
		rs.close();
		ps.close();
		return furnaceno;
	}

	/**
	 * 新增炉信息
	 * 
	 * @param con
	 * @param furnaceEntity
	 * @throws SQLException
	 */
	void addFurnace(Connection con, PlnSteelforfurnaceEntity furnaceEntity)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.addFurnace");
		sql = EntityTool.fillSqlByEntity(sql, furnaceEntity);
		PreparedStatement ps = con.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 新增炉计划信息
	 * 
	 * @param con
	 * @param ordEntity
	 * @throws SQLException
	 */
	void addSteelForOrd(Connection con, PlnSteelforOrdEntity ordEntity)
			throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.addSteelForOrd");
		sql = EntityTool.fillSqlByEntity(sql, ordEntity);
		PreparedStatement ps = con.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 修改订单的组炉量(加量)
	 * 
	 * @param con
	 * @param canWgt
	 * @param canNum
	 * @param proPlanId
	 * @param gxPlanNo
	 * @throws SQLException
	 */
	void updateOrderCastAdd(Connection con, String canWgt, String canNum,
			String proPlanId, String gxPlanNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.updateOrderCastAdd");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, canWgt);
		ps.setObject(2, canNum);
		ps.setObject(3, proPlanId);
		ps.setObject(4, gxPlanNo);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 修改订单的组炉量(减量)
	 * 
	 * @param con
	 * @param canWgt
	 * @param canNum
	 * @param proPlanId
	 * @param gxPlanNo
	 * @throws SQLException
	 */
	void updateOrderCastMove(Connection con, String canWgt, String canNum,
			String proPlanId, String gxPlanNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.updateOrderCastMove");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, canWgt);
		ps.setObject(2, canNum);
		ps.setObject(3, proPlanId);
		ps.setObject(4, gxPlanNo);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 删除炉
	 * 
	 * @param con
	 * @param furnaceno
	 * @throws SQLException
	 */
	void deleteFurnace(Connection con, String furnaceno) throws SQLException {
		String sql = "delete from PLN_STEELFORFURNACE t where t.furnaceno=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, furnaceno);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 删除炉订单
	 * 
	 * @param con
	 * @param furnaceno
	 * @throws SQLException
	 */
	void deleteSteelOrd(Connection con, String furnaceno) throws SQLException {
		String sql = "delete from PLN_STEELFOR_ORD t where t.furnaceno=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, furnaceno);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 查询最大浇次号
	 * 
	 * @param con
	 * @param time
	 * @return
	 * @throws SQLException
	 */
	String getMaxCastno(Connection con, String time) throws SQLException {
		String castno = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmSteelMakingPlanDesign.getMaxCastno");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, time);
		ps.setObject(2, time);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			castno = rs.getString("CAST_NO");
		}
		rs.close();
		ps.close();
		return castno;
	}
}
