package com.steering.pss.plnsaleord.planStove;

import java.sql.Connection;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import CoreFS.SA06.CoreReturnObject;

import CoreFS.SC01.CoreConstantData;

import com.steering.comm.db.DBCommon;

import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.planStove.entity.MaterialChooseEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderDbkSEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyDbkMEntity;

/**
 * 利库/脱单
 * 
 * @author peng
 * 
 */
public class FrmMaterialChoose extends DBCommon {
	/**
	 * 查询库存物料
	 * 
	 * @param materialNo
	 *            物料
	 * @param processCode
	 *            工序
	 * @return CoreReturnObject
	 */
	public CoreReturnObject queryMaterial(String materialNo, String processCode) {
		Object[] params = new Object[] { materialNo };
		if (processCode.equals("E")) {
			return this.getDataBySqlID("FrmMaterialChoose.queryMaterialE",
					params);
		} else if (processCode.equals("F")) {
			return this.getDataBySqlID("FrmMaterialChoose.queryMaterialF",
					params);
		} else if (processCode.equals("G")) {
			return this.getDataBySqlID("FrmMaterialChoose.queryMaterialG",
					params);
		} else {
			return null;
		}

	}

	/**
	 * 利库
	 * 
	 * @param proPlanId
	 *            订单编号
	 * @param gxPlanNo
	 *            排产序号
	 * @param processCode
	 *            工序
	 * @param jsonList
	 *            集合
	 * @param userName
	 *            操作人
	 * @return CoreReturnObject
	 */
	public CoreReturnObject liku(String proPlanId, String gxPlanNo,
			String processCode, ArrayList<String> jsonList, String userName) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// /镦拨扩
//			if (processCode.equals("E")) {
//				/**
//				 * 1.验证订单
//				 */
//				PlnOrderDbkSEntity entity = PlnHelper.getEntityData(con,
//						new String[] { proPlanId, gxPlanNo },
//						"ProducHelperBean.getPlanOrderE",
//						" AND T.PRO_PLAN_ID = ?  AND T.GX_PLAN_NO = ?",
//						PlnOrderDbkSEntity.class);
//				if (entity == null) {
//					core.setV_errMsg("订单编号(" + proPlanId + ")数据异常,请刷新数据!");
//					return core;
//				}
//				if (entity.getIfStoveIssued().equals("1")) {
//					core.setV_errMsg("订单编号(" + proPlanId + ")的炉计划已经下发!");
//					return core;
//				}
//				/**
//				 * 2.利库
//				 */
//				SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//				String timeStr = df.format(new Date());// 当前时间字符串
//				List<MaterialChooseEntity> entityList = PlnHelper
//						.jsonsToEntityList(MaterialChooseEntity.class, jsonList);
//				int sumNum = 0;// 排产订单利库支数
//				double sumWgt = 0;// 排产订单利库重量
//				int readyPlanNo = Integer.parseInt(PlnHelper.getParam(con,
//						"FrmMaterialChoose.getMaxReadyPlanNo",
//						new String[] { proPlanId }, "READY_PLAN_NO"));// 预排序号
//				HashMap<String, PlnZyDbkReadyEntity> map = new HashMap<String, PlnZyDbkReadyEntity>();// <炉号,虚拟炉计划>
//				for (MaterialChooseEntity chEntity : entityList) {
//					int actCount = Integer.parseInt(chEntity.getActCount());// 利库支数
//					String judgeStoveNo = chEntity.getJudgeStoveNo();// 炉号
//					String batchNo = chEntity.getBatchNo();// 批号
//					String batchGroudNo = chEntity.getBatchGroudNo();// 组号
//					// 2.1 查询库存数据
//					List<String[]> matList = PlnHelper.getArrays(con,
//							"FrmMaterialChoose.getMatNoByJudgeLikuE",
//							new String[] { chEntity.getMaterialNo(),
//									judgeStoveNo, batchNo, batchGroudNo },
//							new String[] { "MAT_NO", "ACT_WEIGHT" });
//
//					// 2.2验证库存物料量是否足够
//					if (matList.size() == 0 || matList.size() < actCount) {
//						core.setV_errMsg("炉/批/组号 " + chEntity.getJudgeStoveNo()
//								+ "/" + chEntity.getBatchNo() + "/"
//								+ chEntity.getBatchGroudNo() + "可利库支数少于"
//								+ actCount + "支!");
//						return core;
//					}
//
//					// 2.3生成炉次ID
//					int maxNum = Integer.parseInt(PlnHelper.getParam(con,
//							"FrmMaterialChoose.getMaxHeatPlanNoE",
//							new String[] { timeStr }, "HEAT_PLAN_NO"));// 炉号最大序号
//					String heatPlanNo = "E" + timeStr
//							+ String.format("%04d", maxNum);// 炉次ID
//
//					// 2.4 批量修改库存数据
//					List<Object[]> matNoList = new ArrayList<Object[]>();
//					double actWgt = 0;// 重量
//					for (int i = 0; i < matList.size(); i++) {
//						if (i >= actCount) {
//							break;
//						}
//						String[] strArr = new String[] { "80150103", proPlanId,
//								gxPlanNo, heatPlanNo, matList.get(i)[0] };
//						matNoList.add(strArr);
//						actWgt += Double.parseDouble(matList.get(i)[1]);
//					}
//					PlnHelper.batchDeleteOrUpdate(con,
//							"FrmMaterialChoose.updateMatE", matNoList);
//
//					// 2.5 生成虚拟炉计划
//					String strReadyPlanNo = "";
//					if (!map.containsKey(judgeStoveNo)) {
//						readyPlanNo++;
//						strReadyPlanNo = String.valueOf(readyPlanNo);
//						PlnZyDbkReadyEntity readyEntity = new PlnZyDbkReadyEntity();
//						BeanUtils.copyProperties(readyEntity, entity);
//						readyEntity.setIfMatchOdd("1");// 是否利库记录
//						readyEntity.setIfDoHeatPlan("1");// 是否已做正式炉计划
//						readyEntity.setRealAllotNum(String.valueOf(actCount));
//						readyEntity.setRealAllotWt(String.valueOf(actWgt));
//						readyEntity.setJudgeStoveNo(chEntity.getJudgeStoveNo());// 炉号
//						readyEntity.setReadyPlanNo(String.valueOf(readyPlanNo));// 预排序号
//						readyEntity.setAllotNum(String.valueOf(actCount));
//						readyEntity.setAllotWt(String.valueOf(actWgt));
//						map.put(judgeStoveNo, readyEntity);
//					} else {
//						PlnZyDbkReadyEntity readyEntity = map.get(judgeStoveNo);
//						strReadyPlanNo = readyEntity.getReadyPlanNo();
//						int num = Integer.parseInt(readyEntity.getAllotNum())
//								+ actCount;
//						double wgt = Double.parseDouble(readyEntity
//								.getAllotWt()) + actWgt;
//						int realNum = Integer.parseInt(readyEntity
//								.getRealAllotNum()) + actCount;
//						double realWgt = Double.parseDouble(readyEntity
//								.getRealAllotWt()) + actWgt;
//						readyEntity.setRealAllotNum(String.valueOf(realNum));
//						readyEntity.setRealAllotWt(String.valueOf(realWgt));
//						readyEntity.setAllotNum(String.valueOf(num));
//						readyEntity.setAllotWt(String.valueOf(wgt));
//						map.put(judgeStoveNo, readyEntity);
//					}
//
//					// 2.6 生成实际炉计划
//					PlnZyDbkMEntity zyEntity = new PlnZyDbkMEntity();
//					BeanUtils.copyProperties(zyEntity, entity);
//					zyEntity.setReadyPlanNo(strReadyPlanNo);// 预排序号
//					zyEntity.setHeatPlanNo(heatPlanNo);// 炉计划ID
//					zyEntity.setHeatnoLast(judgeStoveNo);// 炉号
//					zyEntity.setZgBatchNo(batchNo);// 批号
//					zyEntity.setBatchGroudNo(batchGroudNo);// 组号
//					zyEntity.setIfWlMatched("0");// 是否挂料确定
//					zyEntity.setInNum(String.valueOf(actCount));// 计划投入支数
//					zyEntity.setInWt(String.valueOf(actWgt));// 计划投入重量
//					// zyEntity.setOutNum(String.valueOf(actCount));// 计划产出支数
//					zyEntity.setAimlength(entity.getAimlength());// 长度
//					zyEntity.setAimoutdiameter(entity.getAimoutdiameter());// 外径
//					zyEntity.setAimwallthick(entity.getAimwallthick());// 壁厚
//					zyEntity.setLenCutend(entity.getLenCutend());// 切尾
//					zyEntity.setLenCuthead(entity.getLenCuthead());// 切头
//					zyEntity.setCreateName(userName);// 创建人
//					zyEntity.setPlanstatus("0");// 计划状态
//					zyEntity.setStorageNo1(chEntity.getStorageNo());
//					zyEntity.setStorageName1(chEntity.getStorageName());// 仓库
//					String proIndex = PlnHelper.getParam(con,
//							"FrmMaterialChoose.getProdIndexE",
//							new String[] { entity.getZyBatchId() },
//							"PROD_INDEX");//
//					zyEntity.setProdIndex(proIndex);// 批次生产序号
//					PlnHelper.addEntityData(con,
//							"FrmMaterialChoose.addZyDbkME", zyEntity);
//					sumNum += actCount;
//					sumWgt += actWgt;
//				}
//
//				// 新增虚拟炉计划
//				@SuppressWarnings("rawtypes")
//				Iterator iter = map.entrySet().iterator();
//				while (iter.hasNext()) {
//					@SuppressWarnings("rawtypes")
//					Map.Entry entry = (Map.Entry) iter.next();
//					PlnZyDbkReadyEntity readyEntity = (PlnZyDbkReadyEntity) entry
//							.getValue();
//					PlnHelper.addEntityData(con,
//							"FrmMaterialChoose.addZyDbkReadyE", readyEntity);
//				}
//
//				// 2.5修改排产数据
//				PlnHelper.deleteOrUpdate(con,
//						"FrmMaterialChoose.updatePlanDataE", new Object[] {
//								sumNum, sumWgt, sumNum, sumWgt, sumNum, sumWgt,
//								proPlanId, gxPlanNo });
//			}

