package com.steering.mes.mcp.Mch;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.EntityTool;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.StringTool;
import com.steering.mes.mcp.Vrp.FrmVrpInStore;
import com.steering.mes.mcp.common.PlanService;
import com.steering.mes.mcp.entity.*;
import com.steering.mes.mcp.entity.MchEntity.PlnZyJgxCEntity;
import com.steering.mes.mcp.entity.MchEntity.PlnZyJgxMEntity;

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 java.util.Locale;

/**
 *加工上料实绩
 * 
 * @author szl
 * 
 */
public class FrmMcpLoading extends DBCommon {

	/**
	 * 根据计划号查询热处理上料实绩
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getLoadResult(String heatplanNo, String BatchNo) {
		return this.getDataBySqlID("FrmMcpLoading.GetLoadResultByID",
				new Object[] { heatplanNo, BatchNo });
	}

	/**
	 * 查询相同炉计划ID下实绩状态
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getQueryLoadingResult(String heatPlanNo,
			String plinCode) {
		// String sql =
		// CoreXmlSqlParsersFactory.getSql("FrmMcpLoading.getQueryLoadingResult");
		// sql += "AND T.HEAT_PLAN_NO='" + heatPlanNo + "'";
		// sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plinCode);
		// return this.getData(sql);
		return this.getDataBySqlID("FrmMcpLoading.getQueryLoadingResult",
				new Object[] { heatPlanNo, plinCode });
	}

	/**
	 * 获取服务器时间
	 */
	public CoreReturnObject getTime() {
		String sql = "";
		sql = CoreXmlSqlParsersFactory.getSql("FrmMcpLoading.getTime");
		return this.getData(sql);
	}

	/**
	 * 查询操作人员
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getPerson(String proBc, String plineName) {
		return this.getDataBySqlID("FrmMcpLoading.GetPerson", new Object[] {
				proBc, plineName });
	}

	/**
	 * 查询相同炉计划ID下的待上料支数的和
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getquerymaternum(String heatno, String BatchNo) {
		return this.getDataBySqlID("FrmMcpLoading.getquerymaternum",
				new Object[] { heatno, BatchNo });
	}

	/***
	 *输入上料支数带出重量
	 * 
	 * @param plan
	 * @return
	 */
	public CoreReturnObject getQueryWeight(String numb, String judNo,
			String batchNo, String groupNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmMcpLoading.getQueryWeight");
		return this.getData(sql, new Object[] { judNo, batchNo, groupNo,
				Integer.parseInt(numb) + 1 });
	}

	/**
	 * 查询上料实绩支数总和
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getLoadResult1(String heatNo) {
		return this.getDataBySqlID("FrmMcpLoading.GetQuery1",
				new Object[] { heatNo });
	}

	/**
	 * 查询计划排产支数总和
	 * 
	 * @param planNo
	 *            计划号
	 * @return
	 */
	public CoreReturnObject getqueryplan(String heatNo) {
		return this.getDataBySqlID("FrmMcpLoading.GetQueryplan",
				new Object[] { heatNo });
	}