			core.setResult(true);
			core.setV_errMsg("利库成功!");
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
                if (con != null) {
                    con.rollback();
                }
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
		return core;
	}

	/**
	 * 脱单
	 * 
	 * @param jsonList
	 * @param processCode
	 * @param userName
	 * @return
	 */
	public CoreReturnObject monomer(ArrayList<String> jsonList,
			String processCode, String userName) {
		CoreReturnObject core = new CoreReturnObject();
		core.setResult(false);
		Connection con = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// /镦拨扩
			List<MaterialChooseEntity> entityList = PlnHelper
					.jsonsToEntityList(MaterialChooseEntity.class, jsonList);
			if (processCode.equals("E")) {
				for (MaterialChooseEntity chEntity : entityList) {
					/**
					 * 1.验证订单
					 */
					String proPlanId = chEntity.getProPlanId();// 订单编号
					String gxPlanNo = chEntity.getGxPlanNo();// 排产序号
					String heatPlanNo = chEntity.getHeatPlanNo();// 炉号
					PlnOrderDbkSEntity entity = PlnHelper.getEntityData(con,
							new String[] { proPlanId, gxPlanNo },
							"ProducHelperBean.getPlanOrderE",
							" AND T.PRO_PLAN_ID = ?  AND T.GX_PLAN_NO = ?",
							PlnOrderDbkSEntity.class);
					if (entity == null) {
						core.setV_errMsg("订单编号(" + proPlanId + ")数据异常,请刷新数据!");
						return core;
					}
					if (entity.getIfStoveIssued().equals("1")) {
						core.setV_errMsg("订单编号(" + proPlanId + ")的炉计划已经下发!");
						return core;
					}
					/**
					 * 2.验证库存数据
					 */
					int actCount = Integer.parseInt(chEntity.getActCount());// 利库支数
					String judgeStoveNo = chEntity.getJudgeStoveNo();// 炉号
					String batchNo = chEntity.getBatchNo();// 批号
					String batchGroudNo = chEntity.getBatchGroudNo();// 组号
					// 2.1 查询库存数据
					List<String[]> matList = PlnHelper.getArrays(con,
							"FrmMaterialChoose.getMatNoByJudgeMonomerE",
							new String[] { chEntity.getMaterialNo(),
									judgeStoveNo, batchNo, batchGroudNo },
							new String[] { "MAT_NO", "ACT_WEIGHT" });

					// 2.2验证库存物料量是否足够
					if (matList.size() == 0 || matList.size() < actCount) {
						core.setV_errMsg("炉/批/组号 " + chEntity.getJudgeStoveNo()
								+ "/" + chEntity.getBatchNo() + "/"
								+ chEntity.getBatchGroudNo() + "可脱单支数少于"
								+ actCount + "支!");
						return core;
					}
					/**
					 * 3.脱单
					 */
					// 3.1 批量修改库存数据
					List<Object[]> matNoList = new ArrayList<Object[]>();
					double actWgt = 0;// 重量
					for (int i = 0; i < matList.size(); i++) {
						if (i >= actCount) {
							break;
						}
						String[] strArr = new String[] { "80150102", "", "",
								"", matList.get(i)[0] };
						matNoList.add(strArr);
						actWgt += Double.parseDouble(matList.get(i)[1]);
					}
					PlnHelper.batchDeleteOrUpdate(con,
							"FrmMaterialChoose.updateMatE", matNoList);

					// 3.2删除/修改虚拟炉计划
					List<String[]> arrList = PlnHelper.getArrays(con,
							"FrmMaterialChoose.queryDbkMByHeatPlanNo",
							new String[] { heatPlanNo }, new String[] {
									"PRO_PLAN_ID", "GX_PLAN_NO",
									"READY_PLAN_NO", "HEAT_PLAN_NO" });
					if (arrList != null) {
						String[] strArr = arrList.get(0);
						if (arrList.size() == 1) {
							PlnHelper.deleteOrUpdate(con,
									"FrmMaterialChoose.deleteReadyById",
									new Object[] { strArr[0], strArr[1],
											strArr[2] });
						} else {
							PlnHelper.deleteOrUpdate(con,
									"FrmMaterialChoose.updateReadyNum",
									new Object[] { actCount, actWgt, strArr[0],
											strArr[1], strArr[2] });
						}

					}
					// 3.3删除实际炉计划
					PlnHelper.deleteOrUpdate(con,
							"FrmMaterialChoose.deleteDbkMByHeatPlanNo",
							new String[] { heatPlanNo });

					// 2.5修改排产数据
					PlnHelper.deleteOrUpdate(con,
							"FrmMaterialChoose.updatePlanDataE", new Object[] {
									-actCount, -actWgt, -actCount, -actWgt,
									-actCount, -actWgt, proPlanId, gxPlanNo });

				}
			}
			core.setResult(true);
			core.setV_errMsg("脱单成功!");
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
                if (con != null) {
                    con.rollback();
                }
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
		return core;
	}
}