	/***
	 * 查询是否是上料行
	 * 
	 * @param plan
	 * @return
	 */
	public CoreReturnObject getQueryOrderRCLS(String plineCode) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmMcpLoading.getQueryOrderRCLS");
		return this.getData(sql, new Object[] { plineCode, plineCode });
	}

	/***
	 * 查询是否存在上料之后的数据
	 * 
	 * @param plan
	 * @return
	 */
	public CoreReturnObject getQueryInfoPlan(String gx, String planNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmMcpLoading.getQueryInfoPlan");
		return this.getData(sql, new Object[] { gx, planNo });
	}

	public static String querySendOut(Connection conn, String strlist,
			String plineCode) throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");
		SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd");
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("HttLoadingService.queryOutList");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		psta.setString(2, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("OUTSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return seq;
	}

	public static String queryZcSendOut(Connection conn, String strlist,
			String plineCode) throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");
		SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd");
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("HttLoadingService.queryZcOutList");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		psta.setString(2, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("OUTSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return seq;
	}

	public static String querySendIn(Connection conn, String strlist)
			throws Exception {
		String seq = "";
		PreparedStatement psta = null;

		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("HttLoadingService.queryInList");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		psta.setString(2, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return seq;
	}

	public static String queryZcSendIn(Connection conn, String strlist)
			throws Exception {
		String seq = "";
		PreparedStatement psta = null;

		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("HttLoadingService.queryZcInList");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		psta.setString(2, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return seq;
	}

	/**
	 * 每支材料对应的出库流水号
	 * 
	 * @param conn
	 *            c
	 * @param strlist
	 *            出库单号
	 * @return obj
	 * @throws Exception
	 *             异常处理
	 */
	public static String querySendOutList(Connection conn, String strlist)
			throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("HttLoadingService.queryOut");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		psta.setString(2, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("OUTSTOCK_SQE");
		}
		rs.close();
		psta.close();
		return seq;
	}

	public CoreReturnObject DoUpdateFilePath(String HeatPlanNo,String FilePath) throws Exception {


		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();

		try {
			connection.setAutoCommit(false); //


			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DoUpdateFilePath");
			PreparedStatement pst = connection.prepareStatement(sql);
			pst.setObject(1, FilePath);
			pst.setObject(2, HeatPlanNo);
			pst.executeUpdate();
			pst.close();
			core.setV_errMsg("上传成功！");
			core.setResult(1);
			connection.commit();

		} catch (Exception e) {
			core.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return core;

	}

	public CoreReturnObject DoUpdateFilePath2(String HeatPlanNo,String FilePath) throws Exception {


		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();

		try {
			connection.setAutoCommit(false); //


			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DoUpdateFilePath2");
			PreparedStatement pst = connection.prepareStatement(sql);
			pst.setObject(1, FilePath);
			pst.setObject(2, HeatPlanNo);
			pst.executeUpdate();
			pst.close();
			core.setV_errMsg("上传成功！");
			core.setResult(1);
			connection.commit();

		} catch (Exception e) {
			core.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return core;

	}

	public CoreReturnObject DoAdd(String HeatPlanNo, String Sqe1, String load,
			String gx, ArrayList<String> ScrappedList,
			ArrayList<String> SuspiciousList) {
		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		 //  TZH 24.4.24 注销物流接口
//		Connection connection2 = this.getDao("TmsDao").getConnection();
		PreparedStatement psta = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMdd",
				Locale.CHINA);
		SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMM",
				Locale.CHINA);
		String systime = dateFormat.format(now);
		String BalYearMothDay = dateFormat1.format(now);
		String BalYearMoth = ""; //改25号结转

		try {
			connection.setAutoCommit(false); //
			 //  TZH 24.4.24 注销物流接口
//			connection2.setAutoCommit(false); // 取消自动提交事务
			String addport = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddPortNew");// 新增管号队列
			PreparedStatement patsport = connection.prepareStatement(addport);

			String addOut = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddOutList");// 新增出库记录
			PreparedStatement patsAddOut = connection.prepareStatement(addOut);
			String addOutlist = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddOutListQuan");// 新增产权出库
			PreparedStatement patsAddOutlist = connection
					.prepareStatement(addOutlist);

			String sqlAdd = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddLoadResult");// 新增上料实绩
			PreparedStatement patAdd = connection.prepareStatement(sqlAdd);
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updatePlnZyRclM");// 修改加工计划表从表的实际上料支吨
			PreparedStatement patupdate = connection
					.prepareStatement(sqlupdate);

			String sqlupdate2 = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updatePlnZyRclM2");// 修改加工计划表从表的实际上料支吨
			PreparedStatement patupdate2 = connection
					.prepareStatement(sqlupdate2);

			String sqlupdatepln = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updatePlnZyRclMpln");// 修改加工计划表
			PreparedStatement patupdatepln = connection
					.prepareStatement(sqlupdatepln);
			String addPlnInfo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddComInfoResult");// 新增公共信息
			PreparedStatement patsPlan = connection
					.prepareStatement(addPlnInfo);
			String deleteButt = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteButter");// 删除位置表
			PreparedStatement patsButt = connection
					.prepareStatement(deleteButt);
			String updateMat = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updateMatZcPlan");// 修改库存状态
			PreparedStatement patsUpMat = connection
					.prepareStatement(updateMat);

			String updatePath = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.UpdatePath");// 修改队列表工艺路径
			PreparedStatement pastupdatePath = connection
					.prepareStatement(updatePath);

			String deleteMat = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.CopyBcMat");// 复制物料主表到MAT_BC_BACKUP表
			PreparedStatement patsMat = connection.prepareStatement(deleteMat);
			String deteleBcMat = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeteleBcMat");// 删除物料主表
			PreparedStatement deteleBcMatPath = connection
					.prepareStatement(deteleBcMat);
			String addPlnInfo1 = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddComInfoResult1");// 修改队列表材料，工序状态
			PreparedStatement patsPlan1 = connection
					.prepareStatement(addPlnInfo1);

			String InsertIntoOrderGroupNo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.InsertIntoOrderGroupNo");// 修改队列表材料，工序状态
			PreparedStatement patsInsertIntoOrderGroupNo = connection
					.prepareStatement(InsertIntoOrderGroupNo);

			// 获取加工计划实体了
			PlnZyJgxMEntity pln = PlanService.getSendHttPlanCInfo3(connection,
					HeatPlanNo);
			BalYearMoth = com.steering.common.StringTool.GetBalYear(com.steering.common.StringTool.GetSupplyUnit(pln.getPlineCode())); //改25号结转

			/*
			 * // 获取加工计划实体了 PlnZyJgxCEntity plnC =
			 * PlanService.getSendHttPlanCInfo3C(connection, HeatPlanNo,Sqe);
			 */

			MchLoadingResultEntity Result = EntityTool.getEntityByJSONStr(load,
					MchLoadingResultEntity.class);

			// region 检查
			if (pln == null) {
				core.setV_errMsg("找不到炉计划数据！");
				return core;
			}

			// 计划关闭 或计划完成 继续上料 清除结炉状态
			if (pln.getPlanstatus().equals("40")
					|| pln.getPlanstatus().equals("30")) {

				String sql = CoreXmlSqlParsersFactory
						.getSql("FrmMcpLoading.CancelNodeFlag");
				sql = EntityTool.fillSqlByEntity(sql, Result);
				psta = connection.prepareStatement(sql);
				psta.executeUpdate();
				psta.close();

			} else if (!pln.getPlanstatus().equals("10")
					&& !pln.getPlanstatus().equals("20")) {
				core.setV_errMsg("炉计划不处于下发或生产中状态！");
				return core;
			}

			String cutFalg = "";
			String sql = CoreXmlSqlParsersFactory
					.getSql("MchComm.queryComInfo");// 查询 工序是否是结炉状态
			psta = connection.prepareStatement(sql);
			psta.setString(1, HeatPlanNo);
			psta.setString(2, Result.getBatchNo());
			psta.setString(3, gx);
			ResultSet rs = psta.executeQuery();
			if (rs.next()) {
				cutFalg = rs.getString("STATION_STATUS");
			}

			if (cutFalg.equals("2")) {
				core.setV_errMsg("已结炉,不允许此操作！");
				return core;
			}
			rs.close();
			psta.close();
			// endregion

			String resultNo = "";
			int count = 0;
			int detCount = 0;
			double wt = 0d;

			if (StringTool.isInteger(Result.getFailNum())) {
				detCount = Integer.parseInt(Result.getFailNum());
			}
			if (StringTool.isInteger(Result.getProNum())) {
				count = Integer.parseInt(Result.getProNum());
			}
			if (StringTool.isDouble(Result.getProWt())) {
				wt = Double.parseDouble(Result.getProWt());
			}

			if (StringTool.isInteger(Result.getProWt())) {
				wt = Double.parseDouble(Result.getProWt());
			}

			if (count <= 0) {
				core.setV_errMsg("请输入正确的上料支！");
				return core;
			}

			if (wt <= 0.000001) {
				core.setV_errMsg("上料重量异常,,请重新查询再上料！");
				return core;
			}

			if (count < detCount) {
				core.setV_errMsg("废品支数不能大于上料支！");
				return core;
			}

			// 获取最大实绩编号
			sql = CoreXmlSqlParsersFactory
					.getSql("MchComm.queryLoadNewResultNo");
			psta = connection.prepareStatement(sql);
			psta.setObject(1, pln.getPlineCode() + gx);
			psta.setObject(2, pln.getPlineCode() + gx);
			ResultSet rs1 = psta.executeQuery();
			if (rs1.next()) {
				resultNo = rs1.getString("RESULT_NO");
			}
			rs1.close();
			psta.close();

			String StorageNo = PlanService.GetStorageIn(pln.getPlineCode(),
					connection);

			String sqlMatNo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.queryMatZc");// 查询新增物料信息
			psta = connection.prepareStatement(sqlMatNo);
			psta.setObject(1, pln.getHeatPlanNo());
			psta.setObject(2, Result.getBatchNo());
			psta.setObject(3, Result.getBatchGroudNo());
			psta.setObject(4, StorageNo);
			psta.setObject(5, count + 1);
			rs = psta.executeQuery();
			List<MatBcMEntity> listMat = EntityTool.getEntitysByRs(rs,
					MatBcMEntity.class);
			rs.close();
			psta.close();

			if (listMat.size() != count) {
				core.setV_errMsg("无足够的库存！");
				return core;
			}

			String sendOut = querySendOut(connection, "800801", pln
					.getPlineCode());
			// 获取出库流水号
			String butessMatNo = querySendOutList(connection, sendOut);
			int outNo = Integer.parseInt(butessMatNo.substring(butessMatNo
					.length() - 4, butessMatNo.length()));

			String sendOutlist = querySendOut(connection, "800809", pln
					.getPlineCode());
			// 获取出库流水号
			String butessMatNolist = querySendOutList(connection, sendOutlist);
			int outNolist = Integer.parseInt(butessMatNolist.substring(
					butessMatNolist.length() - 4, butessMatNolist.length()));

			List<PlnZyJgxCEntity> plnCs = PlanService.getSendHttPlanCInfo3C(
					connection, HeatPlanNo, Result.getBatchNo(), Result
							.getBatchGroudNo());

			if (pln.getSiglLen().equals("")
					|| Double.parseDouble(pln.getSiglLen()) < 0.0001) {

				String sqlGroup = CoreXmlSqlParsersFactory
						.getSql("FrmMcpLoading.queryOrderGroupNo");//
				psta = connection.prepareStatement(sqlGroup);
				psta.setObject(1, pln.getOrderNo() + "/" + pln.getOrderSeq());
				rs = psta.executeQuery();
				if (!rs.next()) {

					patsInsertIntoOrderGroupNo.setObject(1, pln.getOrderNo()
							+ "/" + pln.getOrderSeq());
					patsInsertIntoOrderGroupNo.setObject(2, pln.getLengthmax());
					patsInsertIntoOrderGroupNo.setObject(3, pln.getLengthmin());
					patsInsertIntoOrderGroupNo.setObject(4, "001");
					patsInsertIntoOrderGroupNo.setObject(5, "<=");
					patsInsertIntoOrderGroupNo.setObject(6, ">=");
					patsInsertIntoOrderGroupNo.addBatch();

					if (pln.getLengthdisc().trim().equals("R1")) {
						patsInsertIntoOrderGroupNo.setObject(1, pln
								.getOrderNo()
								+ "/" + pln.getOrderSeq());
						patsInsertIntoOrderGroupNo.setObject(2, pln
								.getLengthmin());
						patsInsertIntoOrderGroupNo.setObject(3, "4.88");
						patsInsertIntoOrderGroupNo.setObject(4, "002");
						patsInsertIntoOrderGroupNo.setObject(5, "<");
						patsInsertIntoOrderGroupNo.setObject(6, ">=");
						patsInsertIntoOrderGroupNo.addBatch();
					} else if (pln.getLengthdisc().trim().equals("R2")) {
						patsInsertIntoOrderGroupNo.setObject(1, pln
								.getOrderNo()
								+ "/" + pln.getOrderSeq());
						patsInsertIntoOrderGroupNo.setObject(2, pln
								.getLengthmin());
						patsInsertIntoOrderGroupNo.setObject(3, "7.62");
						patsInsertIntoOrderGroupNo.setObject(4, "002");
						patsInsertIntoOrderGroupNo.setObject(5, "<");
						patsInsertIntoOrderGroupNo.setObject(6, ">=");
						patsInsertIntoOrderGroupNo.addBatch();
					} else if (pln.getLengthdisc().trim().equals("R3")) {
						patsInsertIntoOrderGroupNo.setObject(1, pln
								.getOrderNo()
								+ "/" + pln.getOrderSeq());
						patsInsertIntoOrderGroupNo.setObject(2, pln
								.getLengthmin());
						patsInsertIntoOrderGroupNo.setObject(3, "10.36");
						patsInsertIntoOrderGroupNo.setObject(4, "002");
						patsInsertIntoOrderGroupNo.setObject(5, "<");
						patsInsertIntoOrderGroupNo.setObject(6, ">=");
						patsInsertIntoOrderGroupNo.addBatch();
					} else if (!pln.getShortest().equals("")) {
						patsInsertIntoOrderGroupNo.setObject(1, pln
								.getOrderNo()
								+ "/" + pln.getOrderSeq());
						patsInsertIntoOrderGroupNo.setObject(2, pln
								.getLengthmin());
						patsInsertIntoOrderGroupNo.setObject(3, pln
								.getShortest());
						patsInsertIntoOrderGroupNo.setObject(4, "002");
						patsInsertIntoOrderGroupNo.setObject(5, "<");
						patsInsertIntoOrderGroupNo.setObject(6, ">=");
						patsInsertIntoOrderGroupNo.addBatch();
					}

					patsInsertIntoOrderGroupNo.executeBatch();
				}
				rs.close();
				psta.close();

			}

			Integer UsedNum = 0;
			Double UsedWt = 0d;
			Double TWt = 0d;
			Integer CurrentCount = 0;
			PlnZyJgxCEntity CurrentJgxC = plnCs.get(CurrentCount);
			Integer CanLoadNum = Integer.parseInt(CurrentJgxC
					.getPlanIndoubleNum().equals("") ? "0" : CurrentJgxC
					.getPlanIndoubleNum())
					- Integer.parseInt(CurrentJgxC.getRealIndoubleNum().equals(
							"") ? "0" : CurrentJgxC.getRealIndoubleNum());
			Double CanLoadWt = Double.parseDouble(CurrentJgxC
					.getPlanIndoubleWt().equals("") ? "0" : CurrentJgxC
					.getPlanIndoubleWt())
					- Double
							.parseDouble(CurrentJgxC.getRealIndoubleWt()
									.equals("") ? "0" : CurrentJgxC
									.getRealIndoubleWt());

			int CountInstorage = 0;

			for (MatBcMEntity lvMat : listMat) {

				/*if (!"002023005".equals(lvMat.getBelongCode())
						&& "C092".equals(pln.getPlineCode())) {
					core.setV_errMsg("管所属权不属于天淮,不允许上料！清确认管是否倒运至天淮！");
					return core;
				}*/

				if (lvMat.getStorageNo().equals("")) {
					core.setV_errMsg("库存正在倒运中,无法上料!");
					return core;
				}

				if (!lvMat.getStorageNo().equals(StorageNo)) {
					if (pln.getIsLoadFlag().equals("1")) {

						String deleteYdmBack = CoreXmlSqlParsersFactory
								.getSql("FrmMcpLoading.deleteYdmBack");//
						PreparedStatement patsdeleteYdmBack = connection
								.prepareStatement(deleteYdmBack);

						patsdeleteYdmBack.setObject(1, pln.getPlineCode());
						patsdeleteYdmBack.setObject(2, lvMat.getMatNo());
						patsdeleteYdmBack.executeUpdate();
						patsdeleteYdmBack.close();

						// 上料炉号和判定炉号不一致 改成保存判定炉号的位置信息
						String insertYdmBack = CoreXmlSqlParsersFactory
								.getSql("FrmMcpLoading.insertYdmBack");//
						PreparedStatement patsinsertYdmBack = connection
								.prepareStatement(insertYdmBack);
						patsinsertYdmBack.setObject(1, pln.getPlineCode());
						patsinsertYdmBack.setObject(2, lvMat.getMatNo());
						patsinsertYdmBack.executeUpdate();
						patsinsertYdmBack.close();

					} else {

						if (CountInstorage == 0) {
							core.setV_errMsg("库存未在投料库,无法上料");
							return core;
						} else {
							core.setV_errMsg("只有" + CountInstorage
									+ "支在投料库 ,无法上足" + count + "支");
							return core;
						}
					}

				}
				CountInstorage++;

				if ("1".equals(lvMat.getLockFlag())) {
					core.setV_errMsg("库存存在质量封锁料,无法上足" + count + "支");
					return core;
				}

				if ("1".equals(lvMat.getMngLockFlag())) {
					core.setV_errMsg("库存存在管理封锁料,无法上足" + count + "支");
					return core;
				}

				while (UsedNum >= CanLoadNum) {
					patupdate.setObject(1, UsedNum);
					patupdate.setObject(2, UsedWt);
					patupdate.setObject(3, pln.getHeatPlanNo());
					patupdate.setObject(4, CurrentJgxC.getHeatPlanSqe());
					patupdate.addBatch();

					CurrentCount++;

					if (CurrentCount >= plnCs.size()) {
						core.setV_errMsg("上料支超过排产支！");
						return core;
					}

					CurrentJgxC = plnCs.get(CurrentCount);
					CanLoadNum = Integer.parseInt(CurrentJgxC
							.getPlanIndoubleNum().equals("") ? "0"
							: CurrentJgxC.getPlanIndoubleNum())
							- Integer.parseInt(CurrentJgxC.getRealIndoubleNum()
									.equals("") ? "0" : CurrentJgxC
									.getRealIndoubleNum());

					UsedNum = 0;
					UsedWt = 0d;
				}

				patsport.setObject(1, Result.getCreatetUser());
				patsport.setObject(2, Result.getLoadShift());
				patsport.setObject(3, Result.getLoadGroup());
				patsport.setObject(4, pln.getFeedHeatNo());
				patsport.setObject(5, CurrentJgxC.getHeatPlanSqe());
				patsport.setObject(6, BalYearMothDay);
				patsport.setObject(7, BalYearMoth);
				patsport.setObject(8, lvMat.getMatNo());
				patsport.setObject(9, pln.getHeatPlanNo());
				patsport.addBatch();

				UsedNum++;
				UsedWt = UsedWt + Double.parseDouble(lvMat.getActWeight());
				TWt = TWt + Double.parseDouble(lvMat.getActWeight());

				// 新增出库表
				patsAddOut.setObject(1, sendOut
						+ StringTool.formatDecimal(outNo, "0000"));
				patsAddOut.setObject(2, HeatPlanNo);
				patsAddOut.setObject(3, sendOut);
				patsAddOut.setObject(4, "800801");
				patsAddOut.setObject(5, "投料出库");
				patsAddOut.setObject(6, lvMat.getMatNo());
				patsAddOut.setObject(7, lvMat.getJudgeStoveNo());
				patsAddOut.setObject(8, lvMat.getBatchNo());
				patsAddOut.setObject(9, lvMat.getBatchGroudNo());
				patsAddOut.setObject(10, lvMat.getMaterialNo());
				patsAddOut.setObject(11, lvMat.getMaterialName());
				patsAddOut.setObject(12, lvMat.getProduccode());
				patsAddOut.setObject(13, lvMat.getProducname());
				patsAddOut.setObject(14, lvMat.getStdCode());
				patsAddOut.setObject(15, lvMat.getStdName());
				patsAddOut.setObject(16, lvMat.getGradecode());
				patsAddOut.setObject(17, lvMat.getGradename());
				patsAddOut.setObject(18, lvMat.getSteelcode());
				patsAddOut.setObject(19, lvMat.getSteelname());
				patsAddOut.setObject(20, lvMat.getStdStyle());
				patsAddOut.setObject(21, lvMat.getStdStyleDesc());
				patsAddOut.setObject(22, lvMat.getSpecCode());
				patsAddOut.setObject(23, lvMat.getSpecName());
				patsAddOut.setObject(24, lvMat.getModelCode());
				patsAddOut.setObject(25, lvMat.getModelDesc());
				patsAddOut.setObject(26, (lvMat.getPlineCode().equals("100101")
						|| lvMat.getPlineCode().equals("100102") || lvMat
						.getPlineCode().equals("100103")) ? (lvMat
						.getProcessCdoe().equals("D") ? "C008" : lvMat
						.getProcessCdoe().equals("E") ? "C013" : lvMat
						.getProcessCdoe().equals("F") ? "C022" : lvMat
						.getProcessCdoe().equals("G") ? "C028" : "C041")
						: lvMat.getPlineCode());
				patsAddOut.setObject(27, (lvMat.getPlineCode().equals("100101")
						|| lvMat.getPlineCode().equals("100102") || lvMat
						.getPlineCode().equals("100103")) ? (lvMat
						.getProcessCdoe().equals("D") ? "250机组" : lvMat
						.getProcessCdoe().equals("E") ? "冷轧机组" : lvMat
						.getProcessCdoe().equals("F") ? "热处理01#（管加工1号热）"
						: lvMat.getProcessCdoe().equals("G") ? "加工线01#（管加工1#线）"
								: "接箍1（美国PMC1077）") : lvMat.getPlineName());
				patsAddOut.setObject(28, lvMat.getActDimater());
				patsAddOut.setObject(29, lvMat.getActHeight());
				patsAddOut.setObject(30, String.valueOf(lvMat.getActLen()));
				patsAddOut.setObject(31, lvMat.getActLenMin());
				patsAddOut.setObject(32, lvMat.getActLenMax());
				patsAddOut.setObject(33, String.valueOf(lvMat.getActCount()));
				patsAddOut.setObject(34, String.valueOf(lvMat.getActWeight()));
				patsAddOut.setObject(35, String.valueOf(lvMat
						.getActTheoryWeight()));
				patsAddOut.setObject(36, lvMat.getBelongCode());
				patsAddOut.setObject(37, lvMat.getBelongName());
				patsAddOut.setObject(38, lvMat.getStorageNo());
				patsAddOut.setObject(39, lvMat.getLocationNo());
				patsAddOut.setObject(40, lvMat.getLaryNo());
				patsAddOut.setObject(41, lvMat.getLocNo());
				patsAddOut.setObject(42, lvMat.getStorageAttr());
				patsAddOut.setObject(43, lvMat.getStorageAttrName());
				patsAddOut.setObject(44, lvMat.getStorageTypeNo());
				patsAddOut.setObject(45, lvMat.getStorageTypeName());
				patsAddOut.setObject(46, lvMat.getManagementNo());
				patsAddOut.setObject(47, lvMat.getManagementName());
				patsAddOut.setObject(48, systime);
				patsAddOut.setObject(49, lvMat.getProBc());
				patsAddOut.setObject(50, lvMat.getProBz());
				patsAddOut.setObject(51, systime);
				patsAddOut.setObject(52, Result.getLoadShift());
				patsAddOut.setObject(53, Result.getLoadGroup());
				patsAddOut.setObject(54, Result.getCreatetUser());
				patsAddOut.setObject(55, systime);
				patsAddOut.setObject(56, lvMat.getOrdPk());
				patsAddOut.setObject(57, lvMat.getOrdLnPk());
				patsAddOut.setObject(58, lvMat.getOrdLnDlyPk());
				patsAddOut.setObject(59, lvMat.getDepartmentCode());
				patsAddOut.setObject(60, lvMat.getDepartmentDesc());
				patsAddOut.setObject(61, lvMat.getOrderNo());
				patsAddOut.setObject(62, lvMat.getOrderSeq());
				patsAddOut.setObject(63, pln.getDeliveryNo());
				patsAddOut.setObject(64, "801401");
				patsAddOut.setObject(65, "80150105");
				patsAddOut.setObject(66, lvMat.getJudgeStdCode());
				patsAddOut.setObject(67, lvMat.getJudgeStdName());
				patsAddOut.setObject(68, pln.getZyBatchId());
				patsAddOut.setObject(69, lvMat.getStoveNo());
				patsAddOut.setObject(70, Result.getPlineCode());
				patsAddOut.setObject(71, Result.getPlineCode());
				patsAddOut.setObject(72, pln.getOrderNo() + "/"
						+ pln.getOrderSeq());
				patsAddOut.setObject(73, BalYearMoth);
				patsAddOut.setObject(74, lvMat.getProcessCdoe());
				patsAddOut.setObject(75, lvMat.getProcessDesc());
				patsAddOut.addBatch();
				outNo++;

				// 新增产权出库
				patsAddOutlist.setObject(1, sendOutlist
						+ StringTool.formatDecimal(outNolist, "0000"));
				patsAddOutlist.setObject(2, HeatPlanNo);
				patsAddOutlist.setObject(3, sendOutlist);
				patsAddOutlist.setObject(4, "800809");
				patsAddOutlist.setObject(5, "产权出库");
				patsAddOutlist.setObject(6, lvMat.getMatNo());
				patsAddOutlist.setObject(7, lvMat.getJudgeStoveNo());
				patsAddOutlist.setObject(8, lvMat.getBatchNo());
				patsAddOutlist.setObject(9, lvMat.getBatchGroudNo());
				patsAddOutlist.setObject(10, lvMat.getMaterialNo());
				patsAddOutlist.setObject(11, lvMat.getMaterialName());
				patsAddOutlist.setObject(12, lvMat.getProduccode());
				patsAddOutlist.setObject(13, lvMat.getProducname());
				patsAddOutlist.setObject(14, lvMat.getStdCode());
				patsAddOutlist.setObject(15, lvMat.getStdName());
				patsAddOutlist.setObject(16, lvMat.getGradecode());
				patsAddOutlist.setObject(17, lvMat.getGradename());
				patsAddOutlist.setObject(18, lvMat.getSteelcode());
				patsAddOutlist.setObject(19, lvMat.getSteelname());
				patsAddOutlist.setObject(20, lvMat.getStdStyle());
				patsAddOutlist.setObject(21, lvMat.getStdStyleDesc());
				patsAddOutlist.setObject(22, lvMat.getSpecCode());
				patsAddOutlist.setObject(23, lvMat.getSpecName());
				patsAddOutlist.setObject(24, lvMat.getModelCode());
				patsAddOutlist.setObject(25, lvMat.getModelDesc());
				patsAddOutlist.setObject(26, (lvMat.getPlineCode().equals(
						"100101")
						|| lvMat.getPlineCode().equals("100102") || lvMat
						.getPlineCode().equals("100103")) ? (lvMat
						.getProcessCdoe().equals("D") ? "C008" : lvMat
						.getProcessCdoe().equals("E") ? "C013" : lvMat
						.getProcessCdoe().equals("F") ? "C022" : lvMat
						.getProcessCdoe().equals("G") ? "C028" : "C041")
						: lvMat.getPlineCode());
				patsAddOutlist.setObject(27, (lvMat.getPlineCode().equals(
						"100101")
						|| lvMat.getPlineCode().equals("100102") || lvMat
						.getPlineCode().equals("100103")) ? (lvMat
						.getProcessCdoe().equals("D") ? "250机组" : lvMat
						.getProcessCdoe().equals("E") ? "冷轧机组" : lvMat
						.getProcessCdoe().equals("F") ? "热处理01#（管加工1号热）"
						: lvMat.getProcessCdoe().equals("G") ? "加工线01#（管加工1#线）"
								: "接箍1（美国PMC1077）") : lvMat.getPlineName());
				patsAddOutlist.setObject(28, lvMat.getActDimater());
				patsAddOutlist.setObject(29, lvMat.getActHeight());
				patsAddOutlist.setObject(30, String.valueOf(lvMat.getActLen()));
				patsAddOutlist.setObject(31, lvMat.getActLenMin());
				patsAddOutlist.setObject(32, lvMat.getActLenMax());
				patsAddOutlist.setObject(33, String
						.valueOf(lvMat.getActCount()));
				patsAddOutlist.setObject(34, String.valueOf(lvMat
						.getActWeight()));
				patsAddOutlist.setObject(35, String.valueOf(lvMat
						.getActTheoryWeight()));
				patsAddOutlist.setObject(36, lvMat.getBelongCode());
				patsAddOutlist.setObject(37, lvMat.getBelongName());
				patsAddOutlist.setObject(38, lvMat.getStorageNo());
				patsAddOutlist.setObject(39, lvMat.getLocationNo());
				patsAddOutlist.setObject(40, lvMat.getLaryNo());
				patsAddOutlist.setObject(41, lvMat.getLocNo());
				patsAddOutlist.setObject(42, lvMat.getStorageAttr());
				patsAddOutlist.setObject(43, lvMat.getStorageAttrName());
				patsAddOutlist.setObject(44, lvMat.getStorageTypeNo());
				patsAddOutlist.setObject(45, lvMat.getStorageTypeName());
				patsAddOutlist.setObject(46, lvMat.getManagementNo());
				patsAddOutlist.setObject(47, lvMat.getManagementName());
				patsAddOutlist.setObject(48, systime);
				patsAddOutlist.setObject(49, lvMat.getProBc());
				patsAddOutlist.setObject(50, lvMat.getProBz());
				patsAddOutlist.setObject(51, systime);
				patsAddOutlist.setObject(52, Result.getLoadShift());
				patsAddOutlist.setObject(53, Result.getLoadGroup());
				patsAddOutlist.setObject(54, Result.getCreatetUser());
				patsAddOutlist.setObject(55, systime);
				patsAddOutlist.setObject(56, lvMat.getOrdPk());
				patsAddOutlist.setObject(57, lvMat.getOrdLnPk());
				patsAddOutlist.setObject(58, lvMat.getOrdLnDlyPk());
				patsAddOutlist.setObject(59, lvMat.getDepartmentCode());
				patsAddOutlist.setObject(60, lvMat.getDepartmentDesc());
				patsAddOutlist.setObject(61, lvMat.getOrderNo());
				patsAddOutlist.setObject(62, lvMat.getOrderSeq());
				patsAddOutlist.setObject(63, pln.getDeliveryNo());
				patsAddOutlist.setObject(64, "801401");
				patsAddOutlist.setObject(65, "80150105");
				patsAddOutlist.setObject(66, lvMat.getJudgeStdCode());
				patsAddOutlist.setObject(67, lvMat.getJudgeStdName());
				patsAddOutlist.setObject(68, pln.getZyBatchId());
				patsAddOutlist.setObject(69, lvMat.getStoveNo());
				patsAddOutlist.setObject(70, Result.getPlineCode());
				patsAddOutlist.setObject(71, Result.getPlineCode());
				patsAddOutlist.setObject(72, pln.getOrderNo() + "/"
						+ pln.getOrderSeq());
				patsAddOutlist.setObject(73, BalYearMoth);
				patsAddOutlist.setObject(74, lvMat.getProcessCdoe());
				patsAddOutlist.setObject(75, lvMat.getProcessDesc());
				if (!pln.getIfMatchOdd().equals("6"))
					patsAddOutlist.addBatch();

				outNolist++;
				// 修改库存状态
				patsUpMat.setObject(1, "80150105");
				patsUpMat.setObject(2, lvMat.getMatNo());
				patsUpMat.addBatch();
				// 删除位置表
				patsButt.setObject(1, lvMat.getMatNo());
				patsButt.addBatch();
				// 把物料主表复制到List表
				patsMat.setObject(1, lvMat.getMatNo());
				patsMat.addBatch();
				// 删除物料主表
				deteleBcMatPath.setObject(1, lvMat.getMatNo());
				deteleBcMatPath.addBatch();
			}

			patupdate.setObject(1, UsedNum);
			patupdate.setObject(2, UsedWt);
			patupdate.setObject(3, pln.getHeatPlanNo());
			patupdate.setObject(4, CurrentJgxC.getHeatPlanSqe());
			patupdate.addBatch();

			patsport.executeBatch();
			patsAddOut.executeBatch();
			patsAddOutlist.executeBatch();
			patsUpMat.executeBatch();
			patsButt.executeBatch();
			patsMat.executeBatch();
			deteleBcMatPath.executeBatch();

			Result.setOutstockDoc(sendOut);

			// 新增上料实绩
			patAdd.setObject(1, resultNo);
			patAdd.setObject(2, Result.getZyBatchId());
			patAdd.setObject(3, pln.getProPlanId());
			patAdd.setObject(4, pln.getGxPlanNo());
			patAdd.setObject(5, Result.getProNum());
			patAdd.setObject(6, TWt);
			patAdd.setObject(7, Result.getFailNum());
			patAdd.setObject(8, Result.getFailWt());
			patAdd.setObject(9, "");
			patAdd.setObject(10, "");
			patAdd.setObject(11, "");
			patAdd.setObject(12, "");
			patAdd.setObject(13, Result.getLoadTime());
			patAdd.setObject(14, Result.getLoadShift());
			patAdd.setObject(15, Result.getLoadGroup());
			patAdd.setObject(16, "1");
			patAdd.setObject(17, Result.getPlineCode());
			patAdd.setObject(18, Result.getPlineName());
			patAdd.setObject(19, Result.getHeatPlanNo());
			patAdd.setObject(20, systime);
			patAdd.setObject(21, Result.getProducer());
			if (Result.getProducer().equals("")) {
				patAdd.setObject(22, "");
			} else {
				patAdd.setObject(22, Result.getProducerTime());
			}
			patAdd.setObject(23, Result.getCreatetUser());
			patAdd.setObject(24, Result.getOutnumCut());
			patAdd.setObject(25, Result.getLengthIn());
			patAdd.setObject(26, Result.getLengthmaxIn());
			patAdd.setObject(27, Result.getLengthminIn());
			patAdd.setObject(28, sendOut);
			patAdd.setObject(29, Result.getJudgeStoveNo());
			patAdd.setObject(30, Result.getBatchNo());
			patAdd.setObject(31, Result.getBatchGroudNo());
			patAdd.setObject(32, Result.getHeatPlanSqe());
			patAdd.setObject(33, Result.getMatSource());
			patAdd.setObject(34, BalYearMothDay);
			patAdd.setObject(35, BalYearMoth);
			patAdd.addBatch();

			// 新增加工公共信息
			patsPlan.setObject(1, resultNo);
			patsPlan.setObject(2, pln.getZyBatchId());
			patsPlan.setObject(3, "");
			patsPlan.setObject(4, pln.getProPlanId());
			patsPlan.setObject(5, pln.getGxPlanNo());
			patsPlan.setObject(6, pln.getOrderSource());
			patsPlan.setObject(7, pln.getOrderNo());
			patsPlan.setObject(8, pln.getOrderSeq());
			patsPlan.setObject(9, pln.getReqBlId());
			patsPlan.setObject(10, pln.getPlineCode());
			patsPlan.setObject(11, pln.getPlineName());
			patsPlan.setObject(12, gx);
			patsPlan.setObject(13, gx);
			patsPlan.setObject(14, "");
			patsPlan.setObject(15, "");
			patsPlan.setObject(16, pln.getSteelcode());
			patsPlan.setObject(17, pln.getSteelname());
			patsPlan.setObject(18, pln.getOutdiameter());
			patsPlan.setObject(19, pln.getWallthick());
			patsPlan.setObject(20, "");
			patsPlan.setObject(21, "");
			patsPlan.setObject(22, "");
			patsPlan.setObject(23, "");
			patsPlan.setObject(24, "");
			patsPlan.setObject(25, "");
			patsPlan.setObject(26, "");
			patsPlan.setObject(27, "");
			patsPlan.setObject(28, pln.getOutwlId());
			patsPlan.setObject(29, pln.getOutwlDesc());
			patsPlan.setObject(30, pln.getInwlId());
			patsPlan.setObject(31, pln.getInwlDesc());
			patsPlan.setObject(32, pln.getMonitorPoint());
			patsPlan.setObject(33, Result.getIfMonitorRcl());
			patsPlan.setObject(34, pln.getPrdcrNo());
			patsPlan.setObject(35, Result.getProducer());
			if (Result.getProducer().equals("")) {
				patsPlan.setObject(36, "");
			} else {
				patsPlan.setObject(36, Result.getProducerTime());
			}
			patsPlan.setObject(37, pln.getStationRoad());
			patsPlan.setObject(38, pln.getCraftFileNo());
			patsPlan.setObject(39, pln.getCraftFileMan());
			patsPlan.setObject(40, pln.getCraftSeq());
			patsPlan.setObject(41, Result.getProNum());
			patsPlan.setObject(42, TWt);
			patsPlan.setObject(43, Result.getFailNum());
			patsPlan.setObject(44, Result.getFailWt());
			patsPlan.setObject(45, Result.getOfflineNum());
			patsPlan.setObject(46, Result.getOfflineWt());
			patsPlan.setObject(47, Result.getReNum());
			patsPlan.setObject(48, Result.getReWt());
			patsPlan.setObject(49, "1");
			patsPlan.setObject(50, Result.getLoadTime());
			patsPlan.setObject(51, "");
			patsPlan.setObject(52, Result.getLoadShift());
			patsPlan.setObject(53, Result.getLoadGroup());
			patsPlan.setObject(54, "1");
			patsPlan.setObject(55, Result.getCreateTime());
			patsPlan.setObject(56, Result.getCreatetUser());
			patsPlan.setObject(57, pln.getHeatPlanNo());
			patsPlan.setObject(58, pln.getJudgeStoveNo());
			patsPlan.setObject(59, Result.getBatchNo());
			patsPlan.setObject(60, Result.getBatchGroudNo());
			patsPlan.setObject(61, pln.getProduccode());
			patsPlan.setObject(62, pln.getProducname());
			patsPlan.setObject(63, Result.getOutnumCut());
			patsPlan.setObject(64, pln.getSpecCode());
			patsPlan.setObject(65, pln.getSpecName());
			patsPlan.addBatch();

			// 修改计划主表状态
			patupdatepln.setObject(1, "20");
			patupdatepln.setObject(2, "00");
			patupdatepln.setObject(3, HeatPlanNo);
			patupdatepln.addBatch();

			patupdate2.setObject(1, "00");
			patupdate2.setObject(2, pln.getHeatPlanNo());
			patupdate2.setObject(3, Result.getBatchNo());
			patupdate2.addBatch();

			patAdd.executeBatch();
			patsPlan.executeBatch();
			patupdate.executeBatch();
			patupdate2.executeBatch();
			patupdatepln.executeBatch();

			FrmMchBugD.AddMchWaste(connection, HeatPlanNo, resultNo, Result
					.getPlineCode(), Result.getCreatetUser(), gx,
					SuspiciousList, ScrappedList);

			// 更新运输需求上料时间
			FrmVrpInStore frmVrpInStore = new FrmVrpInStore();
			 //  TZH 24.4.24 注销物流接口
//			frmVrpInStore.updateTmsDemandMLoadTime(connection, connection2,
//					core, HeatPlanNo, "G");
			if (core.getV_errMsg().equals("")) {
				core.setV_errMsg("上料成功！");
			}

			// 财务系统接口数据处理
			// FmisTool.addBcOutList(connection,core,HeatPlanNo,resultNo,"G");

			core.setResult(1);
			connection.commit();
			 //  TZH 24.4.24 注销物流接口
//			connection2.commit();
		} catch (Exception e) {
			core.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
					 //  TZH 24.4.24 注销物流接口
//					connection2.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
			 //  TZH 24.4.24 注销物流接口
//			if (connection2 != null) {
//				try {
//					connection.rollback(); // 回滚事务
//					connection2.rollback(); // 回滚事务
//				} catch (Exception e2) {
//				}
//			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
				 //  TZH 24.4.24 注销物流接口
//				if (connection2 != null && !connection2.isClosed()) {
//					connection2.close();
//				}
			} catch (Exception e2) {
			}
		}
		return core;
	}

	/**
	 * 撤销上料
	 * 
	 * @param planNo
	 * @return
	 */
	public CoreReturnObject DoDelete(String LoadStr, String gx, String userName) {
		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		 //  TZH 24.4.24 注销物流接口
//		Connection connection2 = this.getDao("TmsDao").getConnection();
		Date now = new Date();
		SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMM",
				Locale.CHINA);
		String systime1 = ""; //改25号结转

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		String systime = dateFormat.format(new Date());

		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			 //  TZH 24.4.24 注销物流接口
//			connection2.setAutoCommit(false); // 取消自动提交事务
			String sqlDelete = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.ReturnVrpLoadingResult");// 删除上料实绩
			PreparedStatement patDelete = connection
					.prepareStatement(sqlDelete);
			String sqlupdate = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteDbkPlan");// 删除时修改加工计划表从表
			PreparedStatement patupdate = connection
					.prepareStatement(sqlupdate);
			String sqlupdate2 = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteDbkPlan2");// 删除时修改加工计划表从表
			PreparedStatement patupdate2 = connection
					.prepareStatement(sqlupdate2);
			String sqlupdatepln = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteDbkPlanpln");// 删除时修改加工计划表状态
			PreparedStatement patupdatepln = connection
					.prepareStatement(sqlupdatepln);
			String updatePlnInfo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteVrpResult");// 删除加工公共信息
			PreparedStatement patsupdatePlan = connection
					.prepareStatement(updatePlnInfo);
			String deleteButt = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.addButter");// 新增位置表
			PreparedStatement patsButt = connection
					.prepareStatement(deleteButt);
			String addOut = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeleteOutList");// 删除出库记录
			PreparedStatement patsDeleteOut = connection
					.prepareStatement(addOut);
			String addOutList = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeleteOutListQuan");// 删除出库记录产权出库
			PreparedStatement patsDeleteOutList = connection
					.prepareStatement(addOutList);
			String updateMat = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updateMatZcPlanStuts");// 修改库存状态
			PreparedStatement patsUpMat = connection
					.prepareStatement(updateMat);
			String addport = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeletePortVrp");// 删除管号队列
			String addBackup = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.CopyBackup");// 复制MAT_BC_BACKUP表到物料主表
			PreparedStatement patsAddBackup = connection
					.prepareStatement(addBackup);
			String deteleBackup = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeteleBackup");//
			PreparedStatement deteleBackupPath = connection
					.prepareStatement(deteleBackup);

			String deleteOffline = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.DeleteOffline");// 清空离线实绩
			PreparedStatement patsdeleteOffline = connection
					.prepareStatement(deleteOffline);

			String sql4 = CoreXmlSqlParsersFactory
					.getSql("FrmVrpLoading.deleteFmis");// 删除财务系统接口数据
			PreparedStatement deleteFmis = connection.prepareStatement(sql4);

			PreparedStatement patsport = connection.prepareStatement(addport);

			MchLoadingResultEntity load = EntityTool.getEntityByJSONStr(
					LoadStr, MchLoadingResultEntity.class);
			systime1 = com.steering.common.StringTool.GetBalYear(com.steering.common.StringTool.GetSupplyUnit(load.getPlineCode())); //改25号结转

			// 获取加工计划实体了
			PlnZyJgxMEntity pln = PlanService.getSendHttPlanCInfo3(connection,
					load.getHeatPlanNo(), load.getBatchNo());

			if (!pln.getPlineCode().equals(load.getPlineCode())) {
				core.setV_errMsg("不能删除其他产线生成的实绩！");
				return core;
			}

			// 财务系统接口数据处理
			// FmisTool.deleteBcOutList(connection,core,load.getHeatPlanNo(),load.getResultNo(),"G");

			// 获取热处理计划实体了
			// PlnOrderJgxSEntity httOrder =
			// PlanService.getMchOrder(connection,pln.getProPlanId(),pln.getGxPlanNo());

			if (pln == null)
				return core;
			if (pln.getPlanstatus().equals("30")) {
				core.setV_errMsg("该计划已生产完成！");
				return core;
			}

			// if(httOrder==null)
			// {
			// core.setV_errMsg("无订单计划！");
			// return core;
			// }

			/*
			 * if(!httOrder.getExeStatus().equals("0")
			 * &&!httOrder.getExeStatus().equals("1")) {
			 * core.setV_errMsg("订单处于订单处于生产完成/关闭状态,无法撤销上料实绩！"); return core; }
			 */

			String cutFalg = "";
			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.qureyGxComInfo");// 查询工序是否是结炉状态
			PreparedStatement psta = connection.prepareStatement(sql);
			psta.setString(1, load.getHeatPlanNo());
			psta.setString(2, load.getBatchNo());
			psta.setString(3, gx);
			ResultSet rs = psta.executeQuery();
			if (rs.next()) {
				cutFalg = rs.getString("STATION_STATUS");
			}
			if (cutFalg.equals("2")) {
				core.setV_errMsg("已结炉,不允许此操作！");
				return core;
			}
			rs.close();
			psta.close();
			
			String SYNC_FLAG = "0";
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmVrpLoading.SelectSyncFlag");// 查询财务系统同步状态
			psta = connection.prepareStatement(sql);
			psta.setObject(1, pln.getJudgeStoveNo());
			psta.setObject(2, load.getBatchNo());
			psta.setObject(3, load.getHeatPlanNo());
			psta.setObject(4, load.getProNum());
			rs = psta.executeQuery();
			if (rs.next()) {
				SYNC_FLAG = rs.getString("SYNC_FLAG");
			}
			rs.close();
			psta.close();
			if (SYNC_FLAG.equals("1")) {
				core.setV_errMsg("财务系统同步出库信息，请联系财务撤销同步信息!");
				return core;
			}
			// 删除财务系统接口数据
			deleteFmis.setObject(1, pln.getJudgeStoveNo());
			deleteFmis.setObject(2, load.getBatchNo());
			deleteFmis.setObject(3, load.getHeatPlanNo());
			deleteFmis.setObject(4, load.getProNum());
			deleteFmis.addBatch();
			deleteFmis.executeBatch();

			int detCount = 0;
			int count1 = 0;
			Double Wt = 0d;
			if (StringTool.isInteger(load.getFailNum())) {
				detCount = Integer.parseInt(load.getFailNum());
			}
			if (StringTool.isInteger(load.getProNum())) {
				count1 = Integer.parseInt(load.getProNum());
			}
			if (StringTool.isDouble(load.getProWt())) {
				Wt = Double.parseDouble(load.getProWt());
			}

			FrmMchBugD.DeleteMchWaste(connection, load.getHeatPlanNo(), load
					.getResultNo(), load.getPlineCode(), gx, detCount);

			List<YdmBcOutlistEntity> listOut = new ArrayList<YdmBcOutlistEntity>();
			String sqlMatNo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.queryYdmOut");// 查询出库信息
			psta = connection.prepareStatement(sqlMatNo);
			psta.setObject(1, pln.getFeedHeatNo());
			psta.setObject(2, load.getBatchNo());
			psta.setObject(3, load.getBatchGroudNo());
			psta.setObject(4, load.getOutstockDoc());
			psta.setObject(5, load.getHeatPlanNo());
			psta.setObject(6, Integer.parseInt(load.getProNum()) + 1);
			rs = psta.executeQuery();
			listOut = EntityTool.getEntitysByRs(rs, YdmBcOutlistEntity.class);
			rs.close();
			psta.close();

			if (listOut.size() != Integer.parseInt(load.getProNum())) {
				core.setV_errMsg("数据异常,无法找到出库记录!");
				return core;
			}
			for (YdmBcOutlistEntity lvMat : listOut) {
				PortMchBatchSampleResultEntity PortMchBatchSampleResultEntity = PlanService
						.getPortMchBatchSampleResultEntity(
								load.getHeatPlanNo(), lvMat.getMatNo(),
								connection);

				if (PortMchBatchSampleResultEntity.getValidflag().equals("0")) {
					core.setV_errMsg("部分管号已经分切,无法撤销,请先撤销分切实绩！");
					return core;
				}

				if (!PortMchBatchSampleResultEntity.getMatStatus().equals("00")
						&& !(PortMchBatchSampleResultEntity.getOpProcess()
								.equals("701301") && PortMchBatchSampleResultEntity
								.getMatStatus().equals("10"))) {
					core.setV_errMsg("后续工序已经做了离线操作或者剔除,无法撤销！");
					return core;
				}

				if (!lvMat.getBalYearMonth().equals(systime1)) {
					core.setV_errMsg("上料结算日期和撤销上料结算日期不在同一个月，不允许撤销上料!");
					return core;
				}

				if (PortMchBatchSampleResultEntity.getInstoreFlag().equals("1")) {
					core.setV_errMsg("有物料已经做了交库,无法撤销！");
					return core;
				}

				// 修改库存状态
				patsUpMat.setObject(1, "80150103");
				patsUpMat.setObject(2, lvMat.getMatNo());
				patsUpMat.addBatch();

				List<YdmBcButtressEntity> back = new ArrayList<YdmBcButtressEntity>();
				String sqlBack = CoreXmlSqlParsersFactory
						.getSql("FrmMcpLoading.selectBack");// 查询出库信息
				psta = connection.prepareStatement(sqlBack);
				psta.setObject(1, lvMat.getMatNo());
				psta.setObject(2, pln.getPlineCode());
				rs = psta.executeQuery();
				back = EntityTool.getEntitysByRs(rs, YdmBcButtressEntity.class);
				rs.close();
				psta.close();

				if (back != null && back.size() > 0) {
					// 新增位置表
					patsButt.setObject(1, back.get(0).getMatNo());
					patsButt.setObject(2, back.get(0).getJudgeStoveNo());
					patsButt.setObject(3, back.get(0).getBatchNo());
					patsButt.setObject(4, back.get(0).getBatchGroudNo());
					patsButt.setObject(5, back.get(0).getStorageNo());
					patsButt.setObject(6, back.get(0).getLocationNo());
					patsButt.setObject(7, back.get(0).getLaryNo());
					patsButt.setObject(8, back.get(0).getLocNo());
					patsButt.setObject(9, back.get(0).getStorageAttr());
					patsButt.setObject(10, back.get(0).getStorageAttrName());
					patsButt.setObject(11, back.get(0).getStorageTypeNo());
					patsButt.setObject(12, back.get(0).getStorageTypeName());
					patsButt.setObject(13, back.get(0).getManagementNo());
					patsButt.setObject(14, back.get(0).getManagementName());
					patsButt.setObject(15, userName);
					patsButt.setObject(16, systime);
					patsButt.setObject(17, back.get(0).getDepartmentCode());
					patsButt.setObject(18, back.get(0).getDepartmentDesc());
					patsButt.addBatch();
				} else {

					// 新增位置表
					patsButt.setObject(1, lvMat.getMatNo());
					patsButt.setObject(2, lvMat.getJudgeStoveNo());
					patsButt.setObject(3, lvMat.getBatchNo());
					patsButt.setObject(4, lvMat.getBatchGroudNo());
					patsButt.setObject(5, lvMat.getStorageNo());
					patsButt.setObject(6, lvMat.getLocationNo());
					patsButt.setObject(7, lvMat.getLaryNo());
					patsButt.setObject(8, lvMat.getLocNo());
					patsButt.setObject(9, lvMat.getStorageAttr());
					patsButt.setObject(10, lvMat.getStorageAttrName());
					patsButt.setObject(11, lvMat.getStorageTypeNo());
					patsButt.setObject(12, lvMat.getStorageTypeName());
					patsButt.setObject(13, lvMat.getManagementNo());
					patsButt.setObject(14, lvMat.getManagementName());
					patsButt.setObject(15, userName);
					patsButt.setObject(16, systime);
					patsButt.setObject(17, lvMat.getDepartmentCode());
					patsButt.setObject(18, lvMat.getDepartmentDesc());
					patsButt.addBatch();
				}
				// 删除出库表
				patsDeleteOut.setObject(1, lvMat.getOutstockSqe());
				patsDeleteOut.addBatch();

				patsDeleteOutList.setObject(1, lvMat.getMatNo());
				patsDeleteOutList.setObject(2, load.getHeatPlanNo());
				patsDeleteOutList.addBatch();

				patupdate.setObject(1, 1);
				patupdate.setObject(2, PortMchBatchSampleResultEntity
						.getActWeight());
				patupdate.setObject(3, PortMchBatchSampleResultEntity
						.getHeatPlanNo());
				patupdate.setObject(4, PortMchBatchSampleResultEntity
						.getHeatPlanSqe());
				patupdate.addBatch();

				// 删除管号队列
				patsport.setObject(1, load.getHeatPlanNo());
				patsport.setObject(2, lvMat.getMatNo());
				patsport.addBatch();
				// 复制MAT_BC_BACKUP表到物料主表
				patsAddBackup.setObject(1, lvMat.getMatNo());
				patsAddBackup.setObject(2, load.getHeatPlanNo());
				patsAddBackup.addBatch();
				// 删除MAT_BC_BACKUP表
				deteleBackupPath.setObject(1, lvMat.getMatNo());
				deteleBackupPath.setObject(2, load.getHeatPlanNo());
				deteleBackupPath.addBatch();
			}
			patsUpMat.executeBatch();
			patsButt.executeBatch();
			patsDeleteOut.executeBatch();
			patsport.executeBatch();
			patsAddBackup.executeBatch();
			deteleBackupPath.executeBatch();
			patsDeleteOutList.executeBatch();
			// 删除上料实绩
			patDelete.setObject(1, load.getResultNo());
			patDelete.addBatch();
			// 删除上料公共信息
			patsupdatePlan.setObject(1, load.getResultNo());
			patsupdatePlan.addBatch();
			// }
			patDelete.executeBatch();
			patsupdatePlan.executeBatch();

			/*
			 * 
			 * List<PlnZyJgxCEntity> plnCs =
			 * PlanService.getSendHttPlanCInfo3C(connection,
			 * load.getHeatPlanNo(),load.getBatchNo(),load.getBatchGroudNo());
			 * 
			 * 
			 * for (PlnZyJgxCEntity plnC :plnCs ) { Integer ReNum =
			 * Integer.parseInt(plnC.getRealIndoubleNum().equals("")?"0":
			 * plnC.getRealIndoubleNum()); Double ReWt =
			 * Double.parseDouble(plnC.getRealIndoubleWt().equals("")?"0":
			 * plnC.getRealIndoubleWt());
			 * 
			 * if (ReNum>0){
			 * 
			 * count1 = count1 -ReNum; Wt = Wt- ReWt;
			 * 
			 * patupdate.setObject(1, count1 >=0 ? ReNum: ReNum-count1 );
			 * patupdate.setObject(2, Wt >=0 ? ReWt: ReWt-Wt);
			 * patupdate.setObject(3, plnC.getHeatPlanNo());
			 * patupdate.setObject(4, plnC.getHeatPlanSqe());
			 * patupdate.addBatch(); }
			 * 
			 * if(count1<=0) break; }
			 */
			patupdate.executeBatch();

			patupdate2.setObject(1, load.getHeatPlanNo());
			patupdate2.setObject(2, load.getBatchNo());
			patupdate2.addBatch();
			patupdate2.executeBatch();

			patupdatepln.setObject(1, load.getHeatPlanNo());
			patupdatepln.addBatch();
			patupdatepln.executeBatch();

			patsdeleteOffline.setObject(1, load.getHeatPlanNo());
			patsdeleteOffline.addBatch();
			patsdeleteOffline.executeBatch();

			// 更新运输需求上料时间
			FrmVrpInStore frmVrpInStore = new FrmVrpInStore();
			 //  TZH 24.4.24 注销物流接口
//			frmVrpInStore.updateTmsDemandMLoadTime(connection, connection2,
//					core, load.getHeatPlanNo(), "G");
			if (core.getV_errMsg().equals("")) {
				core.setV_errMsg("删除上料成功！");
			}

			core.setResult(1);
			connection.commit();
			 //  TZH 24.4.24 注销物流接口
//			connection2.commit();
		} catch (Exception e) {
			core.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
					 //  TZH 24.4.24 注销物流接口
//					connection2.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
			 //  TZH 24.4.24 注销物流接口
//			if (connection2 != null) {
//				try {
//					connection.rollback(); // 回滚事务
//					connection2.rollback(); // 回滚事务
//				} catch (Exception e2) {
//				}
//			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
				 //  TZH 24.4.24 注销物流接口
//				if (connection2 != null && !connection2.isClosed()) {
//					connection2.close();
//				}
			} catch (Exception e2) {
			}
		}
		return core;
	}

}
