/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-13
 * 描述            ：客户一级账号明细信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.FundManagement.impl;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Api.Mes.impl.DesignInfo;
import market.Api.Mes.impl.MesApiDesignInfoImpl;
import market.Api.Mes.impl.MesApiServiceImpl;
import market.Api.Mes.impl.ProcessPoint;
import market.Api.Mes.impl.Utils;
import market.Api.Qms.vo.SlmOrdDesignMscNpl;
import market.Com.mapper.ComBaseCbYddToYthMapper;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.ComBaseCbYdd;
import market.Com.vo.ComBaseCbYddToYth;
import market.Com.vo.ComBaseddR;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Logistics.impl.Connecttt;
import market.Lms.Logistics.impl.SpmDeliveryServiceImpl;
import market.Lms.Logistics.impl.SpmTransportDetailServiceImpl;
import market.Lms.Logistics.mapper.SpmDeliveryDetailMapper;
import market.Lms.Logistics.mapper.SpmDeliveryMapper;
import market.Lms.Logistics.mapper.SpmDistrbuteMainMapper;
import market.Lms.Logistics.mapper.SpmTransportDetailMapper;
import market.Lms.Logistics.vo.SendToCxSystem;
import market.Lms.Logistics.vo.SpmDelivery;
import market.Lms.Logistics.vo.SpmDeliveryDetail;
import market.Lms.Logistics.vo.SpmDistrbuteMain;
import market.Lms.Logistics.vo.SpmTransportDetail;
import market.Lms.Warehouse.impl.YdmProductDetailBfServiceImpl;
import market.Lms.Warehouse.impl.YdmProductInlistServiceImpl;
import market.Lms.Warehouse.impl.YdmProductOutlistServiceImpl;
import market.Lms.Warehouse.mapper.YdmBaseButtressconfigMapper;
import market.Lms.Warehouse.mapper.YdmHzTempMapper;
import market.Lms.Warehouse.mapper.YdmProductButtresslistMapper;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.mapper.YdmProductOutlistMapper;
import market.Lms.Warehouse.service.YdmProductInlistService;
import market.Lms.Warehouse.vo.IfRawMtrCoilM;
import market.Lms.Warehouse.vo.YdmBaseButtressconfig;
import market.Lms.Warehouse.vo.YdmHzTemp;
import market.Lms.Warehouse.vo.YdmProductButtresslist;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Mes.Cuttolength.Plan.impl.PlnCuttolengthPlanServiceImpl;
import market.Mes.Cuttolength.Plan.mapper.PlnCuttolengthPlanDetailMapper;
import market.Mes.Cuttolength.Plan.vo.PlnCuttolengthPlanDetail;
import market.Mes.Lengthwise.Plan.impl.PlnLengthwisePlanServiceImpl;
import market.Mes.Lengthwise.Plan.mapper.PlnLengthwisePlanDetailMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnMatReplaceLogMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.Lengthwise.Plan.service.PlnMaterielDetailService;
import market.Mes.Lengthwise.Plan.vo.PlnLengthwisePlanDetail;
import market.Mes.Lengthwise.Plan.vo.PlnMatReplaceLog;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.MaterielTrack.mapper.PrcMaterielProcessMapper;
import market.Mes.MaterielTrack.mapper.TbdipdoMapper;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.MaterielTrack.vo.Tbdipdo;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.impl.PlnProdorderGuaDanServiceImpl;
import market.Mes.OrderManager.Plan.mapper.PlnOrderStatisticMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderStatisticMapper;
import market.Mes.OrderManager.Plan.vo.PlnOrderStatistic;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.OrderManager.Plan.vo.PlnProdorderStatistic;
import market.Mes.Packing.Result.mapper.MesPackResultMapper;
import market.Mes.Packing.Result.vo.MesPackResult;
import market.Mes.Pickle.Design.impl.PlnPickleDsnMultinfoServiceImpl;
import market.Mes.Pickle.Plan.mapper.PlnPicklePlanDetailMapper;
import market.Mes.Pickle.Plan.vo.PlnPicklePlanDetail;
import market.Mes.Rolling.Design.impl.PlnRollingDsnMultinfoServiceImpl;
import market.Mes.Rolling.Performance.mapper.MesRcmDMapper;
import market.Mes.Rolling.Performance.mapper.MesRcmDPassMapper;
import market.Mes.Rolling.Performance.vo.MesRcmDPass;
import market.Mes.Rolling.Performance.vo.PlnRollingMaterialDetailSum;
import market.Mes.Rolling.Plan.mapper.PlnRollingPlanDetailMapper;
import market.Mes.Rolling.Plan.vo.PlnRollingPlanDetail;
import market.Mes.Tpm.Design.impl.PlnSkinrollingDsnMultinfoServiceImpl;
import market.Mes.Tpm.mapper.PlnSkinrollingPlanDetailMapper;
import market.Mes.Tpm.vo.PlnSkinrollingPlanDetail;
import market.Mes.anneal.Design.impl.PlnAnnealDsnMultinfoServiceImpl;
import market.Mes.anneal.mapper.PlnAnnealPlanDetailMapper;
import market.Mes.anneal.vo.PlnAnnealPlanDetail;
import market.Qms.com.mapper.BaseSteelMapper;
import market.Qms.com.vo.BaseSteel;
import market.Qms.common.DataHelper;
import market.Qms.qcm.mapper.QcmJudgeMeasureMapper;
import market.Qms.qcm.mapper.QcmJudgeSurfaceFlawMapper;
import market.Qms.qcm.mapper.QcmJudgeSurfaceMapper;
import market.Qms.qcm.mapper.QcmJudgeUltimateMapper;
import market.Qms.qcm.vo.QcmJudgeMeasure;
import market.Qms.qcm.vo.QcmJudgeSurface;
import market.Qms.qcm.vo.QcmJudgeSurfaceFlaw;
import market.Qms.qcm.vo.QcmJudgeUltimate;
import market.Qms.slmord.mapper.SlmOrdDesignMscMapper;
import market.Qms.slmord.mapper.SlmOrdDesignMscPlMapper;
import market.Qms.slmord.mapper.SlmOrdDesignMscPlStiMapper;
import market.Qms.slmord.vo.SlmOrdDesignMsc;
import market.Qms.slmord.vo.SlmOrdDesignMscPl;
import market.Qms.slmord.vo.SlmOrdDesignMscPlSti;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.CustomerInformation.mapper.SlmCustomerInfoMapper;
import market.Slm.CustomerInformation.vo.NcCustomerInfo;
import market.Slm.CustomerInformation.vo.NcCustomerParam;
import market.Slm.CustomerInformation.vo.SlmCustomerInfo;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundFirstDetailMapper;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundFirstDetail;
import market.Slm.OrderManagement.impl.IfSlmContractInfoServiceImpl;
import market.Slm.OrderManagement.mapper.IfSlmContractInfoMapper;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.mapper.SlmProcessPlanMapper;
import market.Slm.OrderManagement.vo.IfTbl02CoilComm;
import market.Slm.OrderManagement.vo.SlmOrderInfo;
import market.Slm.OrderManagement.vo.SlmOrderInfoNline;
import market.Slm.OrderManagement.vo.SlmProcessPlan;
import market.webservice.WebService1_Service;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.mapper.DepartmentMapper;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.vo.Department;
import com.hnshituo.core.auth.vo.User;

@RemoteService(path = "SlmFundFirstDetailService")
public class SlmFundFirstDetailServiceImpl extends
BaseServiceImpl<SlmFundFirstDetail, Object> implements
SlmFundFirstDetailService {
	/**
	 * 回款新增
	 * */
	public ResultModel doAddWeb(SlmFundFirstDetail detail) {
		ResultModel rm = new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String deptId = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
		String deptName = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		try {
			SlmFundFirstAccount account = this.getMapper(SlmFundFirstAccountMapper.class).findById(detail.getFirst_account_no());
			if (account == null) {
				rm.setState("500");
				rm.setMsgInfo("该客户账户数据丢失，请联系管理员");
				return rm;
			}
			if ("1".equals(account.getLock_flag())) {
				rm.setState("500");
				rm.setMsgInfo("该客户账户已经结转，如须新增回款请解锁");
				return rm;
			}
			// 明细表新增
			String id = new SimpleDateFormat("yyyyMMddHHmmssSSS")
			.format(new Date()) + PbMethod.RandomCreate(10);
			if (detail.getDetail_no() == null)
				detail.setDetail_no(id);
			detail.setCreate_dept_no(deptId);
			detail.setCreate_dept_name(deptName);
			detail.setCreate_man_no(userId);
			detail.setCreate_man_name(userName);
			detail.setCreate_time(new Date());
			if (detail.getIn_out_time() == null)
				detail.setIn_out_time(new Date());
			detail.setIs_valid("1"); // 有效
			detail.setIs_effect("0"); // 刚新增设定为未生效
			detail.setCarryover_flag("0"); // 未结转
			this.getMapper(SlmFundFirstDetailMapper.class).insert(detail);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 回款编辑
	 * */
	public ResultModel doUpdateWeb(SlmFundFirstDetail detail) {
		ResultModel rm = new ResultModel();
		try {
			SlmFundFirstDetail check = this.getMapper(SlmFundFirstDetailMapper.class).findById(detail.getDetail_no());
			if (check == null) {
				rm.setState("500");
				rm.setMsgInfo("回款数据丢失，请联系管理员");
				return rm;
			}
			if ("1".equals(check.getIs_effect())) {
				rm.setState("500");
				rm.setMsgInfo("该回款数据已生效，无法编辑");
				return rm;
			}
			this.getMapper(SlmFundFirstDetailMapper.class).update(detail);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 回款删除
	 * */
	public ResultModel doDeleteWeb(SlmFundFirstDetail detail) {
		ResultModel rm = new ResultModel();
		try {
			detail = this.getMapper(SlmFundFirstDetailMapper.class).findById(detail.getDetail_no());
			if (detail == null) {
				rm.setState("500");
				rm.setMsgInfo("回款数据丢失，请联系管理员");
				return rm;
			}
			if ("1".equals(detail.getIs_effect())) {
				rm.setState("500");
				rm.setMsgInfo("该回款数据已生效，无法删除");
				return rm;
			}
			detail.setIs_valid("0"); // 无效
			this.getMapper(SlmFundFirstDetailMapper.class).update(detail);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 回款查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundFirstDetail> sum) {
		ResultModel rm = new ResultModel();
		SlmFundFirstDetail detail = sum.getObject();
		int pageIndex = sum.getPageIndex();
		int pageSize = sum.getPageSize();
		String startTime = sum.getStartTime(); // 进出账时间查询
		String endTime = sum.getEndTime();
		String startTime2 = sum.getStartTime2(); // 兑现时间查询
		String endTime2 = sum.getEndTime2();
		PageModel<SlmFundFirstDetail> pm = new PageModel<SlmFundFirstDetail>(pageIndex, pageSize);
		String flag=sum.getMemo1();
		try {
			String sWhere = " 1=1 ";
			//回款日期
			if (startTime != null && !"".equals(startTime) && !"1".equals(flag)) {
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') >='"	+ startTime.substring(0, 10) + " 00:00:00" + "'";
			}
			if (endTime != null && !"".equals(endTime) && !"1".equals(flag)) {
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+ endTime.substring(0, 10) + " 23:59:59" + "'";
			}
			//查生效时间
			if (startTime != null && !"".equals(startTime)&&"1".equals(flag)) {
				sWhere += " and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') >='"	+ startTime + "'";
			}
			if (endTime != null && !"".equals(endTime)&&"1".equals(flag)) {
				sWhere += " and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+ endTime + "'";
			}
			//兑现日期
			if (startTime2 != null && !"".equals(startTime2)) {
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') >='"+ startTime2 + "'";
			}
			if (endTime2 != null && !"".equals(endTime2)) {
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') <= '"	+ endTime2 + "'";
			}
			detail.setBalance_object_no(null);
			detail.setIs_valid("1");
			List<SlmFundFirstDetail> list = this.getMapper(SlmFundFirstDetailMapper.class).findWithCondition(detail,
							sWhere, "customer_no, is_effect, in_out_time desc", (pageIndex - 1) * pageSize, pageSize);
			int count = this.getMapper(SlmFundFirstDetailMapper.class).countWithCondition(detail, sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 新 回款查询 不分页
	 * */
	public ResultModel doQueryWebDetails(CommonPage<SlmFundFirstDetail> sum) {
		ResultModel rm = new ResultModel();
		SlmFundFirstDetail detail = sum.getObject();
		String first_account_name = detail.getFirst_account_name();
		String startTime = sum.getStartTime(); // 进出账时间查询
		String endTime = sum.getEndTime();
		String startTime2 = sum.getStartTime2(); // 兑现时间查询
		String endTime2 = sum.getEndTime2();
		try {
			String sWhere = " 1=1 and is_valid='1' and is_effect='1' ";
			if (first_account_name != null && !"".equals(first_account_name)) {
				sWhere += " and first_account_name='" + first_account_name + "'";
			}
			if (startTime != null && !"".equals(startTime)) {
				// startTime+=" 00:00:00";
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') >='" + startTime + "'";
			}
			if (endTime != null && !"".equals(endTime)) {
				// endTime+=" 23:59:59";
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') <= '" + endTime + "'";
			}
			if (startTime2 != null && !"".equals(startTime2)) {
				// startTime2+=" 00:00:00";
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') >='" + startTime2 + "'";
			}
			if (endTime2 != null && !"".equals(endTime2)) {
				// endTime2+=" 23:59:59";
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') <= '" + endTime2 + "'";
			}
			List<SlmFundFirstDetail> list = this.getMapper(
					SlmFundFirstDetailMapper.class).findWithCondition(detail,
							sWhere, " IS_VALID desc, CREATE_TIME desc", 0, 0);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	public ResultModel doExportExcelDetails(CommonPage<SlmFundFirstDetail> sum) {
		ResultModel rm = new ResultModel();
		SlmFundFirstDetail detail = sum.getObject();
		String first_account_name = detail.getFirst_account_name();
		String startTime = sum.getStartTime(); // 进出账时间查询
		String endTime = sum.getEndTime();
		String startTime2 = sum.getStartTime2(); // 兑现时间查询
		String endTime2 = sum.getEndTime2();
		try {
			String sWhere = " 1=1 and IS_VALID='1' and IS_EFFECT='1' ";
			if (first_account_name != null && !"".equals(first_account_name)) {
				//
				sWhere += " and FIRST_ACCOUNT_NAME='" + first_account_name
						+ "'";
			}
			if (startTime != null && !"".equals(startTime)) {
				// startTime+=" 00:00:00";
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime + "'";
			}
			if (endTime != null && !"".equals(endTime)) {
				// endTime+=" 23:59:59";
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') <= '"
						+ endTime + "'";
			}
			if (startTime2 != null && !"".equals(startTime2)) {
				// startTime2+=" 00:00:00";
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime2 + "'";
			}
			if (endTime2 != null && !"".equals(endTime2)) {
				// endTime2+=" 23:59:59";
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') <= '"
						+ endTime2 + "'";
			}
			List<SlmFundFirstDetail> list = this.getMapper(
					SlmFundFirstDetailMapper.class).findWithCondition(detail,
							sWhere, " IS_VALID desc, CREATE_TIME desc", 0, 0);
			// 1，创建一个webbook，对应一个Excel文件
			WritableWorkbook workbook;
			// 2,设置用户下载路径
			String path = this.getRequest().getServletContext()
					.getRealPath("/")
					+ "excel" + File.separator; // 临时保存路径
			File dir = new File(path);
			if (!dir.exists()) {
				new File(path).mkdir();
			}
			generateExcel(rm, list, path,startTime,endTime);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 *
	 * 报表打印
	 * **/
	private void generateExcel(ResultModel rm, List<SlmFundFirstDetail> list, String path,String startTime,String endTime)
			throws IOException, WriteException, RowsExceededException {
		String filename ="";
		if(startTime != null && !"".equals(startTime)&&endTime != null && !"".equals(endTime)){
			startTime=startTime.substring(0, 10);
			endTime=endTime.substring(0, 10);
			filename = startTime +"到"+ endTime + "资金进出明细";
		}else{
			filename =  "资金进出明细";
		}
		WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("资金进出明细", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);

		jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##"); //设置数字格式
		jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); //设置表单格式

		//表头
		sheet.mergeCells(0, 0, 0, 1);
		sheet.addCell(new Label(0,0,"序号",cellFormat1));

		sheet.mergeCells(1, 0, 1, 1);
		sheet.addCell(new Label(1,0,"客户名称",cellFormat1));

		sheet.mergeCells(2, 0, 2, 1);
		sheet.addCell(new Label(2,0,"结算部门",cellFormat1));

		sheet.mergeCells(3, 0, 3, 1);
		sheet.addCell(new Label(3,0,"回款金额",cellFormat1));

		sheet.mergeCells(4, 0, 4, 1);
		sheet.addCell(new Label(4,0,"回款时间",cellFormat1));

		sheet.mergeCells(5, 0, 5, 1);
		sheet.addCell(new Label(5,0,"回款类型",cellFormat1));

		sheet.mergeCells(6, 0, 6, 1);
		sheet.addCell(new Label(6,0,"票据编号",cellFormat1));

		sheet.mergeCells(7, 0, 7, 1);
		sheet.addCell(new Label(7,0,"兑现时间",cellFormat1));

		sheet.mergeCells(8, 0, 8, 1);
		sheet.addCell(new Label(8,0,"备注",cellFormat1));

		sheet.mergeCells(9, 0, 9, 1);
		sheet.addCell(new Label(9,0,"确认人",cellFormat1));

		sheet.mergeCells(10, 0, 10, 1);
		sheet.addCell(new Label(10,0,"确认时间",cellFormat1));

		sheet.mergeCells(11, 0, 11, 1);
		sheet.addCell(new Label(11,0,"创建部门",cellFormat1));

		sheet.mergeCells(12, 0, 12, 1);
		sheet.addCell(new Label(12,0,"创建人",cellFormat1));

		sheet.mergeCells(13, 0, 13, 1);
		sheet.addCell(new Label(13,0,"创建时间",cellFormat1));

		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		//时间转字符串的格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat newsdf = new SimpleDateFormat("yyyy-MM-dd");
		double totalIn_out_fund = 0;
		for(int i = 0; i < list.size(); i++) {
			//序号
			sheet.addCell(new Label(0,i+2,""+(i+1),cellFormat));
			//客户名称
			if(list.get(i).getCustomer_name() != null && !"".equals(list.get(i).getCustomer_name())) {
				sheet.addCell(new Label(1,i+2,list.get(i).getCustomer_name(),cellFormat));
			}
			//结算部门
			if(list.get(i).getBalance_object_name() != null && !"".equals(list.get(i).getBalance_object_name())) {
				sheet.addCell(new Label(2,i+2,list.get(i).getBalance_object_name(),cellFormat));
			}
			//回款金额
			if(list.get(i).getIn_out_fund() != null && !"".equals(list.get(i).getIn_out_fund())) {
				totalIn_out_fund =DoubleUtil.add(totalIn_out_fund,list.get(i).getIn_out_fund());
				sheet.addCell(new Label(3,i+2,""+list.get(i).getIn_out_fund(),wcfN));
			}
			//回款时间
			if(list.get(i).getIn_out_time() != null && !"".equals(list.get(i).getIn_out_time())) {	
				sheet.addCell(new Label(4,i+2,newsdf.format(list.get(i).getIn_out_time()),cellFormat));
			}
			//回款类型
			if(list.get(i).getIn_out_type_name()!= null && !"".equals(list.get(i).getIn_out_type_name())) {
				sheet.addCell(new Label(5,i+2,list.get(i).getIn_out_type_name(),cellFormat));
			}
			//票据编号
			if(list.get(i).getBill_no()!= null && !"".equals(list.get(i).getBill_no())) {
				sheet.addCell(new Label(6,i+2,list.get(i).getBill_no(),cellFormat));
			}
			//兑现时间
			if(list.get(i).getCash_date() != null && !"".equals(list.get(i).getCash_date())) {	
				sheet.addCell(new Label(7,i+2,newsdf.format(list.get(i).getCash_date()),cellFormat));
			}
			//备注
			if(list.get(i).getMemo()!= null && !"".equals(list.get(i).getMemo())) {
				sheet.addCell(new Label(8,i+2,list.get(i).getMemo(),cellFormat));
			}
			//确认人
			if(list.get(i).getCheck_man_name()!= null && !"".equals(list.get(i).getCheck_man_name())) {
				sheet.addCell(new Label(9,i+2,list.get(i).getCheck_man_name(),cellFormat));
			}
			//确认时间
			if(list.get(i).getCheck_man_name()!= null && !"".equals(list.get(i).getCheck_man_name())) {
				sheet.addCell(new Label(10,i+2,list.get(i).getCheck_man_name(),cellFormat));
			}
			//创建部门
			if(list.get(i).getCreate_dept_name()!= null && !"".equals(list.get(i).getCreate_dept_name())) {
				sheet.addCell(new Label(11,i+2,list.get(i).getCreate_dept_name(),cellFormat));
			}
			//创建人
			if(list.get(i).getCreate_man_name()!= null && !"".equals(list.get(i).getCreate_man_name())) {
				sheet.addCell(new Label(12,i+2,list.get(i).getCreate_man_name(),cellFormat));
			}
			//创建时间
			if(list.get(i).getCreate_time()!= null && !"".equals(list.get(i).getCreate_time())) {
				sheet.addCell(new Label(13,i+2,sdf.format(list.get(i).getCreate_time()),cellFormat));
			}
		}

		sheet.addCell(new Label(0,list.size()+2,"总计",cellFormat));
		WritableCellFormat cellFormat2 = new WritableCellFormat(font); 
		cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
		DecimalFormat df=new DecimalFormat("0.000");
		sheet.addCell(new Label(1,list.size()+2,""+list.size(),cellFormat2));//统计总条数
		sheet.addCell(new Label(3,list.size()+2,""+df.format(totalIn_out_fund),cellFormat2));//统计总回款金额
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		//关闭
		workbook.write();
		workbook.close();

		rm.setData("/download?filename="+file);
	}
	/**
	 * 回款生效
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doEffectWeb(CommonPage<SlmFundFirstDetail> sum) throws Exception {
		ResultModel rm = new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmFundFirstDetail> list=sum.getObjectList();
		try {
			for(SlmFundFirstDetail detail:list){
				SlmFundFirstDetail newDetail = this.getMapper(SlmFundFirstDetailMapper.class).findById(detail.getDetail_no());
				if (newDetail != null && "1".equals(newDetail.getIs_valid())) {
					if ("1".equals(newDetail.getCarryover_flag())) {
						rm.setState("500");
						rm.setMsgInfo("该回款信息已经结转，如须生效请联系后台人员");
						return rm;
					}
					if ("0".equals(newDetail.getIs_effect())) {
						SlmFundFirstAccount account = this.getMapper(SlmFundFirstAccountMapper.class).findById(newDetail.getFirst_account_no());
						if (account != null) {
							if ("1".equals(account.getLock_flag())) {
								rm.setState("500");
								rm.setMsgInfo("该客户账户已经结转，如须回款生效请解锁");
								continue;
							}
							detail.setIs_effect("1"); // 生效
							detail.setCheck_man_no(userId);
							detail.setCheck_man_name(userName);
							detail.setCheck_time(new Date());
							// 一级账户表修改数据
							account.setFinal_fund(DoubleUtil.add(account.getFinal_fund(),newDetail.getIn_out_fund()));		//可拨+
							account.setUse_fund(DoubleUtil.add(	account.getUse_fund(),newDetail.getIn_out_fund()));		//可用+
							account.setPay_back_fund(DoubleUtil.add(account.getPay_back_fund(),newDetail.getIn_out_fund()));   //回款+
							account.setBalance_fund(DoubleUtil.add(	account.getBalance_fund(),newDetail.getIn_out_fund()));    //财务余额+
							this.getMapper(SlmFundFirstDetailMapper.class).update(detail);
							this.getMapper(SlmFundFirstAccountMapper.class).update(account);
						}
					}
				}
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 回款取消生效
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUnEffectWeb(SlmFundFirstDetail detail)
			throws Exception {
		ResultModel rm = new ResultModel();
		try {
			SlmFundFirstDetail newDetail = this.getMapper(SlmFundFirstDetailMapper.class).findById(detail.getDetail_no());
			if (newDetail != null && "1".equals(newDetail.getIs_valid())) {
				if ("1".equals(newDetail.getCarryover_flag())) {
					rm.setState("500");
					rm.setMsgInfo("该回款信息已经结转，如须取消回款生效请联系后台管理人员");
					return rm;
				}
				if ("1".equals(newDetail.getIs_effect())) {
					SlmFundFirstAccount account = this.getMapper(SlmFundFirstAccountMapper.class).findById(newDetail.getFirst_account_no());
					if (account != null) {
						if ("1".equals(account.getLock_flag())) {
							rm.setState("500");
							rm.setMsgInfo("该客户账户已经结转，如须取消回款生效请解锁");
							return rm;
						}
						detail.setIs_effect("0"); // 生效
						detail.setCheck_man_no("");
						detail.setCheck_man_name("");
						detail.setCheck_time(new Date());
						// if(newDetail.getIn_out_fund()>account.getFinal_fund()||newDetail.getIn_out_fund()>account.getUse_fund()){
						// rm.setState("500");
						// rm.setMsgInfo("可用金额不足，无法取消生效");
						// return rm;
						// }

						// 一级账户表修改数据
						account.setFinal_fund(DoubleUtil.add(account.getFinal_fund(),-newDetail.getIn_out_fund()));
						account.setUse_fund(DoubleUtil.add(account.getUse_fund(),-newDetail.getIn_out_fund()));
						account.setPay_back_fund(DoubleUtil.add(account.getPay_back_fund(),-newDetail.getIn_out_fund()));
						account.setBalance_fund(DoubleUtil.add(account.getBalance_fund(),	-newDetail.getIn_out_fund()));
						this.getMapper(SlmFundFirstDetailMapper.class).update(detail);
						this.getMapper(SlmFundFirstAccountMapper.class).update(account);
						rm.setState("200");
						return rm;
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("该记录已经取消生效");
					return rm;
				}
			}
			rm.setState("500");
			rm.setMsgInfo("该数据存在异常，请联系管理员修复");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * for用友接口 creationtime-- > 创建时间 pk_balatype-- > 收款方式 pk_gather-- > NC收款单主键
	 * creatorid-- > 创建人 pk_deptid-- > 部门 customerid-- > 客户名称 money-- > 收款金
	 * billno-- > 收款单单据号 def3-- > 票据单号 def21-- > 票据到期日 productname-- > 产品类型名称
	 * 3、	资金系统的对接 将NC系统收款单的单据信息传递给MES系统
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doSynchronizingFundBack(NcCustomerParam param)	throws Exception {
		ResultModel rm = new ResultModel();
		List<NcCustomerInfo> list = param.getList();
		try {
			if(list==null){
				rm.setState("500");
				rm.setMsgInfo("参数格式错误，请按批量格式上传");
				return rm;
			}
			
			System.out.println("本次传递收款单数量：" + list.size());
			
			SlmFundFirstDetail check = new SlmFundFirstDetail();
			for (NcCustomerInfo customer : list) {
				
				System.out.println("1");
				
				SlmFundFirstAccount account = new SlmFundFirstAccount();
				account.setCustomer_name(customer.getCustomerid());
				List<SlmFundFirstAccount> account_list = this.getMapper(SlmFundFirstAccountMapper.class).find(account, 0, 0);
				if (account_list.size() ==1) {

					System.out.println("2");
					
					account = account_list.get(0);
				} else if(account_list.size()>1){
					System.out.println("3");
					
					rm.setState("500");
					String msg="【"+customer.getCustomerid()+"】未在MES中维护客户账户信息，请先新增客户账户；或者MES与NC系统中客户名称不一致";
					if(customer.getCustomerid()==null||"".equals(customer.getCustomerid())){
						msg="传输的客户名称为空！【"+customer.getCustomerid()+"】";
					}
					throw new Exception(msg);
				} else if(account_list.size()<1){
					System.out.println("4");
					
					// 自动新增账户
					String sWhere = " customer_name like '%"	+ customer.getCustomerid() + "%'";
					List<SlmCustomerInfo> customer_list = this.getMapper(	SlmCustomerInfoMapper.class).findWithCondition(null, sWhere, null, 0, 0);
					if (customer_list.size() ==1) {
						System.out.println("5");
						
						account.setCustomer_name(customer_list.get(0).getCustomer_name());
						account.setCustomer_no(customer_list.get(0).getCustomer_no());
						account.setBalance_object_no("20180113143042611374");
						account.setBalance_object_name("综合财务部");
						account.setFirst_account_name(customer_list.get(0).getCustomer_abbr());
						if (account.getFirst_account_name() == null){
							account.setFirst_account_name(customer_list.get(0).getCustomer_name());
						}
						account.setInit_fund(0d);
						rm = this.getBean(SlmFundFirstAccountServiceImpl.class).doAddWeb(account);
						System.out.println("6");
						
						String account_id = (String) rm.getData();
						account.setFirst_account_no(account_id);
					}
				}
				if(customer.getBillno()!=null){
					
					System.out.println("有customer.getBillno");
					
					check.setReceipt_no(customer.getBillno()); 	
					check.setIs_valid("1");
					int count=this.getMapper(SlmFundFirstDetailMapper.class).count(check);
					
					System.out.println("有billno且count：" + count);
					
					if(count>0){
						continue;
					}
				}

				System.out.println("7");
				
				SlmFundFirstDetail detail = new SlmFundFirstDetail();
				String id = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + PbMethod.RandomCreate(10);
				// 明细表新增
				detail.setDetail_no(id);
				List<Department> dept_list = this.getMapper(DepartmentMapper.class).findWithCondition(null," name='" + customer.getCustomerid() + "'", null, 0, 0);

				System.out.println("8");
				
				if (dept_list.size() > 0){
					System.out.println("9");
				
					detail.setCreate_dept_no(dept_list.get(0).getId());
				}
				detail.setCreate_dept_name(customer.getPk_deptid());
				detail.setCreate_man_name(customer.getCreatorid());
				detail.setCreate_man_no("");
				List<User> user_list = this.getMapper(UserMapper.class).findWithCondition(	null," username='" + detail.getCreate_man_name()+ "'", null, 0, 0);
				if (user_list.size() > 0){
					System.out.println("10");
				
					detail.setCreate_man_no(user_list.get(0).getId());
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				if(customer.getCreationtime()!=null&&!"".equals(customer.getCreationtime())){
					detail.setCreate_time(sdf.parse(customer.getCreationtime())); // 创建时间
				}
				if(customer.getBilldate()!=null&&!"".equals(customer.getBilldate())){
					detail.setIn_out_time(sdf2.parse(customer.getBilldate()));//回款时间
				}	
				System.out.println("11");
				
				detail.setBill_no(customer.getDef3()); // 票据编号
				detail.setReceipt_no(customer.getBillno()); 		//收款单据号
				
				System.out.println("收款单据号：" + customer.getBillno());
				
				if(customer.getDef21()!=null&&!"".equals(customer.getDef21())){
					detail.setCash_date(sdf.parse(customer.getDef21())); // 票据到期日
				}
				detail.setIs_valid("1"); // 有效
				detail.setIs_effect("0"); // 刚新增设定为未生效
				detail.setCarryover_flag("0"); // 未结转
				detail.setFirst_account_no(account.getFirst_account_no());
				detail.setFirst_account_name(account.getFirst_account_name());
				detail.setBalance_object_no(account.getBalance_object_no());
				detail.setBalance_object_name(account.getBalance_object_name());
				detail.setCustomer_no(account.getCustomer_no());
				detail.setCustomer_name(account.getCustomer_name());
				detail.setIn_out_type_name(customer.getPk_balatype());
				detail.setIn_out_fund(Double.parseDouble(customer.getMoney()));
				System.out.println("12");
				
				if (customer.getCreationtime() != null) {
					detail.setCreate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(customer.getCreationtime()));
					if (detail.getIn_out_time() == null){
						detail.setIn_out_time(detail.getCreate_time());
					}
				}
				System.out.println("13");
				
				if(customer.getCustomerid()==null||"".equals(customer.getCustomerid())){
					detail.setMemo("NC系统未传客户名称："+customer.getCustomerid());
				}
				
				System.out.println("14");
				
				this.getMapper(SlmFundFirstDetailMapper.class).insert(detail);
				System.out.println("15");
				
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	//=======================APP eason add 2019-07-15===================
	/**
	 * 回款查询
	 * */
	public ResultModel doQueryApp(CommonPage<SlmFundFirstDetail> sum) {
		ResultModel rm = new ResultModel();
		SlmFundFirstDetail detail = sum.getObject();
		int pageIndex = sum.getPageIndex();
		int pageSize = sum.getPageSize();
		String startTime = sum.getStartTime(); // 进出账时间查询
		String endTime = sum.getEndTime();
		String startTime2 = sum.getStartTime2(); // 兑现时间查询
		String endTime2 = sum.getEndTime2();
		PageModel<SlmFundFirstDetail> pm = new PageModel<SlmFundFirstDetail>(pageIndex, pageSize);
		String flag=sum.getMemo1();
		
		try {
			detail.setCustomer_no((String)this.getSession().getAttribute(HomeService.SESSION_DEPT_ID));
			String sWhere = " 1=1 and is_valid = '1'";
			if (startTime != null && !"".equals(startTime)&&!"1".equals(flag)) {
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') >='"	+ startTime + "'";
			}
			if (endTime != null && !"".equals(endTime)&&!"1".equals(flag)) {
				sWhere += " and to_char(in_out_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+ endTime + "'";
			}
			//查生效时间
			if (startTime != null && !"".equals(startTime)&&"1".equals(flag)) {
				sWhere += " and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') >='"	+ startTime + "'";
			}
			if (endTime != null && !"".equals(endTime)&&"1".equals(flag)) {
				sWhere += " and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+ endTime + "'";
			}
			if (startTime2 != null && !"".equals(startTime2)) {
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') >='"+ startTime2 + "'";
			}
			if (endTime2 != null && !"".equals(endTime2)) {
				sWhere += " and to_char(cash_date, 'yyyy-mm-dd hh24:mi:ss') <= '"	+ endTime2 + "'";
			}
			if (StringUtils.isNotEmpty(sum.getMemo2())) {//回款类型
				sWhere += " and in_out_type_name = '"+sum.getMemo2()+"'";
			}
			List<SlmFundFirstDetail> list = this.getMapper(
					SlmFundFirstDetailMapper.class).findWithCondition(detail,
							sWhere, " is_effect, CREATE_TIME desc",
							(pageIndex - 1) * pageSize, pageSize);
			int count = this.getMapper(SlmFundFirstDetailMapper.class).countWithCondition(detail, sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	//==========================================不需要登录的接口：20230803
	
	/**
	 * ceshi20230802刘侣
	 * */
	public ResultModel doCustomerceshi() {
		ResultModel rm = new ResultModel();
		
		
		try {
//			this.getMapper(YdmProductDetailMapper.class).changeUltimate("测试", "ZY2311210084");
			
			rm.setData("同步成功");
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	
	/**
	 * 客户信息同步20230802刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCustomerSync(CommonPage<SlmCustomerInfo> sum) {
		ResultModel rm = new ResultModel();
		SlmCustomerInfo customer = sum.getObject();
		
		try {
			if (customer == null) {
				throw new Exception("缺少object参数");
			}
			SlmCustomerInfo sci = examine(customer);
			
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			// 如果iud：1insert, 2update,0delete
			if ("1".equals(sci.getIud())) {
				this.getMapper(SlmCustomerInfoMapper.class).insert(sci);
			} else if ("2".equals(sci.getIud())) {
				this.getMapper(SlmCustomerInfoMapper.class).update(sci);
			} else {
				sci.setValid_flag("0");
				this.getMapper(SlmCustomerInfoMapper.class).update(sci);
			}

			
			rm.setData("同步成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			return rm;
		}
		
		//日志
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "客户信息同步", "一体化", opr_time, null, null, null, null, customer.getCustomer_name());
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
	
	
	public SlmCustomerInfo examine(SlmCustomerInfo sci) throws Exception {
		
		if (sci.getIud() == null || "".equals(sci.getIud())) {
			throw new Exception("缺少状态标志");
		}
		if (sci.getCustomer_no() == null || "".equals(sci.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (sci.getCustomer_name() == null || "".equals(sci.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		sci.setCustomer_abbr(sci.getCustomer_name());
		sci.setSale_org_no("20171218221814830158");
		sci.setSale_org_name("新余新钢优特钢带有限公司");
		sci.setValid_flag("1");
		sci.setCustomer_industry_name("带钢");
		sci.setCustomer_industry_no("100605");
		return sci;
		
	}
		
	
	/**
	 * 牌号信息同步20230803刘侣：后续可能还要增加修改删除接口
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSteelnameSync(CommonPage<ComBaseSteel> sum) {
		ResultModel rm = new ResultModel();
		ComBaseSteel cbs = sum.getObject();
		
		try {
			if (cbs == null) {
				throw new Exception("缺少object参数");
			}
			
			ComBaseSteel cbsNew = examineSteel(cbs);
			
			// 先注释，防止测试时调用接口insert了：20230807刘侣
//			this.getMapper(ComBaseSteelMapper.class).insert(cbsNew);
			
			// 如果opt_type：1insert, 2update,0delete
			if ("1".equals(cbs.getOpr_type())) {
				// 检测是否已经存在相同牌号：
				List<BaseSteel> cbslist = getSteelCode(cbsNew.getSteel_name());
				if (cbslist.size() > 0) {
					throw new Exception("牌号：" + cbsNew.getSteel_name() + " 在优特钢已经存在，请点击修改牌号");
				}
				
				// 设置steelCode：
				String maxCode=this.getMapper(BaseSteelMapper.class).GetMaxCode();
				if(DataHelper.IsNullOrSpace(maxCode)){
					maxCode="1000";
				}else{
					maxCode=Integer.valueOf(maxCode)+1+"";
				}
				cbsNew.setSteel_code(maxCode);
				
				this.getMapper(ComBaseSteelMapper.class).insert(cbsNew);
			} else if ("2".equals(cbs.getOpr_type())) {
				ComBaseSteel cbsQ = new ComBaseSteel();
				cbsQ.setSteel_name(cbsNew.getSteel_name());
				List<ComBaseSteel> listSteel = this.getMapper(ComBaseSteelMapper.class).find(cbsQ, 0, 0);
				if (listSteel.size() <= 0) {
					throw new Exception("牌号：" + cbsNew.getSteel_name() + " 在优特钢不存在，请新增");
				}
				if (listSteel.size() > 1) {
					throw new Exception("牌号：" + cbsNew.getSteel_name() + " 在优特钢存在相同的两个");
				}
				cbsNew.setSteel_code(listSteel.get(0).getSteel_code());
				this.getMapper(ComBaseSteelMapper.class).update(cbsNew);
			} else {
				ComBaseSteel cbsQ = new ComBaseSteel();
				cbsQ.setSteel_name(cbsNew.getSteel_name());
				List<ComBaseSteel> listSteel = this.getMapper(ComBaseSteelMapper.class).find(cbsQ, 0, 0);
				if (listSteel.size() <= 0) {
					throw new Exception("牌号：" + cbsNew.getSteel_name() + " 在优特钢不存在，请新增");
				}
				cbsNew.setSteel_code(listSteel.get(0).getSteel_code());
				cbsNew.setValidflag("0");
				this.getMapper(ComBaseSteelMapper.class).update(cbsNew);
			}
			
			rm.setData("同步牌号成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			return rm;
		}
		
		//日志
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "牌号信息同步", "一体化", opr_time, null, null, null, null, cbs.getSteel_name());
		this.getMapper(MesOprLogMapper.class).insert(mol);
				
		return rm;
	}
	
	public ComBaseSteel examineSteel(ComBaseSteel cbs) throws Exception {
		
		
		if (cbs.getSteel_name() == null || "".equals(cbs.getSteel_name())) {
			throw new Exception("缺少牌号名称");
		}
		if (cbs.getSteel_type() == null || "".equals(cbs.getSteel_type())) {
			throw new Exception("缺少钢种名称");
		}
		if (cbs.getIs_yg() == null || "".equals(cbs.getIs_yg())) {
			throw new Exception("缺少是否优钢");
		}
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		cbs.setSteel_style("2"); // 类型(1:钢级, 2:牌号)：暂时固定为2；
		cbs.setValidflag("1");
//		cbs.setValid_flag("1");
		return cbs;
		
	}
	
	
	/**
	 * 接收合同头信息20230803刘侣：后续可能还要增加删除接口，合同不需要删除接口；
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveContractInfo(CommonPage<SlmContractHeatInfo> sum) throws Exception {
		ResultModel rm = new ResultModel();
		Date date = new Date();
		SlmContractHeatInfo schi = sum.getObject();
		List<SlmOrderInfoNline> soiList = sum.getObjectList2();
		
		try {
			if (schi == null) {
				throw new Exception("缺少object合同参数");
			}
			if (soiList == null || soiList.size() <= 0) {
				throw new Exception("缺少objectList2订单参数");
			}
			
			SlmContractHeatInfo schiNew = examinecontract(schi);
			
			// 只新增订单也合并到这个接口，如果有这个有效合同则只新增订单：20231023刘侣
			SlmContractHeatInfo heat = this.getMapper(SlmContractHeatInfoMapper.class).findById(schiNew.getContract_pk());
			if (heat != null && "1".equals(heat.getValid_flag())) {
				// 合同已经存在，不新增合同，只新增订单：
				// 但是合同头信息可能会修改：统一执行更新操作
				this.getMapper(SlmContractHeatInfoMapper.class).update(schiNew);
				
			} else {
				// 合同不存在，新增合同：
				// 再拿合同号查是否存在合同信息，如果存在就抛错：20240412刘侣
				SlmContractHeatInfo newHeat=new SlmContractHeatInfo();
				newHeat.setContract_no(schiNew.getContract_no());
				int newCount=this.getMapper(SlmContractHeatInfoMapper.class).count(newHeat);
				if (newCount > 0) {
					throw new Exception("合同 " + schiNew.getContract_no() + " 已经存在，请在一体化先撤回合同");
				}
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmContractHeatInfoMapper.class).insert(schiNew);
				
				// 如果客户信息不存在，则新增客户信息：20240327 刘侣
				if (schiNew.getCustomer_name() != null && !"".equals(schiNew.getCustomer_name())) {
					int cusNum = this.getMapper(SlmCustomerInfoMapper.class).countWithCondition(null, " customer_name LIKE '%"+schiNew.getCustomer_name()+"%'");
					if (cusNum <= 0) {
						// 没有维护该客户：新增该客户
						SlmCustomerInfo info = new SlmCustomerInfo();
						info.setCustomer_no(schiNew.getCustomer_no());
						info.setCustomer_name(schiNew.getCustomer_name());
						info.setCustomer_abbr(schiNew.getCustomer_name().length() > 4 ? schiNew.getCustomer_name().substring(0, 4) : schiNew.getCustomer_name());
						info.setCreate_time(date);
						info.setCustomer_industry_name("带钢");
						info.setCustomer_industry_no("100605");
						
						this.getMapper(SlmCustomerInfoMapper.class).insert(info);
					}
				}
				// end
			}
			// end
			
			// 接收订单数据并生成合同行数据：
			CommonPage<SlmOrderInfoNline> soiNlist = new CommonPage<SlmOrderInfoNline>();
			soiNlist.setObjectList(soiList);
			ResultModel rmSoi = doReceiveOrderInfo(soiNlist);
			if ("500".equals(rmSoi.getState())) {
				throw new Exception(rmSoi.getMsgInfo());
			}
			
			
			rm.setData("合同及订单接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception(e.getMessage());
		}
		

		//日志
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "合同信息同步", "一体化", opr_time, null, null, null, null, schi.getContract_no());
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
	
	/**
	 * 接收合同头信息20230803刘侣：后续可能还要增加删除接口，合同不能删除
	 * */
//	public ResultModel doDelContractInfo(CommonPage<SlmContractHeatInfo> sum) {
//		ResultModel rm = new ResultModel();
//		SlmContractHeatInfo schi = sum.getObject();
//		
//		try {
//			if (schi == null) {
//				throw new Exception("缺少object参数");
//			}
//			if (schi.getContract_pk() == null || schi.getContract_no() == null) {
//				throw new Exception("缺少合同主键或者合同号");
//			}
//			if ()
//			
//			this.getMapper(SlmContractHeatInfoMapper.class).delete(schi.getContract_pk());
//			
//			rm.setData("合同停用成功");
//			rm.setState("200");
//		} catch (Exception e) {
//			rm.setState("500");
//			rm.setMsgInfo(e.getMessage());
//		}
//		return rm;
//	}
	
	public SlmContractHeatInfo examinecontract(SlmContractHeatInfo info) throws Exception {
		
		if (info.getContract_pk() == null || "".equals(info.getContract_pk())) {
			throw new Exception("缺少合同主键");
		}
		if (info.getCustomer_no() == null || "".equals(info.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (info.getCustomer_name() == null || "".equals(info.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
		if (info.getContract_no() == null || "".equals(info.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (info.getContract_type_no() == null || "".equals(info.getContract_type_no())) {
			throw new Exception("缺少合同类型编号");
		}
		if (info.getContract_type_name() == null || "".equals(info.getContract_type_name())) {
			throw new Exception("缺少合同类型");
		}
		if (info.getSign_date() == null || "".equals(info.getSign_date())) {
			throw new Exception("缺少签订日期");
		}
		if (info.getSign_address() == null || "".equals(info.getSign_address())) {
			throw new Exception("缺少签订地点");
		}
		if (info.getEffec_start_date() == null || "".equals(info.getEffec_start_date())) {
			throw new Exception("缺少签订开始日期");
		}
		if (info.getEffec_end_date() == null || "".equals(info.getEffec_end_date())) {
			throw new Exception("缺少签订结束日期");
		}
		if (info.getCreate_man_name() == null || "".equals(info.getCreate_man_name())) {
			throw new Exception("缺少创建人名称");
		}
		if (info.getCreate_man_no() == null || "".equals(info.getCreate_man_no())) {
			throw new Exception("缺少创建人编号");
		}
		if (info.getDeliver_date() == null || "".equals(info.getDeliver_date())) {
			throw new Exception("缺少交货日期");
		}
		
		
		// 增加缺少但是能自己生成的：
		String strContractPk=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());						
//		info.setContract_pk(strContractPk+PbMethod.RandomCreate(3));//合同号PK：20210519104710575 + 562
		
		int mNo=this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, " substr(manage_no,0,6)='"+strContractPk.substring(0,6)+"'")+1;
		info.setManage_no(strContractPk.substring(0,6)+String.format("%04d", mNo));
		
		info.setIs_order_contract("0");
		info.setCustomer_abr(info.getCustomer_name());
		info.setTrade_type_no("100801");
		info.setTrade_type_name("内贸");
		info.setSupply_unit_no("20180122102823908069");
		info.setSupply_unit_name("新余新钢优特钢带有限公司");
		info.setBalance_unit_no(info.getCustomer_no());
		info.setBalance_unit_name(info.getCustomer_name());
		info.setOrder_unit_no(info.getCustomer_no());
		info.setOrder_unit_name(info.getCustomer_name());
		info.setPrice_type_no("101801");
		info.setPrice_type_name("锁价");
		info.setIs_tax("1");
		info.setSale_org_no("20171218221814830158");
		info.setSale_org_name("新余新钢优特钢带有限公司");
		info.setSale_area_no("0007");
		info.setSale_area_name("新余城西");
		String year=new SimpleDateFormat("yyyy").format(new Date());	
		info.setContract_year(year);
		info.setContract_flag_no("102104");
		info.setContract_flag_name("生效");
		info.setMake_price_type_no("102201");
		info.setMake_price_type_name("采购价");
		info.setValid_flag("1");
		info.setCreate_time(new Date());
		info.setSupplier_address("新钢公司创效路");
		info.setCurrency_no("101901");
		info.setCurrency_name("人民币");
		info.setPayment_type_no("102001");
		info.setPayment_type_name("现款和银行承兑");
		info.setLegal_man("法人");
		info.setBack("开户银行");
		info.setAddress("公司注册地址");
		info.setTax_registra_number("纳税人识别号");
		info.setTelphone("电话");
		// 合同类型：原本是有：现款合同101601，现货合同101602，厂内合同101603，自用合同101604，现款协议合同101605，来料加工合同101606，委托加工合同101607
		// 加工合同分为：委托加工和来料加工，所以得进一步区分：20231031刘侣
		String cTypeN = "现款合同".equals(info.getContract_type_name()) ? "现款协议合同" : "加工合同".equals(info.getContract_type_name()) ? "委托加工合同" : info.getContract_type_name();
		String cTypeCode = "现款合同".equals(cTypeN) ? "101601" : "现货合同".equals(cTypeN) ? "101602" : "厂内合同".equals(cTypeN) ? "101603" : "自用合同".equals(cTypeN) ? "101604" : "现款协议合同".equals(cTypeN) ? "101605" : "来料加工合同".equals(cTypeN) ? "101606" : "委托加工合同".equals(cTypeN) ? "101607" : info.getContract_type_no();
		info.setContract_type_name(cTypeN);
		info.setContract_type_no(cTypeCode);
		return info;
		
	}	
	
    public List<BaseSteel> getSteelCode (String steelName) {
		BaseSteel cbs = new BaseSteel();
		cbs.setSteelName(steelName);
		List<BaseSteel> cbsList = this.getMapper(BaseSteelMapper.class).find(cbs, 0, 0);
		return cbsList;
	}
	
	/**
	 * 接收订单信息20230803刘侣：后续可能还要增加删除接口，下发了在生产的订单只能撤回，不需要删除功能
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveOrderInfo(CommonPage<SlmOrderInfoNline> sum) throws Exception {
		ResultModel rm = new ResultModel();
		// 一次接收多条订单
		List<SlmOrderInfoNline> soiList = sum.getObjectList();
		
		try {
			if (soiList == null || soiList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			for (SlmOrderInfoNline soi : soiList) {
				SlmOrderInfoNline sc = examineorderinfo(soi);
				
				// 检测订单是否已经存在：
				List<SlmOrderInfo> soiL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, " CONTRACT_NO || ORDER_SEQ = '" + sc.getContract_no() + sc.getOrder_seq() + "'", null, 0, 0);
				if (soiL != null && soiL.size() > 0) {
					// 已经有这个订单存在：
					throw new Exception("订单：" + soi.getContract_no() + soi.getOrder_seq() + " 已经存在");
				}
				
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+sc.getContract_no() + sc.getOrder_seq() + sc.getOrder_seq()+"'", null, 0, 0);
				if (ppoL != null && ppoL.size() > 0) {
					throw new Exception("订单：" + soi.getContract_no() + soi.getOrder_seq() + " 的生产订单已经存在");
				}
				
				// 拼合同行数据:
				SlmContractLineInfo scli = new SlmContractLineInfo();
				scli.setContract_line_no(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) );
				scli.setContract_line_seq(sc.getOrder_seq()); // 改成和订单序号一致：20231005刘侣
				scli.setContract_pk(sc.getContract_pk());
				scli.setContract_no(sc.getContract_no());
				// 缺少psc和mes看需不需要存储:
				scli.setPsc_desc(sc.getPsc_desc());
				scli.setMsc_desc(sc.getMsc_desc());
				scli.setMsc_type_name(sc.getMsc_type_name());
				scli.setUse_code(sc.getUse_code());
				scli.setUse_desc(sc.getUse_desc());
				scli.setProd_cls_name(sc.getProd_cls_name());
				scli.setProd_code(sc.getProd_code());
				scli.setProd_name(sc.getProd_name());
				scli.setStd_code(sc.getStd_code());
				scli.setStd_name(sc.getStd_name());
				scli.setSteel_code(sc.getSteel_code());
				scli.setSteel_name(sc.getSteel_name());
				scli.setProd_figure_name(sc.getProd_figure_name());
				scli.setEstimate_weight(sc.getEstimate_weight());
				scli.setDelivery_error_max(sc.getDelivery_error_max());
				scli.setDelivery_error_min(sc.getDelivery_error_min());
				scli.setWeight_type_name(sc.getWeight_type_name());
				scli.setWeight_type_no("净重".equals(sc.getWeight_type_name()) ? "102301" : "毛重".equals(sc.getWeight_type_name()) ? "102302" : "102301");
				scli.setSingle_weight_max(sc.getSingle_weight_max());
				scli.setSingle_weight_min(sc.getSingle_weight_min());
				scli.setSingle_weight_unit_name("t");
				scli.setSingle_weight_unit_no("100306");
				scli.setCut_edge_type_name(sc.getCut_edge_type_name());
				scli.setCut_edge_type_no("四毛".equals(sc.getCut_edge_type_name()) ? "102501" : "二切".equals(sc.getCut_edge_type_name()) ? "102502" : "四切".equals(sc.getCut_edge_type_name()) ? "102503" : "");
				scli.setDiameter_inn_unit_no("100304");
				scli.setDiameter_inn_unit_name("mm");
				scli.setDiameter_out_unit_no("100304");
				scli.setDiameter_out_unit_name("mm");
				scli.setThick(sc.getThick());
				scli.setThick_unit_no("100304");
				scli.setThick_unit_name("mm");
				scli.setWidth(sc.getWidth());
				scli.setWidth_unit_no("100304");
				scli.setWidth_unit_name("mm");
				scli.setLine_flag_no("102608");
				scli.setLine_flag_name("生效");
				scli.setValid_flag("1");
				scli.setCreate_man_name(sc.getCreate_man_name());
				scli.setCreate_time(new Date());
				scli.setEstimate_weight_unit_no("100306");
				scli.setEstimate_weight_unit_name("t");
				scli.setDelivery_unit_no("100306");
				scli.setDelivery_unit_name("t");
				scli.setDelivery_state_desc(sc.getDelivery_state_desc());
//				scli.setDelivery_state_code();
				scli.setIs_tax("1");
				scli.setTax_rate(13.000);
				scli.setCurrency_name("人民币");
				scli.setDelivery_error_rate(sc.getDelivery_error_rate());
				scli.setPrecisicon_type_desc(sc.getPrecisicon_type_desc());
				scli.setPrecisicon_type_code("PT.A".equals(sc.getPrecisicon_type_desc()) ? "411205" : "PT.B".equals(sc.getPrecisicon_type_desc()) ? "411206" : "");
				scli.setPk_ask_desc(sc.getPk_ask_desc());
				scli.setPk_ask_code("裸包".equals(sc.getPk_ask_desc()) ? "201101" : "简包".equals(sc.getPk_ask_desc()) ? "201102" : "普包".equals(sc.getPk_ask_desc()) ? "201103" : "精包".equals(sc.getPk_ask_desc()) ? "201104" : "薄膜包".equals(sc.getPk_ask_desc()) ? "201105" : "出口包装".equals(sc.getPk_ask_desc()) ? "201106" : "");
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmContractLineInfoMapper.class).insert(scli);
				
				
				// 拼接订单信息:
				SlmOrderInfo soii = new SlmOrderInfo();
				soii.setOrder_no(scli.getContract_line_no() + "001"); // 有合同行号 + 三位流水号生成：20230920刘侣
				soii.setContract_no(sc.getContract_no());
				soii.setContract_line_no(scli.getContract_line_no());
				soii.setContract_line_seq(scli.getContract_line_seq());
				soii.setOrder_seq(sc.getOrder_seq());
				soii.setDeliver_date(sc.getDeliver_date());
				soii.setSupplier_unit_no("20180122102823908069");
				soii.setSupplier_unit_name("新余新钢优特钢带有限公司");
				soii.setSupplier_address("新钢公司创效路");
				soii.setReciver_unit_no(sc.getReciver_unit_no());
				soii.setReciver_unit_name(sc.getReciver_unit_name());
				soii.setReciver_address(sc.getReciver_address());
				soii.setIs_pickup("0");
				soii.setIs_liku("0");
				soii.setIs_lock("0");
				soii.setOrder_flag_no(sc.getOrder_flag_no());
				soii.setOrder_flag_name(sc.getOrder_flag_name());
				soii.setMemo(sc.getMemo());
				soii.setValid_flag("1");
				soii.setCreate_man_name(sc.getCreate_man_name());
				soii.setCreate_time(new Date());
				soii.setContract_pk(sc.getContract_pk());
				soii.setEstimate_weight(sc.getEstimate_weight());
				soii.setEstimate_weight_unit_no("100306");
				soii.setEstimate_weight_unit_name("t");
				soii.setPsc_desc(sc.getPsc_desc());
				soii.setMsc_desc(sc.getMsc_desc());
				soii.setBalance_unit_no(sc.getCustomer_no());
				soii.setBalance_unit_name(sc.getCustomer_name());
				soii.setPrice_type_no("101801");
				soii.setPrice_type_name("锁价");
				soii.setIs_tax("1");
				soii.setCustomer_no(sc.getCustomer_no());
				soii.setCustomer_name(sc.getCustomer_name());
				soii.setWeight_type_name(sc.getWeight_type_name());
				// 如果是磅计理计的话一律按净重走：102301
				soii.setWeight_type_no("净重".equals(sc.getWeight_type_name()) ? "102301" : "毛重".equals(sc.getWeight_type_name()) ? "102302" : "102301");
				soii.setOrder_nature(sc.getOrder_nature());
				soii.setMsc_type_name("卷材+板材");
				soii.setMsc_type_no("A");
				soii.setUse_code("STD0000075000");
				soii.setUse_desc("/");
				soii.setProd_code(sc.getProd_code());
				soii.setProd_name(sc.getProd_name());
				soii.setStd_code(sc.getStd_code());
				soii.setStd_name(sc.getStd_name());
				soii.setSteel_code(sc.getSteel_code());
				soii.setSteel_name(sc.getSteel_name());
				soii.setProd_figure_name(sc.getProd_figure_name());
				soii.setDelivery_state_desc(sc.getDelivery_state_desc());
				soii.setPlan_memo(sc.getPlan_memo());
				soii.setPrecisicon_type_code(scli.getPrecisicon_type_code());
				soii.setPrecisicon_type_desc(scli.getPrecisicon_type_desc());
				soii.setWhole_coil(sc.getWhole_coil());
				soii.setProcess(sc.getProcess());
				soii.setIs_split("0");
				soii.setPk_ask_code(scli.getPk_ask_code());
				soii.setPk_ask_desc(scli.getPk_ask_desc());
				soii.setIs_oil(sc.getIs_oil());
				soii.setIs_side_cute(sc.getIs_side_cute());
				soii.setLevel_name(sc.getLevel_name());
				soii.setLevel_code("FA".equals(sc.getLevel_name()) ? "41110101" : "FB".equals(sc.getLevel_name()) ? "41110102" : "FC".equals(sc.getLevel_name()) ? "41110103" : "FD".equals(sc.getLevel_name()) ? "41110104" : "CP".equals(sc.getLevel_name()) ? "41110105" : "FP".equals(sc.getLevel_name()) ? "41110106" : "S1".equals(sc.getLevel_name()) ? "41110107" : "");
				soii.setIndia_require(sc.getIndia_require());
				soii.setSolutions_no("运输方案");
				soii.setSolutions_name("运输方案");
				soii.setIssuer_time(new Date());
				// 增加客户牌号特殊要求：
				soii.setCustomer_alpha_desc(sc.getCustomer_alpha_desc());
				soii.setAdd_ask_no(sc.getAdd_ask_no());
				soii.setAdd_ask_desc(sc.getAdd_ask_desc());
				
				// 增加订单预排期字段：20240613刘侣
				soii.setUser_no(sc.getUser_no());
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmOrderInfoMapper.class).insert(soii);
				
				// 需要同时生成生产订单信息：测试时看订单待接收页面数据情况而定：20230815刘侣
				if (sc.getObjectList() != null && sc.getObjectList().size() > 0) {
					CommonPage<SlmProcessPlan> processlist = new CommonPage<SlmProcessPlan>();
					processlist.setObjectList(sc.getObjectList());
					processlist.setMemo1(soii.getOrder_no());
					ResultModel planRm = doReceivePlan(processlist);
					if("500".equals(planRm.getState())) {
						throw new Exception(planRm.getMsgInfo());
					}
				}

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单信息同步", "一体化", opr_time, null, null, null, null, soii.getContract_no() + soii.getContract_line_seq() + soii.getOrder_seq());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
				
			}
			
			
			
			rm.setData("订单接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw new Exception(e.getMessage());
		}
		return rm;
	}
	
	
	public SlmOrderInfoNline examineorderinfo(SlmOrderInfoNline info) throws Exception {
		
//		if (info.getObjectList() == null || "".equals(info.getObjectList())) {
//			throw new Exception("缺少ObjectList加工计划参数");
//		}
		
//		if (info.getCut_edge_type_name() == null || "".equals(info.getContract_pk())) {
//			throw new Exception("缺少切边方式名称");
//		}
		if (info.getThick() == null || "".equals(info.getThick())) {
			throw new Exception("缺少厚度");
		}
		if (info.getWidth() == null || "".equals(info.getWidth())) {
			throw new Exception("缺少宽度");
		}
		if (info.getContract_pk() == null || "".equals(info.getContract_pk())) {
			throw new Exception("缺少合同主键");
		}
		if (info.getContract_no() == null || "".equals(info.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (info.getPsc_desc() == null || "".equals(info.getPsc_desc())) {
			throw new Exception("缺少产品规范码名称");
		}
		if (info.getMsc_desc() == null || "".equals(info.getPsc_desc())) {
			throw new Exception("缺少冶金规范码名称");
		}
//		if (info.getMsc_type_name() == null || "".equals(info.getMsc_type_name())) {
//			throw new Exception("缺少冶金规范类型名称");
//		}
//		if (info.getUse_desc() == null || "".equals(info.getUse_desc())) {
//			throw new Exception("缺少用途编号");
//		}
//		if (info.getUse_code() == null || "".equals(info.getUse_code())) {
//			throw new Exception("缺少用途名称");
//		}
		if (info.getProd_cls_name() == null || "".equals(info.getProd_cls_name())) {
			throw new Exception("缺少品种分类名称");
		}
		if (info.getProd_code() == null || "".equals(info.getProd_code())) {
			throw new Exception("缺少品种编号");
		}
		if (info.getProd_name() == null || "".equals(info.getProd_name())) {
			throw new Exception("缺少品种名称");
		}
//		if (info.getStd_code() == null || "".equals(info.getStd_code())) {
//			throw new Exception("缺少标准编号");
//		}
		if (info.getStd_name() == null || "".equals(info.getStd_name())) {
			throw new Exception("缺少标准名称");
		}
		
		if (info.getSteel_name() == null || "".equals(info.getSteel_name())) {
			throw new Exception("缺少牌号名称");
		}
//		if (info.getProd_figure_no() == null || "".equals(info.getProd_figure_no())) {
//			throw new Exception("缺少产品形态编号");
//		}
		if (info.getProd_figure_name() == null || "".equals(info.getProd_figure_name())) {
			throw new Exception("缺少产品形态名称");
		}
		if (info.getEstimate_weight() == null || "".equals(info.getEstimate_weight())) {
			throw new Exception("缺少订单估算重量");
		}
		if (info.getDelivery_error_max() == null || "".equals(info.getDelivery_error_max())) {
			throw new Exception("缺少交货量误差上限");
		}
		if (info.getDelivery_error_min() == null || "".equals(info.getDelivery_error_min())) {
			throw new Exception("缺少交货量误差下限");
		}
		if (info.getSingle_weight_max() == null || "".equals(info.getSingle_weight_max())) {
			throw new Exception("缺少单重上限");
		}
		if (info.getSingle_weight_min() == null || "".equals(info.getSingle_weight_min())) {
			throw new Exception("缺少单重下限");
		}
		if (info.getWeight_type_no() == null || "".equals(info.getWeight_type_no())) {
			throw new Exception("缺少计重方式编号");
		}
		if (info.getWeight_type_name() == null || "".equals(info.getWeight_type_name())) {
			throw new Exception("缺少计重方式名称");
		}
		if (info.getSingle_weight() == null || "".equals(info.getSingle_weight())) {
			throw new Exception("缺少单重");
		}
		if (info.getDelivery_error_rate() == null || "".equals(info.getDelivery_error_rate())) {
			throw new Exception("缺少交货量误差率");
		}
		if (info.getOrder_no() == null || "".equals(info.getOrder_no())) {
			throw new Exception("缺少订单主键");
		}
		if (info.getOrder_seq() == null || "".equals(info.getOrder_seq())) {
			throw new Exception("缺少订单序号");
		}
		if (info.getDeliver_date() == null || "".equals(info.getDeliver_date())) {
			throw new Exception("缺少订单交货期");
		}
		if (info.getCustomer_no() == null || "".equals(info.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (info.getCustomer_name() == null || "".equals(info.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
		if (info.getReciver_unit_name() == null || "".equals(info.getReciver_unit_name())) {
			throw new Exception("缺少收货单位");
		}
		if (info.getReciver_address() == null || "".equals(info.getReciver_address())) {
			throw new Exception("缺少收货地址");
		}
		if (info.getOrder_nature() == null || "".equals(info.getOrder_nature())) {
			throw new Exception("缺少订单属性");
		}
//		if (info.getDelivery_state_code() == null || "".equals(info.getDelivery_state_code())) {
//			throw new Exception("缺少订单交货状态编号");
//		}
		if (info.getDelivery_state_desc() == null || "".equals(info.getDelivery_state_desc())) {
			throw new Exception("缺少订单交货状态名称");
		}
//		if (info.getPrecisicon_type_code() == null || "".equals(info.getPrecisicon_type_code())) {
//			throw new Exception("缺少精度类型代码");
//		}
		if (info.getPrecisicon_type_desc() == null || "".equals(info.getPrecisicon_type_desc())) {
			throw new Exception("缺少精度类型名称");
		}
		if (info.getWhole_coil() == null || "".equals(info.getWhole_coil())) {
			throw new Exception("缺少是否整卷");
		}
//		if (info.getPk_ask_code() == null || "".equals(info.getPk_ask_code())) {
//			throw new Exception("缺少包装要求编号");
//		}
		if (info.getPk_ask_desc() == null || "".equals(info.getPk_ask_desc())) {
			throw new Exception("缺少订单包装要求");
		}
		
		
		// 验证是否有合同信息：
		SlmContractHeatInfo shi = new SlmContractHeatInfo();
		shi.setContract_no(info.getContract_no());
		shi.setContract_pk(info.getContract_pk());
		int num =  this.getMapper(SlmContractHeatInfoMapper.class).count(shi);
		if (num <= 0) {
			throw new Exception("合同号：" + info.getContract_no() + " 不存在");
		}
		
		
		SlmOrderInfo soiQ = new SlmOrderInfo();
		soiQ.setContract_no(info.getContract_no());
		soiQ.setContract_line_seq(info.getOrder_seq());
		soiQ.setOrder_seq(info.getOrder_seq());
		soiQ.setValid_flag("1");
		int soiNum = this.getMapper(SlmOrderInfoMapper.class).count(soiQ);
		if (soiNum > 0) {
			throw new Exception("订单：" + soiQ.getContract_no() + soiQ.getOrder_seq() + " 已经存在，不允许下发");
		}
		
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		info.setValid_flag("1");
		info.setSupplier_unit_no("20180122102823908069");
		info.setSupplier_unit_name("新余新钢优特钢带有限公司");
		info.setSupplier_address("新钢公司创效路");
		// 收货单位改成一体化实际的收货单位，而不是和客户名称一样：20240717 刘侣
//		info.setReciver_unit_no(info.getCustomer_no());
//		info.setReciver_unit_name(info.getCustomer_name());
		
		info.setIs_pickup("0");
		info.setIs_liku("0");
		info.setIs_lock("0");
		info.setOrder_flag_no("103406");
		info.setOrder_flag_name("下发");
		info.setIs_split("0");
		info.setStd_code("");
		info.setSolutions_no("运输方案");
		info.setSolutions_name("运输方案");
		// 订单属性 1：原料卷；2：需加工；3：非计划
		info.setOrder_nature(info.getOrder_nature().contains("原料卷") ? "1" : info.getOrder_nature().contains("需加工") ? "2" : info.getOrder_nature().contains("非计划") ? "3" : info.getOrder_nature().contains("冷轧") ? "4" : info.getOrder_nature().contains("酸洗") ? "5" : "");
		
		
		// 获取本地牌号编号：
		List<BaseSteel> cbsList = getSteelCode(info.getSteel_name());
		if (cbsList.size() <= 0) {
			throw new Exception("牌号：" + info.getSteel_name() + " 未与优特钢系统同步，请联系管理员");
		}
		info.setSteel_code(cbsList.get(0).getSteelCode());
		
		
		
		
		
		return info;
		
	}
	
	/**
	 * 加工计划信息同步20230802刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceivePlan(CommonPage<SlmProcessPlan> sum) {
		ResultModel rm = new ResultModel();
		List<SlmProcessPlan> sppList = sum.getObjectList();
		String orderno = sum.getMemo1();
		
		try {
			if (sppList == null || sppList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			for(SlmProcessPlan spp : sppList) {
				spp.setOrder_no(orderno);
				SlmProcessPlan sci = examinePlan(spp);
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmProcessPlanMapper.class).insert(sci);
			}
			
			rm.setData("加工计划接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	public SlmProcessPlan examinePlan(SlmProcessPlan sci) throws Exception {
		
//		if (sci.getPlan_no() == null || "".equals(sci.getPlan_no())) {
//			throw new Exception("缺少加工计划主键");
//		}
		if (sci.getContract_no() == null || "".equals(sci.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (sci.getOrder_seq() == null || "".equals(sci.getOrder_seq())) {
			throw new Exception("缺少订单序号");
		}
//		if (sci.getSteel_code() == null || "".equals(sci.getSteel_code())) {
//			throw new Exception("缺少牌号编号");
//		}
		if (sci.getSteel_name() == null || "".equals(sci.getSteel_name())) {
			throw new Exception("缺少牌号");
		}
		if (sci.getSpec() == null || "".equals(sci.getSpec())) {
			throw new Exception("缺少规格");
		}
		if (sci.getCut_type() == null || "".equals(sci.getCut_type())) {
			throw new Exception("缺少分切方式");
		}
		if (sci.getEstimate_weight() == null || "".equals(sci.getEstimate_weight())) {
			throw new Exception("缺少估算重量");
		}
		if (sci.getCut_order_no() == null || "".equals(sci.getCrosscut_stype())) {
			throw new Exception("缺少分切序号");
		}
		if (sci.getOrder_no() == null || "".equals(sci.getOrder_no())) {
			throw new Exception("缺少订单主键");
		}
		if (sci.getThick() == null || "".equals(sci.getThick())) {
			throw new Exception("缺少厚度");
		}
		if (sci.getWidth() == null || "".equals(sci.getWidth())) {
			throw new Exception("缺少宽度");
		}
		if (sci.getCut_num() == null || "".equals(sci.getCut_num())) {
			throw new Exception("缺少条数");
		}
		if (sci.getCreate_man_no() == null || "".equals(sci.getCreate_man_no())) {
			throw new Exception("缺少创建人编号");
		}
		if (sci.getCreate_man_name() == null || "".equals(sci.getCreate_man_name())) {
			throw new Exception("缺少创建人");
		}
		if (sci.getMsc_desc() == null || "".equals(sci.getMsc_desc())) {
			throw new Exception("缺少冶金规范");
		}
		
		// 获取本地牌号编号：
		List<BaseSteel> cbsList = getSteelCode(sci.getSteel_name());
		if (cbsList.size() <= 0) {
			throw new Exception("牌号：" + sci.getSteel_name() + " 未与优特钢系统同步，请联系管理员");
		}
		sci.setSteel_code(cbsList.get(0).getSteelCode());
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		sci.setContract_line_seq(sci.getOrder_seq());
//		sci.setPlan_no(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
		
		// 根据合同号,和同行号订单序号查询订单表的合同行主键
		
		SlmOrderInfo order = new SlmOrderInfo();
		order.setContract_no(sci.getContract_no());
		order.setOrder_seq(sci.getOrder_seq());
		order.setContract_line_seq(order.getOrder_seq());
		List<SlmOrderInfo> orderL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, null,null, 0, 0);
		if (orderL.size() > 0) {
			sci.setContract_line_no(orderL.get(0).getContract_line_no());
		}
		
		List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(null, " plan_no like concat('"+sci.getContract_line_no()+"','%')"," plan_no desc",0,0);
		int count=1;
		if(list.size()>0){
			String planNo=list.get(0).getPlan_no();
			planNo=planNo.substring(planNo.length()-3);
			count=Integer.parseInt(planNo);
		}	
		String plan_no=sci.getContract_line_no()+String.format("%03d", (count+1));
//		String plan_no=orderL.get(0).getOrder_no();
		sci.setPlan_no(plan_no);
		sci.setEstimate_weight_unit_no("100306");
		sci.setEstimate_weight_unit_name("t");
//		sci.setCreate_time(new Date());
		sci.setPlan_flag("103414");
		sci.setValid_flag("1");
		
		return sci;
		
	}
		
	
	/**
	 * 取消订单下发订单信息20230803刘侣：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelReceiveOrder(CommonPage<SlmOrderInfoNline> sum) {
		ResultModel rm = new ResultModel();
		// 一次接收多条订单
		List<SlmOrderInfoNline> soiList = sum.getObjectList();
		
		try {
			if (soiList == null || soiList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			for (SlmOrderInfoNline soi : soiList) {
				
				// 校验：订单是否存在且有效且是下发状态：传的是订单主键：他们那边没有订单主键，所以使用合同号去查：
				List<SlmOrderInfo> soiL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, " CONTRACT_NO || ORDER_SEQ = '" + soi.getOrder_no() + "'", null, 0, 0);
				if (soiL == null || soiL.size() <= 0) {
					throw new Exception("订单：" + soi.getOrder_no() + " 不存在");
				}
				SlmOrderInfo soiQ = soiL.get(0);
				if (soiQ == null || "".equals(soiQ)) {
					throw new Exception("订单：" + soi.getOrder_no() + " 不存在");
				}
				if (!"1".equals(soiQ.getValid_flag())) {
					throw new Exception("订单：" + soi.getOrder_no() + " 是无效状态");
				}
				// 一体化确认过当前订单没有挂单的卷了：
				if (!"103406".equals(soiQ.getOrder_flag_no())) {
					throw new Exception("订单：" + soi.getOrder_no() + "不是下发状态，请先将订单撤回到待接收状态");
				}
				
				// 且生产订单也没有了：
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+soiQ.getContract_no() + soiQ.getContract_line_seq() + soiQ.getOrder_seq()+"'", null, 0, 0);
				if (ppoL != null && ppoL.size() > 0) {
					// 有生产订单存在：
					throw new Exception("订单：" + soi.getOrder_no() + "已经接收，请先将订单撤回到 待接收 状态");
				}
				
				// 加个校验：订单是否没有卷；得在库：20241010刘侣
				List<YdmProductDetail> ypdL = this.getMapper(YdmProductDetailMapper.class).findWithCondition(null, " ORDERNO='" + soiQ.getContract_no() + soiQ.getContract_line_seq() + soiQ.getOrder_seq() + "' and STATE in ('0', '2', '7')", null, 0, 0);
				if (ypdL != null && ypdL.size() > 0) {
					throw new Exception("订单：" + soi.getOrder_no() + " 上还有未脱单的卷");
				}
				
				// 删除合同行，订单，加工计划：
				// 先注释，防止测试时调用接口insert了：20230912刘侣
				this.getMapper(SlmContractLineInfoMapper.class).delete(soiQ.getContract_line_no());
				this.getMapper(SlmOrderInfoMapper.class).delete(soiQ.getOrder_no());
				this.getMapper(SlmProcessPlanMapper.class).doDelete(soiQ.getContract_no(), soiQ.getContract_line_seq(), soiQ.getOrder_seq());

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "取消订单下发信息同步", "一体化", opr_time, null, null, null, null, soiQ.getContract_no() + soiQ.getContract_line_seq() + soiQ.getOrder_seq());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
			rm.setData("订单取消下发成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}

		return rm;
	}
	
	
	/**
	 * 质量设计接收20230802刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveZLSJ(CommonPage<SlmOrdDesignMscNpl> sum) {
		ResultModel rm = new ResultModel();
		SlmOrdDesignMscNpl sc = sum.getObject();
		
		try {
			if (sc == null) {
				throw new Exception("缺少object参数");
			}
			// 校验质量设计是否design_key（订单的订单号）下发过：
			SlmOrdDesignMsc ismsc = this.getMapper(SlmOrdDesignMscMapper.class).findById(sc.getDesign_key());
			if (ismsc != null) {
				throw new Exception("订单：" + sc.getDesign_key() + " 已经存在质量设计，请联系管理员");
			}
			
			SlmOrdDesignMscNpl sci = examineZLSJ(sc);
			
			// 拼接质量设计主表信息:
			SlmOrdDesignMsc msc = new SlmOrdDesignMsc ();
			msc.setDesign_key(sci.getDesign_key());
			msc.setDesign_seq("01");
			msc.setContract_line_no(sci.getContract_line_no());
			msc.setPsc_desc(sci.getPsc_desc());
			msc.setMsc_desc(sci.getMsc_desc());
			msc.setProd_code(sci.getProd_code());
			msc.setProd_name(sci.getProd_name());
			msc.setSteel_code(sci.getSteel_code());
			msc.setSteel_name(sci.getSteel_name());
			msc.setDelivery_state_desc(sci.getDelivery_state_desc());
			msc.setDelivery_state_code(sci.getDelivery_state_desc()); // 暂时
			msc.setStd_code(sci.getStd_code());
			msc.setStd_name(sci.getStd_name());
			msc.setThick(sci.getThick());
			msc.setWidth(sci.getWidth());
//			msc.setCreate_time(sci.getCreate_time());
//			msc.setCreate_name(sci.getCreate_name());
			msc.setPsc("psc");
			msc.setMsc("msc");
			msc.setValidflag("1");
			msc.setDesign_result("1"); // 评审通过
			msc.setCreate_name("一体化销售");
			msc.setCreate_time(new Date());
			
			msc.setIs_pic_exmt(sci.getIs_pic_exmt()); // 是否需要送样
			
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			this.getMapper(SlmOrdDesignMscMapper.class).insert(msc);
			
			
			SlmOrdDesignMscPl pl = new SlmOrdDesignMscPl();
			pl.setDesign_key(sci.getDesign_key());
			pl.setMsc_pline(sci.getMsc_pline());
			pl.setWhole_backlog(sci.getWhole_backlog());
			pl.setWhole_backlog_desc(sci.getWhole_backlog_desc());
			
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			this.getMapper(SlmOrdDesignMscPlMapper.class).insert(pl);
			
			// 调用生成设计从表数据：
			if (sc.getObjectList() == null || "".equals(sc.getObjectList())) {
				throw new Exception("缺少质量设计明细数据");
			}
			if (sc.getObjectList().size() <= 0) {
				throw new Exception("缺少质量设计明细数据");
			}
			CommonPage<SlmOrdDesignMscPlSti> sti = new CommonPage<>();
			sti.setObjectList(sc.getObjectList());
			ResultModel result = doReceiveZLMX(sti);
			if ("500".equals(result.getState())) {
				throw new Exception(result.getMsgInfo());
			}
			
			rm.setData("质量设计同步成功");
			rm.setState("200");

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收质量设计信息同步", "一体化", opr_time, null, null, null, null, sci.getContract_line_no());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		
		
		return rm;
	}
	
	
	/**
	 * 取消质量设计接收20230802刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDelZLSJ(CommonPage<SlmOrdDesignMscNpl> sum) {
		ResultModel rm = new ResultModel();
		SlmOrdDesignMscNpl sc = sum.getObject();
		
		try {
			if (sc == null) {
				throw new Exception("缺少object参数");
			}
			if (sc.getDesign_key() == null) {
				throw new Exception("缺少质量设计主键");
			}
			
			this.getMapper(SlmOrdDesignMscMapper.class).delete(sc.getDesign_key());
			
			this.getMapper(SlmOrdDesignMscPlMapper.class).DeleteByDesignKey(sc.getDesign_key());
			
			this.getMapper(SlmOrdDesignMscPlStiMapper.class).DeleteByDesignKey(sc.getDesign_key());
		
			rm.setData("删除成功");
			rm.setState("200");

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "取消接收质量设计信息同步", "一体化", opr_time, null, null, null, null, sc.getDesign_key());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	public SlmOrdDesignMscNpl examineZLSJ(SlmOrdDesignMscNpl sci) throws Exception {
		
		if (sci.getDesign_key() == null || "".equals(sci.getDesign_key())) {
			throw new Exception("缺少质量设计主键");
		}
		if (sci.getContract_line_no() == null || "".equals(sci.getContract_line_no())) {
			throw new Exception("缺少订单主键");
		}
		if (sci.getPsc_desc() == null || "".equals(sci.getPsc_desc())) {
			throw new Exception("缺少产品规范描述");
		}
		if (sci.getMsc_desc() == null || "".equals(sci.getMsc_desc())) {
			throw new Exception("缺少冶金规范描述");
		}
		if (sci.getProd_code() == null || "".equals(sci.getMsc_desc())) {
			throw new Exception("缺少产品名称代码");
		}
		if (sci.getProd_name() == null || "".equals(sci.getProd_name())) {
			throw new Exception("缺少产品名称");
		}
		
		if (sci.getSteel_name() == null || "".equals(sci.getSteel_name())) {
			throw new Exception("缺少牌号名称");
		}
		if (sci.getDelivery_state_desc() == null || "".equals(sci.getDelivery_state_desc())) {
			throw new Exception("缺少交货状态");
		}
		if (sci.getStd_code() == null || "".equals(sci.getStd_code())) {
			throw new Exception("缺少标准号代码");
		}
		if (sci.getStd_name() == null || "".equals(sci.getStd_name())) {
			throw new Exception("缺少标准号名称");
		}
		if (sci.getThick() == null || "".equals(sci.getThick())) {
			throw new Exception("缺少厚度");
		}
		if (sci.getWidth() == null || "".equals(sci.getWidth())) {
			throw new Exception("缺少宽度");
		}
		if (sci.getMsc_pline() == null || "".equals(sci.getMsc_pline())) {
			throw new Exception("缺少全程产线号");
		}
		if (sci.getWhole_backlog() == null || "".equals(sci.getWhole_backlog())) {
			throw new Exception("缺少全程产线码");
		}
		if (sci.getWhole_backlog_desc() == null || "".equals(sci.getWhole_backlog_desc())) {
			throw new Exception("缺少全程途径描述");
		}
		
		// 获取本地牌号编号：
		List<BaseSteel> cbsList = getSteelCode(sci.getSteel_name());
		if (cbsList.size() <= 0) {
			throw new Exception("牌号：" + sci.getSteel_name() + " 未与优特钢系统同步，请联系管理员");
		}
		sci.setSteel_code(cbsList.get(0).getSteelCode());
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		sci.setValidflag("1");
		sci.setCreate_time(new Date());
		
		// 设计主表内design_key是订单号：
		sci.setPsc("psc");
		
		
		
		return sci;
		
	}
	
	
	/**
	 * 质量设计明细接收20230802刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveZLMX(CommonPage<SlmOrdDesignMscPlSti> sum) {
		ResultModel rm = new ResultModel();
		List<SlmOrdDesignMscPlSti> customerList = sum.getObjectList();
		
		try {
			if (customerList == null || customerList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			for(SlmOrdDesignMscPlSti customer : customerList) {
				SlmOrdDesignMscPlSti sci = examineZLMX(customer);
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmOrdDesignMscPlStiMapper.class).insert(sci);
			}
			
			rm.setData("质量设计明细接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	public SlmOrdDesignMscPlSti examineZLMX(SlmOrdDesignMscPlSti sci) throws Exception {
		
		if (sci.getDesign_key() == null || "".equals(sci.getDesign_key())) {
			throw new Exception("缺少质量设计主键");
		}
		if (sci.getMsc_pline() == null || "".equals(sci.getMsc_pline())) {
			throw new Exception("缺少全程产线号");
		}
		if (sci.getWhole_backlog() == null || "".equals(sci.getWhole_backlog())) {
			throw new Exception("缺少全程途径码");
		}	
		if (sci.getWhole_backlog_desc() == null || "".equals(sci.getWhole_backlog_desc())) {
			throw new Exception("缺少全程途径描述");
		}
		if (sci.getBacklog_seq() == null || "".equals(sci.getWhole_backlog_desc())) {
			throw new Exception("缺少全程工序顺序号");
		}
		if (sci.getProcess_code() == null || "".equals(sci.getProcess_code())) {
			throw new Exception("缺少工序代码");
		}
		if (sci.getProcess_desc() == null || "".equals(sci.getProcess_desc())) {
			throw new Exception("缺少工序名称");
		}
//		if (sci.getProcess_seq() == null || "".equals(sci.getProcess_seq())) {
//			throw new Exception("缺少同工序流水号");
//		}
//		if (sci.getProcess_code_c() == null || "".equals(sci.getProcess_code_c())) {
//			throw new Exception("缺少二级工序代码");
//		}
//		if (sci.getProcess_desc_c() == null || "".equals(sci.getProcess_desc_c())) {
//			throw new Exception("缺少二级工序名称");
//		}
//		if (sci.getProcess_point_seq() == null || "".equals(sci.getProcess_point_seq())) {
//			throw new Exception("缺少工序点顺序号");
//		}
//		if (sci.getProcess_point_code() == null || "".equals(sci.getProcess_point_seq())) {
//			throw new Exception("缺少工序点代码");
//		}
//		if (sci.getProcess_point_desc() == null || "".equals(sci.getProcess_point_desc())) {
//			throw new Exception("缺少工序点名称");
//		}
//		if (sci.getProcess_point_type() == null || "".equals(sci.getProcess_point_type())) {
//			throw new Exception("缺少工序点类型");
//		}
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
	    // Process_point_code  Process_point_desc  backlog_seq
		sci.setProcess_seq(1L);
		sci.setProcess_point_code(sci.getProcess_code());
		sci.setProcess_point_desc(sci.getProcess_desc());
		sci.setProcess_code_c("processc");
		sci.setProcess_desc_c("processc");
		sci.setProcess_point_seq(1L);
		
		// back_log_seq: 1,2,3  process_point_seq: 1，1，1
		
		
		return sci;
		
	}
	
	/**
	 * 提单头接收20230807刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveBillHeat(CommonPage<SlmLadingBillHeat> sum) {
		ResultModel rm = new ResultModel();
		SlmLadingBillHeat customer = sum.getObject();
		
		try {
			if (customer == null) {
				throw new Exception("缺少object参数");
			}
			
			SlmLadingBillHeat sci = examineBillHeat(customer);
			
			SlmLadingBillHeat billQ = this.getMapper(SlmLadingBillHeatMapper.class).findById(sci.getBill_no());
			if (billQ != null) {
				throw new Exception("提单：" + sci.getBill_no() + " 已经存在");
			}
			
			if (sci.getMemo() != null && "一次结算".equals(sci.getMemo().trim())) {
				sci.setSolutions_name(sci.getSolutions_name() == null ? "优特到优特" : sci.getSolutions_name());
				sci.setSolutions_no(sci.getSolutions_name() == null ? "优特到优特" : sci.getSolutions_name());
				// 如果是一次结算提单的话，提单状态默认：1 编辑
				sci.setValid_status("1");
			} else if (sci.getMemo() != null && sci.getMemo().contains("废副品发运")) {
				sci.setSolutions_name("废副品发运");
				sci.setSolutions_no("废副品发运");
			} else {
				sci.setSolutions_name(sci.getSolutions_name() == null ? "正常装车" : sci.getSolutions_name());
				sci.setSolutions_no(sci.getSolutions_name() == null ? "正常装车" : sci.getSolutions_name());
			}
			
			
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			this.getMapper(SlmLadingBillHeatMapper.class).insert(sci);
			
			if (sci.getObjectList() == null || sci.getObjectList().size() <= 0) {
				throw new Exception("缺少提单明细数据");
			}
			
			// 提单行和提单头：
			CommonPage<SlmLadingBillDetail> sdL = new CommonPage<SlmLadingBillDetail>();
			sdL.setObjectList(sci.getObjectList());
			
			// 分开接收：
			if (sci.getMemo() != null && sci.getMemo().contains("废副品发运")) {
				// 废副品发运提单：
				ResultModel sdRm = doReceiveBillDetailF(sdL);
				if ("500".equals(sdRm.getState())) {
					throw new Exception(sdRm.getMsgInfo());
				}
			} else {
				// 正常发运提单和一次结算提单：
				ResultModel sdRm = doReceiveBillDetail(sdL);
				if ("500".equals(sdRm.getState())) {
					throw new Exception(sdRm.getMsgInfo());
				}
			}
			
			if (sci.getMemo() != null && "一次结算".equals(sci.getMemo())) {
				// 如果是一次结算提单，直接执行一次虚拟发运：
				CommonPage<SlmLadingBillHeat> cp = new CommonPage<>();
				SlmLadingBillHeat heat = new SlmLadingBillHeat();
				heat.setBill_no(sci.getBill_no());
				List<SlmLadingBillHeat> list = new ArrayList<>();
				list.add(heat);
				cp.setObjectList(list);
				
				ResultModel rm2 = doFirstSettleBillYTH(cp);
				if (!"200".equals(rm2.getState())) {
					throw new Exception(rm2.getMsgInfo());
				}
				
				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收提单一次结算成功", "一体化", opr_time, null, null, null, null, sci.getBill_no() + ",memo=" + sci.getMemo());
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
			
			rm.setData("提单接收成功");
			rm.setState("200");

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收提单信息同步", "一体化", opr_time, null, null, null, null, sci.getBill_no() + ",memo=" + sci.getMemo());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 一次结算功能：一体化
	 * @param detail
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doFirstSettleBillYTH(CommonPage<SlmLadingBillHeat> cp) {
		ResultModel rm = new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(now);		
		// *** 防止数据量过大，先第一步进行判断
		List<SlmLadingBillHeat> paramList = cp.getObjectList();
		List<SlmLadingBillHeat> slbhList = new ArrayList<SlmLadingBillHeat>();
		for (SlmLadingBillHeat param : paramList) {
			SlmLadingBillHeat slbh = this.getMapper(SlmLadingBillHeatMapper.class).findById(param.getBill_no());			
			if (slbh!=null) {
				if (!"1".equals(slbh.getValid_status()) || "0".equals(slbh.getValid_flag())) {
					rm.setState("500");
					rm.setMsgInfo("提单【"+param.getBill_no()+"】的状态不是【编辑】或者【提单无效】，无法一次结算");
					return rm;
				}
				if (!slbh.getSolutions_name().contains("到优特")) {
					rm.setState("500");
					rm.setMsgInfo("提单【"+param.getBill_no()+"】的运输方案不含【到优特】，无法一次结算");
					return rm;
				}
//				if (Math.abs((slbh.getCreate_time().getTime()-now.getTime())/1000) < 10) {
//					rm.setState("500");
//					rm.setMsgInfo("操作过快，请稍候。。。。。。");
//					return rm;
//				}
				slbhList.add(slbh);
			}
		}
		
		//开始处理业务逻辑
		try{
			for (SlmLadingBillHeat slbh : slbhList) {
				//1.提单状态直接转换至【实际关闭】
				slbh.setValid_status("11");		//实际关闭
				slbh.setUpdate_man_no(userId);
				slbh.setUpdate_man_name(userName);
				slbh.setUpdate_time(now);
				slbh.setMemo("一次结算");
				slbh.setIssuer_time(now);
				slbh.setIssuer_man_name(userName);
				slbh.setIssuer_man_no(userId);
				this.getMapper(SlmLadingBillHeatMapper.class).update(slbh);
				//理货单号
				String distrbuteno = this.getBean(SpmDeliveryServiceImpl.class).createDistrbuteNO();
				//装车单号
				String outbillno = this.getBean(SpmTransportDetailServiceImpl.class).createOutBillNo();
				//同车序号
				String carSeq = this.getMapper(SpmDeliveryMapper.class).getCode(new SimpleDateFormat("yyyyMMdd").format(new Date()));
				//2.提单行处理：
				String condition = " and bill_no = '"+slbh.getBill_no()+"'";
				List<SlmLadingBillLine> slblList = this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, condition, "line_no desc", 0, 0);
				
				// 接收一体化一次结算提单时自动返回装车实绩：20231021刘侣
				JSONArray ja = new JSONArray();
				// end
				
				for (SlmLadingBillLine slbl : slblList) {
					//2.1 反写实际支数和实际重量
					SlmLadingBillLine SLBL = this.getMapper(SlmLadingBillLineMapper.class).doQuaryRebackForLine(slbl.getLine_no());
					this.getMapper(SlmLadingBillLineMapper.class).update(SLBL);
					//2.2 新增SpmDeliveryDetail
					SpmDeliveryDetail sdd = new SpmDeliveryDetail();
					sdd.setDeliveryno(slbh.getBill_no());
					sdd.setLineNo(slbl.getLine_no());
					sdd.setDistrbutequantity(SLBL.getActual_quantity().intValue());
					sdd.setDisTheoryWeight(SLBL.getDis_theory_weight());
					sdd.setDisFactWeight(SLBL.getDis_fact_weight());
					sdd.setQuantity(SLBL.getActual_quantity().intValue());
					sdd.setLoadFactWeight(SLBL.getActual_weight());
					sdd.setLoadTheoryWeight(SLBL.getDis_theory_weight());
					sdd.setStarttime(slbh.getEffect_start_time());
					sdd.setOvertime(slbh.getEffect_end_time());
					sdd.setCloser(userName);
					sdd.setClosetime(now);
					sdd.setState("3");//已装车
					sdd.setReceiver(userName);
					sdd.setReceivetime(now);
					sdd.setCarno("8");
					sdd.setPlanStartTime(slbh.getEffect_start_time());
					sdd.setPlanEndTime(slbh.getEffect_end_time());
					sdd.setCreater(userName);
					sdd.setCreatedate(now);
					// 销售出厂-提货单实绩表(从)
					this.getMapper(SpmDeliveryDetailMapper.class).insert(sdd);
					
					// 一次结算时将订单由 生产/缴库 改成 发货：20230720刘侣
					SlmOrderInfo orderYC=new SlmOrderInfo();
					orderYC.setContract_no(slbl.getContract_no());
					orderYC.setContract_line_seq(slbl.getContract_line_seq());
					orderYC.setOrder_seq(slbl.getOrder_seq());
					List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(orderYC,0,0);
					if(order_list.size()>0){
						orderYC=order_list.get(0);
						if(orderYC!=null&&("103409".equals(orderYC.getOrder_flag_no())||"103408".equals(orderYC.getOrder_flag_no()))){
							orderYC.setP_order_flag_no(orderYC.getOrder_flag_no());
							orderYC.setP_order_flag_name(orderYC.getOrder_flag_name());
							orderYC.setOrder_flag_no("103410");
							orderYC.setOrder_flag_name("发货");
							this.getMapper(SlmOrderInfoMapper.class).update(orderYC);
						}
					}
					// end
					// 一次结算时计算当前订单内的所有一次结算重量是否达到订单要求的90%：20231007 刘侣
					PlnProdorder pp = new PlnProdorder();
					pp.setOrder_no(slbl.getOrder_no());
					List<PlnProdorder> ppL = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 0);
					if (ppL != null && ppL.size() > 0 && order_list.size()>0) {
						// 获取订单内所有一次结算重量：
						Double ycW = this.getMapper(SlmLadingBillHeatMapper.class).getYCW(slbl.getOrder_no());
						
						if (order_list.get(0).getEstimate_weight() != null) {
							if (ycW >= order_list.get(0).getEstimate_weight() * 0.9) {
								// 订单一次结算总量大于等于订单总量的90%：修改生产订单状态为发货完成：
								ppL.get(0).setStatus("0PAA50");
								this.getMapper(PlnProdorderMapper.class).update(ppL.get(0));
							}
						}
					}
					// end
					
					//3.提单明细处理
					condition = " and line_no = '"+slbl.getLine_no()+"'";
					List<SlmLadingBillDetail> slbdList = this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, condition, "coilno desc", 0, 0);
					if (CollectionUtils.isNotEmpty(slbdList)) {
						
						for (SlmLadingBillDetail slbd : slbdList) {
							//3.0 修改
							
							//3.2 新增SpmTransportDetail 销售出厂-装车单从表
							SpmTransportDetail std = new SpmTransportDetail();
							std.setOutbillno(outbillno);
							std.setDistrbuteno(distrbuteno);
							std.setBillNo(slbd.getBill_no());//特别注意，这里的billNO
							std.setLineNo(slbd.getLine_no());
							std.setLoaddate(now);
							std.setLoadoperator(userName);
							YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(slbd.getCoilno());
							if (ypd!=null) {
								
								// 限制已经一次结算过，不允许再次一次结算20230224刘侣
								if("507102".equals(ypd.getObject_attr())) {
									throw new Exception("卷号：" + slbd.getCoilno() + " 已经是客户属性，不允许再次做一次结算。");
								}
								// end
								
								//3.1 转换客户属性(一次结算，物料不进行出库操作)						
								ypd.setObject_attr("507102");
								ypd.setState("0");
								ypd.setUpdatedate(now);
								ypd.setUpdater(userName);
								this.getMapper(YdmProductDetailMapper.class).update(ypd);
								this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());
								
								
								
								//3.2 调用物料进行跟踪
								PrcMaterielProcess pmp = new PrcMaterielProcess();
								pmp.setObject_no(ypd.getCoilno());
								pmp.setPrc_code("5BYS10");
								pmp.setCreate_time(now);
								pmp.setRemark("一次结算装车出库");
								pmp.setCreate_man_name(userName);
								PrcMaterielProcess pmp1 = new PrcMaterielProcess();
								pmp1.setObject_no(ypd.getCoilno());
								pmp1.setPrc_code("5BYZ10");
								pmp1.setCreate_time(now);
								pmp1.setRemark("一次结算"+time);
								pmp1.setCreate_man_name(userName);
								this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp1);
								this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
								
								std.setObjectno(ypd.getCoilno());
								std.setObjectnotype(ypd.getCoiltype());
								std.setMaterailtype(ypd.getMaterailtype());
								std.setSource(ypd.getSource());					
								std.setBatchno(ypd.getBatchno());
								std.setHeatno(ypd.getHeatno());
								std.setSmpNo(ypd.getSmpno());
								std.setManagementno(ypd.getManagementno());
								std.setStorageattr(ypd.getStorageattr());
								std.setPrdCode(ypd.getProd_code());
								std.setPrdName(ypd.getProd_name());
								std.setStdCode(ypd.getStd_code());
								std.setStdName(ypd.getStd_name());
								std.setUsgCode(ypd.getUse_code());
								std.setUsgName(ypd.getUse_name());
								std.setHeight(ypd.getThick());
								std.setWidth(ypd.getWidth());
								std.setLength(ypd.getLength());
								std.setDiameter(ypd.getDiameter_out());
								std.setInterdiameter(ypd.getDiameter_inn());
								std.setQuantity(1);
								std.setTheoryweight(ypd.getTheoryweight());
								std.setFactweight(ypd.getFactweight());
								std.setCustomerNo(ypd.getCustomer_no());
								std.setCustomerNm(ypd.getCustomer_nm());
								std.setReceivNo(ypd.getReceiv_no());
								std.setReceivNm(ypd.getReceiv_nm());
								std.setOrderno(ypd.getOrderno());
								std.setProdorderno(ypd.getProdorderno());
								std.setSteelcode(ypd.getSteelcode());
								std.setJudgesteelcode(ypd.getJudgesteelcode());
								std.setChemresult(ypd.getChemresult());
								std.setSizeresult(ypd.getSizeresult());							
								std.setSurfaceresult(ypd.getSurfaceresult());
								std.setWeightresult(ypd.getWeightresult());
								std.setJudgeresult(ypd.getJudgeresult());
								std.setPhysresult(ypd.getPhysresult());
								std.setProducedate(ypd.getProducedate());
								std.setProduceteam(ypd.getProduceteam());
								std.setProduceorder(ypd.getProduceorder());
								std.setInteam(ypd.getInteam());
								std.setIndate(ypd.getIndate());
								std.setState("1");
							} else {
								// 直接抛错，来防止一次结算不改变卷子属性成客户20230224刘侣
								throw new Exception("卷号：" + slbd.getCoilno() + " 未查询到，请联系管理员；");
								// end
							}
							std.setOutlistno(null);//一次结算，物料不进行出库操作
							std.setCreater(userName);
							std.setCreatedate(now);
							this.getMapper(SpmTransportDetailMapper.class).doInsert(std);
							
							// 返回装车实绩：
							JSONObject obj = new JSONObject();
							obj.put("transno", std.getBillNo());
							
							SpmDistrbuteMain sdm=new SpmDistrbuteMain();
							sdm.setDeliveryno(std.getBillNo());
							obj.put("carno", "8");
							obj.put("loaddate", new SimpleDateFormat("yyyy-MM-dd").format(std.getLoaddate()));
							obj.put("loadtime", new SimpleDateFormat("HH:mm:ss").format(std.getLoaddate()));
							obj.put("totalwgt", std.getFactweight() != null ? std.getFactweight() / 1000 : std.getFactweight());
							obj.put("pactno", std.getOrderno().substring(0, std.getOrderno().length() - 6));
							obj.put("orderno", std.getOrderno().substring(0, std.getOrderno().length() - 3));
							obj.put("labelno", std.getObjectno());
							obj.put("quantity", std.getQuantity());
							obj.put("wgt", std.getTheoryweight() != null ? std.getTheoryweight() / 1000 : std.getTheoryweight());
							obj.put("thick", std.getHeight());
							obj.put("width", std.getWidth());
							obj.put("length", std.getLength());
							obj.put("transplanno", std.getBillNo());

							ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(std.getJudgesteelcode());
							if (cbs!=null) {
								obj.put("tradeno", cbs.getSteel_name());
							}
							
							YdmProductDetail ypdQQ = this.getMapper(YdmProductDetailMapper.class).doFind(std.getObjectno(), null);
							if (ypdQQ != null) {
								obj.put("stoveno", ypdQQ.getHeatno());
							}
							
							obj.put("rollno", std.getBatchno());
							
							// 如果是实际发运的话，卷子已经出库是没有垛位的
							String butname = this.getMapper(YdmProductDetailMapper.class).doQueryCButtressOne(std.getObjectno());
							if (butname != null) {
								obj.put("buttress", butname);
							}

							String prodline = ypdQQ.getCoilno().contains("S") ? "YTSX" : ypdQQ.getCoilno().contains("L") ? "YTZZ" : ypdQQ.getCoilno().contains("P") ? "YTPZ" : ypdQQ.getCoilno().contains("T") ? "YTTH" : ypdQQ.getCoilno().contains("K") ? "YTHJ" : ypdQQ.getCoilno().contains("F") ? "YTZJ" : "YT1";
							obj.put("prodline", prodline);
							
							ja.add(obj);
							// end 
							
							// 补充装车异动点：20231130刘侣 
							ComBaseCbYdd cd = new ComBaseCbYdd();
							cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
							cd.setInstDisp("01");
							cd.setDataTypeIdx("O");
							// 当前产线：
							String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
							cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setInvQtyUnit("块");
							cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
							cd.setCreateId(userId);
							cd.setActivityId("69A");
							cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
							cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setProdName(ypd.getProd_name());
							cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
							
							String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
							// 上道产线：
							String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
							cd.setRefnoA(prevcoil); // 投料卷号
							cd.setSysId("IA");
							cd.setOrderItem(ypd.getOrderno());
							cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setBeTransUnit("t");
							cd.setExecJobFunc("N");
							ComBaseSteel cbs2 = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
							if (cbs2 != null) {
								cd.setAlloyNo(cbs2.getSteel_name()); // 牌号
							}
							
							cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
							cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
							cd.setProdTypeNo("CTR");
							cd.setAppId("优特钢产出卷发货");
							cd.setInvId(ypd.getCoilno());
							cd.setInvQty("1");
//							cd.setSrcFac("1");
							cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
							cd.setProdClassNo("H");
							
							String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
							
							// setSrcFac根据卷的物料属性去判断：一次结算srcfac固定为1 20231210刘侣
							cd.setSrcFac("1");
							
							// 去掉只有原料卷才需要增加综判异动点,zhouxubin：20231110刘侣
							// 优特钢带属性卷最后一道工序不合格发货时：卷综判判废给11az，其他结果给 11ac和69a:zhouxubin：20231110刘侣
							// 卷判废才给 11az  xuli 20231227
//							if (ypd.getCoilno().length() <= 8) {
								cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
								cd.setActivityId("11AC");
								if ("40740804".equals(ypd.getJudgeresult())) {
									cd.setActivityId("11AZ");
									cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
								}
								cd.setAppId("优特" + currentMName + "综判");
								cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
								cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
								cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
								
								// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
//								doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
//							}
							// end
							
							// 存入表：1、上料一抛：原料转库（47）（原料上料准备生产时抛送）
							cd.setActivityId("69A");
							cd.setExecJobFunc("N");
							cd.setDataTypeIdx("O");
							cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
							cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
							cd.setCoilStus("1"); // 综判前算半成品0，综判入库后算成品1
							cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setManageip(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
							cd.setLocNo(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//							String prevMName = prevcoil.contains("S") ? "酸洗" : prevcoil.contains("L") ? "冷轧" : prevcoil.contains("P") ? "平整" : prevcoil.contains("T") ? "退火" : prevcoil.contains("K") ? "开平" : prevcoil.contains("F") ? "分条" : "原料";
							cd.setAppId("优特" + currentMName + "发货");
							
							doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
							
						}
						
					}
				}

				// 发送装车虚拟装车实绩：
//				System.out.println("一次结算虚拟装车实绩参数：" + ja.toString());
//				// 原来的：http://172.16.0.169/CXZCXSMESIMPL/http/SENDGOODS
//				// http://172.16.0.169:82/CxzcCBDY/http/SENDGOODS 改成杨佳俊的接口：http://172.16.4.136:14008/il/ilApi/sendGoods
//				String result = Connecttt.postJsonParams("http://172.16.4.136:14008/il/ilApi/sendGoods", ja.toString());
//				JsonObject resObj = new JsonParser().parse(result).getAsJsonObject();
////				System.out.println(resObj.get("code"));
//				String code = resObj.get("code").toString();
//				if (!"1000".equals(code)) {
//					throw new Exception("提单装车实绩报错：" + resObj.get("message"));
//				}
				
				// 改为存入READY_SEND_ZCSJ ，后续发送过去：20231221刘侣：这个等周一正式更新
				this.getMapper(YdmProductDetailMapper.class).readySendZCSJ(slbh.getBill_no(), ja.toString());
				// end
				
				//3.新增Spm_Delivery
				SlmLadingBillHeat SLBH = this.getMapper(SlmLadingBillLineMapper.class).doQuaryRebackForBill(slbh.getBill_no());
				SpmDelivery sd = new SpmDelivery();
				sd.setDeliveryno(slbh.getBill_no());
				sd.setDistrbutequantity(SLBH.getQuantity());
				sd.setDisTheoryWeight(SLBH.getDis_theory_weight());
				sd.setDisFactWeight(SLBH.getDis_fact_weight());
				sd.setQuantity(SLBH.getQuantity());
				sd.setLoadTheoryWeight(SLBH.getDis_theory_weight());
				sd.setLoadFactWeight(Double.parseDouble(SLBH.getFact_weight()));
				sd.setStarttime(slbh.getEffect_start_time());
				sd.setOvertime(slbh.getEffect_end_time());
				sd.setReceiver(userName);
				sd.setReceivetime(now);
				sd.setCloser(userName);
				sd.setClosetime(now);
				sd.setIssuer_time(now);
				sd.setState("6");//实际关闭
				sd.setPlanStartTime(slbh.getEffect_start_time());
				sd.setPlanEndTime(slbh.getEffect_end_time());
				sd.setCreater(userName);
				sd.setCreatedate(now);
				sd.setCar_seq(carSeq);//同车序号
				this.getMapper(SpmDeliveryMapper.class).insert(sd);
				//自动脱单
				this.getMapper(YdmProductDetailMapper.class).doTuoDan(sd.getDeliveryno());
				//4. 新增SpmDistrbuteMain理货单主表
				SpmDistrbuteMain sdm = new SpmDistrbuteMain();
				sdm.setDistrbuteno(distrbuteno);//理货单号：主键
				sdm.setDeliveryno(slbh.getBill_no());
				sdm.setLineNo(null);
				sdm.setOutbillno(outbillno);
				sdm.setDistrbutequantity(SLBH.getQuantity());
				sdm.setDisFactWeight(SLBH.getDis_fact_weight());
				sdm.setDisTheoryWeight(SLBH.getDis_theory_weight());
				sdm.setQuantity(SLBH.getQuantity());
				sdm.setLoadfactweight(Double.parseDouble(SLBH.getFact_weight()));//实际重量
				sdm.setLoadtheoryweight(SLBH.getDis_theory_weight());
				sdm.setStarttime(slbh.getEffect_start_time());
				sdm.setOvertime(slbh.getEffect_end_time());
				sdm.setCloser(userName);
				sdm.setClosetime(now);
				sdm.setState("2");
				sdm.setCarno("8");//一次结算：装8
				sdm.setLoadstore("500203");//固定，整个表都是500203
				sdm.setPlanStartTime(slbh.getEffect_start_time());
				sdm.setPlanEndTime(slbh.getEffect_end_time());
				sdm.setCreater(userName);
				sdm.setCreatedate(now);
				this.getMapper(SpmDistrbuteMainMapper.class).insert(sdm);
				
				// 对每个提货单号进行检测，看是否生成了spm几个表的数据：如果一次结算失败spm几个表是没有数据的：2023109刘侣
				List<SpmDistrbuteMain> sdmL = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, " DELIVERYNO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (sdmL == null || sdmL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmDistrbuteMain");
				}
				List<SpmTransportDetail> ssdL = this.getMapper(SpmTransportDetailMapper.class).findWithCondition(null, " BILL_NO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (ssdL == null || ssdL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmTransportDetail");
				}
				List<SpmDelivery> sdlL = this.getMapper(SpmDeliveryMapper.class).findWithCondition(null, " DELIVERYNO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (sdlL == null || sdlL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmDelivery");
				}
				// end
			}
		}catch(Exception e){
			// 如果有trycatch，则需要设置手动20230304 刘侣
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			// end
			rm.setState("500");
			rm.setMsgInfo("一次结算失败："+e.getMessage());
			return rm;
		}
		rm.setState("200");
		rm.setMsgInfo("一次结算成功");
		return rm;
	}
	
	
	
	public SlmLadingBillHeat examineBillHeat(SlmLadingBillHeat sci) throws Exception {
		
		if (sci.getBill_no() == null || "".equals(sci.getBill_no())) {
			throw new Exception("缺少提单编号");
		}
		if (sci.getCustomer_no() == null || "".equals(sci.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (sci.getCustomer_name() == null || "".equals(sci.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
		if (sci.getReciver_address() == null || "".equals(sci.getReciver_address())) {
			throw new Exception("缺少收货地址");
		}
		if (sci.getCreate_man_name() == null || "".equals(sci.getCreate_man_name())) {
			throw new Exception("缺少创建人");
		}
		if (sci.getCreate_man_no() == null || "".equals(sci.getCreate_man_no())) {
			throw new Exception("缺少创建人编号");
		}
		if (sci.getContract_no() == null || "".equals(sci.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (sci.getTrans_type() == null || "".equals(sci.getTrans_type())) {
			throw new Exception("缺少提单类型");
		}
		if (sci.getObjectList() == null || sci.getObjectList().size() <= 0) {
			throw new Exception("缺少提单明细");
		}
		if (sci.getReciver_unit_name() == null || "".equals(sci.getReciver_unit_name())) {
			throw new Exception("缺少收货单位");
		}
		
		
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
		sci.setSupplier_unit_no("20180122102823908069");
		sci.setSupplier_unit_name("新余新钢优特钢带有限公司");
		sci.setSupplier_address("新钢公司创效路");
//		sci.setReciver_unit_no(sci.getCustomer_no());
//		sci.setReciver_unit_name(sci.getCustomer_name());
		sci.setTrans_unit_no("506001");
		sci.setTrans_unit_name("中新物流");
		sci.setBill_type("1");
		sci.setValid_status("4"); // 默认下发状态
		sci.setEffect_start_time(new Date());
		// 默认开始时间后的一个月：
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		sci.setEffect_end_time(cal.getTime());
		sci.setValid_flag("1");
		sci.setCreate_time(new Date());
		sci.setIssuer_man_no(sci.getCustomer_no());
		sci.setIssuer_man_name(sci.getCustomer_name());
		sci.setIssuer_time(new Date());
		return sci;
		
	}
	
	
	/**
	 * 提单明细接收20230807刘侣：需要批量
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveBillDetail(CommonPage<SlmLadingBillDetail> sum) {
		ResultModel rm = new ResultModel();
		List<SlmLadingBillDetail> customerList = sum.getObjectList();
		
		try {
			if (customerList == null || customerList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			// 还得生成提单行数据：
//			Double billWeight = 0.00;
			
			// 有多少明细生成多少提单行：
			for(SlmLadingBillDetail customer : customerList) {
				SlmLadingBillDetail sci = examineBillDetail(customer);
				// 生成提单行：
				SlmLadingBillLine sbl = new SlmLadingBillLine();
				sbl.setLine_no(sci.getDetail_no());
				sbl.setBill_no(sci.getBill_no());
				sbl.setContract_no(sci.getContract_no());
				// 根据合同号,和同行好订单序号查询订单表的合同行主键
				SlmOrderInfo order = new SlmOrderInfo();
				order.setContract_no(sci.getContract_no());
				order.setOrder_seq(sci.getOrder_seq());
				order.setContract_line_seq(sci.getOrder_seq());
				List<SlmOrderInfo> orderL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, null,null, 0, 0);
				if (orderL.size() > 0) {
					sbl.setContract_line_no(orderL.get(0).getContract_line_no());
					sbl.setPsc_desc(orderL.get(0).getPsc_desc());
					sbl.setWeight_type_no(orderL.get(0).getWeight_type_no());
					sbl.setWeight_type_name(orderL.get(0).getWeight_type_name());
					sbl.setOrder_nature(orderL.get(0).getOrder_nature());
					sbl.setProcess(orderL.get(0).getProcess());
				} else {
					throw new Exception("订单：" + order.getContract_no() + order.getOrder_seq() + " 未找到。");
				}
				sbl.setOrder_no(sci.getContract_no() + sci.getOrder_seq() + sci.getOrder_seq());
//				for(SlmLadingBillDetail customerIn : customerList) {
//					billWeight += (customerIn.getFactweight() == null ? 0 : customerIn.getFactweight());
//				}
				sbl.setBill_weight(sci.getFactweight());
				sbl.setActual_weight(sci.getFactweight());
				sbl.setActual_quantity(1.00);
				sbl.setBill_weight_unit_no("100306");
				sbl.setBill_weight_unit_name("t");
				sbl.setValid_flag("1");
				sbl.setCreate_man_no(sci.getCreate_man_no());
				sbl.setCreate_man_name(sci.getCreate_man_name());
				sbl.setCreate_time(new Date());
				sbl.setContract_pk(sci.getContract_pk());
				sbl.setOrder_seq(sci.getOrder_seq());
				sbl.setContract_line_seq(sci.getOrder_seq());
				sbl.setIs_detail("1");
				sbl.setGross_weight(sci.getFactweight());
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmLadingBillLineMapper.class).insert(sbl);
				
				// 生成提单明细：
				
				sci.setLine_no(sbl.getLine_no());
				
				sci.setContract_line_no(sbl.getContract_line_no());
				sci.setContract_line_seq(sbl.getOrder_seq());
				
				// 得校验卷号是否在库，并将它改成发运锁定：
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(sci.getCoilno(), null);
				if (ypd == null || "".equals(ypd)) {
					throw new Exception("卷号：" + ypd.getCoilno() + " 不存在，不能下发提单");
				}
				if (!"0".equals(ypd.getState())) {
					throw new Exception("卷号：" + ypd.getCoilno() + " 不在库，不能下发提单");
				}
				// 如果是否可发运不可发，也不行：
				if (ypd.getIs_can_load() == null || "0".equals(ypd.getIs_can_load())) {
					throw new Exception("卷号：" + ypd.getCoilno() + " 不是可发运状态，不能下发提单");
				}

				// 得检测卷是否满足：当卷的订单包装要求非裸包时，卷是否存在包装实绩：20240723刘侣
				int resNum = this.getMapper(SlmLadingBillHeatMapper.class).isMeetRequire(sci.getCoilno());
				if (resNum <= 0) {
					throw new Exception("卷号：" + sci.getCoilno() + " 未包装，无法接收提单明细");
				}
				
				// 如果是综判不合格，也不行：
				if (ypd.getJudgeresult() == null) {
					throw new Exception("卷号：" + ypd.getCoilno() + " 综判不存在，不能下发提单");
				}
				
				List<PlnMaterielDetail> pmdL = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "object_no = '"+ypd.getCoilno()+"' and nvl(invalid_flg,0) = 0", "", 0, 0);
				if (pmdL != null && pmdL.size() > 0) {
					if (pmdL.get(0).getNext_process_code() != null) {
						throw new Exception("卷 " + ypd.getCoilno() + " 存在下道加工工序");
					}
				}
				
				// 如果是以XB,XS结尾合同的协议品，就不需要综判合格，只需要综判了：
				if (sci.getContract_no().contains("XB") || sci.getContract_no().contains("XS") || sci.getContract_no().startsWith("67") || sci.getContract_no().startsWith("X67")) {
					// 协议品
				} else {
					// 普通合同：就需要验证卷子是否综判合格；
					if (!"40740801".equals(ypd.getJudgeresult())) {
						throw new Exception("卷号：" + ypd.getCoilno() + " 综判不合格，不能下发提单");
					}
				}
				
				// 卷是否已经在有效的提单内了：
				String billNo = this.getMapper(SlmLadingBillDetailMapper.class).isCunZai(sci.getCoilno());
				if (billNo != null && "".equals(billNo)) {
					// 这个卷已经存在在提单明细内：
					throw new Exception("卷号：" + ypd.getCoilno() + " 已经存在在提单：" + billNo);
				}
				
				ypd.setState("2");
				ypd.setBill_no(sci.getBill_no());
				ypd.setLine_no(sci.getLine_no());
				this.getMapper(YdmProductDetailMapper.class).update(ypd);
				this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmLadingBillDetailMapper.class).insert(sci);
			}
			
			
			rm.setData("提单接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 废副品提单明细接收20241128 刘侣：需要批量 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReceiveBillDetailF(CommonPage<SlmLadingBillDetail> sum) {
		ResultModel rm = new ResultModel();
		List<SlmLadingBillDetail> customerList = sum.getObjectList();
		
		try {
			if (customerList == null || customerList.size() == 0) {
				throw new Exception("缺少objectList参数");
			}
			
			// 还得生成提单行数据：
//			Double billWeight = 0.00;
			
			// 有多少明细生成多少提单行：
			for(SlmLadingBillDetail customer : customerList) {
				SlmLadingBillDetail sci = examineBillDetailF(customer);
				// 生成提单行：
				SlmLadingBillLine sbl = new SlmLadingBillLine();
				sbl.setLine_no(sci.getDetail_no());
				sbl.setBill_no(sci.getBill_no());
				sbl.setContract_no(sci.getContract_no());
				// 根据合同号,和同行好订单序号查询订单表的合同行主键
				SlmOrderInfo order = new SlmOrderInfo();
				order.setContract_no(sci.getContract_no());
				order.setOrder_seq(sci.getOrder_seq());
				order.setContract_line_seq(sci.getOrder_seq());
				List<SlmOrderInfo> orderL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, null,null, 0, 0);
				if (orderL.size() > 0) {
					sbl.setContract_line_no(orderL.get(0).getContract_line_no());
					sbl.setPsc_desc(orderL.get(0).getPsc_desc());
					sbl.setWeight_type_no(orderL.get(0).getWeight_type_no());
					sbl.setWeight_type_name(orderL.get(0).getWeight_type_name());
					sbl.setOrder_nature(orderL.get(0).getOrder_nature());
					sbl.setProcess(orderL.get(0).getProcess());
				} else {
					throw new Exception("订单：" + order.getContract_no() + order.getOrder_seq() + " 未找到。");
				}
				sbl.setOrder_no(sci.getContract_no() + sci.getOrder_seq() + sci.getOrder_seq());
//				for(SlmLadingBillDetail customerIn : customerList) {
//					billWeight += (customerIn.getFactweight() == null ? 0 : customerIn.getFactweight());
//				}
				sbl.setBill_weight(sci.getFactweight());
				sbl.setActual_weight(sci.getFactweight());
				sbl.setActual_quantity(1.00);
				sbl.setBill_weight_unit_no("100306");
				sbl.setBill_weight_unit_name("t");
				sbl.setValid_flag("1");
				sbl.setCreate_man_no(sci.getCreate_man_no());
				sbl.setCreate_man_name(sci.getCreate_man_name());
				sbl.setCreate_time(new Date());
				sbl.setContract_pk(sci.getContract_pk());
				sbl.setOrder_seq(sci.getOrder_seq());
				sbl.setContract_line_seq(sci.getOrder_seq());
				sbl.setIs_detail("1");
				sbl.setGross_weight(sci.getFactweight());
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmLadingBillLineMapper.class).insert(sbl);
				
				// 生成提单明细：
				sci.setLine_no(sbl.getLine_no());
				sci.setContract_line_no(sbl.getContract_line_no());
				sci.setContract_line_seq(sbl.getOrder_seq());
				
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmLadingBillDetailMapper.class).insert(sci);
			}
			
			
			rm.setData("废副品提单接收成功");
			rm.setState("200");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	public SlmLadingBillDetail examineBillDetail(SlmLadingBillDetail sci) throws Exception {
		
		if (sci.getBill_no() == null || "".equals(sci.getBill_no())) {
			throw new Exception("缺少提单编号");
		}
		if (sci.getContract_no() == null || "".equals(sci.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (sci.getDetail_no() == null || "".equals(sci.getDetail_no())) {
			throw new Exception("缺少提单明细编号");
		}
//		if (sci.getOrder_no() == null || "".equals(sci.getOrder_no())) {
//			throw new Exception("缺少订单编号");
//		}
		if (sci.getContract_pk() == null || "".equals(sci.getContract_pk())) {
			throw new Exception("缺少合同主键");
		}
		if (sci.getOrder_seq() == null || "".equals(sci.getOrder_seq())) {
			throw new Exception("缺少订单序号");
		}
		if (sci.getCustomer_no() == null || "".equals(sci.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (sci.getCustomer_name() == null || "".equals(sci.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
		if (sci.getCoilno() == null || "".equals(sci.getCoilno())) {
			throw new Exception("缺少卷号");
		}
		if (sci.getStd_code() == null || "".equals(sci.getStd_code())) {
			throw new Exception("缺少标准号代码");
		}
		if (sci.getStd_name() == null || "".equals(sci.getStd_name())) {
			throw new Exception("缺少标准号名称");
		}
//		if (sci == null || "".equals(sci.getStd_name())) {
//			throw new Exception("缺少标准号名称");
//		}
//		if (sci.getJudgesteelcode() == null || "".equals(sci.getJudgesteelcode())) {
//			throw new Exception("缺少牌号编号");
//		}
		if (sci.getJudgesteelcname() == null || "".equals(sci.getJudgesteelcname())) {
			throw new Exception("缺少牌号");
		}
		if (sci.getProd_code() == null || "".equals(sci.getProd_code())) {
			throw new Exception("缺少品名编号");
		}
		if (sci.getProd_name() == null || "".equals(sci.getProd_name())) {
			throw new Exception("缺少品名");
		}
//		if (sci.getThick() == null || "".equals(sci.getThick())) {
//			throw new Exception("缺少厚度");
//		}
//		if (sci.getWidth() == null || "".equals(sci.getWidth())) {
//			throw new Exception("缺少宽度");
//		}
		if (sci.getFactweight() == null || "".equals(sci.getFactweight())) {
			throw new Exception("缺少实重");
		}
//		if (sci.getTheoryweight() == null || "".equals(sci.getTheoryweight())) {
//			throw new Exception("缺少理重");
//		}
		if (sci.getCreate_man_no() == null || "".equals(sci.getCreate_man_no())) {
			throw new Exception("缺少创建人编号");
		}
		if (sci.getCreate_man_name() == null || "".equals(sci.getCreate_man_name())) {
			throw new Exception("缺少创建人");
		}
		if (sci.getReciver_unit_name() == null || "".equals(sci.getReciver_unit_name())) {
			throw new Exception("缺少收货单位");
		}
		
		// 获取本地牌号编号：
		List<BaseSteel> cbsList = getSteelCode(sci.getJudgesteelcname());
		if (cbsList.size() <= 0) {
			throw new Exception("牌号：" + sci.getSteel_name() + " 未与优特钢系统同步，请联系管理员");
		}
		sci.setJudgesteelcode(cbsList.get(0).getSteelCode());
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
//		sci.setReciver_unit_no(sci.getCustomer_no());
//		sci.setReciver_unit_name(sci.getCustomer_name());
		sci.setCreate_time(new Date());
		sci.setOrder_no(sci.getContract_no() + sci.getOrder_seq() + sci.getOrder_seq());
		
		// 根据卷号获取原料卷号：
		YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(sci.getCoilno(), null);
		sci.setMaterailcoilno(ypd.getMaterailcoilno());
		return sci;
		
	}
	
	public SlmLadingBillDetail examineBillDetailF(SlmLadingBillDetail sci) throws Exception {
		
		if (sci.getBill_no() == null || "".equals(sci.getBill_no())) {
			throw new Exception("缺少提单编号");
		}
		if (sci.getContract_no() == null || "".equals(sci.getContract_no())) {
			throw new Exception("缺少合同号");
		}
		if (sci.getDetail_no() == null || "".equals(sci.getDetail_no())) {
			throw new Exception("缺少提单明细编号");
		}
//		if (sci.getOrder_no() == null || "".equals(sci.getOrder_no())) {
//			throw new Exception("缺少订单编号");
//		}
		if (sci.getContract_pk() == null || "".equals(sci.getContract_pk())) {
			throw new Exception("缺少合同主键");
		}
		if (sci.getOrder_seq() == null || "".equals(sci.getOrder_seq())) {
			throw new Exception("缺少订单序号");
		}
		if (sci.getCustomer_no() == null || "".equals(sci.getCustomer_no())) {
			throw new Exception("缺少客户编号");
		}
		if (sci.getCustomer_name() == null || "".equals(sci.getCustomer_name())) {
			throw new Exception("缺少客户名称");
		}
//		if (sci.getCoilno() == null || "".equals(sci.getCoilno())) {
//			throw new Exception("缺少卷号");
//		}
		if (sci.getStd_code() == null || "".equals(sci.getStd_code())) {
			throw new Exception("缺少标准号代码");
		}
		if (sci.getStd_name() == null || "".equals(sci.getStd_name())) {
			throw new Exception("缺少标准号名称");
		}
//		if (sci == null || "".equals(sci.getStd_name())) {
//			throw new Exception("缺少标准号名称");
//		}
//		if (sci.getJudgesteelcode() == null || "".equals(sci.getJudgesteelcode())) {
//			throw new Exception("缺少牌号编号");
//		}
		if (sci.getJudgesteelcname() == null || "".equals(sci.getJudgesteelcname())) {
			throw new Exception("缺少牌号");
		}
		if (sci.getProd_code() == null || "".equals(sci.getProd_code())) {
			throw new Exception("缺少品名编号");
		}
		if (sci.getProd_name() == null || "".equals(sci.getProd_name())) {
			throw new Exception("缺少品名");
		}
//		if (sci.getThick() == null || "".equals(sci.getThick())) {
//			throw new Exception("缺少厚度");
//		}
//		if (sci.getWidth() == null || "".equals(sci.getWidth())) {
//			throw new Exception("缺少宽度");
//		}
		if (sci.getFactweight() == null || "".equals(sci.getFactweight())) {
			throw new Exception("缺少实重");
		}
//		if (sci.getTheoryweight() == null || "".equals(sci.getTheoryweight())) {
//			throw new Exception("缺少理重");
//		}
		if (sci.getCreate_man_no() == null || "".equals(sci.getCreate_man_no())) {
			throw new Exception("缺少创建人编号");
		}
		if (sci.getCreate_man_name() == null || "".equals(sci.getCreate_man_name())) {
			throw new Exception("缺少创建人");
		}
		if (sci.getReciver_unit_name() == null || "".equals(sci.getReciver_unit_name())) {
			throw new Exception("缺少收货单位");
		}
		
		// 获取本地牌号编号：
		List<BaseSteel> cbsList = getSteelCode(sci.getJudgesteelcname());
		if (cbsList.size() <= 0) {
//			throw new Exception("牌号：" + sci.getSteel_name() + " 未与优特钢系统同步，请联系管理员");
		}
		sci.setJudgesteelcode(cbsList.get(0).getSteelCode());
		
		// 有些字段没有：需要手动补充，比如可以写死的，可以截取的这些；
//		sci.setReciver_unit_no(sci.getCustomer_no());
//		sci.setReciver_unit_name(sci.getCustomer_name());
		sci.setCreate_time(new Date());
		sci.setOrder_no(sci.getContract_no() + sci.getOrder_seq() + sci.getOrder_seq());
		
		// 废副品发运：没有卷号和原料卷号，自己编 20241128 刘侣
		// F + 24 + B + 0001 + H0101
		String coilNo = this.getMapper(SlmLadingBillHeatMapper.class).getFCoil();
		
		sci.setCoilno(coilNo);
		sci.setMaterailcoilno(coilNo);
		
		sci.setThick(0.00);
		sci.setWidth(0.00);
		sci.setLen(0.00);
		
		return sci;
		
	}
	
	/**
	 * 存入data的json数据到表里：20230811刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCbDataIns(ComBaseCbYdd cd, String activity, String mat_coil) {
		ResultModel rm = new ResultModel("200", "成功");
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date date = new Date();
		
		try {
			
			cd.setCreateId(username != null ? username : cd.getCreateId());
			
		
			// 组装data：
			JSONObject data = new JSONObject();
			data.put("coilStus", cd.getCoilStus());
			data.put("instDisp", cd.getInstDisp());
			data.put("dataTypeIdx", cd.getDataTypeIdx());
			data.put("locNo", cd.getLocNo());
			data.put("invQtyUnit", cd.getInvQtyUnit());
			data.put("invWidth", cd.getInvWidth());
			data.put("CreateId", cd.getCreateId() == null ? "管理员" : cd.getCreateId());
			data.put("activityId", cd.getActivityId());
			data.put("invLength", cd.getInvLength());
			data.put("manageip", cd.getManageip());
			data.put("ProdName", cd.getProdName());
			data.put("invThick", cd.getInvThick());
			data.put("RefnoA", cd.getRefnoA());
			data.put("SysId", cd.getSysId());
			data.put("orderItem", cd.getOrderItem());
			data.put("crntMill", cd.getCrntMill());
			data.put("beTransUnit", cd.getBeTransUnit());
			data.put("execJobFunc", cd.getExecJobFunc());
			data.put("AlloyNo", cd.getAlloyNo());
			data.put("acctDate", cd.getAcctDate());
			data.put("lastMill", cd.getLastMill());
			data.put("beTransWgt", cd.getBeTransWgt());
			data.put("prodTypeNo", cd.getProdTypeNo());
			data.put("AppId", cd.getAppId());
			data.put("InvId", cd.getInvId());
			data.put("invQty", cd.getInvQty());
			data.put("srcFac", cd.getSrcFac());
			data.put("grade", cd.getGrade());
			data.put("prodClassNo", cd.getProdClassNo());
			
			// 组装待insert数据：
			ComBaseCbYddToYth cy = new ComBaseCbYddToYth();
			cy.setQueueid(activity); // 先固定和 activityid 一样
			cy.setData(data.toString());
			cy.setTimestramp(date.getTime() + "");
			cy.setCreate_time(date);
			cy.setIs_send("0"); // 默认为0，未发送
			cy.setOperation(cd.getInvId() + cd.getAppId());
			// 得需要一个唯一值：uuid DataHelper.getUUID()
			cy.setGuid(DataHelper.getUUID());
			
			
			// 存入CBYDD_TO_YTH 表内：
			this.getMapper(ComBaseCbYddToYthMapper.class).insert(cy);
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	/**
	 * 存入data的json数据到表里：20231013刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doProsIns(PrcMaterielProcess cd) {
		ResultModel rm = new ResultModel("200", "成功");
//		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date date = new Date();
		
		try {
			// 组装data：
			JSONObject data = new JSONObject();
			data.put("serial_no", cd.getSerial_no());
			data.put("object_no", cd.getObject_no());
			data.put("prc_code_bf", cd.getPrc_code_bf());
			data.put("prc_code", cd.getPrc_code());
			data.put("order_no", cd.getOrder_no());
			data.put("prod_order_no", cd.getProd_order_no());
			data.put("lw_design_no", cd.getLw_design_no());
			data.put("rl_design_no", cd.getRl_design_no());
			data.put("sr_design_no", cd.getSr_design_no());
			data.put("an_design_no", cd.getAn_design_no());
			data.put("pc_design_no", cd.getPc_design_no());
			data.put("lw_plan_no", cd.getLw_plan_no());
			data.put("rl_plan_no", cd.getRl_plan_no());
			data.put("sr_plan_no", cd.getSr_plan_no());
			data.put("an_plan_no", cd.getAn_plan_no());
			data.put("pc_plan_no", cd.getPc_plan_no());
			data.put("create_man_name", cd.getCreate_man_name());
			data.put("create_time", new SimpleDateFormat("yyyyMMddHHmmss").format(cd.getCreate_time()));
			data.put("invalid_flg", cd.getInvalid_flg());
			data.put("remark", cd.getRemark());
			
			// type: 20 insert update, 21 delete
			
			// 组装待insert数据：
			Tbdipdo cy = new Tbdipdo();
			cy.setTimestamp(date.getTime());
			cy.setSerialno(DataHelper.getUUID());
			cy.setQueueid("20");
			cy.setHeader(cd.getSerial_no() + "");
			cy.setData(data.toString());
			cy.setStatus("0");
			cy.setProcesstime(date);
			cy.setDescription(cd.getObject_no());
		
			
			// 存入CBYDD_TO_YTH 表内：
			this.getMapper(TbdipdoMapper.class).insert(cy);
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	
	/**
	 * 存入data的json数据到表里：20231013刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doProsUpd(PrcMaterielProcess cd) {
		ResultModel rm = new ResultModel("200", "成功");
//		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date date = new Date();
		
		// 获取更新后的数据：
		cd = this.getMapper(PrcMaterielProcessMapper.class).findById(cd.getSerial_no());
		
		try {
			// 组装data：
			JSONObject data = new JSONObject();
			data.put("serial_no", cd.getSerial_no());
			data.put("object_no", cd.getObject_no());
			data.put("prc_code_bf", cd.getPrc_code_bf());
			data.put("prc_code", cd.getPrc_code());
			data.put("order_no", cd.getOrder_no());
			data.put("prod_order_no", cd.getProd_order_no());
			data.put("lw_design_no", cd.getLw_design_no());
			data.put("rl_design_no", cd.getRl_design_no());
			data.put("sr_design_no", cd.getSr_design_no());
			data.put("an_design_no", cd.getAn_design_no());
			data.put("pc_design_no", cd.getPc_design_no());
			data.put("lw_plan_no", cd.getLw_plan_no());
			data.put("rl_plan_no", cd.getRl_plan_no());
			data.put("sr_plan_no", cd.getSr_plan_no());
			data.put("an_plan_no", cd.getAn_plan_no());
			data.put("pc_plan_no", cd.getPc_plan_no());
			data.put("create_man_name", cd.getCreate_man_name());
			data.put("create_time", new SimpleDateFormat("yyyyMMddHHmmss").format(cd.getCreate_time()));
			data.put("invalid_flg", cd.getInvalid_flg());
			data.put("remark", cd.getRemark());
			
			// type: 20 insert update, 21 delete
			
			// 组装待insert数据：
			Tbdipdo cy = new Tbdipdo();
			cy.setTimestamp(date.getTime());
			cy.setSerialno(DataHelper.getUUID());
			cy.setQueueid("20");
			cy.setHeader(cd.getSerial_no() + "");
			cy.setData(data.toString());
			cy.setStatus("0");
			cy.setProcesstime(date);
			cy.setDescription(cd.getObject_no());
		
			
			// 存入CBYDD_TO_YTH 表内：
			this.getMapper(TbdipdoMapper.class).insert(cy);
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	
	/**
	 * 20230825刘侣，物料进程（增加接口提供给一体化5分钟调一次）查询的就是物料进程表的数据
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel queryProcessPerF(CommonPage<YdmProductDetail> sum) {
		ResultModel rm = new ResultModel("200", "成功");
		String startTime = sum.getStartTime();
		String endTime = sum.getEndTime();
		if (startTime == null || endTime == null) {
			rm.setState("500");
			rm.setMsgInfo("请传入时间");
			return rm;
		}
		List<PrcMaterielProcess> hashmap = this.getMapper(PrcMaterielProcessMapper.class).queryProcessPerF(startTime, endTime);
		
		rm.setData(hashmap);
		return rm;
		
	}
	
	/**
	 * 20231011刘侣，物料进程（增加接口提供给一体化5分钟调一次）查询的就是物料进程表的数据
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel queryProcessByCoil(String coilNo) {
		ResultModel rm = new ResultModel("200", "成功");
		
		if (coilNo == null || "".equals(coilNo)) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号");
			return rm;
		}
		List<PrcMaterielProcess> hashmap = this.getMapper(PrcMaterielProcessMapper.class).queryProcessByCoil(coilNo);
		
		rm.setData(hashmap);
		return rm;
		
	}
	
	/**
	 * 20231022刘侣，轧机和退火机组根据生产开始时间和结束时间查询数据
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel machinesProdTime(CommonPage<YdmProductDetail> sum) {
		ResultModel rm = new ResultModel("200", "查询成功");
		String startTime = sum.getStartTime() + " 00:00:00";
		String endTime = sum.getEndTime() + " 23:59:59";
		String machine = sum.getMemo1();
		if (startTime == null || endTime == null) {
			rm.setState("500");
			rm.setMsgInfo("请传入时间");
			return rm;
		}
		if (machine == null || "".equals(machine)) {
			rm.setState("500");
			rm.setMsgInfo("请传入产线");
			return rm;
		}
		
		// 根据不同产线：
		if ("YTTH".equals(machine)) {
			rm.setData(this.getMapper(PrcMaterielProcessMapper.class).queryTHProd(startTime, endTime));
		}else if ("YTZZ".equals(machine)) {
			rm.setData(this.getMapper(PrcMaterielProcessMapper.class).queryZZProd(startTime, endTime));
		}
		
		return rm;
		
	}
	
	/**
	 * 20230829刘侣，合同订单加工计划撤回：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doContractBack(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm = new ResultModel("200", "成功");
		try {
			SlmContractHeatInfo sh = sum.getObject();
			if (sh == null || "".equals(sh)) {
				throw new Exception("缺少object参数");
			}
			String contractNo = sh.getContract_no();
			if (contractNo == null || "".equals(contractNo)) {
				throw new Exception("缺少合同号");
			}
			// 对订单进行校验：订单回退到待接收，订单表状态为：Order_flag_no("103406") 下发，
			// 只要对订单状态进行校验即可：
			SlmOrderInfo soi = new SlmOrderInfo();
			soi.setContract_no(contractNo);
			List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).find(soi, 0, 0);
			if (soiList == null || soiList.size() <= 0) {
				throw new Exception("未找到订单");
			}
			for(SlmOrderInfo s : soiList) {
				if (!"103406".equals(s.getOrder_flag_no())) {
					throw new Exception("订单 " + s.getContract_no() + "" + s.getContract_line_seq() + "" + s.getOrder_seq() + " 的状态不为 待接收 状态");
				}
			}
			
			// 执行删除合同头：
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			this.getMapper(SlmContractHeatInfoMapper.class).doDelete(contractNo);
			
			// 删除合同行和订单：一个订单一个合同行
			for(SlmOrderInfo s : soiList) {
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmContractLineInfoMapper.class).delete(s.getContract_line_no());
				this.getMapper(SlmOrderInfoMapper.class).delete(s.getOrder_no());
				
				// 删除加工计划：
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(SlmProcessPlanMapper.class).doDelete(s.getContract_no(), s.getContract_line_seq(), s.getOrder_seq());
			}

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "合同订单加工计划撤回信息同步", "一体化", opr_time, null, null, null, null, contractNo);
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
		
	}

	/**
	 * 20230829刘侣，提单撤回：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doLadingBillBack(CommonPage<SlmLadingBillHeat> sum) {
		ResultModel rm = new ResultModel("200", "提单作废成功");
		try {
			if(sum.getObject() == null || "".equals(sum.getObject())) {
				throw new Exception("缺少object参数");
			}
			SlmLadingBillHeat bill = sum.getObject();
			String billNo = bill.getBill_no();
			if (billNo == null || "".equals(billNo)) {
				throw new Exception("缺少提单号");
			}
			// ladingbill得存在，得是有效状态：
			SlmLadingBillHeat billQ = this.getMapper(SlmLadingBillHeatMapper.class).findById(billNo);
			if (billQ == null) {
				throw new Exception("提单：" + billNo + " 不存在");
			}
			// 提单头和提单行只能无效：提单明细要删除；
			if ("0".equals(billQ.getValid_flag())) {
				throw new Exception("提单：" + billNo + " 已经是无效状态");
			}
			// 4是下发状态：不为4，就意味着提单已经接收，需要撤回到下发待接收状态;
			if (!"4".equals(billQ.getValid_status())) {
				throw new Exception("提单：" + billNo + " 已经接收，请先撤销提单接收。");
			}
			SpmDelivery spmQ = this.getMapper(SpmDeliveryMapper.class).findById(billNo);
			if (spmQ != null && "".equals(spmQ)) {
				throw new Exception("提单：" + billNo + " 存在装车实绩，请联系管理员。");
			}
			// 一次结算提单先不能撤回：这个允许一次结算提单撤回 20240319刘侣
//			if (billQ != null && "一次结算".equals(billQ.getMemo())) {
//				throw new Exception("提单：" + billNo + " 是一次结算提单，不能撤回");
//			}
			
			// 只允许不为 废副品发运 的提单修改：
			if (billQ.getSolutions_name() != null && "废副品发运".equals(billQ.getSolutions_name())) {
				// 废副品卷号虚拟：20250109刘侣
			} else {
				// 将卷号改为在库：
				SlmLadingBillDetail billInfo = new SlmLadingBillDetail();
				billInfo.setBill_no(billNo);
				List<SlmLadingBillDetail> sdL = this.getMapper(SlmLadingBillDetailMapper.class).find(billInfo, 0, 0);
				for(SlmLadingBillDetail sd : sdL) {
					YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(sd.getCoilno(), null);
					if (ypd == null || "".equals(ypd)) {
						throw new Exception("卷：" + sd.getCoilno() + " 不存在");
					}
					if (!"2".equals(ypd.getState())) {
						throw new Exception("卷：" + sd.getCoilno() + " 不为发运锁定状态");
					}
					ypd.setState("0");
					ypd.setBill_no("");
					ypd.setLine_no("");
					this.getMapper(YdmProductDetailMapper.class).update(ypd);
					this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());
				}
			}
			
			
			// 他们那边可能会将原提单修改又下发：所以我这里得彻底删除：
			// 先注释，防止测试时调用接口insert了：20230807刘侣
			this.getMapper(SlmLadingBillHeatMapper.class).delete(billNo);
			this.getMapper(SlmLadingBillLineMapper.class).doDelete(billNo);
			this.getMapper(SlmLadingBillDetailMapper.class).doDeleteByBillNo(billNo);
			
			
			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "提单撤回信息同步", "一体化", opr_time, null, null, null, null, billNo);
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
		
	}
	
	
	/**
	 * 20230829刘侣，提单手动撤销装车实绩：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel billCancelZSHand(String billNo) {
		ResultModel rm = new ResultModel("200", "提单手动撤销装车实绩成功");
		try {
			
			
			// 撤销装车实绩的话估计得挪到一体化撤回提单的时候撤销：20240702刘侣
			// 一体化提单：撤销装车实绩 20231023刘侣
			List<SlmLadingBillLine> lineL = this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, " bill_no='"+billNo+"' and valid_flag='1'", null, 0, 0);
			if (lineL != null && lineL.size() > 0) {
				if (lineL.get(0).getOrder_no() != null) {
					// 在这里获取装车实绩从表，并发送装车实绩：
					// ["1","2"] 格式json
					JSONArray ja = new JSONArray();
					ja.add(billNo);
					// http://172.16.4.136:14008/il/ilApi/cancelYtSendGoods
					System.out.println("装车实绩参数：" + ja.toString());
					String result = Connecttt.postJsonParams("http://172.16.4.136:14008/il/ilApi/cancelYtSendGoods", ja.toString());
					JsonObject resObj = new JsonParser().parse(result).getAsJsonObject();
					System.out.println(resObj.toString());
					String code = resObj.get("code").toString();
					// 发送指令过去，但是区分报错信息：不抛错20231218刘侣
					if (!"1000".equals(code)) {
						throw new Exception("提单取消装车实绩报错：" + resObj.get("message"));
					}
//					String str = resObj.get("message").getAsString();
				}
			}
			// end
			
			
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
		
	}
	
	
	
	/**
	 * 20230901刘侣，这个是订单一体化挂单后，将订单号和会挂的卷子到我本地，本地还需要做一次自动挂单，以生成相关生产数据；
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdAuto(ComBaseddR soi) {
		ResultModel rm = new ResultModel("200", "订单操作成功");
		try {
			
			// 这个得根据actType判断：1：挂单，2：脱单
			if (soi.getActType() == null || "".equals(soi.getActType())) {
				throw new Exception("缺少 actType 参数");
			}
			
			if ("1".equals(soi.getActType())) {
				examineDDR(soi);
				// 需要订单号和多个卷组成的卷号串：
				
				// 订单传过来默认是没有合同行序号的，加上：YT-HZ02023081222 002
				String realOrdNo = soi.getOrdNo() + soi.getOrdSeq() + soi.getOrdSeq();
				// 1、订单得存在并有效：
				String condition = "contract_no||contract_line_seq||order_seq = '"+realOrdNo+"' "
						+ "and nvl(change_flag,'0') <> '1' and nvl(VALID_FLAG, '0') = '1'";
				int ss1Num = this.getMapper(SlmOrderInfoMapper.class).countWithCondition(null, condition);
				if (ss1Num <= 0) {
					throw new Exception("订单：" + soi.getOrdNo() + " 不存在或者处于关闭状态");
				}
				
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为订单保留状态，不允许挂单");
				}
				if ("0PAA70".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为订单作废状态，不允许挂单");
				}
				
				
				// 2、卷子得没有订单，是脱单在库状态：
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(soi.getCoilNo(), null);
				if (ypd == null || "".equals(ypd)) {
					throw new Exception("卷：" + soi.getCoilNo() + " 不存在");
				}
				if (ypd.getOrderno() != null) {
					throw new Exception("卷：" + soi.getCoilNo() + " 还未脱单，当前订单为：" + ypd.getOrderno());
				}
				if (!"0".equals(ypd.getState())) {
					throw new Exception("卷：" + soi.getCoilNo() + " 不在库");
				}
				
				// 挂单接口：
				CommonPage<String[]> param = new CommonPage<>();
				String[] arrs = {soi.getCoilNo()};
				param.setObject(arrs);
				param.setMemo1(ppoL.get(0).getProd_order_no());
				// H-A-B-C：因为此时这个工艺路径可能会变化，所以统一使用一体化传过来的工艺路径去挂单
				// // 先注释，防止测试时调用接口insert了：20230807刘侣
				if (soi.getNextProc() != null && !"".equals(soi.getNextProc())) {
					ResultModel grm = doRelationOrderAuto(param, soi.getNextProc());
					if ("500".equals(grm.getState())) {
						throw new Exception(grm.getMsgInfo());
					}
				} else {
//					System.out.println("直接挂单发运");
					// 下道工序为空，直接挂单发运的：
					ResultModel trm = doRelationOrderNoValidingSteelFY(param);
					if ("500".equals(trm.getState())) {
						throw new Exception(trm.getMsgInfo());
					}
				}
				
				

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收一体化手动挂单信息同步", "一体化", opr_time, null, null, null, null, realOrdNo + ",挂的工序为：" + soi.getNextProc() + " ，卷为：" + soi.getCoilNo());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			} else if ("2".equals(soi.getActType())) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("缺少订单号");
				}
				if (soi.getCoilNo() == null || "".equals(soi.getCoilNo())) {
					throw new Exception("缺少卷号");
				}
				
				// 订单传过来默认是没有合同行序号的，加上：YT-HZ02023081222 002
				String realOrdNo = soi.getOrdNo() + soi.getOrdSeq() + soi.getOrdSeq();
				// 1、订单得存在并有效：
				String condition = "contract_no||contract_line_seq||order_seq = '"+realOrdNo+"' "
						+ "and nvl(change_flag,'0') <> '1' and nvl(VALID_FLAG, '0') = '1'";
				int ss1Num = this.getMapper(SlmOrderInfoMapper.class).countWithCondition(null, condition);
				if (ss1Num <= 0) {
					throw new Exception("订单：" + soi.getOrdNo() + " 不存在或者处于无效状态");
				}
				
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为订单保留状态，不允许脱单");
				}
				if ("0PAA70".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为订单作废状态，不允许脱单");
				}
				
				
				// 2、卷子得没有订单，是脱单在库状态：
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(soi.getCoilNo(), null);
				if (ypd == null || "".equals(ypd)) {
					throw new Exception("卷：" + soi.getCoilNo() + " 不存在");
				}
				if (ypd.getOrderno() == null) {
					throw new Exception("卷：" + soi.getCoilNo() + " 已经脱单");
				}
				if (!"0".equals(ypd.getState())) {
					throw new Exception("卷：" + soi.getCoilNo() + " 不在库");
				}
				
				// 直接调用脱单：
				// 执行脱单：
				// doMaterialReplace
				CommonPage<PlnMaterielDetail> oci = new CommonPage<>();
				List<PlnMaterielDetail> lpm = new ArrayList<>();
				PlnMaterielDetail pmd = new PlnMaterielDetail();
//				pmd.setObject_no_vt(ypd.getObject_no_vt());
				pmd.setObject_no(ypd.getCoilno());
//				pmd.setObject_type(ypd.getCoiltype());
				lpm.add(pmd);
				oci.setObjectList(lpm);
				oci.setMemo1("一体化的降级接口手动执行脱单，卷号：" + ypd.getCoilno());
				
				ResultModel tdRes = tuodan(oci);
				if ("500".equals(tdRes.getState())) {
					throw new Exception(tdRes.getMsgInfo());
				}
				
				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收一体化手动脱单信息同步", "一体化", opr_time, null, null, null, null, realOrdNo + " ,卷为：" + soi.getCoilNo());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			} else {
				throw new Exception("请选择充当1或者降级2");
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
		
	public ComBaseddR examineDDR(ComBaseddR sci) throws Exception {
		
		if (sci.getOrdNo() == null || "".equals(sci.getOrdNo())) {
			throw new Exception("缺少订单号");
		}
		if (sci.getCoilNo() == null || "".equals(sci.getCoilNo())) {
			throw new Exception("缺少卷号");
		}
//		if (sci.getCurProc() == null || "".equals(sci.getCurProc())) {
//			throw new Exception("缺少当前已经执行工艺路径");
//		}
//		if (sci.getNextProc() == null || "".equals(sci.getNextProc())) {
//			throw new Exception("缺少后续工艺路径");
//		}
		// 挂单分为：有后续工序，和没后续工序挂单发运的；
		
		return sci;
	}
	
	
	/**
	 * 挂单管理：挂单操作
	 * @param CP
	 * @return 20230901 刘侣
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRelationOrderAuto(CommonPage<String[]> CP, String nextProcess) throws Exception{
		
//		String nextProcess = CP.getMemo4();
		
	    String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
	    String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		Date now = new Date();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm=new ResultModel();
		// 工序点信息
		List<ComBaseInfo> infoI = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, "sort_code = '2002' AND validflag = '1'",null, 0, 0);
		//获取工序点
		ProcessPoint processpoint = new ProcessPoint(infoI);
		
		String[] path = null;
		ArrayList<String> validpath = new ArrayList<>();
		//实物卷号数组
		String[] sCoilNo=CP.getObject();
		String pd = CP.getMemo2(); //是否强制挂单  【1强制挂单】
		String is_judge_steel = CP.getMemo3();//是否检验牌号[no 不检验牌号]
		if(CP.getMemo1()==null||"".equals(CP.getMemo1().trim())||sCoilNo==null||sCoilNo.length==0){
			rm.setState("500");
			rm.setMsgInfo("条件传入错误!");
			return rm;
		}

		//验证生产订单号是否存在
		PlnProdorder pp=new PlnProdorder();
		pp.setProd_order_no(CP.getMemo1().trim());
		List<PlnProdorder> lpp=this.getMapper(PlnProdorderMapper.class).find(pp, 0, 1);
		if(lpp==null||lpp.size()==0){
			rm.setState("500");
			rm.setMsgInfo("生产订单["+pp.getProd_order_no()+"]不存在!");
			return rm;
		}
		
		pp = lpp.get(0);//生产订单号唯一约束
		
		// 验证生产订单是否锁定
		if ("2".equals(pp.getFinished_status())) {
			throw new Exception("生产订单已经锁定[订单变更中],不允许挂单!");
		}
		
		if ("0PAA60".equals(pp.getStatus())) {
			throw new Exception("生产订单处于 ‘订单保留’ 状态,不允许挂单!");
		}
		if ("0PAA70".equals(pp.getStatus())) {
			throw new Exception("生产订单处于 ‘订单作废’ 状态,不允许挂单!");
		}
		
		// 验证后续需要挂的工艺路径是否是 生产订单的 工艺路径 的一部分或者全部：整卷发运订单不会有工艺路径
		if (pp.getWhole_process_codes() == null || "".equals(pp.getWhole_process_codes() == null)) {
			throw new Exception("生产订单的工艺路径不存在！");
		}
		
		if (nextProcess != null && !pp.getWhole_process_codes().contains(nextProcess)) {
			throw new Exception("生产订单的工艺路径：" + pp.getWhole_process_codes() + " 和当前工艺路径 " + nextProcess + " 不匹配");
		}
		
		String prevProCodes = pp.getWhole_process_codes();
		
		// 将生产订单的工艺路径覆盖成当前工艺路径：
		pp.setWhole_process_codes(nextProcess);
		
		// 合同是否是厂内合同 101603
		boolean flag_c = false;
		if ("101603".equals(pp.getContract_type_no())) {
			flag_c = true;
		}		
		// 合同是都是来料加工合同 
		boolean flag_j = false;
		if ("101606".equals(pp.getContract_type_no())) {
			flag_j = true;
		}
				
		//物料充当脱单履历
		List<PlnMatReplaceLog> lmmrl=this.getMapper(PlnMatReplaceLogMapper.class).findWithCondition(null, "", " serial_no desc ", 0, 1);
		long iNo=1;
		if(lmmrl!=null&&lmmrl.size()>0){
			iNo=lmmrl.get(0).getSerial_no()+1;
		}
		
		//获取运输方案:调用新接口
		//boolean soLutions = this.getBean(PlnProdorderBakServiceImpl.class).getSoLutions(pp.getProd_order_no());
	
		// 判断订单是否是净重交货102301 (true 不走虚拟发运,不校验第一次挂单信息)
		boolean flag = false;
		if ("102301".equals(pp.getWeight_type_no())) {
			flag = true;
		}
		
		//订单属性不是原料卷和非计划，即订单属性是【需加工，冷轧，酸洗】
		if(!"1".equals(pp.getOrder_nature()) && !"3".equals(pp.getOrder_nature())){
			//处理逻辑1
			if("0PAA12".compareTo(pp.getStatus())>0){
				rm.setState("500");
				rm.setMsgInfo("[需加工]的订单，要下发生产后才能挂单！");
				return rm;
			}
			
			for(String CoilNo:sCoilNo){
				List<DesignInfo> infos = new ArrayList<>();
				//处理逻辑
				//对传入的实物卷，查询库存信息[物流接口]
				//存在信息，则读取之； 若不存在信息，则报错“库存中无实物[xxx]信息”
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(CoilNo, null);
				if(ypd==null) {
					rm.setState("500");
					rm.setMsgInfo("库存中无实物["+CoilNo+"]信息!");
					return rm;
				}
				
				if (ypd.getOrderno() != null) {
					rm.setState("500");
					rm.setMsgInfo("实物["+CoilNo+"]已绑定订单["+ypd.getOrderno()+"]! 不能再次操作!");
					return rm;
				}
				
				// 牌号不对，提示需要做强制挂单：应孔云飞要求，将充当内所有关于厚宽，牌号是否一致的校验去除：20231020刘侣
//				if(!pp.getSteel_code().equals(ypd.getJudgesteelcode()) && !"no".equals(is_judge_steel)){
//					throw new Exception("卷牌号和订单牌号不一致，请选择不检验牌号强制挂单；");
//				}
				
				// 挂单后判断该卷是否已经iscanload：是 就置为null，让其重新判断iscanload；20230210刘侣
				YdmProductDetail ypdCanLoad = new YdmProductDetail();
				ypdCanLoad.setCoilno(CoilNo);
				ypdCanLoad.setIs_can_load("1");
				List<YdmProductDetail> ypdCanList = this.getMapper(YdmProductDetailMapper.class).find(ypdCanLoad, 0, 0);
				if (ypdCanList != null && ypdCanList.size() > 0) {
					ypdCanList.get(0).setIs_can_load("0");
					this.getMapper(YdmProductDetailMapper.class).update(ypdCanList.get(0));
					this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypdCanList.get(0).getCoilno());
				}
				// end
				
				//如果不是场内合同和来料加工合同  TODO
				if(!flag_c && !flag_j){
					PlnMaterielDetail pmd = new PlnMaterielDetail();
					pmd.setObject_no(ypd.getCoilno());
					List<PlnMaterielDetail> pmdd = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd, "nvl(invalid_flg,0) = 0", "", 0, 0);
					if (pmdd != null && pmdd.size()>0) {
						for (PlnMaterielDetail plnmaterieldetail : pmdd) {
							plnmaterieldetail.setObject_no("");
							this.getMapper(PlnMaterielDetailMapper.class).update(plnmaterieldetail);
						}
					}
				}
				//如果不是强制挂单
				if (!"1".equals(pd)) {
					if ("500203".equals(ypd.getStorageattr()) && !"1".equals(ypd.getIsbl()) && ypd.getJudgeresult()==null){
						rm.setState("500");
						rm.setMsgInfo("成品挂单之前需要综合判定!");
						return rm;
					}
					// 判断实物，和订单原料卷的宽，如果实物比订单值小，则报错退出：应孔云飞要求，将充当内所有关于厚宽，牌号是否一致的校验去除：20231020刘侣
//					if (ypd.getWidth().doubleValue() < pp.getWidth().doubleValue()) {
//						throw new Exception("实物卷的宽比订单要求值小，不能上料！");
//					}
				}
				
				// 如果是充当的时候牌号不一致，卷牌号需要改成订单牌号吗  一体化有要求吗，可能要改，看一体化要求20231020刘侣
				// 原本是有改成订单牌号的：每次都检测 || !pp.getSteel_code().equals(ypd.getSteelcode())：20231205刘侣
				if(!pp.getSteel_code().equals(ypd.getJudgesteelcode()) || !pp.getSteel_code().equals(ypd.getSteelcode())){
//					if ("no".equals(is_judge_steel)) {//如果不检验牌号
						// 1、备份库存信息
						CommonPage<YdmProductDetail> sum = new CommonPage<YdmProductDetail>();
						YdmProductDetail detail = new YdmProductDetail();
						detail.setCoilno(CoilNo);

//						detail.setSteelcode(ypd.getSteelcode());
//						detail.setJudgesteelcode(ypd.getJudgesteelcode());
//						detail.setCreatedate(new Date());
						
						List<YdmProductDetail> ydmlist = new ArrayList<YdmProductDetail>();
						ydmlist.add(detail);
						sum.setObjectList(ydmlist);
						this.getBean(YdmProductDetailBfServiceImpl.class).doAddDetailBf(sum);
						// 2、修改牌号
						detail.setSteelcode(lpp.get(0).getSteel_code());
						detail.setSteel_name(lpp.get(0).getSteel_name());
						this.getMapper(YdmProductDetailMapper.class).update(detail);
//					}else {						
//						rm.setState("500");
//						rm.setMsgInfo("牌号不匹配，请选择检验牌号强制挂单！");
//						return rm;
//					}
				}
				// end
				
				// 应一体化要求，去掉厚宽等限制20231020刘侣：
				//如果不是强制挂单，需要验证信息
//				if (!"1".equals(pd)) {
//					// 拆分订单不验证合同号
//					if (!(pp.getIs_split() != null && "1".equals(pp.getIs_split()))) {//如果不是拆分订单
//						if (!flag && !flag_c && !flag_j) {
//							// 判断第一次挂单与第二次挂单合同号contract_no是否一致 2018-09-05 通过挂单日志表获取最后一条脱单的订单信息(原料卷订单 属性为新钢
//							// 最后一个)
//							//如果不是厂内合同，来料加工合同且是毛重
//							List<PlnProdorder> plnlog = this.getMapper(PlnMatReplaceLogMapper.class).findreplacelog(CoilNo);
//							if (Utils.isNotEmpty(plnlog)) {
//								if (!lpp.get(0).getContract_no().equals(plnlog.get(0).getContract_no())) {
//									throw new Exception("合同号不匹配，不能上料! 合同号 : [" + plnlog.get(0).getContract_no() + ","
//											+ lpp.get(0).getContract_no() + "]");
//								}
//							} else {
//								//throw new Exception("未找到[" + CoilNo + "]对应原料卷订单挂单信息!");
//							}
//						}
//					}
//					if (pp.getThick() == null) {
//						throw new Exception("未找到生产订单厚度，不能上料！");
//					}
//					if (ypd.getThick() == null) {
//						throw new Exception("未找到实物厚度，不能上料！");
//					}
//					
//					// 应一体化要求，去掉厚宽等限制20231020刘侣：
//					ResultModel rmInfo = this.getBean(MesApiServiceImpl.class).CompareValues(lpp.get(0).getThick().doubleValue(),ypd.getThick().doubleValue());
//					if (!"200".equals(rmInfo.getState())) {
//						throw new Exception(rmInfo.getMsgInfo());
//					}
//					// end
//
//					
//					
//					//毛重交货的需要验证客户信息是否一致
//					if (!flag && ypd.getCustomer_no() != null && lpp.get(0).getCustomer_no() != null
//							&& !ypd.getCustomer_no().equals(pp.getCustomer_no())) {
//						throw new Exception("库存中实物卷的客户信息与对应生产订单的客户信息不一致! 可选强制挂单! \r\n "
//										+ "卷号:[" + CoilNo + "] 客户名称:["+ ypd.getCustomer_nm()+ "] \r\n "
//										+ "生产订单号 :["+ pp.getProd_order_no() + "] 客户名称 :[" + pp.getCustomer_name() + "]");
//					}
//				}
				// end
				
				// 生成设计信息
				if (Utils.isNotEmpty(pp.getWhole_process_codes()) && !"1".equals(pp.getWhole_coil())) { //有工艺路径且不是整卷
					// 1、获取有效工艺路径
					//temp = processpoint.slitting_code + StringUtils.substringAfter(pp.getWhole_process_codes(), processpoint.slitting_code);
					//path = temp.split("-");
					path = pp.getWhole_process_codes().split("-");
					validpath = this.getBean(MesApiDesignInfoImpl.class).getProcessPath(path);
					// 调用设计信息接口
					DesignInfo info = new DesignInfo();
					// 如果实物对应的虚拟物料信息存在,即传入虚拟物料号(厂内合同成品再加工)
					List<PlnMaterielDetail> pmd_c = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "object_no = '"+CoilNo+"' and nvl(invalid_flg,0) = 0", "", 0, 0);
					if (Utils.isNotEmpty(pmd_c)) {
						info.setObject_no_vt(pmd_c.get(0).getObject_no_vt());
					}
					info.setCurrentProcIndex(0);
					info.setObject_no(CoilNo);
					info.setProcess(validpath);
					info.setProd_order_no(CP.getMemo1());
					info.setSingle_wgt(ypd.getFactweight());
					infos.add(info);
					ResultModel result = this.getBean(MesApiDesignInfoImpl.class).Design_Plan_Info(infos,null);
					if (!"200".equals(result.getState())) {
						throw new Exception("生产设计信息失败" + result.getMsgInfo());
					}
				}
				
				
				//**************调用质量接口，传入 订单号和实物卷号，判断其他要求是否符合，不符合则报错退出**********
				
				// 整卷发运
				if ("1".equals(pp.getWhole_coil())) {				
					//保存相关数据
					//修改生产订单进程表[PLN_PRODORDER_STATISTIC]
					PlnProdorderStatistic pps=new PlnProdorderStatistic();
					pps.setProd_order_no(pp.getProd_order_no());
					pps.setReplaced(ypd.getFactweight());
					pps.setReplaced_cnt(1);
					pps.setReplaced_times(1);
					pps.setUnscheduled(ypd.getFactweight()==null?null:(-ypd.getFactweight()));
					this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);
					
					
					//修改订单进程表[PLN_ORDER_STATISTIC]
					PlnOrderStatistic pos=new PlnOrderStatistic();
					pos.setOrder_no(pp.getOrder_no());
					pos.setReplaced(ypd.getFactweight());
					pos.setReplaced_cnt(1);
					pos.setReplaced_times(1);
					pos.setUnscheduled(ypd.getFactweight()==null?null:(-ypd.getFactweight()));
					this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
					
					//调用物流接口，关联实物和生产订单信息
					ypd.setProdorderno(pp.getProd_order_no());
					ypd.setOrderno(pp.getOrder_no());
					ypd.setCustomer_no(pp.getCustomer_no());
					ypd.setCustomer_nm(pp.getCustomer_name());
					ypd.setReceiv_nm(pp.getReciver_unit_name());
					ypd.setReceiv_no(pp.getReciver_unit_no());
					ypd.setDelivery_state_code(pp.getDelivery_state_code());
					ypd.setDelivery_state_desc(pp.getDelivery_state_desc());
					this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);
					
					
					//写物料充当脱单履历表[MIL_MAT_REPLACE_LOG]  MilMatReplaceLog
					PlnMatReplaceLog mmrl=new PlnMatReplaceLog();
					mmrl.setSerial_no(iNo++);
					mmrl.setObject_no(ypd.getCoilno());
					mmrl.setOpt_type("2");
					mmrl.setOrder_no(pp.getOrder_no());
					mmrl.setProd_order_no(pp.getProd_order_no());
					mmrl.setCreate_man_name(userName);
					mmrl.setCreate_time(new Date());
					
					if (prevProCodes != pp.getWhole_process_codes()) {
						// 之前生产订单表的工艺路径和当前路径不一致：
						mmrl.setProcess(pp.getWhole_process_codes().substring(0, 1));
					}
					
					mmrl.setRemark("整卷发运");
					this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
				}else {
					//如果不是整卷发运
					
					// 修改生产订单进程表[PLN_PRODORDER_STATISTIC] 订单进程表
					this.getBean(MesApiDesignInfoImpl.class).updateOrderStatic(pp.getProd_order_no(), pp.getOrder_no(), pp.getWhole_process_codes(), ypd.getFactweight(),true);
					
					List<PlnMaterielDetail> pmdetail = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, " object_no = '"+CoilNo+"' and nvl(invalid_flg,0)=0", null, 0, 1);
					
					//调用物流接口，关联实物和生产订单信息
					ypd.setCustomer_no(pp.getCustomer_no());
					ypd.setCustomer_nm(pp.getCustomer_name());
					ypd.setReceiv_nm(pp.getReciver_unit_name());
					ypd.setReceiv_no(pp.getReciver_unit_no());
					ypd.setProdorderno(pp.getProd_order_no());
					ypd.setOrderno(pp.getOrder_no());
					ypd.setObject_no_vt(pmdetail.get(0).getObject_no_vt());
					ypd.setDelivery_state_code(pp.getDelivery_state_code());
					ypd.setDelivery_state_desc(pp.getDelivery_state_desc());
					this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);
					
					
					//写物料充当脱单履历表[PLN_MAT_REPLACE_LOG]
					PlnMatReplaceLog mmrl=new PlnMatReplaceLog();
					BeanUtils.copyProperties(pmdetail.get(0), mmrl);
					mmrl.setSerial_no(iNo++);
					if (prevProCodes != pp.getWhole_process_codes()) {
						// 之前生产订单表的工艺路径和当前路径不一致：
						mmrl.setProcess(pp.getWhole_process_codes().substring(0, 1));
					} else {
						mmrl.setProcess(processpoint.slitting_code);
					}
					mmrl.setOpt_type("2");
//					mmrl.setProcess(processpoint.slitting_code);
					mmrl.setCreate_man_name(userName);
					mmrl.setCreate_time(new Date());
					mmrl.setRemark("1".equals(pd)?"强制充当":"");
					this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
					
					// 生成物料附加信息：这里的第三个参数得使用：当前路径的第一个工序code：根据是否一直来判断：
					String firsCode = "";
					if (prevProCodes != pp.getWhole_process_codes()) {
						// 之前生产订单表的工艺路径和当前路径不一致：
						firsCode = pp.getWhole_process_codes().substring(0, 1);
					} else {
						firsCode = processpoint.slitting_code;
					}
					this.getBean(MesApiDesignInfoImpl.class).addMaterielExinfo(lpp.get(0), pmdetail.get(0), firsCode);
					
					// 拆分订单如果还需继续生产,判断是否需要移动库存 2019-08-05
					if ((pp.getIs_split() != null && "1".equals(pp.getIs_split()))) {
						// 如果物料在成品库挪到在制库
						if ("500203".equals(ypd.getStorageattr())) {
							//ypd.setStorageattr("500203");
							CommonPage<YdmProductDetail> tmp = new CommonPage<YdmProductDetail>();
							List<YdmProductDetail> ydm = new ArrayList<YdmProductDetail>();
							ypd.setMemo("拆分订单["+pp.getOrder_no()+"]增加["+pp.getWhole_process_names()+"]工序->移至在制库");
							ydm.add(ypd);
							tmp.setObjectList(ydm);
							tmp.setMemo1("500202");
							tmp.setMemo2("0");
							this.getBean(LmsApiServiceImpl.class).doChangeMaterialStorage(tmp);
						}
					}
				}
				
				try {
					
//					String solution = this.getMapper(SlmLadingBillDetailMapper.class).doQuarySolutionByCoilno(CoilNo);
//					20200422 如果成品库 需加工订单，运输方案到优特：自动挂单这里不需要再判断运输方案了20231109刘侣
					if("500203".equals(ypd.getStorageattr()) && "2".equals(pp.getOrder_nature())) {
						ResultModel rmChange = this.getBean(PlnProdorderGuaDanServiceImpl.class).doChangeStorageattr(ypd, userName, order, team, now);
						if (!"200".equals(rmChange.getState())) {
							rm.setState("500");
							rm.setMsgInfo("需加工成品库自动入库失败:"+rmChange.getMsgInfo());
							return rm;
						}
						YdmProductDetail y = new YdmProductDetail();
						y.setCoilno(ypd.getCoilno());
						y.setStorageattr("500201");
						
						// 需加工挂单重新入原料库有两种情况：1、有下道工序，回原料库再生产；2、没有下道工序，到原料库发运；20230217刘侣
						// 如果是没有下道工序到原料库发运的话，就需要将库存表的iscanload置为1；日志表的日期更新；
						// 前提：日志表中有这卷的记录，表示这卷已经通过了可下发判定，此时的库存表的可下发为1；
						List<PlnMaterielDetail> coilHasNext = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(
								null, "OBJECT_NO='"+ypd.getCoilno()+"' and NEXT_PROCESS_CODE is null", null, 0, 0);
						if (coilHasNext != null && coilHasNext.size() > 0) {
							// 将日志表的日期更新：
							List<MesOprLog> xfLogs = this.getMapper(MesOprLogMapper.class).findWithCondition(
								null, "COILNO = '"+ypd.getCoilno()+"' and OPR_FUNCTION = '自动判定是否可发运' order by OPR_TIME desc ", null, 0, 0);
							if (xfLogs != null && xfLogs.size() > 0) {
								y.setIs_can_load("1");
								// 将这条日志的日期更新到当前：
								xfLogs.get(0).setOpr_time(opr_time);
								this.getMapper(MesOprLogMapper.class).update(xfLogs.get(0));
							}
						} else {
							// 还有下道工序：
							y.setIs_can_load("0");
						}
						y.setMemo("需加工挂单重新入原料库!!!");
						this.getMapper(YdmProductDetailMapper.class).update(y);
						this.getMapper(YdmProductDetailMapper.class).kctbYdd(y.getCoilno());
						// 从成品库入原料库后抛送取消综判异动点：20240425刘侣
						cancelUltiYdd(y.getCoilno());
					}
					
				} catch (Exception e) {
					// 如果有trycatch，则需要设置手动20230703 刘侣
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					// end
					throw new Exception(e.getMessage());
				}
				this.getMapper(YdmProductDetailMapper.class).kctbYdd(CoilNo);
				
				ResultModel rejRes = reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				ycjsPYdd(CoilNo, true); // 一次结算后抛异动点
				
			}
			
		}else{
			//订单属性是原料卷和非计划			
			for(String CoilNo:sCoilNo){
				//处理逻辑
				//对传入的实物卷，查询库存信息[物流接口]
				//存在信息，则读取之； 若不存在信息，则报错“库存中无实物[xxx]信息”
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(CoilNo, null);
				if(ypd==null) {
					rm.setState("500");
					rm.setMsgInfo("库存中无实物["+CoilNo+"]信息!");
					return rm;
				}
				if (ypd.getOrderno() != null) {
					rm.setState("500");
					rm.setMsgInfo("实物["+CoilNo+"]已绑定订单["+ypd.getOrderno()+"]! 不能再次操作!");
					return rm;
				}
				//如果不是场内合同和来料加工合同  TODO
				if(!flag_c && !flag_j){
					PlnMaterielDetail pmd = new PlnMaterielDetail();
					pmd.setObject_no(ypd.getCoilno());
					List<PlnMaterielDetail> pmdd = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd, "nvl(invalid_flg,0) = 0", "", 0, 0);
					if (pmdd != null && pmdd.size()>0) {
						for (PlnMaterielDetail plnmaterieldetail : pmdd) {
							plnmaterieldetail.setObject_no("");
							this.getMapper(PlnMaterielDetailMapper.class).update(plnmaterieldetail);
						}
					}
				}
				//判断实物，和订单原料卷的牌号是否匹配
				if(!pp.getSteel_code().equals(ypd.getJudgesteelcode()) || !pp.getSteel_code().equals(ypd.getSteelcode())){
					if ("no".equals(is_judge_steel)) {//如果不检验牌号
						// 1、备份库存信息
						CommonPage<YdmProductDetail> sum = new CommonPage<YdmProductDetail>();
						YdmProductDetail detail = new YdmProductDetail();
						detail.setCoilno(CoilNo);

//						detail.setSteelcode(ypd.getSteelcode());
//						detail.setJudgesteelcode(ypd.getJudgesteelcode());
//						detail.setCreatedate(new Date());
						
						List<YdmProductDetail> ydmlist = new ArrayList<YdmProductDetail>();
						ydmlist.add(detail);
						sum.setObjectList(ydmlist);
						this.getBean(YdmProductDetailBfServiceImpl.class).doAddDetailBf(sum);
						// 2、修改牌号
						detail.setSteelcode(lpp.get(0).getSteel_code());
						detail.setSteel_name(lpp.get(0).getSteel_name());
						this.getMapper(YdmProductDetailMapper.class).update(detail);
					}else {						
						rm.setState("500");
						rm.setMsgInfo("牌号不匹配，不能上料！");
						return rm;
					}
				}
				
				// 挂单管理，当前挂的需加工的话，需要判断卷子是否之前做过一次结算；20230214刘侣
				// flag_c = true 厂内合同: 非厂内合同且是需加工
//				if (!flag_c && "2".equals(pp.getOrder_nature()) && CoilNo.length() > 8) {
//					String coilYl = CoilNo.substring(0, 8);
//					List<SlmLadingBillHeat> lists = this.getMapper(SlmLadingBillHeatMapper.class).doQIfYCJS(coilYl);
//					if (lists == null || lists.size() <= 0) {
//						throw new Exception("卷号：" + CoilNo + "之前还没做一次结算，不能挂需加工订单");
//					}
//				}
				// end
				
				// 挂单后判断该卷是否已经iscanload：是 就置为null，让其重新判断iscanload；20230210刘侣
				YdmProductDetail ypdCanLoad = new YdmProductDetail();
				ypdCanLoad.setCoilno(CoilNo);
				ypdCanLoad.setIs_can_load("1");
				List<YdmProductDetail> ypdCanList = this.getMapper(YdmProductDetailMapper.class).find(ypdCanLoad, 0, 0);
				if (ypdCanList != null && ypdCanList.size() > 0) {
					ypdCanList.get(0).setIs_can_load("0");
					this.getMapper(YdmProductDetailMapper.class).update(ypdCanList.get(0));
					this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypdCanList.get(0).getCoilno());
				}
				// end
				
				//如果不是强制挂单，需要验证信息
				if(!"1".equals(pd)){
					if(lpp.get(0).getThick()!=null){
						ResultModel rmInfo=this.getBean(MesApiServiceImpl.class).CompareValues(lpp.get(0).getThick().doubleValue(), ypd.getThick().doubleValue());
						if(!"200".equals(rmInfo.getState())){
							throw new Exception(rmInfo.getMsgInfo());
						}
					}		
					// 应一体化充当要求，去掉限制20231020刘侣
					//判断实物，和订单原料卷的宽、重量信息，如果实物比订单值小，则报错退出
//					if(pp.getWidth()!=null && ypd.getWidth().doubleValue() < pp.getWidth().doubleValue()){
//						throw new Exception("实物卷的宽比订单要求值小，不能上料！");
//					}
					
//					if(pp.getSingle_weight_max()!=null){
//						if(ypd.getFactweight().doubleValue() > pp.getSingle_weight_max().doubleValue()){
//							throw new Exception("实物卷的重量比订单要求重量上限大，不能上料！");
//						}
//					}
//					if(pp.getSingle_weight_min()!=null){
//						if(ypd.getFactweight().doubleValue() < pp.getSingle_weight_min().doubleValue()){
//							throw new Exception("实物卷的重量比订单要求重量下限小，不能上料！");
//						}
//					}					
				}
				
				//保存相关数据
				//修改生产订单进程表[PLN_PRODORDER_STATISTIC]
				PlnProdorderStatistic pps=new PlnProdorderStatistic();
				pps.setProd_order_no(pp.getProd_order_no());
				pps.setReplaced(ypd.getFactweight());
				pps.setReplaced_cnt(1);
				pps.setReplaced_times(1);
				pps.setUnscheduled(ypd.getFactweight()==null?null:(-ypd.getFactweight()));
				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);
				
				
				//修改订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos=new PlnOrderStatistic();
				pos.setOrder_no(pp.getOrder_no());
				pos.setReplaced(ypd.getFactweight());
				pos.setReplaced_cnt(1);
				pos.setReplaced_times(1);
				pos.setUnscheduled(ypd.getFactweight()==null?null:(-ypd.getFactweight()));
				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
				
				
				//调用物流接口，关联实物和生产订单信息
				ypd.setProdorderno(pps.getProd_order_no());
				ypd.setOrderno(pos.getOrder_no());
				ypd.setCustomer_no(pp.getCustomer_no());
				ypd.setCustomer_nm(pp.getCustomer_name());
				ypd.setReceiv_nm(pp.getReciver_unit_name());
				ypd.setReceiv_no(pp.getReciver_unit_no());
				ypd.setDelivery_state_code(pp.getDelivery_state_code());
				ypd.setDelivery_state_desc(pp.getDelivery_state_desc());
				this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);
				
				
				//写物料充当脱单履历表[MIL_MAT_REPLACE_LOG]  MilMatReplaceLog
				PlnMatReplaceLog mmrl=new PlnMatReplaceLog();
				mmrl.setSerial_no(iNo++);
				mmrl.setObject_no(ypd.getCoilno());
				mmrl.setOpt_type("1");
				mmrl.setOrder_no(pos.getOrder_no());
				mmrl.setProd_order_no(pps.getProd_order_no());
				mmrl.setCreate_man_name(userName);
				mmrl.setCreate_time(new Date());
				mmrl.setRemark("1".equals(pd)?"强制充当":"");
				this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
				
				this.getMapper(YdmProductDetailMapper.class).kctbYdd(CoilNo);
				
				ResultModel rejRes = reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				ycjsPYdd(CoilNo, true);
				
			}
		}
		
		//日志
		MesOprLog mol = new MesOprLog("生产管理", "一体化充当挂单", "挂单", userName, opr_time, null, null, null, null, Arrays.toString(sCoilNo) + ": " + is_judge_steel);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		rm.setState("200");
		return rm;
	}
	
	
	/**
	 * 成品挂单 memo1 生产订单号
	 * 
	 * @throws Exception [{"memo1":"1804130000001","object":["Y1831023"]}] 挂单
	 *                   [{"memo1":"1804110000002","object":["Y1830550","Y1830551"]}]
	 *                   挂单
	 *                   [{"memo1":"1804110000002","object":["Y1830550","Y1830551"],"memo2":"1"}]
	 *                   强制挂单 不验证牌号 
	 * 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doRelationOrderNoValidingSteelFY(CommonPage<String[]> oci) throws Exception {
		ResultModel rm = new ResultModel();
		Date createTime = new Date();
		// 实物卷号数组
		String[] sCoilNo = oci.getObject();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

		if (oci.getMemo1() == null || "".equals(oci.getMemo1().trim()) || sCoilNo == null || sCoilNo.length == 0) {
			rm.setState("500");
			rm.setMsgInfo("条件传入错误!");
			return rm;
		}

		PlnProdorder pp = new PlnProdorder();
		pp.setProd_order_no(oci.getMemo1().trim());
		List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 1);
		if (lpp == null || lpp.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("生产订单[" + pp.getProd_order_no() + "]不存在!");
			return rm;
		}
		
		// 验证生产订单状态是否为订单保留：20230908刘侣
		if ("0PAA60".equals(lpp.get(0).getStatus())) {
			rm.setState("500");
			rm.setMsgInfo("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许挂单");
			return rm;
		}
		if ("0PAA70".equals(lpp.get(0).getStatus())) {
			rm.setState("500");
			rm.setMsgInfo("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许挂单");
			return rm;
		}
		
		// 合同是否是厂内合同
		boolean flag_c = this.getBean(MesApiDesignInfoImpl.class).getContractType(oci.getMemo1().trim());
		
		// 合同是都是来料加工合同
		boolean flag_j = this.getBean(MesApiDesignInfoImpl.class).getCont_Type(oci.getMemo1().trim());

		// 验证生产订单是否锁定
		boolean flag_l = this.getBean(MesApiDesignInfoImpl.class).pOrdIsLocked(oci.getMemo1().trim());
		if (flag_l) {
			throw new Exception("生产订单已经锁定[订单变更中],不允许挂单!");
		}

		// 物料充当脱单履历
		List<PlnMatReplaceLog> lmmrl = this.getMapper(PlnMatReplaceLogMapper.class).findWithCondition(null, "",
				" serial_no desc ", 0, 1);
		long iNo = 1;
		if (lmmrl != null && lmmrl.size() > 0) {
			iNo = lmmrl.get(0).getSerial_no() + 1;
		}

		if ("2".equals(lpp.get(0).getOrder_nature())) {
			// 处理逻辑1
			if ("0PAA12".compareTo(lpp.get(0).getStatus()) > 0) {
				rm.setState("500");
				rm.setMsgInfo("[需加工]的订单，要下发生产后才能挂单！");
				return rm;
			}

			// 判断订单是否是净重交货 (true 不走虚拟发运,不校验第一次挂单信息)
			boolean flag = this.getBean(MesApiServiceImpl.class).judgeOrderWeightType(oci.getMemo1());
			for (String CoilNo : sCoilNo) {
				// 处理逻辑
				// 对传入的实物卷，查询库存信息[物流接口]
				// 存在信息，则读取之； 若不存在信息，则报错“库存中无实物[xxx]信息”
				CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
				YdmProductDetail ypd = new YdmProductDetail();
				ypd.setCoilno(CoilNo);
				cp.setObject(ypd);
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doFindCoilno(cp);
				if (!"200".equals(rmValid.getState())) {
					throw new Exception(rmValid.getMsgInfo());
				}
				// 2018-06-15 限制重复挂单加此操作
				@SuppressWarnings("unchecked")
				List<YdmProductDetail> lypd = (List<YdmProductDetail>) rmValid.getData();
				for (YdmProductDetail ydmp : lypd) {
					if (ydmp.getOrderno() != null) {
						rm.setState("500");
						rm.setMsgInfo(
								"实物[" + cp.getObject().getCoilno() + "]已绑定订单[" + ydmp.getOrderno() + "]! 不能再次操作!");
						return rm;
					} else if(!flag_c && !flag_j){
						PlnMaterielDetail pmd = new PlnMaterielDetail();
						pmd.setObject_no(ydmp.getCoilno());
						List<PlnMaterielDetail> pmdd = this.getMapper(PlnMaterielDetailMapper.class)
								.findWithCondition(pmd, "nvl(invalid_flg,0) = 0", "", 0, 0);
						if (pmdd != null && pmdd.size() > 0) {
							for (PlnMaterielDetail plnmaterieldetail : pmdd) {
								plnmaterieldetail.setObject_no("");
								this.getMapper(PlnMaterielDetailMapper.class).update(plnmaterieldetail);
							}
						}
					}
				}

				// 拆分订单不验证合同号
				if (!(lpp.get(0).getIs_split() != null && "1".equals(lpp.get(0).getIs_split()))) {
					if (!flag && !flag_c && !flag_j) {
						// 判断第一次挂单与第二次挂单合同号contract_no是否一致 2018-09-05 通过挂单日志表获取最后一条脱单的订单信息(原料卷订单 属性为新钢
						// 最后一个)
						List<PlnProdorder> plnlog = this.getMapper(PlnMatReplaceLogMapper.class).findreplacelog(CoilNo);
						if (Utils.isNotEmpty(plnlog)) {
							if (!lpp.get(0).getContract_no().equals(plnlog.get(0).getContract_no())) {
								// 去掉这个限制lanyushan：20231113刘侣
//								throw new Exception("合同号不匹配，不能上料! 合同号 : [" + plnlog.get(0).getContract_no() + ","
//										+ lpp.get(0).getContract_no() + "]");
							}
						} else {
							//throw new Exception("未找到[" + CoilNo + "]对应原料卷订单挂单信息!");
						}
					}
				}

				// 如果牌号不匹配
				if (!lpp.get(0).getSteel_code().equals(lypd.get(0).getJudgesteelcode()) || !lpp.get(0).getSteel_code().equals(lypd.get(0).getSteelcode())) {
					// 1、备份库存信息
					CommonPage<YdmProductDetail> sum = new CommonPage<YdmProductDetail>();
					YdmProductDetail detail = new YdmProductDetail();
					detail.setCoilno(CoilNo);

//					detail.setSteelcode(ypd.getSteelcode());
//					detail.setJudgesteelcode(ypd.getJudgesteelcode());
//					detail.setCreatedate(new Date());
					
					List<YdmProductDetail> ydmlist = new ArrayList<YdmProductDetail>();
					ydmlist.add(detail);
					sum.setObjectList(ydmlist);
					this.getBean(YdmProductDetailBfServiceImpl.class).doAddDetailBf(sum);
					// 2、修改牌号
					detail.setSteelcode(lpp.get(0).getSteel_code());
					detail.setSteel_name(lpp.get(0).getSteel_name());
					this.getMapper(YdmProductDetailMapper.class).update(detail);
				}

				// 生成一条虚拟物料记录
				// 生成虚拟物料信息倒叙去一条
				List<PlnMaterielDetail> lpmd = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "",
						" serial_no desc ", 0, 1);
				long PMDNo = 1;
				if (lpmd != null && lpmd.size() > 0) {
					PMDNo = lpmd.get(0).getSerial_no() + 1;
				}
				String sDate = new SimpleDateFormat("yyMMdd").format(new Date());
				int objectnoVtNo = this.getMapper(PlnMaterielDetailMapper.class).getObjectVtMaxNoForDate(sDate) + 1;
				PlnMaterielDetail pme = new PlnMaterielDetail();
				pme.setObject_no(CoilNo);
				pme.setSerial_no(PMDNo++);
				pme.setProc_repeat_index(1);
				pme.setObject_no_vt(sDate + String.format("%06d", objectnoVtNo++));
				pme.setOrder_no(lpp.get(0).getOrder_no());
				pme.setPline_code(lpp.get(0).getPline_code());
				pme.setIs_finished("0");
				pme.setIs_mat(1);// 母卷：1
				pme.setOrder_no(lpp.get(0).getOrder_no());
				pme.setProd_order_no(lpp.get(0).getProd_order_no());
				pme.setIs_multi("0");
				pme.setSteel_code(lpp.get(0).getSteel_code());
				// 母卷厚度、宽度使用计划值
				pme.setWidth(lpp.get(0).getWidth());
				pme.setThick(lpp.get(0).getThick());
				pme.setLength(lpp.get(0).getLength());
				pme.setDiameter_inn(lpp.get(0).getDiameter_inn());
				pme.setDiameter_out(lpp.get(0).getDiameter_out());
				pme.setSingle_weight(lypd.get(0).getFactweight());
				pme.setFixed_length_type_no(lpp.get(0).getFixed_length_type_no());
				pme.setCut_edge_type_no(lpp.get(0).getCut_edge_type_no());
				pme.setOrd_flg("1");
				pme.setCreate_man_name(userName);
				pme.setCreate_time(new Date());
				pme.setDeliver_date_earliest(lpp.get(0).getDeliver_date());
				pme.setDeliver_date_latest(lpp.get(0).getDeliver_date());
				this.getMapper(PlnMaterielDetailMapper.class).insert(pme);
				
				// 整卷发运直接在库发运
				if ("1".equals(lpp.get(0).getWhole_coil())) {

					// 保存相关数据
					// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
					PlnProdorderStatistic pps = new PlnProdorderStatistic();
					pps.setProd_order_no(lpp.get(0).getProd_order_no());
					pps.setReplaced(lypd.get(0).getFactweight());
					pps.setReplaced_cnt(1);
					pps.setReplaced_times(1);
					pps.setUnscheduled(lypd.get(0).getFactweight() == null ? null : (-lypd.get(0).getFactweight()));
					this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

					// 修改订单进程表[PLN_ORDER_STATISTIC]
					PlnOrderStatistic pos = new PlnOrderStatistic();
					pos.setOrder_no(lpp.get(0).getOrder_no());
					pos.setReplaced(lypd.get(0).getFactweight());
					pos.setReplaced_cnt(1);
					pos.setReplaced_times(1);
					pos.setUnscheduled(lypd.get(0).getFactweight() == null ? null : (-lypd.get(0).getFactweight()));
					this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);

					// 调用物流接口，关联实物和生产订单信息
					ypd.setProdorderno(lpp.get(0).getProd_order_no());
					ypd.setOrderno(lpp.get(0).getOrder_no());
					ypd.setCustomer_no(lpp.get(0).getCustomer_no());
					ypd.setCustomer_nm(lpp.get(0).getCustomer_name());
					ypd.setReceiv_nm(lpp.get(0).getReciver_unit_name());
					ypd.setReceiv_no(lpp.get(0).getReciver_unit_no());
					ypd.setDelivery_state_code(lpp.get(0).getDelivery_state_code());
					ypd.setDelivery_state_desc(lpp.get(0).getDelivery_state_desc());
					this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);

					// 写物料充当脱单履历表[MIL_MAT_REPLACE_LOG] MilMatReplaceLog
					PlnMatReplaceLog mmrl = new PlnMatReplaceLog();
					mmrl.setSerial_no(iNo++);
					mmrl.setObject_no(lypd.get(0).getCoilno());
					mmrl.setOpt_type("2");
					mmrl.setOrder_no(lpp.get(0).getOrder_no());
					mmrl.setProd_order_no(lpp.get(0).getProd_order_no());
					mmrl.setCreate_man_name(userName);
					mmrl.setCreate_time(new Date());
					mmrl.setRemark("整卷发运");
					this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);

				} else {
					// 修改生产订单进程表[PLN_PRODORDER_STATISTIC] 订单进程表
					this.getBean(MesApiDesignInfoImpl.class).updateOrderStatic(lpp.get(0).getProd_order_no(),
							lpp.get(0).getOrder_no(), lpp.get(0).getWhole_process_codes(), lypd.get(0).getFactweight(),
							true);

					// 查询虚拟物料表【PLN_MATERIEL_DETAIL】---- where NVL(INVALID_FLG,0)=0 AND OBJECT_NO =
					// 实物卷号
					List<PlnMaterielDetail> pmdd = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
							" NVL(INVALID_FLG,0)=0 AND OBJECT_NO = '" + CoilNo + "'", "", 0, 0);

					// 调用物流接口，关联实物和生产订单信息
					ypd.setCustomer_no(lpp.get(0).getCustomer_no());
					ypd.setCustomer_nm(lpp.get(0).getCustomer_name());
					ypd.setReceiv_nm(lpp.get(0).getReciver_unit_name());
					ypd.setReceiv_no(lpp.get(0).getReciver_unit_no());
					ypd.setProdorderno(lpp.get(0).getProd_order_no());
					ypd.setOrderno(lpp.get(0).getOrder_no());
					ypd.setObject_no_vt(pmdd.get(0).getObject_no_vt());
					ypd.setDelivery_state_code(lpp.get(0).getDelivery_state_code());
					ypd.setDelivery_state_desc(lpp.get(0).getDelivery_state_desc());
					this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);

					// 写物料充当脱单履历表[MIL_MAT_REPLACE_LOG] MilMatReplaceLog
					PlnMatReplaceLog mmrl = new PlnMatReplaceLog();
					BeanUtils.copyProperties(pmdd.get(0), mmrl);
					mmrl.setSerial_no(iNo++);
					mmrl.setOpt_type("2");
					mmrl.setCreate_man_name(userName);
					mmrl.setCreate_time(createTime);
					mmrl.setRemark("强制挂单不验证牌号");
					this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
				}

				ResultModel rejRes = reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				ycjsPYdd(CoilNo, true);
				
			}
		} else {
			// 处理逻辑2
			for (String CoilNo : sCoilNo) {
				// 处理逻辑
				// 对传入的实物卷，查询库存信息[物流接口]
				// 存在信息，则读取之； 若不存在信息，则报错“库存中无实物[xxx]信息”
				CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
				YdmProductDetail ypd = new YdmProductDetail();
				ypd.setCoilno(CoilNo);
				cp.setObject(ypd);
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doFindCoilno(cp);
				if (!"200".equals(rmValid.getState())) {
					throw new Exception(rmValid.getMsgInfo());
				}

				// 2018-06-15 限制重复挂单加此操作
				@SuppressWarnings("unchecked")
				List<YdmProductDetail> lypd = (List<YdmProductDetail>) rmValid.getData();
				for (YdmProductDetail ydmp : lypd) {
					if (ydmp.getOrderno() != null) {
						rm.setState("500");
						rm.setMsgInfo(
								"实物[" + cp.getObject().getCoilno() + "]已绑定订单[" + ydmp.getOrderno() + "]! 不能再次操作!");
					} else if(!flag_c){
						PlnMaterielDetail pmd = new PlnMaterielDetail();
						pmd.setObject_no(ydmp.getCoilno());
						List<PlnMaterielDetail> pmdd = this.getMapper(PlnMaterielDetailMapper.class)
								.findWithCondition(pmd, "nvl(invalid_flg,0) = 0", "", 0, 0);
						if (pmdd != null && pmdd.size() > 0) {
							for (PlnMaterielDetail plnmaterieldetail : pmdd) {
								plnmaterieldetail.setObject_no("");
								this.getMapper(PlnMaterielDetailMapper.class).update(plnmaterieldetail);
							}
						}
					}
				}

				// 如果牌号不匹配
				if (!lpp.get(0).getSteel_code().equals(lypd.get(0).getJudgesteelcode()) || !lpp.get(0).getSteel_code().equals(lypd.get(0).getSteelcode())) {
					// 1、备份库存信息
					CommonPage<YdmProductDetail> sum = new CommonPage<YdmProductDetail>();
					YdmProductDetail detail = new YdmProductDetail();
					detail.setCoilno(CoilNo);

//					detail.setSteelcode(ypd.getSteelcode());
//					detail.setJudgesteelcode(ypd.getJudgesteelcode());
//					detail.setCreatedate(new Date());
					
					List<YdmProductDetail> ydmlist = new ArrayList<YdmProductDetail>();
					ydmlist.add(detail);
					sum.setObjectList(ydmlist);
					this.getBean(YdmProductDetailBfServiceImpl.class).doAddDetailBf(sum);
					// 2、修改牌号
					detail.setSteelcode(lpp.get(0).getSteel_code());
					detail.setSteel_name(lpp.get(0).getSteel_name());
					this.getMapper(YdmProductDetailMapper.class).update(detail);
				}

				// 保存相关数据
				// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
				PlnProdorderStatistic pps = new PlnProdorderStatistic();
				pps.setProd_order_no(lpp.get(0).getProd_order_no());
				pps.setReplaced(lypd.get(0).getFactweight());
				pps.setReplaced_cnt(1);
				pps.setReplaced_times(1);
				pps.setUnscheduled(lypd.get(0).getFactweight() == null ? null : (-lypd.get(0).getFactweight()));
				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

				// 修改订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos = new PlnOrderStatistic();
				pos.setOrder_no(lpp.get(0).getOrder_no());
				pos.setReplaced(lypd.get(0).getFactweight());
				pos.setReplaced_cnt(1);
				pos.setReplaced_times(1);
				pos.setUnscheduled(lypd.get(0).getFactweight() == null ? null : (-lypd.get(0).getFactweight()));
				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);

				// 调用物流接口，关联实物和生产订单信息
				ypd.setProdorderno(pps.getProd_order_no());
				ypd.setOrderno(pos.getOrder_no());
				ypd.setCustomer_no(lpp.get(0).getCustomer_no());
				ypd.setCustomer_nm(lpp.get(0).getCustomer_name());
				ypd.setReceiv_nm(lpp.get(0).getReciver_unit_name());
				ypd.setReceiv_no(lpp.get(0).getReciver_unit_no());
				ypd.setDelivery_state_code(lpp.get(0).getDelivery_state_code());
				ypd.setDelivery_state_desc(lpp.get(0).getDelivery_state_desc());
				this.getMapper(YdmProductDetailMapper.class).doFinshedProductActUpdate(ypd);

				// 写物料充当脱单履历表[MIL_MAT_REPLACE_LOG] MilMatReplaceLog
				PlnMatReplaceLog mmrl = new PlnMatReplaceLog();
				mmrl.setSerial_no(iNo++);
				mmrl.setObject_no(lypd.get(0).getCoilno());
				mmrl.setOpt_type("1");
				mmrl.setOrder_no(pos.getOrder_no());
				mmrl.setProd_order_no(pps.getProd_order_no());
				mmrl.setCreate_man_name(userName);
				mmrl.setCreate_time(createTime);
				mmrl.setRemark("强制挂单不验证牌号");
				this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
				
				ResultModel rejRes = reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				ycjsPYdd(CoilNo, true);
				
			}
		}
		rm.setState("200");
		return rm;
	}
	
	
	
	/**
	 * 20230908刘侣，点击订单保留
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdReserve(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "订单保留成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo().substring(0, soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3);
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]已经是 ‘订单保留’ 状态");
				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus("0PAA60");
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单保留信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230908刘侣，点击订单取消保留
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelOrdReserve(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "订单取消保留成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo().substring(0, soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3);
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if (!"0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]非 ‘订单保留’ 状态");
				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setStatus(pp.getP_status());
				pp.setP_status("0PAA60");
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单保留信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 20230908刘侣，点击订单生产完成
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdReserveSC(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "改成订单生产完成成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo().substring(0, soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3);
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 去掉：得让lys能够将订单改成生产完成：
				// 验证生产订单状态是否为订单保留：
//				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
//					thception("生产订单["+ppoL.get(0).getProd_order_no()+"]已经是 ‘订单保留’ 状态");
//				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus("0PAA20"); // 生产完成
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单生产完成信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 20230908刘侣，点击订单发货完成
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdReserveFH(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "改成订单发货完成成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo().substring(0, soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3);
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 去掉：得让lys能够将订单改成发货完成：
				// 验证生产订单状态是否为订单保留：
//				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
//					thception("生产订单["+ppoL.get(0).getProd_order_no()+"]已经是 ‘订单保留’ 状态");
//				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus("0PAA50"); // 发货完成
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单发货完成信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 20230908刘侣，点击订单生产进行
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdReserveKQ(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "改成订单生产进行成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo().substring(0, soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3) + soi.getOrdNo().substring(soi.getOrdNo().length() - 3);
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 去掉：得让lys能够将订单改成发货完成：
				// 验证生产订单状态是否为订单保留：
//				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
//					thception("生产订单["+ppoL.get(0).getProd_order_no()+"]已经是 ‘订单保留’ 状态");
//				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus("0PAA15"); // 生产进行：点击后 开启订单：固定为转到生产进行
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单固定为生产进行信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 20230908刘侣，点击订单保留
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdReserveLYS(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "订单保留成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo();
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]已经是 ‘订单保留’ 状态");
				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus("0PAA60");
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单保留信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230908刘侣，点击取消订单保留
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelOrdReserveLYS(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "订单取消保留成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：
				String realOrdNo = soi.getOrdNo();
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if (!"0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]非 ‘订单保留’ 状态");
				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setStatus(pp.getP_status());
				pp.setP_status("0PAA60");
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单保留信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230908刘侣，点击订单关闭
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doOrdCloseLYS(CommonPage<ComBaseddR> sum) {
		ResultModel rm = new ResultModel("200", "订单关闭成功");
		List<ComBaseddR> sumList = sum.getObjectList();
		if (sumList == null || sumList.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入ObjectList参数");
		}
		try {
			for(ComBaseddR soi : sumList) {
				if (soi.getOrdNo() == null || "".equals(soi.getOrdNo())) {
					throw new Exception("请传入订单号");
				}
				// 拼接优特钢订单号：合同号 合同行序号 订单序号：coilNo 这个借用为生产订单状态；
				String realOrdNo = soi.getOrdNo();
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO='"+realOrdNo+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + soi.getOrdNo() + " 不存在");
				}
				// 验证生产订单状态是否为订单关闭：0PAA99
				if (soi.getCoilNo().equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单号["+ppoL.get(0).getProd_order_no()+"]已经是 ‘生产完成或发货完成’ 状态");
				}
				// 将生产订单状态改成：订单保留
				PlnProdorder pp = ppoL.get(0);
				pp.setP_status(pp.getStatus());
				pp.setStatus(soi.getCoilNo());
				// 先注释，防止测试时调用接口insert了：20230807刘侣
				this.getMapper(PlnProdorderMapper.class).update(pp);
				

				//日志
				Date now = new Date();
				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
				MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "订单关闭信息同步", "一体化", opr_time, null, null, null, null, realOrdNo);
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，发送检验数据：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendToJYWT(String coilNo, boolean isTB) {
		ResultModel rm = new ResultModel("200", "发送检验委托成功");
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		if (coilNo == null || "".equals(coilNo)) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号");
		}
		
		// 如果是头尾和边丝：直接不发送检验委托和待判：
		String lastChar = coilNo.substring(coilNo.length()-1);
		if ("B".equals(lastChar) || "H".equals(lastChar)) {
			return rm;
		}
		
		YdmProductDetail y = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
		
		// 调用新质量系统sql去判断，是否需要发送检验委托：
		String orderno = y.getOrderno().substring(0, y.getOrderno().length() - 3);
		int num = this.getMapper(YdmProductDetailMapper.class).isFSJy(orderno);
		if (num <= 0) {
			// 新质量系统里面这个订单不需要做检验委托：
//			System.out.println("卷：" + coilNo + " 不需要做检验委托 " + orderno);
			return rm;
		}
		
		try {
			
			// 发送检验信息：先注释掉，这个没有测试环境，得等上线，先将参数发小龙去本地测试；
//			String param = "";
			// 拼接参数：
			JSONArray arr = new JSONArray();
			JSONObject json = new JSONObject();
			
			YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
			if (ypdQ == null || "".equals(ypdQ)) {
				throw new Exception("卷库存信息未找到");
			}
			
			
			
			ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypdQ.getSteelcode());
			if (cbs == null || "".equals(cbs)) {
				throw new Exception("卷牌号未找到");
			}
			
			String currentMachine = coilNo.contains("S") ? "YTSX" : coilNo.contains("L") ? "YTZZ" : coilNo.contains("P") ? "YTPZ" : coilNo.contains("T") ? "YTTH" : coilNo.contains("K") ? "YTHJ" : coilNo.contains("F") ? "YTZJ" : "YT1";
			String ordernoYT = ypdQ.getOrderno().substring(0, ypdQ.getOrderno().length() - 6) + ypdQ.getOrderno().substring(ypdQ.getOrderno().length() - 3);
			
			json.put("INSPECTION_LOT", ypdQ.getInspection_lot() != null ? ypdQ.getInspection_lot() : ypdQ.getBatchno());
			json.put("DESIGN_KEY", ordernoYT);
			json.put("PSC", null);
			json.put("HEAT_NO", ypdQ.getHeatno());
			json.put("BATCH_NO", ypdQ.getBatchno());
			json.put("BOARD_NO", ypdQ.getCoilno().substring(0, ypdQ.getCoilno().length() - 2));
			json.put("GRADE_CODE", ypdQ.getSteelcode());
			json.put("GRADE_NAME", cbs.getSteel_name());
			json.put("MATERIAL_NO", ypdQ.getCoilno());
			json.put("MSC_PLINE", null);
			json.put("PLINE_CODE", "YT1");
			json.put("PLINE_NAME", "优特钢");
			json.put("DELIVERY_STATE_CODE", ypdQ.getDelivery_state_code());
			json.put("DELIVERY_STATE_DESC", ypdQ.getDelivery_state_desc());
			json.put("PROCESS_CODE", currentMachine);
			json.put("THICK", ypdQ.getThick() == null ? "" : ypdQ.getThick().toString());
			json.put("WIDTH", ypdQ.getWidth());
			json.put("LENGTH", ypdQ.getLength());
			json.put("IS_QTLY", "1");
			json.put("IS_CHEM", "0");
			json.put("TYPE", "0");
			json.put("USER_NAME", username);
			json.put("MEMO", "");
			arr.add(json);
			
//			System.out.println("检验委托json参数：");
//			System.out.println(arr);
			
			
			
			
			WebService1_Service ws = new WebService1_Service();
			String res = ws.getWebService1ImplPort().autoGenerationSampleInfoYT(arr.toString());
			if (!"1".equals(res)) {
				throw new Exception("发送检验信息失败：" + coilNo + " ," + res);
			}
			// end
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，发送检验数据：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendToJYWTLS(String coilNo) {
		ResultModel rm = new ResultModel("200", "发送检验委托成功");
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		if (coilNo == null || "".equals(coilNo)) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号");
		}
		
		// 如果是头尾和边丝：直接不发送检验委托和待判：
		String lastChar = coilNo.substring(coilNo.length()-1);
		if ("B".equals(lastChar) || "H".equals(lastChar)) {
			return rm;
		}
		
		YdmProductDetail y = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
		
		// 调用新质量系统sql去判断，是否需要发送检验委托：
		String orderno = y.getOrderno().substring(0, y.getOrderno().length() - 3);
		int num = this.getMapper(YdmProductDetailMapper.class).isFSJy(orderno);
		if (num <= 0) {
			// 新质量系统里面这个订单不需要做检验委托：
			System.out.println("卷：" + coilNo + " 不需要做检验委托 " + orderno);
			return rm;
		}
		
		try {
			
			// 发送检验信息：先注释掉，这个没有测试环境，得等上线，先将参数发小龙去本地测试；
//			String param = "";
			// 拼接参数：
			JSONArray arr = new JSONArray();
			JSONObject json = new JSONObject();
			
			YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
			if (ypdQ == null || "".equals(ypdQ)) {
				throw new Exception("卷库存信息未找到");
			}
			
			
			ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypdQ.getSteelcode());
			if (cbs == null || "".equals(cbs)) {
				throw new Exception("卷牌号未找到");
			}
			
			String currentMachine = coilNo.contains("S") ? "YTSX" : coilNo.contains("L") ? "YTZZ" : coilNo.contains("P") ? "YTPZ" : coilNo.contains("T") ? "YTTH" : coilNo.contains("K") ? "YTHJ" : coilNo.contains("F") ? "YTZJ" : "YT1";
			String ordernoYT = ypdQ.getOrderno().substring(0, ypdQ.getOrderno().length() - 6) + ypdQ.getOrderno().substring(ypdQ.getOrderno().length() - 3);
			
			json.put("INSPECTION_LOT", ypdQ.getInspection_lot() != null ? ypdQ.getInspection_lot() : ypdQ.getBatchno());
			json.put("DESIGN_KEY", ordernoYT);
			json.put("PSC", null);
			json.put("HEAT_NO", ypdQ.getHeatno());
			json.put("BATCH_NO", ypdQ.getBatchno());
			json.put("BOARD_NO", ypdQ.getCoilno().substring(0, ypdQ.getCoilno().length() - 2));
			json.put("GRADE_CODE", ypdQ.getSteelcode());
			json.put("GRADE_NAME", cbs.getSteel_name());
			json.put("MATERIAL_NO", ypdQ.getCoilno());
			json.put("MSC_PLINE", null);
			json.put("PLINE_CODE", "YT1");
			json.put("PLINE_NAME", "优特钢");
			json.put("DELIVERY_STATE_CODE", ypdQ.getDelivery_state_code());
			json.put("DELIVERY_STATE_DESC", ypdQ.getDelivery_state_desc());
			json.put("PROCESS_CODE", currentMachine);
			json.put("THICK", ypdQ.getThick() == null ? "" : ypdQ.getThick().toString());
			json.put("WIDTH", ypdQ.getWidth());
			json.put("LENGTH", ypdQ.getLength());
			json.put("IS_QTLY", "1");
			json.put("IS_CHEM", "0");
			json.put("TYPE", "0");
			json.put("USER_NAME", username);
			json.put("MEMO", "");
			arr.add(json);
			
//			System.out.println("检验委托json参数：");
//			System.out.println(arr);
			
			
			
			
			WebService1_Service ws = new WebService1_Service();
			String res = ws.getWebService1ImplPort().autoGenerationSampleInfoYT(arr.toString());
			if (!"1".equals(res)) {
				throw new Exception("发送检验信息失败：" + coilNo + " ," + res);
			}
			// end
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，发送判定信息数据：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendToPD(String coilNo, boolean isTB, String isfinal) {
		ResultModel rm = new ResultModel("200", "发送待判信息成功");
//		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		if (coilNo == null || "".equals(coilNo)) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号");
		}
		
		// 如果是头尾和边丝：直接不发送检验委托和待判：
		YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
		String lastChar = coilNo.substring(coilNo.length()-1);
		if ("B".equals(lastChar) || "H".equals(lastChar)) {
			// 综判默认直接判废：不需要，交工的时候默认已经给了头尾和边丝合格和判废：
			
//			if (ypdQ != null) {
//				ypdQ.setJudgeresult("40740804");
//				this.getMapper(YdmProductDetailMapper.class).update(ypdQ);
//			}
			return rm;
		}
		
		try {
			// 写入质量表：
			if (isTB) {
				
				int num1 = this.getMapper(YdmProductDetailMapper.class).countToQSys(coilNo);
				int num2 = this.getMapper(YdmProductDetailMapper.class).countToSysLog(coilNo);
				
				if (num1 > 0) {
					// 这个卷已经存在：执行更新：
//					System.out.println("update1");
					
				} else {
					// 这个卷不存在，执行插入：
					this.getMapper(YdmProductDetailMapper.class).insertToQSysTB(coilNo);
					this.getMapper(YdmProductDetailMapper.class).insertToQSysTBLog(coilNo); // 这个插入log的先注释掉：20230921刘侣恢复20230926
				}
				
				
			} else {
				int num1 = this.getMapper(YdmProductDetailMapper.class).countToQSys(coilNo);
				if (num1 > 0) {
					
				} else {
					this.getMapper(YdmProductDetailMapper.class).insertToQSys(coilNo, isfinal, ypdQ.getInspection_lot() != null ? ypdQ.getInspection_lot() : ypdQ.getBatchno());
					this.getMapper(YdmProductDetailMapper.class).insertToQSysTBLogTh(coilNo);
				}
				
				
			}
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，发送判定信息数据：退火
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendToTHPD(String coilNo, boolean isTB, String isfinal) {
		ResultModel rm = new ResultModel("200", "发送待判信息成功");
//		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		if (coilNo == null || "".equals(coilNo)) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号");
		}
		
		YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(coilNo, null);
		
		try {
			int num1 = this.getMapper(YdmProductDetailMapper.class).countToQSys(coilNo);
			
			if (num1 > 0) {
				// 执行更新：
//				System.out.println("update");
			} else {

				// 写入质量表：
				this.getMapper(YdmProductDetailMapper.class).insertToQSysTh(coilNo, isfinal, ypdQ.getInspection_lot() != null ? ypdQ.getInspection_lot() : ypdQ.getBatchno());
				this.getMapper(YdmProductDetailMapper.class).insertToQSysTBLogTh(coilNo); // 这个插入log的先注释掉：20230921刘侣恢复20230926
			
			}
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
//	public ResultModel jc (String coilno) throws Exception {
//		// 卷必须没有经过任何计划编制：2023011301 pm.getObject_no()
//		List<PlnPicklePlanDetail> pdList = this.getMapper(PlnPicklePlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+coilno+"'", null, 0, 1);
//		List<PlnLengthwisePlanDetail> pleList = this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+coilno+"'", null, 0, 1);
//		List<PlnAnnealPlanDetail> plaList = this.getMapper(PlnAnnealPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+coilno+"'", null, 0, 1);
//		List<PlnSkinrollingPlanDetail> plsList = this.getMapper(PlnSkinrollingPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+coilno+"'", null, 0, 1);
//		List<PlnRollingPlanDetail> plrList = this.getMapper(PlnRollingPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+coilno+"'", null, 0, 1);
//		
//		if (pdList.size() > 0 || pleList.size() > 0 || plaList.size() > 0 || plsList.size() > 0 || plrList.size() > 0) {
//			throw new Exception("卷号" + coilno + "已经计划编制，不允许脱单！");
//		}
//	}
	
	
	/**
	 * 20231115刘侣，补发待判信息数据：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel bfSendToPD(CommonPage<YdmProductDetail> sum) {
		ResultModel rm = new ResultModel("200", "补发送待判信息成功");
//		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		List<YdmProductDetail> ypdL = sum.getObjectList();
		
		if (ypdL == null || ypdL.size() <= 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入卷号信息");
		}
		
		try {
			
			for(YdmProductDetail ypd : ypdL) {
				// 如果是头尾和边丝：直接不发送检验委托和待判：
				YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(ypd.getCoilno(), null);
			
				// 写入质量表：
				int num1 = this.getMapper(YdmProductDetailMapper.class).countToQSys(ypdQ.getCoilno());
				if (num1 > 0) {
					
				} else {
					String isfinal = "500203".equals(ypdQ.getStorageattr()) ? "1" : "0";
					this.getMapper(YdmProductDetailMapper.class).insertToQSys(ypdQ.getCoilno(), isfinal, ypdQ.getInspection_lot() != null ? ypdQ.getInspection_lot() : ypdQ.getBatchno());
					this.getMapper(YdmProductDetailMapper.class).insertToQSysTBLogTh(ypdQ.getCoilno());
				}
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 20230909刘侣，接收公差判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel receiveResMeasure(CommonPage<QcmJudgeMeasure> sum) {
		ResultModel rm = new ResultModel("200", "公差检验结果接收成功");
		QcmJudgeMeasure gc = sum.getObject();
		if (gc == null || "".equals(gc)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			examineGc(gc);
			
			// 将结果update进库存表：
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(gc.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不是在库状态，不允许公差判定");
			}
			
			// 将之前可能存在的该卷的综判：20231120刘侣
			List<QcmJudgeMeasure> qjmList = this.getMapper(QcmJudgeMeasureMapper.class).findWithCondition(null, " MATERIAL_NO='"+gc.getMaterial_no()+"'", "SIC_ID desc", 0, 0);
			if (qjmList != null && qjmList.size() > 0) {
				// 存在历史公差判定信息，逐个清除：
				for (QcmJudgeMeasure m : qjmList) {
					this.getMapper(QcmJudgeMeasureMapper.class).delete(m.getSic_id());
				}
			}
			
////			-- SIZERESULT：
////			-- {ID: '40740301', TEXT: '合格'},
////			-- {ID: '40740302', TEXT: '不合格'} {ID: '40740303', TEXT: '判次'} {ID: '40740304', TEXT: '判废'}
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeMeasureMapper.class).insert(gc);
			
			String sizeResult = "合格".equals(gc.getSic_result_desc()) ? "40740301" : "不合格".equals(gc.getSic_result_desc()) ? "40740302" : "判次".equals(gc.getSic_result_desc()) ? "40740303" : "判废".equals(gc.getSic_result_desc()) ? "40740304" : "0";
			ypd.setSizeresult(sizeResult);
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "公差接收信息同步", gc.getJudge_name(), opr_time, null, null, null, null, gc.getMaterial_no());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，取消接收公差判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel cancelReceiveResMeasure(CommonPage<QcmJudgeMeasure> sum) {
		ResultModel rm = new ResultModel("200", "取消公差检验结果接收成功");
		QcmJudgeMeasure gc = sum.getObject();
		if (gc == null || "".equals(gc)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			if (gc.getSic_id() == null || "".equals(gc.getSic_id())) {
				throw new Exception("缺少公差检验索引号参数");
			}
			// 将结果update进库存表：
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(gc.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不是在库状态，不允许取消公差判定");
			}
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeMeasureMapper.class).delete(gc.getSic_id());
////			-- SIZERESULT：
////			-- {ID: '40740301', TEXT: '合格'},
////			-- {ID: '40740302', TEXT: '不合格'}
			ypd.setSizeresult(""); // null会不生效
			this.getMapper(YdmProductDetailMapper.class).update(ypd);

			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	public void examineGc(QcmJudgeMeasure gc) throws Exception {
		if (gc.getSic_id() == null || "".equals(gc.getSic_id())) {
			throw new Exception("缺少公差检验索引号参数");
		}
//		if (gc.getInspection_lot() == null || "".equals(gc.getInspection_lot())) {
//			throw new Exception("缺少检验号参数");
//		}
		if (gc.getMaterial_no() == null || "".equals(gc.getMaterial_no())) {
			throw new Exception("缺少卷号参数");
		}
		if (gc.getSic_result_desc() == null || "".equals(gc.getSic_result_desc())) {
			throw new Exception("缺少公差检验结果参数");
		}
		
		gc.setSic_result_code("合格".equals(gc.getSic_result_desc()) ? "40740301" : "不合格".equals(gc.getSic_result_desc()) ? "40740302" : "判次".equals(gc.getSic_result_desc()) ? "40740303" : "判废".equals(gc.getSic_result_desc()) ? "40740304" : "0");
	}
		
	/**
	 * 20230909刘侣，接收综合判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel receiveResUltimate(CommonPage<QcmJudgeUltimate> sum) {
		ResultModel rm = new ResultModel("200", "综合判定检验结果接收成功");
//		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		Date now = new Date();
		QcmJudgeUltimate zp = sum.getObject();
		if (zp == null || "".equals(zp)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			examineZp(zp);
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			// 将结果update进库存表：
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(zp.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + zp.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + zp.getMaterial_no() + " 不是在库状态，不允许综合判定");
			}
////			-- JUDGERESULT:
////			-- 合格：40740801
////			-- 不合格：40740802
////			-- 判次：40740803
////			-- 判废：40740804
			this.getMapper(QcmJudgeUltimateMapper.class).insert(zp);
			String judgeResult = "合格".equals(zp.getUtm_result_desc()) ? "40740801" : "不合格".equals(zp.getUtm_result_desc()) ? "40740802" : "次品".equals(zp.getUtm_result_desc()) ? "40740803" : "废品".equals(zp.getUtm_result_desc()) ? "40740804" : "0";
			ypd.setJudgeresult(judgeResult);
			ypd.setPhysresult_id(zp.getPic_id());
			// 再次接收综判的时候库存表内的表面结果，表面id，公差结果需要重新填进去：20231122刘侣
			String sizeResult = "合格".equals(zp.getSic_result_desc()) ? "40740301" : "不合格".equals(zp.getSic_result_desc()) ? "40740302" : "判次".equals(zp.getSic_result_desc()) ? "40740303" : "判废".equals(zp.getSic_result_desc()) ? "40740304" : null;
			ypd.setSizeresult(sizeResult);
			String surfaceResult = "合格".equals(zp.getSfu_result_desc()) ? "40740601" : "不合格".equals(zp.getSfu_result_desc()) ? "40740602" : "判次".equals(zp.getSfu_result_desc()) ? "40740603" : "判废".equals(zp.getSfu_result_desc()) ? "40740604" : null;
			ypd.setUp_surface_result(surfaceResult);
			ypd.setSurfaceresult(surfaceResult);
			ypd.setUp_surface_result_id(zp.getSfu_id());
			
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());
			
			// 可能需要将综判在入库后的这部分数据进行 二次的综判撤回和发送异动点：20240510刘侣
			// 因为现在是入库后抛送产出 里面就再抛送综判，但可能有的卷综判是在入库之后：这部分要改
			if ("0".equals(ypd.getState())) {
				// 接收综判的时候已经入库：那么就需要给综判结果更新，后续再看结果吧看要不要改
				qXUltiYdd(ypd.getCoilno());
				receiveUltiYdd(ypd.getCoilno());
			}
			
			
			
			// 综判异动点后移到入库时才发送，因为要先发送产出异动点：20240509刘侣
			// 优特钢带属性卷最后一道工序不合格：不抛综判异动点；zhouxunbin提出：20231110刘侣
			// 接收综判不抛综判异动点，只在发货的时候抛送异动点：xuli 20231227刘侣
			// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425 zhouxunbin
			// 且只有进成品库及该卷是优特钢带属性的卷才发 综判异动点：20240429 zhouxunbin
//			if ("500203".equals(ypd.getStorageattr()) && "507101".equals(ypd.getObject_attr())) {
//				// 记录成本异动点：20230811刘侣
//				ComBaseCbYdd cd = new ComBaseCbYdd();
//				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
//				cd.setInstDisp("01");
//				cd.setDataTypeIdx("O");
//				// 当前产线：
//				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
//				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setInvQtyUnit("块");
//				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
//				cd.setCreateId(userId);
//				cd.setActivityId("69A");
//				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
//				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setProdName(ypd.getProd_name());
//				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
//				
//				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
//				// 上道产线：
//				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
//				cd.setRefnoA(prevcoil); // 投料卷号
//				cd.setSysId("IA");
//				cd.setOrderItem(ypd.getOrderno());
//				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setBeTransUnit("t");
//				cd.setExecJobFunc("N");
//				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
//				if (cbs != null) {
//					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
//				}
//				
//				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
//				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
//				cd.setProdTypeNo("CTR");
//				cd.setAppId("优特钢产出卷发货");
//				cd.setInvId(ypd.getCoilno());
//				cd.setInvQty("1");
//				cd.setSrcFac("1");
//				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
//				cd.setProdClassNo("H");
//				
//				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
//				
//				// setSrcFac根据卷的物料属性去判断：
//				cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
//				
//				// 去掉只有原料卷才需要增加综判异动点,zhouxubin：20231110刘侣
//				// 优特钢带属性卷最后一道工序不合格发货时：卷综判判废给11az，其他结果给 11ac和69a:zhouxubin：20231110刘侣
//				// 卷子质量系统判废就 给 11AZ xuli需求 20231227 刘侣
//				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
//				cd.setActivityId("11AC");
//				if ("40740804".equals(ypd.getJudgeresult())) {
//					cd.setActivityId("11AZ");
//					cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
//				}
//				cd.setAppId("优特" + currentMName + "综判");
//				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
//				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
//				
//				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
//				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
//				// end 20240425刘侣
//			}
			
			// 如果综判不合格，脱单：并且不是非计划合同
			if (!"40740801".equals(judgeResult) && !ypd.getOrderno().startsWith("67") && !ypd.getOrderno().startsWith("X67")) {
				// 执行脱单：
				// doMaterialReplace
				CommonPage<PlnMaterielDetail> oci = new CommonPage<>();
				List<PlnMaterielDetail> lpm = new ArrayList<>();
				PlnMaterielDetail pmd = new PlnMaterielDetail();
//				pmd.setObject_no_vt(ypd.getObject_no_vt());
				pmd.setObject_no(ypd.getCoilno());
//				pmd.setObject_type(ypd.getCoiltype());
				lpm.add(pmd);
				oci.setObjectList(lpm);
				oci.setMemo1("新质量系统综判不合格自动脱单，卷号：" + ypd.getCoilno());
				
				tuodan(oci);
				
			}
			
			//日志
//			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收综判信息同步", zp.getJudge_name(), opr_time, null, null, null, null, ypd.getCoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
//			System.out.println(e.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	
	/**
	 * 脱单接口(五合一) 传入参数(虚拟物料号、实物卷号、备注、操作人) 没有经过生产的直接删掉,子卷也删掉
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel tuodan(CommonPage<PlnMaterielDetail> oci) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<PlnMaterielDetail> lpm = oci.getObjectList();
		
		// 工序点信息
		List<ComBaseInfo> infoI = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null,
				"sort_code = '2002' AND validflag = '1'", null, 0, 0);
		ProcessPoint processpoint = new ProcessPoint(infoI);
		// 物料充当脱单履历
		List<PlnMatReplaceLog> lmmrl = this.getMapper(PlnMatReplaceLogMapper.class).findWithCondition(null, "",
				" serial_no desc ", 0, 1);
		long iNo = 1;
		if (lmmrl != null && lmmrl.size() > 0) {
			iNo = lmmrl.get(0).getSerial_no() + 1;
		}

		int num = 0 ;
		for (PlnMaterielDetail pm : lpm) {
			YdmProductDetail ypd  = this.getMapper(YdmProductDetailMapper.class).findById(pm.getObject_no());
			// 不存在物料信息
			if (ypd == null) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + pm.getObject_no() + "]库存信息不存在！");
				
				throw new Exception("物料[" + pm.getObject_no() + "]库存信息不存在！");
			}
			
			ycjsPYdd(ypd.getCoilno(), false);
			
			// 卷号是唯一的值
			// 实际物料 不是在库状态
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + ypd.getCoilno() + "]不是[在库]状态，不能脱单！");
//				return rm;
				throw new Exception("物料[" + ypd.getCoilno() + "]不是[在库]状态，不能脱单！");
			}
			//20191114脱单时判断是否有综合判定，如果没有综合判定，不允许脱单
			if (StringUtils.isEmpty(ypd.getJudgeresult())) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + ypd.getCoilno() + "]没有综合判定结果，不能脱单！");
//				return rm;
				throw new Exception("物料[" + ypd.getCoilno() + "]没有综合判定结果，不能脱单！");
			}
			
			// 卷必须没有经过任何计划编制：2023011301 pm.getObject_no()
			List<PlnPicklePlanDetail> pdList = this.getMapper(PlnPicklePlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+pm.getObject_no()+"'", null, 0, 1);
			List<PlnLengthwisePlanDetail> pleList = this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+pm.getObject_no()+"'", null, 0, 1);
			List<PlnAnnealPlanDetail> plaList = this.getMapper(PlnAnnealPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+pm.getObject_no()+"'", null, 0, 1);
			List<PlnSkinrollingPlanDetail> plsList = this.getMapper(PlnSkinrollingPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+pm.getObject_no()+"'", null, 0, 1);
			List<PlnRollingPlanDetail> plrList = this.getMapper(PlnRollingPlanDetailMapper.class).findWithCondition(null, " OBJECT_NO = '"+pm.getObject_no()+"'", null, 0, 1);
			
			if (pdList.size() > 0 || pleList.size() > 0 || plaList.size() > 0 || plsList.size() > 0 || plrList.size() > 0) {
				throw new Exception("卷号" + pm.getObject_no() + "已经计划编制，不允许脱单！");
			}
			// end
			
			// 物料充当脱单履历表
			PlnMatReplaceLog mmrl = new PlnMatReplaceLog();
			mmrl.setSerial_no(iNo++);
			mmrl.setOpt_type("0");
			mmrl.setStatus(ypd.getState());
			mmrl.setCreate_man_name(userName);
			mmrl.setCreate_time(new Date());
			mmrl.setObject_no(pm.getObject_no());
			mmrl.setRemark(pm.getRemark());
			mmrl.setMemo(oci.getMemo1());//脱单备注
			if (pm.getObject_no_vt() == null || "".equals(pm.getObject_no_vt().trim())) {
				// 虚拟物料号不存在，则调用逻辑1
				// 对物料对应的生产订单，查询生产订单表[PLN_PRODORDER],若不存在信息，则报错“生产订单[xxx]信息不存在”。
				PlnProdorder pp = new PlnProdorder();
				pp.setOrder_no(ypd.getOrderno());
				List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 0);
				if (lpp == null || lpp.size() == 0) {
					// 生产订单[xxx]信息不存在
					rm.setState("500");
					rm.setMsgInfo("生产订单[" + pp.getOrder_no() + "]信息不存在");
//					return rm;
					throw new Exception("生产订单[" + pp.getOrder_no() + "]信息不存在");
				}
				
				// 验证生产订单状态是否为订单保留：20230908刘侣
				if ("0PAA60".equals(lpp.get(0).getStatus())) {
					rm.setState("500");
					rm.setMsgInfo("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许脱单");
//					return rm;
					throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许脱单");
				}
				if ("0PAA70".equals(lpp.get(0).getStatus())) {
					rm.setState("500");
					rm.setMsgInfo("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许脱单");
//					return rm;
					throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许脱单");
				}
				
				// 验证生产订单是否锁定
				boolean flag = this.getBean(MesApiDesignInfoImpl.class).pOrdIsLocked(ypd.getProdorderno());
				if (flag) {
					throw new Exception("生产订单已经锁定[订单变更中],不允许脱单!");
				}

				// 最后一道工序为分条工序
				// if(processpoint.slitting_code.equals(this.getBean(QmsApiServiceImpl.class).GetWrkPlanCode(pp.getOrder_no()))){
				// 获得生产订单进程表[PLN_PRODORDER_STATISTIC]
				PlnProdorderStatistic pps = new PlnProdorderStatistic();
				pps.setProd_order_no(lpp.get(0).getProd_order_no());
				pps.setReplaced(ypd.getFactweight() == null ? null : (-ypd.getFactweight()));
				pps.setReplaced_cnt(-1);
				pps.setUnscheduled(ypd.getFactweight());
				// pps.setUnscheduled_cnt(1);
				// pps.setReplaced_times(-1);
				pps.setDivorced_times(1);

				// 欠分条设计_成品量[LW_UNDSN]+=实物重量；欠分条设计_成品数[LW_UNDSN_CNT]+=1
				// pps.setLw_undsn(lypd.get(0).getFactweight());
				// pps.setLw_undsn_cnt(1);

				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

				// 修改订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos = new PlnOrderStatistic();
				pos.setOrder_no(lpp.get(0).getOrder_no());

				pos.setReplaced(ypd.getFactweight() == null ? null : (-ypd.getFactweight()));
				pos.setReplaced_cnt(-1);
				pos.setUnscheduled(ypd.getFactweight());
				// pos.setUnscheduled_cnt(1);
				// pos.setReplaced_times(-1);
				pos.setDivorced_times(1);
				// 欠分条设计_成品量[LW_UNDSN]+=实物重量；欠分条设计_成品数[LW_UNDSN_CNT]+=1
				// pos.setLw_undsn(lypd.get(0).getFactweight());
				// pos.setLw_undsn_cnt(1);

				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);

				// }

				// 将 虚拟物料表 的 OBJECT_NO 物料(卷/带/板)号 设置为NULL
				List<PlnMaterielDetail> pmds = this.getMapper(PlnMaterielDetailMapper.class)
						.findWithCondition(null, " object_no = '"+pm.getObject_no()+"' and nvl(invalid_flg,0) = 0 ", null, 0, 1);
				if (Utils.isNotEmpty(pmds)) {
					pmds.get(0).setObject_no(null);
					pmds.get(0).setDivorced_times(
							(pmds.get(0).getDivorced_times() == null ? 0 : pmds.get(0).getDivorced_times()) + 1);
					this.getMapper(PlnMaterielDetailMapper.class).doMaterialReplaceUpdate(pmds.get(0));
					
				}

				// 调用物流接口，将 实物物料 对应的虚拟物料号 置位NULL
				this.getMapper(YdmProductDetailMapper.class).doMaterialReplaceUpdate(ypd);

				mmrl.setOrder_no(lpp.get(0).getOrder_no());
				mmrl.setProd_order_no(ypd.getProdorderno());

			} else {
				// 虚拟物料号存在，则调用逻辑2
				// 对物料对应的虚拟物料号，查询虚拟物料表[PLN_MATERIEL_DETAIL]根据虚拟物料号查询物料信息
				PlnMaterielDetail pmd = new PlnMaterielDetail();
				pmd.setObject_no_vt(pm.getObject_no_vt());
				List<PlnMaterielDetail> lpmd = this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 0);

				// 查询生产订单信息
				List<PlnProdorder> pln = this.getMapper(PlnProdorderMapper.class).findWithCondition(null,
						" prod_order_no = '" + lpmd.get(0).getProd_order_no() + "'", null, 0, 1);
				if (Utils.isEmpty(pln)) {
					rm.setState("500");
					rm.setMsgInfo("生产订单[" + pm.getProd_order_no() + "]信息不存在!");
//					return rm;

					throw new Exception("生产订单[" + pm.getProd_order_no() + "]信息不存在!");
				}

				// 验证生产订单是否锁定
				boolean flag = this.getBean(MesApiDesignInfoImpl.class).pOrdIsLocked(ypd.getProdorderno());
				if (flag) {
					throw new Exception("生产订单已经锁定[订单变更中],不允许脱单!");
				}

				// 厂内合同并且已生生产完成--脱单,修改库存信息
				boolean flag_Ct = this.getBean(MesApiDesignInfoImpl.class).getContractType(lpmd.get(0).getProd_order_no());
				boolean flag_Mf = this.getBean(MesApiDesignInfoImpl.class).matIsFinish(pm.getObject_no());
				if (flag_Mf && flag_Ct) {
					this.getMapper(YdmProductDetailMapper.class).doMaterialReplaceUpdate(ypd);
					// 物料充当脱单履历
					this.getBean(MesApiDesignInfoImpl.class).createMatLog(lpmd.get(0), "厂内合同脱单",userName, "" , "-1", pm.getObject_no());
					if(++num == lpm.size()) {
						rm.setData("200");
						rm.setMsgInfo("脱单成功!");
						return rm ;
					}
					continue ;
				}
				
				// 如果子卷已经挂单不允许脱单
				int child = this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null,
						"mat_object_no_vt = '" + pm.getObject_no_vt()
								+ "' and object_no is not null and nvl(invalid_flg,0) = 0");
				if (child > 0) {
					rm.setState("500");
					rm.setMsgInfo("虚拟物料[" + pm.getObject_no_vt() + "]对应的成品已经挂单,不允许脱单!");
//					return rm;

					throw new Exception("虚拟物料[" + pm.getObject_no_vt() + "]对应的成品已经挂单,不允许脱单!");
				}
				if (lpmd == null || lpmd.size() == 0) {
					rm.setState("500");
					rm.setMsgInfo("虚拟物料[" + pm.getObject_no_vt() + "]信息不存在");
//					return rm;

					throw new Exception("虚拟物料[" + pm.getObject_no_vt() + "]信息不存在");
				}

				boolean V_CanDelete_VT = false;

				// 如果是成品挂单
				if(lpmd.get(0).getIs_fin_prods()==1) {
					V_CanDelete_VT = true ;
					// 判断是否分条或者开平工序成品虚拟物料(是否是最终成品)----2018-07-08----- 2018-09-20 罩退 ----2018-10-17平整	
				} else if ((processpoint.slitting_code.equals(lpmd.get(0).getPrev_process_code())
						|| processpoint.cross_cutting_code.equals(lpmd.get(0).getPrev_process_code())
						|| processpoint.anneal_code.equals(lpmd.get(0).getPrev_process_code())
						|| processpoint.smooth_code.equals(lpmd.get(0).getPrev_process_code())
						|| processpoint.rolling_code.equals(lpmd.get(0).getPrev_process_code())
						|| processpoint.pickle_code.equals(lpmd.get(0).getPrev_process_code()))
						&& !"1".equals(lpmd.get(0).getIs_next_finished())) {
//					if (lpmd.get(0).getIs_next_finished() != null && !"1".equals(lpmd.get(0).getIs_next_finished())) { 2018-11-14 修改多工序一起生产,第二个工序的虚拟物料信息上下工序都存在
					// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
					PlnProdorderStatistic pps = new PlnProdorderStatistic();
					pps.setProd_order_no(lpmd.get(0).getProd_order_no());
					if ("1".equals(lpmd.get(0).getIs_replaced())) {
						pps.setReplaced(ypd.getFactweight() == null ? null : (-ypd.getFactweight()));
						pps.setReplaced_cnt(-1);
					}
					pps.setUnscheduled(ypd.getFactweight());
					pps.setUnscheduled_cnt(1);
					// pps.setReplaced_times(-1);
					this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

					// 修改订单进程表[PLN_ORDER_STATISTIC]
					PlnOrderStatistic pos = new PlnOrderStatistic();
					pos.setOrder_no(lpmd.get(0).getOrder_no());
					if ("1".equals(lpmd.get(0).getIs_replaced())) {
						pos.setReplaced(ypd.getFactweight() == null ? null : (-ypd.getFactweight()));
						pos.setReplaced_cnt(-1);
					}
					pos.setUnscheduled(ypd.getFactweight());
					pos.setUnscheduled_cnt(1);
					// pos.setReplaced_times(-1);

					this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
//					}

				} else if (processpoint.slitting_code.equals(lpmd.get(0).getNext_dsn_process_code())) {
					if (lpmd.get(0).getLw_plan_no() != null && !"".equals(lpmd.get(0).getLw_plan_no())) {
						PlnLengthwisePlanDetail plpd = new PlnLengthwisePlanDetail();
						plpd.setLw_plan_no(lpmd.get(0).getLw_plan_no());
						plpd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnLengthwisePlanDetail> lplpd = this.getMapper(PlnLengthwisePlanDetailMapper.class)
								.find(plpd, 0, 1);

						if (lplpd != null && lplpd.size() > 0) {
							if ("5BLW02".compareTo(lplpd.get(0).getStatus()) <= 0) {
								throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BLW01, 则脱掉虚拟物料的纵剪计划
							if ("5BLW01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnLengthwisePlanServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}
					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_lw_divorced(ypd.getFactweight());
						pps.setMat_lw_divorced_cnt(1);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_lw_divorced(ypd.getFactweight());
						pos.setMat_lw_divorced_cnt(1);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);

					} else {
						V_CanDelete_VT = true;
					}

				} else if (processpoint.cross_cutting_code.equals(lpmd.get(0).getNext_dsn_process_code())) {

					if (lpmd.get(0).getCl_plan_no() != null && !"".equals(lpmd.get(0).getCl_plan_no())) {
						PlnCuttolengthPlanDetail plpd = new PlnCuttolengthPlanDetail();
						plpd.setCl_plan_no(lpmd.get(0).getCl_plan_no());
						plpd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnCuttolengthPlanDetail> lplpd = this.getMapper(PlnCuttolengthPlanDetailMapper.class)
								.find(plpd, 0, 1);

						if (lplpd != null && lplpd.size() > 0) {
							if ("5BCL02".compareTo(lplpd.get(0).getStatus()) >= 0) {
								throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BCL01, 则脱掉虚拟物料的横剪计划
							if ("5BCL01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnCuttolengthPlanServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}

					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_cl_divorced(ypd.getFactweight());
						pps.setMat_cl_divorced_cnt(1);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_cl_divorced(ypd.getFactweight());
						pos.setMat_cl_divorced_cnt(1);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdateClPlaned(pos);
					} else {
						V_CanDelete_VT = true;
					}
				} else if (processpoint.anneal_code.equals(lpmd.get(0).getNext_dsn_process_code())) {
					if (lpmd.get(0).getAn_plan_no() != null && !"".equals(lpmd.get(0).getAn_plan_no())) {
						PlnAnnealPlanDetail plpd = new PlnAnnealPlanDetail();
						plpd.setAn_plan_no(lpmd.get(0).getAn_plan_no());
						plpd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnAnnealPlanDetail> lplpd = this.getMapper(PlnAnnealPlanDetailMapper.class).find(plpd, 0,
								1);

						if (lplpd != null && lplpd.size() > 0) {
							if ("5BAN02".compareTo(lplpd.get(0).getStatus()) <= 0) {
								throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BCL01, 则脱掉虚拟物料的罩退计划
							if ("5BAN01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnAnnealDsnMultinfoServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}

					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_an_divorced(ypd.getFactweight());
						pps.setMat_an_divorced_cnt(1l);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_an_divorced(ypd.getFactweight());
						pos.setMat_an_divorced_cnt(1l);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdateSrPlaned(pos);
					} else {
						V_CanDelete_VT = true;
					}
				} else if (processpoint.smooth_code.equals(lpmd.get(0).getNext_dsn_process_code())) {
					if (Utils.isNotEmpty(lpmd.get(0).getSr_plan_no())) {
						PlnSkinrollingPlanDetail plpd = new PlnSkinrollingPlanDetail();
						plpd.setSr_plan_no(lpmd.get(0).getSr_plan_no());
						plpd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnSkinrollingPlanDetail> lplpd = this.getMapper(PlnSkinrollingPlanDetailMapper.class)
								.find(plpd, 0, 1);
						if (lplpd != null && lplpd.size() > 0) {
							if ("5BSR02".compareTo(lplpd.get(0).getStatus()) <= 0) {
								throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BCL01, 则脱掉虚拟物料的平整计划
							if ("5BSR01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnSkinrollingDsnMultinfoServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}

					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_sr_divorced(ypd.getFactweight());
						pps.setMat_sr_divorced_cnt(1l);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_sr_divorced(ypd.getFactweight());
						pos.setMat_sr_divorced_cnt(1l);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdateSrPlaned(pos);
					} else {
						V_CanDelete_VT = true;
					}
				} else if (processpoint.rolling_code.equals(lpmd.get(0).getNext_dsn_process_code())) {
					if (Utils.isNotEmpty(lpmd.get(0).getSr_plan_no())) {
						PlnRollingPlanDetail plpd = new PlnRollingPlanDetail();
						plpd.setRl_plan_no(lpmd.get(0).getRl_plan_no());
						plpd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnRollingPlanDetail> lplpd = this.getMapper(PlnRollingPlanDetailMapper.class)
								.find(plpd, 0, 1);
						if (lplpd != null && lplpd.size() > 0) {
							if ("5BRL02".compareTo(lplpd.get(0).getStatus()) <= 0) {
								throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BCL01, 则脱掉虚拟物料的平整计划
							if ("5BRL01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnRollingDsnMultinfoServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}

					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_rl_divorced(ypd.getFactweight());
						pps.setMat_rl_divorced_cnt(1l);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_rl_divorced(ypd.getFactweight());
						pos.setMat_rl_divorced_cnt(1l);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdateRlPlaned(pos);
					} else {
						V_CanDelete_VT = true;
					}
				}else if (processpoint.pickle_code.equals(lpmd.get(0).getNext_dsn_process_code())) {
					if (Utils.isNotEmpty(lpmd.get(0).getPc_plan_no())) {
						PlnPicklePlanDetail pppd = new PlnPicklePlanDetail();
						pppd.setPc_plan_no(lpmd.get(0).getPc_plan_no());
						pppd.setObject_no_vt(lpmd.get(0).getObject_no_vt());
						List<PlnPicklePlanDetail> lplpd = this.getMapper(PlnPicklePlanDetailMapper.class)
								.find(pppd, 0, 1);
						if (lplpd != null && lplpd.size() > 0) {
							if ("5BPC02".compareTo(lplpd.get(0).getStatus()) <= 0) {
								//throw new Exception("物料[" + pm.getObject_no() + "]已经开始生产，不允许脱单！");
							}
							// 如果找到 且 记录的 STATUS =5BCL01, 则脱掉虚拟物料的平整计划
							if ("5BPC01".compareTo(lplpd.get(0).getStatus()) == 0) {
								this.getBean(PlnPickleDsnMultinfoServiceImpl.class).doCheckCancelPlanChild(lplpd);
							}
						}
					}

					// (原料)操作次数[OPT_TIMES]>0 ，则 需重新加工(原料)[NEED_EXTOPT ]标记为 1
					if (lpmd.get(0).getOpt_times() != null && lpmd.get(0).getOpt_times() > 0) {
						lpmd.get(0).setNeed_extopt("1");

						// 修改生产订单进程表[PLN_PRODORDER_STATISTIC]
						PlnProdorderStatistic pps = new PlnProdorderStatistic();
						pps.setProd_order_no(lpmd.get(0).getProd_order_no());
						pps.setMat_pc_divorced(ypd.getFactweight());
						pps.setMat_pc_divorced_cnt(1l);
						this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

						// 修改订单进程表[PLN_ORDER_STATISTIC]
						PlnOrderStatistic pos = new PlnOrderStatistic();
						pos.setOrder_no(lpmd.get(0).getOrder_no());
						pos.setMat_pc_divorced(ypd.getFactweight());
						pos.setMat_pc_divorced_cnt(1l);
						this.getMapper(PlnOrderStatisticMapper.class).doUpdatePcPlaned(pos);
					} else {
						V_CanDelete_VT = true;
					}
				}else {
					rm.setState("500");
					rm.setMsgInfo("虚拟物料不是分条/开平/罩退/平整/轧制/酸洗工序的原料或成品物料，无法脱单！\n (请刷新检查分条/开平坯料设计是否有变化)");
					return rm;
				}

				// 解除 实际和虚拟 物料的绑定
				if (V_CanDelete_VT) {
					lpmd.get(0).setDivorced_times(null);
//					String temp = "";
					String[] path = null;
					ArrayList<String> validpath = new ArrayList<>();
//					temp = lpmd.get(0).getCreate_process_code() + StringUtils
//							.substringAfter(pln.get(0).getWhole_process_codes(), lpmd.get(0).getCreate_process_code());
//					if (lpmd.get(0).getProc_repeat_index() == 2) {
//						temp = StringUtils
//								.substringAfter(
//										StringUtils.substringAfter(pln.get(0).getWhole_process_codes(),
//												lpmd.get(0).getCreate_process_code()),
//										lpmd.get(0).getCreate_process_code());
//					}
//					path = temp.split("-");
					path = pln.get(0).getWhole_process_codes().split("-");
					validpath = this.getBean(MesApiDesignInfoImpl.class).getProcessPath(path);
					if(lpmd.get(0).getIs_fin_prods()==1) {
						// 删除虚拟物料
						this.getMapper(PlnMaterielDetailMapper.class).delete(lpmd.get(0).getSerial_no());
					}else {
						// 调用函数 【删除虚拟母卷sheet】:传入参数(虚拟母卷号)以及其后工序
						this.getService(PlnMaterielDetailService.class).doCancelChild(lpmd);
					}
					// 修改生产订单以及订单进程量
					this.getBean(MesApiDesignInfoImpl.class).updateOrderStatic(pln.get(0).getProd_order_no(),
							pln.get(0).getOrder_no(), validpath.toString(), ypd.getFactweight(), false);
				}

				// 修改虚拟物料表
				// 脱单次数[DIVORCED_TIMES]+=1;
				if (!V_CanDelete_VT) {
					lpmd.get(0).setDivorced_times(
							(lpmd.get(0).getDivorced_times() == null ? 0 : lpmd.get(0).getDivorced_times()) + 1);
					lpmd.get(0).setObject_no(null);
					// 将虚拟物料表的OBJECT_NO 物料(卷/带/板)号设置为NULL
					this.getMapper(PlnMaterielDetailMapper.class).doMaterialReplaceUpdate(lpmd.get(0));
				}

				// 调用物流接口，将实物物料对应的虚拟物料号置位NULL
				this.getMapper(YdmProductDetailMapper.class).doMaterialReplaceUpdate(ypd);
				mmrl.setPline_code(lpmd.get(0).getPline_code());
				mmrl.setObject_type(lpmd.get(0).getObject_type());
				mmrl.setObject_no_vt(pm.getObject_no_vt());
				mmrl.setOrder_no(lpmd.get(0).getOrder_no());
				mmrl.setProd_order_no(lpmd.get(0).getProd_order_no());
				mmrl.setLw_design_no(lpmd.get(0).getLw_design_no());
				mmrl.setCl_design_no(lpmd.get(0).getCl_design_no());
				mmrl.setRl_design_no(lpmd.get(0).getRl_design_no());
				mmrl.setAn_design_no(lpmd.get(0).getAn_design_no());
				mmrl.setLw_plan_no(lpmd.get(0).getLw_plan_no());
				mmrl.setCl_plan_no(lpmd.get(0).getCl_plan_no());
				mmrl.setRl_plan_no(lpmd.get(0).getRl_plan_no());
				mmrl.setAn_plan_no(lpmd.get(0).getAn_plan_no());
			}
			this.getMapper(PlnMatReplaceLogMapper.class).insert(mmrl);
			// 清空物料附加信息
			this.getBean(MesApiDesignInfoImpl.class).updateMaterielExinfo(pm.getObject_no());			
			//日志
			MesOprLog mol = new MesOprLog("生产管理", "脱单管理", "自动脱单", userName, opr_time, mmrl.getObject_no(), null, null, null, "");
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		rm.setState("200");
		return rm;
	}
	
	
	
	
	/**
	 * 20230909刘侣，取消接收综合判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel cancelReceiveUltimate(CommonPage<QcmJudgeUltimate> sum) {
		ResultModel rm = new ResultModel("200", "取消综合判定结果接收成功");
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		Date now = new Date();
		QcmJudgeUltimate gc = sum.getObject();
		if (gc == null || "".equals(gc)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			if (gc.getUtm_id() == null || "".equals(gc.getUtm_id())) {
				throw new Exception("缺少综合判定记录号参数");
			}
			
			// 将结果update进库存表：
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(gc.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + gc.getMaterial_no() + " 不是在库状态，不允许取消综合判定");
			}
			
			// 综判异动点后移到入库时才发送，因为要先发送产出异动点：20240509刘侣
//			if ("500203".equals(ypd.getStorageattr()) && "507101".equals(ypd.getObject_attr())) {
//				// 记录成本异动点：20230811刘侣
//				ComBaseCbYdd cd = new ComBaseCbYdd();
//				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
//				cd.setInstDisp("01");
//				cd.setDataTypeIdx("O");
//				// 当前产线：
//				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
//				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setInvQtyUnit("块");
//				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
//				cd.setCreateId(userId);
//				cd.setActivityId("69A");
//				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
//				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setProdName(ypd.getProd_name());
//				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
//				
//				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
//				// 上道产线：
//				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
//				cd.setRefnoA(prevcoil); // 投料卷号
//				cd.setSysId("IA");
//				cd.setOrderItem(ypd.getOrderno());
//				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setBeTransUnit("t");
//				cd.setExecJobFunc("D");
//				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
//				if (cbs != null) {
//					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
//				}
//				
//				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
//				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
////				cd.setProdTypeNo("CTR");
////				cd.setAppId("优特钢产出卷取消发货");
//				cd.setInvId(ypd.getCoilno());
//				cd.setInvQty("1");
//				cd.setSrcFac("1");
//				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
//				cd.setProdClassNo("H");
//				
//				// 增加取消综判异动点：20231130刘侣
//				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
//				cd.setActivityId("11AC");
//				if ("40740804".equals(ypd.getJudgeresult())) {
//					cd.setActivityId("11AZ");
//				}
//				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
//				cd.setAppId("优特" + currentMName + "取消综判");
//				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
//				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
//				
//				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
//				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
//				// end 20240425刘侣
//			}
			
			
////			-- JUDGERESULT:
////			-- 合格：40740801
////			-- 不合格：40740802
////			-- 判次：40740803
////			-- 判废：40740804
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeUltimateMapper.class).delete(gc.getUtm_id());
			ypd.setJudgeresult("");
			ypd.setPhysresult_id("");
			ypd.setIs_can_load("0");
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());

		
			//日志
//			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "取消综判信息同步", gc.getJudge_name(), opr_time, null, null, null, null, ypd.getCoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	// 取消接收综判异动点：只在成品库进原料库时 且该卷是优特钢带属性的卷 才取消接收综判异动点 20240425刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel cancelUltiYdd(String coilno) {
		Date now = new Date();
//				String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		ResultModel rm = new ResultModel("200", "取消接收综判异动点成功");
		
		try {
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(coilno, null);
			if (ypd == null) {
				throw new Exception("卷号信息不存在：" + coilno);
			}
			// 只在成品库进原料库时 且该卷是优特钢带属性的卷 才取消接收综判异动点
			if ("500201".equals(ypd.getStorageattr()) && "507101".equals(ypd.getObject_attr())) {
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				cd.setDataTypeIdx("O");
				// 当前产线：
				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("69A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdName(ypd.getProd_name());
				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
				
				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
				// 上道产线：
				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
				cd.setRefnoA(prevcoil); // 投料卷号
				cd.setSysId("IA");
				cd.setOrderItem(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransUnit("t");
				cd.setExecJobFunc("D");
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
				if (cbs != null) {
					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
				}
				
				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
//				cd.setProdTypeNo("CTR");
//				cd.setAppId("优特钢产出卷取消发货");
				cd.setInvId(ypd.getCoilno());
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");
				
				// 增加取消综判异动点：20231130刘侣
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setActivityId("11AC");
				if ("507101".equals(ypd.getObject_attr()) && "40740802".equals(ypd.getJudgeresult())) {
					cd.setActivityId("11AZ");
				}
				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
				cd.setAppId("优特" + currentMName + "取消综判");
				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
				
				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				// end 20240425刘侣
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 入库的时候自动发送综判异动点：20240509刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel receiveUltiYdd(String coilno) {
		Date now = new Date();
//					String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		ResultModel rm = new ResultModel("200", "发送综判异动点成功");
		
		try {
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(coilno, null);
			if (ypd == null) {
				throw new Exception("卷号信息不存在：" + coilno);
			}
			
			if ("500203".equals(ypd.getStorageattr()) && "507101".equals(ypd.getObject_attr())) {
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				cd.setDataTypeIdx("O");
				// 当前产线：
				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("69A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdName(ypd.getProd_name());
				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
				
				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
				// 上道产线：
				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
				cd.setRefnoA(prevcoil); // 投料卷号
				cd.setSysId("IA");
				cd.setOrderItem(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransUnit("t");
				cd.setExecJobFunc("N");
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
				if (cbs != null) {
					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
				}
				
				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
				cd.setProdTypeNo("CTR");
				cd.setAppId("优特钢产出卷发货");
				cd.setInvId(ypd.getCoilno());
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");
				
				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
				
				// setSrcFac根据卷的物料属性去判断：
				cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
				
				// 去掉只有原料卷才需要增加综判异动点,zhouxubin：20231110刘侣
				// 优特钢带属性卷最后一道工序不合格发货时：卷综判判废给11az，其他结果给 11ac和69a:zhouxubin：20231110刘侣
				// 卷子质量系统判废就 给 11AZ xuli需求 20231227 刘侣
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setActivityId("11AC");
				if (ypd.getJudgeresult() != null && "40740804".equals(ypd.getJudgeresult())) {
					cd.setActivityId("11AZ");
					cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
				}
				cd.setAppId("优特" + currentMName + "综判");
				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
				
				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 撤销入库的时候自动发送取消综判异动点：20240509刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel qXUltiYdd(String coilno) {
		Date now = new Date();
//						String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		ResultModel rm = new ResultModel("200", "发送取消综判异动点成功");
		
		try {
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(coilno, null);
			if (ypd == null) {
				throw new Exception("卷号信息不存在：" + coilno);
			}
			
			if ("500203".equals(ypd.getStorageattr()) && "507101".equals(ypd.getObject_attr())) {
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				cd.setDataTypeIdx("O");
				// 当前产线：
				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("69A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdName(ypd.getProd_name());
				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
				
				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
				// 上道产线：
				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
				cd.setRefnoA(prevcoil); // 投料卷号
				cd.setSysId("IA");
				cd.setOrderItem(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransUnit("t");
				cd.setExecJobFunc("D");
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
				if (cbs != null) {
					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
				}
				
				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
//				cd.setProdTypeNo("CTR");
//				cd.setAppId("优特钢产出卷取消发货");
				cd.setInvId(ypd.getCoilno());
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");
				
				// 增加取消综判异动点：20231130刘侣
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setActivityId("11AC");
				if (ypd.getJudgeresult() != null && "40740804".equals(ypd.getJudgeresult())) {
					cd.setActivityId("11AZ");
				}
				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
				cd.setAppId("优特" + currentMName + "取消综判");
				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
				
				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				// end 20240425刘侣
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
		
	// 接收综判异动点：手动发送 20240526 刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel recUltiYddhand() {
		Date now = new Date();
//					String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		ResultModel rm = new ResultModel("200", "手动发送综判异动点成功");
		List<YdmProductDetail> ypdList = this.getMapper(YdmProductDetailMapper.class).queryUnSendUltYdd();
		try {
			for(YdmProductDetail ypd : ypdList) {
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				cd.setDataTypeIdx("O");
				// 当前产线：
				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("69A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdName(ypd.getProd_name());
				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
				
				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
				// 上道产线：
				String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
				cd.setRefnoA(prevcoil); // 投料卷号
				cd.setSysId("IA");
				cd.setOrderItem(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransUnit("t");
				cd.setExecJobFunc("N");
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
				if (cbs != null) {
					cd.setAlloyNo(cbs.getSteel_name()); // 牌号
				}
				
				cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
				cd.setProdTypeNo("CTR");
				cd.setAppId("优特钢产出卷发货");
				cd.setInvId(ypd.getCoilno());
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");
				
				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
				
				// setSrcFac根据卷的物料属性去判断：
				cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
				
				// 去掉只有原料卷才需要增加综判异动点,zhouxubin：20231110刘侣
				// 优特钢带属性卷最后一道工序不合格发货时：卷综判判废给11az，其他结果给 11ac和69a:zhouxubin：20231110刘侣
				// 卷子质量系统判废就 给 11AZ xuli需求 20231227 刘侣
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setActivityId("11AC");
				if ("40740804".equals(ypd.getJudgeresult())) {
					cd.setActivityId("11AZ");
					cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
				}
				cd.setAppId("优特" + currentMName + "综判");
				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
				
				// 综判异动点发送：在最后一倒工序完成后发送，不再是发货时发送 20240425刘侣
				doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				// end 20240425刘侣
//				System.out.println("发送成功");
			}
			
//			System.out.println("总共成功：" + ypdList.size() + " 条");
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	public void examineZp(QcmJudgeUltimate gc) throws Exception {
		if (gc.getUtm_id() == null || "".equals(gc.getUtm_id())) {
			throw new Exception("缺少综判记录号参数");
		}
//		if (gc.getInspection_lot() == null || "".equals(gc.getInspection_lot())) {
//			throw new Exception("缺少检验号参数");
//		}
		if (gc.getMaterial_no() == null || "".equals(gc.getMaterial_no())) {
			throw new Exception("缺少卷号参数");
		}
		if (gc.getUtm_result_desc() == null || "".equals(gc.getUtm_result_desc())) {
			throw new Exception("缺少综判结果参数");
		}
		
		gc.setUtm_result_code("合格".equals(gc.getUtm_result_desc()) ? "40740801" : "不合格".equals(gc.getUtm_result_desc()) ? "40740802" : "次品".equals(gc.getUtm_result_desc()) ? "40740803" : "废品".equals(gc.getUtm_result_desc()) ? "40740804" : "0");
	}
	
	/**
	 * 20230909刘侣，接收外观判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel receiveResSurface(CommonPage<QcmJudgeSurface> sum) {
		ResultModel rm = new ResultModel("200", "表面检验结果接收成功");
		QcmJudgeSurface bm = sum.getObject();
		if (bm == null || "".equals(bm)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			examineBm(bm);
			
			// 将结果update进库存表：
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(bm.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + bm.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + bm.getMaterial_no() + " 不是在库状态，不允许表面判定");
			}
			
			// 将之前可能存在的该卷的综判：20231120刘侣
			List<QcmJudgeSurface> qjsuList = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, " MATERIAL_NO='"+bm.getMaterial_no()+"'", "SURFACE_ID desc", 0, 0);
			if (qjsuList != null && qjsuList.size() > 0) {
				for(QcmJudgeSurface s : qjsuList) {
					this.getMapper(QcmJudgeSurfaceMapper.class).delete(s.getSurface_id()); // 只需要清空表面信息，缺陷信息不需要
				}
			}
			
////			-- UP_SURFACE_RESULT：
////			-- 合格：40740601
////			-- 不合格：40740602
////			-- 判次：40740606
////			-- 判废：40740604
			
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeSurfaceMapper.class).insert(bm);
			
			String surfaceResult = "合格".equals(bm.getSf_result_desc()) ? "40740601" : "不合格".equals(bm.getSf_result_desc()) ? "40740602" : "判次".equals(bm.getSf_result_desc()) ? "40740606" : "判废".equals(bm.getSf_result_desc()) ? "40740604" : "0";
			ypd.setUp_surface_result(surfaceResult);
			ypd.setSurfaceresult(surfaceResult);
			ypd.setUp_surface_result_id(bm.getSurface_id());
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			
			List<QcmJudgeSurfaceFlaw> flaws = bm.getObjectList();
			for (QcmJudgeSurfaceFlaw flaw : flaws) {
				examineFlaw(flaw);
				// 先注释，防止测试时调用接口insert了：20230912刘侣
				this.getMapper(QcmJudgeSurfaceFlawMapper.class).insert(flaw);
			}

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "接收外观判定信息同步", bm.getJudge_name(), opr_time, null, null, null, null, ypd.getCoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	/**
	 * 20230909刘侣，取消接收外观判定结果：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel cancelReceiveResSurface(CommonPage<QcmJudgeSurface> sum) {
		ResultModel rm = new ResultModel("200", "取消表面检验结果接收成功");
		QcmJudgeSurface bm = sum.getObject();
		if (bm == null || "".equals(bm)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {

			if (bm.getSurface_id() == null || "".equals(bm.getSurface_id())) {
				throw new Exception("缺少表面检验记录号参数");
			}
			
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(bm.getMaterial_no(), null);
			if (ypd == null || "".equals(ypd)) {
				throw new Exception("卷：" + bm.getMaterial_no() + " 不存在，请联系管理员");
			}
			if (!"0".equals(ypd.getState()) && !"-1".equals(ypd.getState())) {
				throw new Exception("卷：" + bm.getMaterial_no() + " 不是在库状态，不允许取消表面判定");
			}
////			-- UP_SURFACE_RESULT：
////			-- 合格：40740601
////			-- 不合格：40740602
////			-- 判次：40740606
////			-- 判废：40740604
			ypd.setUp_surface_result("");
			ypd.setSurfaceresult("");
			ypd.setUp_surface_result_id("");
			this.getMapper(YdmProductDetailMapper.class).update(ypd);

			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeSurfaceMapper.class).delete(bm.getSurface_id());
			// 将结果update进库存表：
			
			
			
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(QcmJudgeSurfaceFlawMapper.class).deleteBySurId(bm.getSurface_id());
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	public void examineBm(QcmJudgeSurface gc) throws Exception {
		if (gc.getSurface_id() == null || "".equals(gc.getSurface_id())) {
			throw new Exception("缺少表面检验记录号参数");
		}
//		if (gc.getInspection_lot() == null || "".equals(gc.getInspection_lot())) {
//			throw new Exception("缺少检验号参数");
//		}
		if (gc.getMaterial_no() == null || "".equals(gc.getMaterial_no())) {
			throw new Exception("缺少卷号参数");
		}
		if (gc.getSf_result_desc() == null || "".equals(gc.getSf_result_desc())) {
			throw new Exception("缺少表面检验结果结果参数");
		}
		
		gc.setSf_result_code("合格".equals(gc.getSf_result_desc()) ? "40740601" : "不合格".equals(gc.getSf_result_desc()) ? "40740602" : "判次".equals(gc.getSf_result_desc()) ? "40740606" : "判废".equals(gc.getSf_result_desc()) ? "40740604" : "0");
		gc.setSf_type("U");
	}
	
	public void examineFlaw(QcmJudgeSurfaceFlaw gc) throws Exception {
		if (gc.getSurface_id() == null || "".equals(gc.getSurface_id())) {
			throw new Exception("缺少表面检验记录号参数");
		}
		if (gc.getPrimary_flag() == null || "".equals(gc.getPrimary_flag())) {
			throw new Exception("缺少主缺陷标志参数");
		}
		if (gc.getFlaw_seq() == null || "".equals(gc.getFlaw_seq())) {
			throw new Exception("缺少缺陷序号参数");
		}
		if (gc.getFlaw_desc() == null || "".equals(gc.getFlaw_desc())) {
			throw new Exception("缺少缺陷描述参数");
		}
		if (gc.getFlaw_type_desc() == null || "".equals(gc.getFlaw_desc())) {
			throw new Exception("缺少缺陷类型参数");
		}
		if (gc.getFlaw_area() == null || "".equals(gc.getFlaw_area())) {
			throw new Exception("缺少缺陷所在区域参数");
		}
		
		// 表面缺陷默认第一个做主缺陷：20240102 刘侣
		List<QcmJudgeSurfaceFlaw> qjsfuList = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+gc.getSurface_id()+"' and PRIMARY_FLAG = '1'", null, 0, 0);
		if (qjsfuList != null && qjsfuList.size() > 0) {
			gc.setPrimary_flag("0");
		}
	}
	
	/**
	 * 20230909刘侣，作废订单：
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel orderCancel(CommonPage<SlmOrderInfo> sum) {
		ResultModel rm = new ResultModel("200", "作废订单成功");
		SlmOrderInfo soi = sum.getObject();
		if (soi == null || "".equals(soi)) {
			rm.setState("500");
			rm.setMsgInfo("请传入object参数内容");
		}
		
		try {
			String orderno = soi.getOrder_no().substring(0, soi.getOrder_no().length() - 3) + soi.getOrder_no().substring(soi.getOrder_no().length() - 3) + soi.getOrder_no().substring(soi.getOrder_no().length() - 3);
			
			// 订单是否存在：
			List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, " CONTRACT_NO || CONTRACT_LINE_SEQ || ORDER_SEQ = '" + orderno + "'", null, 0, 0);
			if (soiList == null || soiList.size() <= 0) {
				throw new Exception("订单：" + soi.getOrder_no() + " 不存在");
			}
			
			List<PlnProdorder> ppL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ORDER_NO = '"+ orderno +"'", null, 0, 0);
			if (ppL == null || ppL.size() <= 0) {
				throw new Exception("生产订单：" + soi.getOrder_no() + " 不存在");
			}
			if ("0PAA60".equals(ppL.get(0).getStatus())) {
				throw new Exception("生产订单：" + soi.getOrder_no() + " 处于生产保留状态，要作废请先取消订单生产保留");
			}
			
			// 订单是否有卷：
			List<YdmProductDetail> ypdL = this.getMapper(YdmProductDetailMapper.class).findWithCondition(null, " ORDERNO = '" + orderno + "' and STATE in ('-1', '0', '2', '7')", null, 0, 0);
			if (ypdL.size() > 0) {
				throw new Exception("订单：" + soi.getOrder_no() + " 还存在未脱单的卷，请先脱单");
			}
			
			SlmOrderInfo soiQ = soiList.get(0);
			soiQ.setValid_flag("0");
			
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(SlmOrderInfoMapper.class).update(soiQ);
			
			PlnProdorder ppoQ = ppL.get(0);
			ppoQ.setStatus("0PAA70");// 状态：订单作废
			
			// 先注释，防止测试时调用接口insert了：20230912刘侣
			this.getMapper(PlnProdorderMapper.class).update(ppoQ);

			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "作废订单信息同步", "一体化", opr_time, null, null, null, null, ppoQ.getOrder_no());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
		
	}
	
	// 补发装车实绩：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel bfLoad(SlmLadingBillHeat sh) {
		ResultModel rm = new ResultModel("200", "补发装车实绩成功");
		String billno = sh.getBill_no();
		try {
			// 在这里获取装车实绩从表，并发送装车实绩：
			// [{},{}]
			JSONArray ja = new JSONArray();
			List<SpmTransportDetail> ls=this.getMapper(SpmTransportDetailMapper.class).doSelectSpm(billno);
			for(SpmTransportDetail spd : ls) {
				JSONObject obj = new JSONObject();
				obj.put("transno", spd.getBillNo());
				
				SpmDistrbuteMain sdm=new SpmDistrbuteMain();
				sdm.setDeliveryno(billno);
				List<SpmDistrbuteMain> main=this.getMapper(SpmDistrbuteMainMapper.class).find(sdm, 0, 0);
				obj.put("carno", main.get(0).getCarno());
				obj.put("loaddate", new SimpleDateFormat("yyyy-MM-dd").format(spd.getLoaddate()));
				obj.put("loadtime", new SimpleDateFormat("HH:mm:ss").format(spd.getLoaddate()));
				obj.put("totalwgt", spd.getFactweight() != null ? spd.getFactweight() / 1000 : spd.getFactweight());
				obj.put("pactno", spd.getOrderno().substring(0, spd.getOrderno().length() - 6));
				obj.put("orderno", spd.getOrderno().substring(0, spd.getOrderno().length() - 3));
				obj.put("labelno", spd.getObjectno());
				obj.put("quantity", spd.getQuantity() + "");
				obj.put("wgt", spd.getTheoryweight() != null ? (spd.getTheoryweight() / 1000) : 0);
				obj.put("thick", spd.getHeight() + "");
				obj.put("width", spd.getWidth() + "");
				obj.put("length", spd.getLength() + "");
				obj.put("transplanno", spd.getBillNo());

				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(spd.getSteelcode());
				if (cbs!=null) {
					obj.put("tradeno", cbs.getSteel_name());
				}
				
				YdmProductDetail ypdQQ = this.getMapper(YdmProductDetailMapper.class).doFind(spd.getObjectno(), null);
				if (ypdQQ != null) {
					obj.put("stoveno", ypdQQ.getHeatno());
				}
				
				obj.put("rollno", spd.getBatchno());
				
				
				String butname = this.getMapper(YdmProductDetailMapper.class).doQueryCButtressOne(spd.getObjectno());
				if (butname != null) {
					obj.put("buttress", butname);
				}
//				String prevcoil = spd.getObjectno();
				String prodline = ypdQQ.getCoilno().contains("S") ? "YTSX" : ypdQQ.getCoilno().contains("L") ? "YTZZ" : ypdQQ.getCoilno().contains("P") ? "YTPZ" : ypdQQ.getCoilno().contains("T") ? "YTTH" : ypdQQ.getCoilno().contains("K") ? "YTHJ" : ypdQQ.getCoilno().contains("F") ? "YTZJ" : "YT1";
				obj.put("prodline", prodline);
				
				ja.add(obj);
				
			}
//			System.out.println(ja.toString());
			// 原来的：http://10.70.0.237:9030/ZhbXSDataService/GetSendList
			// 这个暂时不用：http://172.16.0.169/CXZCXSMESIMPL/http/SENDGOODS  用杨佳俊的
			String result = Connecttt.postJsonParams("http://172.16.4.136:14008/il/ilApi/sendGoods", ja.toString());
//			System.out.println(result);
			
			JsonObject resObj = new JsonParser().parse(result).getAsJsonObject();
//			System.out.println(resObj.get("code"));
			String code = resObj.get("code").toString();
			if (!"1000".equals(code)) {
				throw new Exception("提单装车实绩报错：" + resObj.get("message"));
			}
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			return rm;
		}
		

		//日志
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "发送装车实绩信息同步", "一体化", opr_time, null, null, null, null, billno);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		
		return rm;
	}
	
	
	// 补发装车实绩：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel bfLoadDelete() {
		ResultModel rm = new ResultModel("200", "补发装车实绩成功");
		Date date = new Date();
		try {
			// 在这里获取装车实绩从表，并发送装车实绩：
			// [{},{}]
			JSONArray ja = new JSONArray();
			
			JSONObject obj = new JSONObject();
			obj.put("transno", "202311020130");
			
			
			obj.put("carno", "赣K58057");
			obj.put("loaddate", "2023-11-01");
			obj.put("loadtime", "09:10:46");
			obj.put("totalwgt", "19.83");
			obj.put("pactno", "W61202310S642");
			obj.put("orderno", "W61202310S642003");
			obj.put("labelno", "Y2381442S0101");
			obj.put("quantity", "1");
			obj.put("wgt", "19.83");
			obj.put("thick", "2.76");
			obj.put("width", "1256");
			obj.put("length", "773000");
			obj.put("transplanno", "202311020130");
			obj.put("tradeno", "XG65MnJC");
			obj.put("stoveno", "J32-08268A");
			obj.put("rollno", "PC230821014");
			
//				String butname = this.getMapper(YdmProductDetailMapper.class).doQueryCButtressOne(spd.getObjectno());
			
			obj.put("buttress", "L30");
			
			String prodline = "YTSX";
			obj.put("prodline", prodline);
			
			ja.add(obj);
				
			
//			System.out.println(ja.toString());
			// 原来的：http://10.70.0.237:9030/ZhbXSDataService/GetSendList
//			String result = Connecttt.postJsonParams("http://172.16.0.169/CXZCXSMESIMPL/http/SENDGOODS", ja.toString());
//			System.out.println(result);
//			
//			JsonObject resObj = new JsonParser().parse(result).getAsJsonObject();
//			System.out.println(resObj.get("code"));
//			String code = resObj.get("code").toString();
//			if (!"1000".equals(code)) {
//				throw new Exception("提单装车实绩报错：" + resObj.get("message"));
//			}
			
			// 改为存入READY_SEND_ZCSJ ，然后再后续发送过去：20231221刘侣
			this.getMapper(YdmProductDetailMapper.class).readySendZCSJ("202311020130", ja.toString());
			
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			return rm;
		}
		

		//日志
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		MesOprLog mol = new MesOprLog("一体化指令", "一体化指令", "发送装车实绩信息同步", "一体化", opr_time, null, null, null, null, "202310130779");
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		
		return rm;
	}
		
	
	// 手动同步异动点库存：暂时先同步9月26日备份库存
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel syncYdd() throws Exception {
		ResultModel rm = new ResultModel("200", "发送库存异动点成功");
		
		try {
			List<YdmProductDetail> hisL = this.getMapper(YdmProductDetailMapper.class).ypdHisQ();
			if (hisL != null && hisL.size() > 0) {
				for(YdmProductDetail ypd : hisL) {
//					System.out.println(ypd.getCoilno());
					// 记录成本异动点：20230811刘侣
//					YdmProductDetail ypd = hisL.get(0);
					// 记录成本异动点：20230811刘侣
					ComBaseCbYdd cd = new ComBaseCbYdd();
					cd.setCoilStus(ypd.getStorageattr() != null && ("500203".equals(ypd.getStorageattr()) || "500205".equals(ypd.getStorageattr())) && ypd.getJudgeresult() != null && !"40740804".equals(ypd.getJudgeresult()) ? "1" : "0"); // 综判前算半成品，综判入库后算成品
					cd.setInstDisp("01");
					cd.setDataTypeIdx("O");
					// 当前产线：
					String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
					cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setInvQtyUnit("块");
					cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
					cd.setCreateId("优特钢");
					cd.setActivityId("01A");
					cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
					cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setProdName(ypd.getProd_name());
					cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
					
					String prevcoil = ypd.getCoilno().startsWith("Y") ? this.getBean(YdmProductInlistServiceImpl.class).doQueryTl(ypd.getCoilno()) : ypd.getCoilno();
					// 上道产线：
					String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
					cd.setRefnoA("YT1".equals(prevMachine) ? ypd.getMaterailcoilno() : prevcoil); // 投料卷号：如果是第一道工序就拿卷板号，如果不是就拿优特钢上道工序卷号；
					cd.setSysId("IA");
					cd.setOrderItem(ypd.getOrderno());
					cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setBeTransUnit("t");
					cd.setExecJobFunc("N");
					
					cd.setAlloyNo(ypd.getSteelcode()); // 牌号
					
					
					cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
					cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setBeTransWgt(ypd.getFactweight()); // 查询sql已经除了1000了；
					cd.setProdTypeNo("CTR");
					cd.setAppId("优特钢库存卷");
					cd.setInvId("YT1".equals(currentMachine) ? ypd.getMaterailcoilno() : ypd.getCoilno());
					cd.setInvQty("1");

					// setSrcFac根据卷的物料属性去判断：20231031刘侣
					cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
					
					cd.setGrade("1"); // 正品　1　协议　3　次品　5：默认抛正品
					cd.setProdClassNo("H");
					
					// 产出分为：1、，2、酸洗重量调整（如果有重量改了也抛送一条）
					// 存入表：1、酸洗产出（11，生产完成）
//					String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
					cd.setExecJobFunc("N");
					cd.setDataTypeIdx("N");
					cd.setProdTypeNo("YT1".equals(currentMachine) && cd.getInvId().startsWith("L") ? "CCR" : "YT1".equals(currentMachine) ? "HCR" : "CTR");
					cd.setCoilStus("1"); // 综判前算半成品0，综判入库后算成品1
					cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setManageip(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
					cd.setLocNo(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ

//					// 客户属性，不管在哪个库都是srcfac:3：
//					if ("507102".equals(ypd.getObject_attr())) {
//						cd.setSrcFac("3");
//					}
					// 非计划卷统一抛送半成品（"coilStus":"0"），先以卷是否有订单来区分：
//					if (ypd.getOrderno() == null || "".equals(ypd.getOrderno())) {
////						cd.setCoilStus("0");
//						
//					} else {
						// 都是有订单的卷：
						// 最后一道工序并且综判（不是判废）才是成品（"coilStus":"1"）
						if (("500203".equals(ypd.getStorageattr()) || "500205".equals(ypd.getStorageattr())) && ypd.getJudgeresult() != null && !"40740804".equals(ypd.getJudgeresult())) {
							cd.setCoilStus("1");
						} else {
							cd.setCoilStus("0");
						}
//					}
					
					doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				}
			}
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 手动同步库存表库存
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel syncYpd() {
		ResultModel rm = new ResultModel("200", "发送库存同步成功");
		
		try {

			List<YdmProductDetail> hisL = this.getMapper(YdmProductDetailMapper.class).ypdCurQ();
			
			for(YdmProductDetail ypd : hisL) {
//				System.out.println(ypd.getCoilno());
				this.getMapper(YdmProductDetailMapper.class).insertKC(ypd.getCoilno());
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		
		return rm;
	}
	
	// 查询质量设计里冷轧目标厚度：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel queryLZThick(String orderNo, String coilNo) {
		ResultModel rm = new ResultModel("200", "查询冷轧目标厚度成功");
		
		try {
			// 查出这个订单的所有冷轧的目标厚度当作参考：
			String realOrd = orderNo.substring(0, orderNo.length() - 3);
			List<String> thickL = this.getMapper(YdmProductDetailMapper.class).lzThick(realOrd);
			int i = 1;
			String ck = "";
			JSONArray thArr = new JSONArray();
			for(String thick : thickL) {
				if (thick != null) {
					thArr.add(thick);
					ck += ("第 " + i + " 次冷轧目标厚度为：" + thick + " ; ");
					i++;
				}
			}
			String realCoilno = coilNo.substring(0, 8);
			int num = this.getMapper(YdmProductDetailMapper.class).isLz(realCoilno);
			
			JSONArray ja = new JSONArray();
			ja.add(ck);
			ja.add(num > 0 ? true : false);
			ja.add(thArr);
			
			rm.setData(ja);
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		
		return rm;
	}
	
	// 查询质量设计里冷轧目标厚度：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel isChao(String processno, String object_no_vt, String rl_plan_no) {
		ResultModel rm = new ResultModel("200", "没超限");
		
		try {
			
			// 这里的订单厚度得获取左下角出口卷计划里的：
			PlnMaterielDetail mcsm = new PlnMaterielDetail();
			mcsm.setRl_plan_no(rl_plan_no);
			mcsm.setMat_object_no_vt(object_no_vt);
			List<PlnRollingMaterialDetailSum> pmdL = this.getMapper(MesRcmDMapper.class).doQueryWeb(mcsm);
			
			MesRcmDPass mrPass = new MesRcmDPass();
		    mrPass.setProcess_no(processno);
			
			List<MesRcmDPass> passL = this.getMapper(MesRcmDPassMapper.class).findWithCondition(mrPass, null, " CURR_PASS_NO desc", 0, 1);
			if (passL != null && passL.size() > 0) {
				// 最后一道轧制的厚度得存在：
				if (passL.get(0).getPass_exit_thick() != null && !"".equals(passL.get(0).getPass_exit_thick())) {
					// 计划厚度得存在：
					if (pmdL.get(0).getThick() != null && !"".equals(pmdL.get(0).getThick())) {
						// 计算公式：误差不超过5%：
						// 只有当产出厚度和订单厚度不一致时才做校验：
						Double ckThk = Double.valueOf(passL.get(0).getPass_exit_thick());
						Double planThk = Double.valueOf(pmdL.get(0).getThick());
						if (ckThk != 0 && planThk != 0) {
							Double res = Math.round((Math.abs(ckThk - planThk) / (ckThk >= planThk ? ckThk : planThk)) * 100.0) / 100.0;
							if (res > 0.05) {
								throw new Exception("最后一道轧制厚度：" + ckThk + " 与订单厚度：" + planThk + " 相差大于5%，不能交工");
							}
						}
					}
				}
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		
		return rm;
	}
		
	// 查询火运提单：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel queryTrain(CommonPage<SlmLadingBillHeat> cp) {
		ResultModel rm = new ResultModel("200", "火运提单查询成功");
		SlmLadingBillHeat heat = cp.getObject();
		String startTime = cp.getStartTime() + " 00:00:00";
		String endTime = cp.getEndTime() + " 23:59:59";
		try {
			
			rm.setData(this.getMapper(SlmLadingBillHeatMapper.class).getTrainBill(heat.getBill_no(), startTime, endTime));
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		
		return rm;
	}
	
	// 火运提单：修改火车号
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel noChange(CommonPage<SlmLadingBillHeat> cp) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel("200", "火运提单火车号修改成功");
		SlmLadingBillHeat heat = cp.getObject();
		try {

			String bill_no = heat.getBill_no();
			String newCarno = cp.getMemo1();
			
			// 验证传递参数是否正确：
			if (bill_no == null || "".equals(bill_no)) {
				throw new Exception("请传入提单号");
			}
			if (newCarno == null || "".equals(newCarno)) {
				throw new Exception("请传入火车号");
			}
			
			// 验证提单是否存在：
			List<HashMap> billS = this.getMapper(SlmLadingBillHeatMapper.class).getTrainBill(bill_no, null, null);
			if (billS == null || billS.size() <= 0) {
				throw new Exception("火运提单：" + bill_no + " 不存在");
			}
			
			// 提单内是没有车号的，所以修改装车实绩表内的车号：SPM_DELIVERY_DETAIL SPM_DISTRBUTE_MAIN 
			SpmDeliveryDetail sdd = new SpmDeliveryDetail();
			sdd.setDeliveryno(bill_no);
			List<SpmDeliveryDetail> lisSp = this.getMapper(SpmDeliveryDetailMapper.class).find(sdd, 0,0);
			if (lisSp != null && lisSp.size() > 0) {
				for(SpmDeliveryDetail d : lisSp) {
					d.setCarno(newCarno);
					this.getMapper(SpmDeliveryDetailMapper.class).update(d);
				}
			}
			List<SpmDistrbuteMain> mainL = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, "deliveryno='"+bill_no+"'", null, 0, 0);
			if (mainL != null && mainL.size() > 0) {
				for(SpmDistrbuteMain d : mainL) {
					d.setCarno(newCarno);
					this.getMapper(SpmDistrbuteMainMapper.class).update(d);
				}
			}
			
			// 调用一体化接口，修改一体化火车号：
			// 火运提单发送装车实绩：
			ResultModel loadRm = bfLoad(heat);
			if (!"200".equals(loadRm.getState())) {
				throw new Exception(loadRm.getMsgInfo());
			}
			
			
			// 记录原来汽车号日志：
			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("物流管理", "提货单管理", "修改装车车号为火车号", username, opr_time, null, null, bill_no, null, "修改提单：" + bill_no + " 汽车号 " + billS.get(0).get("CARNO") + " 成火车号为：" + newCarno);
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 火运提单：修改火车号
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel noChange2(CommonPage<SlmLadingBillHeat> cp) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel("200", "火运提单火车号修改成功");
		SlmLadingBillHeat heat = cp.getMyObject();
		try {

			String bill_no = heat.getBill_no();
			String newCarno = cp.getMemo1();
			
			// 验证传递参数是否正确：
			if (bill_no == null || "".equals(bill_no)) {
				throw new Exception("请传入提单号");
			}
			if (newCarno == null || "".equals(newCarno)) {
				throw new Exception("请传入火车号");
			}
			
			// 验证提单是否存在：
			List<HashMap> billS = this.getMapper(SlmLadingBillHeatMapper.class).getTrainBill(bill_no, null, null);
			if (billS == null || billS.size() <= 0) {
				throw new Exception("火运提单：" + bill_no + " 不存在");
			}
			
			// 提单内是没有车号的，所以修改装车实绩表内的车号：SPM_DELIVERY_DETAIL SPM_DISTRBUTE_MAIN 
			SpmDeliveryDetail sdd = new SpmDeliveryDetail();
			sdd.setDeliveryno(bill_no);
			List<SpmDeliveryDetail> lisSp = this.getMapper(SpmDeliveryDetailMapper.class).find(sdd, 0,0);
			if (lisSp != null && lisSp.size() > 0) {
				for(SpmDeliveryDetail d : lisSp) {
					d.setCarno(newCarno);
					this.getMapper(SpmDeliveryDetailMapper.class).update(d);
				}
			}
			List<SpmDistrbuteMain> mainL = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, "deliveryno='"+bill_no+"'", null, 0, 0);
			if (mainL != null && mainL.size() > 0) {
				for(SpmDistrbuteMain d : mainL) {
					d.setCarno(newCarno);
					this.getMapper(SpmDistrbuteMainMapper.class).update(d);
				}
			}
			
			// 调用一体化接口，修改一体化火车号：
			// 火运提单发送装车实绩：
			ResultModel loadRm = bfLoad(heat);
			if (!"200".equals(loadRm.getState())) {
				throw new Exception(loadRm.getMsgInfo());
			}
			
			
			// 记录原来汽车号日志：
			//日志
			Date now = new Date();
			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
			MesOprLog mol = new MesOprLog("物流管理", "提货单管理", "修改装车车号为火车号", username, opr_time, null, null, bill_no, null, "修改提单：" + bill_no + " 汽车号 " + billS.get(0).get("CARNO") + " 成火车号为：" + newCarno);
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	
	// 清空综判：20231123刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel reAutoUltiJudge(String coilno) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "清理综判信息成功");
		
		try {
			
			if (coilno == null || "".equals(coilno)) {
				throw new Exception("卷号没传，无法清理综判信息");
			}
			
			// 排除掉头尾卷和原料卷：
			if (coilno.length() <= 8) {
				return rm;
			}
			String lastChar = coilno.substring(coilno.length()-1);
			if ("B".equals(lastChar) || "H".equals(lastChar)) {
				return rm;
			}
			
			YdmProductDetail y = this.getMapper(YdmProductDetailMapper.class).doFind(coilno, null);
			// 来料加工合同  J ， 一次结算后再加工的合同 J  和  非计划合同 67 的卷都不需要重新综判，加上 WJW 或者 JW 开头的 20240319刘侣
			if (y.getOrderno() != null && (y.getOrderno().startsWith("67") || y.getOrderno().startsWith("J") || y.getOrderno().startsWith("X67") || y.getOrderno().startsWith("JW") || y.getOrderno().startsWith("WJW"))) {
				return rm;
			}
			
			// 挂单的时候清空的：需要重新综判；
			// 清理重量系统的判定信息：
			// 如果该卷在质量系统有过判定，则清理：
			int num = this.getMapper(YdmProductDetailMapper.class).isPdCoil(coilno);
			if (num > 0) {
				this.getMapper(YdmProductDetailMapper.class).changeResult(coilno);
				this.getMapper(YdmProductDetailMapper.class).changeLog(coilno);	
			} else {
				// 如果没判定过，本地都不能清空，也不需要再次发送待判：20231124刘侣
				return rm;
			}
			
			
			// 只需要清空综判表和库存表里这卷的信息：
			List<QcmJudgeUltimate> utmList = this.getMapper(QcmJudgeUltimateMapper.class).findWithCondition(null, " material_no='"+coilno+"'", null, 0, 0);
			for (QcmJudgeUltimate u : utmList) {
				// 清理重量系统的判定信息：
				if (num > 0) {
					this.getMapper(YdmProductDetailMapper.class).changeUltimate("优特钢", u.getUtm_id());
					this.getMapper(QcmJudgeUltimateMapper.class).delete(u.getUtm_id());
				}
				
			}
			// 如果没判定过，本地都不能清空：20231124刘侣
			if (num > 0) {
				
				y.setJudgeresult("");
				this.getMapper(YdmProductDetailMapper.class).update(y);
			}
			
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		MesOprLog mol = new MesOprLog("物流管理", "各机组挂单管理", "清空综判", username, opr_time, coilno, null, null, null, "清空综判以便重新接收" + coilno);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
	
	// 清空综判：20231123刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel reAutoUltiJudgeRK(String coilno) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "清理综判信息成功");
		
		try {
			
			if (coilno == null || "".equals(coilno)) {
				throw new Exception("卷号没传，无法清理综判信息");
			}
			
			// 排除掉头尾卷和原料卷：
			if (coilno.length() <= 8) {
				return rm;
			}
			String lastChar = coilno.substring(coilno.length()-1);
			if ("B".equals(lastChar) || "H".equals(lastChar)) {
				return rm;
			}
			
			YdmProductDetail y = this.getMapper(YdmProductDetailMapper.class).doFind(coilno, null);
			// 入库的时候所有订单的卷都需要做检测：所以注释掉
			// 来料加工合同  J ， 一次结算后再加工的合同 J  和  非计划合同 67 的卷都不需要重新综判
//				if (y.getOrderno() != null && (y.getOrderno().startsWith("67") || y.getOrderno().startsWith("J") || y.getOrderno().startsWith("X67"))) {
//					return rm;
//				}
			
			// 挂单的时候清空的：需要重新综判；
			// 清理重量系统的判定信息：
			// 如果该卷在质量系统有过判定，则清理：
			int num = this.getMapper(YdmProductDetailMapper.class).isPdCoil(coilno);
			if (num > 0) {
				this.getMapper(YdmProductDetailMapper.class).changeResult(coilno);
				this.getMapper(YdmProductDetailMapper.class).changeLog(coilno);	
			} else {
				// 如果没判定过，本地都不能清空，也不需要再次发送待判：20231124刘侣
				return rm;
			}
			
			
			// 只需要清空综判表和库存表里这卷的信息：
			List<QcmJudgeUltimate> utmList = this.getMapper(QcmJudgeUltimateMapper.class).findWithCondition(null, " material_no='"+coilno+"'", null, 0, 0);
			for (QcmJudgeUltimate u : utmList) {
				// 清理重量系统的判定信息：
				if (num > 0) {
					this.getMapper(YdmProductDetailMapper.class).changeUltimate(username, u.getUtm_id());
					this.getMapper(QcmJudgeUltimateMapper.class).delete(u.getUtm_id());
				}
				
			}
			// 如果没判定过，本地都不能清空：20231124刘侣
			if (num > 0) {
				
				y.setJudgeresult("");
				this.getMapper(YdmProductDetailMapper.class).update(y);
			}
			
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		MesOprLog mol = new MesOprLog("物流管理", "各机组入库管理", "清空综判", username, opr_time, coilno, null, null, null, "清空综判以便重新接收" + coilno);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
		
	
	// 20231130成本异动点需求：挂单后一次结算的卷第一次挂单时抛送时抛送异动点：appid:客户属性入库
	// 客户属性入库和来料加工 这两个异动点重复所以去掉 客户属性入库 异动点 20231227 刘侣
	// 改造成由成品库回到原料库时抛送异动点：20231228 刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel hYlkPYdd(String coilno) {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		Date now = new Date();
		ResultModel rm = new ResultModel("200", "成功");
		
		try {
			
			// 记录成本异动点：20230811刘侣
		    YdmProductDetail ypdM = this.getMapper(YdmProductDetailMapper.class).findById(coilno);
			    
	    	ComBaseCbYdd cd = new ComBaseCbYdd();
	 		cd.setInstDisp("01");
	 		// 当前产线：
	 		String currentMachine = ypdM.getCoilno().contains("S") ? "YTSX" : ypdM.getCoilno().contains("L") ? "YTZZ" : ypdM.getCoilno().contains("P") ? "YTPZ" : ypdM.getCoilno().contains("T") ? "YTTH" : ypdM.getCoilno().contains("K") ? "YTHJ" : ypdM.getCoilno().contains("F") ? "YTZJ" : "YT1";
	 		cd.setInvQtyUnit("块");
	 		cd.setInvWidth(ypdM.getWidth() != null ? String.valueOf(ypdM.getWidth()) : "0");
	 		cd.setCreateId(userId);
	 		cd.setInvLength(ypdM.getLength() != null ? String.valueOf(ypdM.getLength()) : "0");
	 		cd.setProdName(ypdM.getProd_name());
	 		cd.setInvThick(ypdM.getThick() != null ? String.valueOf(ypdM.getThick()) : "0");
	 		
	 		String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypdM.getCoilno());
	 		// 上道产线：
	 		String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
	 		cd.setRefnoA("YT1".equals(prevMachine) ? ypdM.getMaterailcoilno() : prevcoil); // 投料卷号
	 		cd.setSysId("IA");
	 		cd.setOrderItem(ypdM.getOrderno());
	 		cd.setBeTransUnit("t");
	 		ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypdM.getSteelcode());
	 		if (cbs != null) {
	 			cd.setAlloyNo(cbs.getSteel_name()); // 牌号
	 		}
	 		cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
	 		cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
	 		cd.setBeTransWgt(ypdM.getFactweight() != null ? (ypdM.getFactweight() / 1000) : ypdM.getFactweight());
	 		
	 		cd.setInvId("YT1".equals(currentMachine) ? ypdM.getMaterailcoilno() : ypdM.getCoilno());
	 		cd.setInvQty("1");
			// setSrcFac根据卷的物料属性去判断：20231031刘侣
			cd.setSrcFac("507101".equals(ypdM.getObject_attr()) ? "1" : "3");
	 		cd.setGrade("1"); // 正品　1　协议　3　次品　5
	 		cd.setProdClassNo("H");
	 		
			cd.setActivityId("11AC");
			cd.setExecJobFunc("D");
			cd.setDataTypeIdx("O");
			cd.setProdTypeNo("YT1".equals(prevMachine) && cd.getInvId().startsWith("L") ? "CCR" : "YT1".equals(prevMachine) ? "HCR" : "CTR");
			cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
			cd.setCrntMill(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setManageip(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setLocNo(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setAppId("可发状态取消");
			
			doCbDataIns(cd, cd.getActivityId(), ypdM.getMaterailcoilno());
			    
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
		
	// 20231130成本异动点需求：挂单后一次结算的卷第一次挂单时抛送时抛送异动点：appid:客户属性入库
	// 客户属性入库和来料加工 这两个异动点重复所以去掉 来料加工 异动点 xuli 20231229 刘侣
	@Transactional(value = "tm", rollbackFor = {Exception.class})
	  public ResultModel ycjsPYdd(String coilno, boolean isGD) {
	    String userId = (String)getSession().getAttribute("user_id");
	    Date now = new Date();
	    
	    ResultModel rm = new ResultModel("200", "成功");
	    
	    try {
	      int isYcJs = this.getMapper(YdmProductDetailMapper.class).isHasYcJs(coilno);
	      if (isYcJs > 0) {
	        YdmProductDetail ypdM = this.getMapper(YdmProductDetailMapper.class).findById(coilno);
	        
	        if (ypdM != null && "507102".equals(ypdM.getObject_attr())) {
	          ComBaseCbYdd cd = new ComBaseCbYdd();
	          cd.setInstDisp("01");
	          
	          String currentMachine = ypdM.getCoilno().contains("S") ? "YTSX" : ypdM.getCoilno().contains("L") ? "YTZZ" : ypdM.getCoilno().contains("P") ? "YTPZ" : ypdM.getCoilno().contains("T") ? "YTTH" : ypdM.getCoilno().contains("K") ? "YTHJ" : ypdM.getCoilno().contains("F") ? "YTZJ" : "YT1";
	          cd.setInvQtyUnit("块");
	          cd.setInvWidth((ypdM.getWidth() != null) ? String.valueOf(ypdM.getWidth()) : "0");
	          cd.setCreateId(userId);
	          cd.setInvLength((ypdM.getLength() != null) ? String.valueOf(ypdM.getLength()) : "0");
	          cd.setProdName(ypdM.getProd_name());
	          cd.setInvThick((ypdM.getThick() != null) ? String.valueOf(ypdM.getThick()) : "0");
	          
	          String prevcoil = ypdM.getCoilno();
	          
	          String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
	          cd.setRefnoA("YT1".equals(prevMachine) ? ypdM.getMaterailcoilno() : prevcoil);
	          cd.setSysId("IA");
	          cd.setOrderItem(ypdM.getOrderno());
	          cd.setBeTransUnit("t");
	          ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypdM.getSteelcode());
	          if (cbs != null) {
	            cd.setAlloyNo(cbs.getSteel_name());
	          }
	          cd.setAcctDate((new SimpleDateFormat("yyyyMMdd")).format(now));
	          cd.setLastMill(prevMachine);
	          cd.setBeTransWgt(Double.valueOf((ypdM.getFactweight() != null) ? (ypdM.getFactweight().doubleValue() / 1000) : ypdM.getFactweight().doubleValue()));
	          
	          cd.setInvId("YT1".equals(currentMachine) ? ypdM.getMaterailcoilno() : ypdM.getCoilno());
	          cd.setInvQty("1");
	          
	          cd.setSrcFac("507101".equals(ypdM.getObject_attr()) ? "1" : "3");
	          cd.setGrade("1");
	          cd.setProdClassNo("H");
	          
	          cd.setActivityId("12AB");
	          cd.setExecJobFunc(isGD ? "N" : "D");
	          cd.setDataTypeIdx("O");
	          cd.setProdTypeNo("YT1".equals(prevMachine) && cd.getInvId().startsWith("L") ? "CCR" : "YT1".equals(prevMachine) ? "HCR" : "CTR");
	          cd.setCoilStus("0");
	          cd.setCrntMill(prevMachine);
	          cd.setManageip(prevMachine);
	          cd.setLocNo(prevMachine);

	          
	          cd.setAppId(isGD ? "客户属性入库" : "取消客户属性入库");
	          
	          doCbDataIns(cd, cd.getActivityId(), ypdM.getMaterailcoilno());
	        }
	      
	      }
	    
	    } catch (Exception e) {
	      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	      rm.setState("500");
	      rm.setMsgInfo(e.getMessage());
	    } 
	    
	    return rm;
	  }
	
	// 查询已发送到冷轧系统的数据：20240124刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel querySendLz(CommonPage<YdmProductDetail> cp) {
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "查询移送到冷轧数据成功");
		
		try {
			
			// 先无条件查吧  条件之后再加：
			List<YdmHzTemp> hzList = this.getMapper(YdmHzTempMapper.class).querySendLz();
			rm.setData(hzList);
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 发送到冷轧系统：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendToLzSys(CommonPage<YdmProductDetail> cp) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "优特钢数据发送到卷板成功");
		
		try {
			
			List<YdmProductDetail> ypdL = cp.getObjectList();
			
			if (ypdL.size() <= 0) {
				throw new Exception("请勾选至少一条进行操作");
			}
			for (YdmProductDetail ypd : ypdL) {
				YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(ypd.getCoilno(), null);
				if (ypdQ == null) {
					throw new Exception(ypd.getCoilno() + " 不存在库存信息");
				}
				if (!"0".equals(ypdQ.getState())) {
					throw new Exception("卷 " + ypdQ.getCoilno() + " 不是在库状态:" + ypdQ.getState());
				}
				// 卷得没脱单：
				if (ypdQ.getOrderno() == null) {
					throw new Exception("卷：" + ypdQ.getCoilno() + " 已经脱单");
				}
				
				// 将卷信息送到冷轧系统：
				// 拼接参数：
				IfTbl02CoilComm it = new IfTbl02CoilComm();
				it.setCoil_no(ypd.getCoilno().length()==8? (ypd.getCoilno()+"S0101") : ypd.getCoilno());
				it.setOld_sampl_no(it.getCoil_no());//真实钢卷号（优特钢内部）
				List<PlnProdorder> v_rec_prod = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, "prod_order_no='"+ypd.getProdorderno()+"'", null, 0, 0);
				if (v_rec_prod.size() <= 0) {	
					throw new Exception("生产订单信息不存在：" + ypd.getOrderno());
				}
				it.setInstr_coil_thk(v_rec_prod.get(0).getThick());//订单厚度
				it.setInstr_coil_wth(v_rec_prod.get(0).getWidth());
				it.setInstr_coil_len(v_rec_prod.get(0).getLength());
				// 获取订单信息：
				String condition = "contract_no || contract_line_seq || order_seq = '"+ypd.getOrderno()+"' and nvl(change_flag,0) <> '1'";
				List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, condition, "", 0, 0);
				if (soiList.size() <= 0) {	
					throw new Exception("订单信息不存在：" + ypd.getOrderno());
				}
				it.setDevlmt_dtime(new SimpleDateFormat("yyyyMMdd").format(soiList.get(0).getDeliver_date()));//交货期
				it.setOrdcust_cd(null);//客户
				it.setCoil_thk(ypd.getThick());
				it.setCoil_wth(ypd.getWidth());
				it.setCoil_len(ypd.getLength());
				it.setAct_wgt(ypd.getFactweight());						
				it.setOrd_no(ypd.getLzorderno());
				it.setSlab_no(ypd.getHeatno());
				it.setStl_grd(soiList.get(0).getSteel_name());//牌号
				it.setSpec_stl_grd(soiList.get(0).getSteel_name());
				
				String sciCondition = " and ORDERNO||PRODORDERNO = '"+ypd.getLzorderno()+"'";
				List<IfRawMtrCoilM> sciList = this.getMapper(IfSlmContractInfoMapper.class).doQuaryIfSlmContractInfo2(sciCondition, 0, 1);
				if (sciList!=null && sciList.size()>0) {								
					it.setOrd_use_cd(sciList.get(0).getPrdCode());//订单用途代码  
					it.setOrd_seq(sciList.get(0).getProdorderno());//订单序号
				}
				
				String condition1 = " coilno = '"+ypd.getCoilno()+"'";
				List<YdmProductButtresslist> ypbList = this.getMapper(YdmProductButtresslistMapper.class).findWithCondition(null, condition1, "createdate desc", 0, 1);
				if (ypbList!=null && ypbList.size()>0) {
					YdmBaseButtressconfig ybb = this.getMapper(YdmBaseButtressconfigMapper.class).findById(ypbList.get(0).getButtressno());
					if (ybb!=null) {
						it.setCur_load_loc(ybb.getButtressname());//垛位
					}
				}else {
					it.setCur_load_loc("酸洗L");//垛位
				}
				it.setSpec_abbsym(ypd.getStd_name());//标准
				it.setCur_prog_cd_dtime(new SimpleDateFormat("yyyyMMddHHmmss").format(now));
				//成分判定等级
				if (ypd.getChemresult()!=null) {
					if (ypd.getChemresult().endsWith("01")) {										
						it.setIngr_dec_grd("1");//1 合格
					}else {
						it.setIngr_dec_grd("2");//2 不合格
					}
				}
				//外观判定等级
				if (ypd.getSurfaceresult()!=null) {
					if (ypd.getSurfaceresult().endsWith("01")) {
						it.setExtshape_dec_grd("1");
					}else {
						it.setExtshape_dec_grd("2");
					}
				}
				//SIZE判定等级
				if (ypd.getSizeresult()!=null) {
					if (ypd.getSizeresult().endsWith("01")) {
						it.setSize_dec_rst("1");
					}else {
						it.setSize_dec_rst("2");
					}
				}
				//材质判定等级
				if (ypd.getPhysresult()!=null) {
					if (ypd.getPhysresult().endsWith("01")) {
						it.setMatlqlty_dec_grd("1");
					}else {
						it.setMatlqlty_dec_grd("2");
					}
				}
				//综合判定等级
				if (ypd.getJudgeresult()!=null) {
					if (ypd.getJudgeresult().endsWith("01")) {
						it.setTot_dec_grd("1");
					}else {
						it.setTot_dec_grd("2");
					}
				}
				
				it.setMill_dtime(new SimpleDateFormat("yyyyMMddHHmmss").format(ypd.getCreatedate()));//轧钢时间
				it.setSmp_no(ypd.getSmpno());//试样号
				it.setH_coil_no1(ypd.getMaterailcoilno());//热轧卷号
				String pk_ask_code = soiList.get(0).getPk_ask_code();
				if(pk_ask_code!=null){
					if("201101".equals(pk_ask_code)){//裸包
						it.setPackage_level("1");//包装等级(1-不包;2-简包;3-普包;4-精包)
						it.setPackage_fl("0");//是否包装(0-未包装;1-已包装)
					}else if("201102".equals(pk_ask_code)){//简包
						it.setPackage_level("2");//包装等级(1-不包;2-简包;3-普包;4-精包)
						it.setPackage_fl("1");//是否包装(0-未包装;1-已包装)
					}else if("201103".equals(pk_ask_code)){//普包
						it.setPackage_level("3");//包装等级(1-不包;2-简包;3-普包;4-精包)	
						it.setPackage_fl("1");//是否包装(0-未包装;1-已包装)
					}else if("201104".equals(pk_ask_code)){//精包
						it.setPackage_level("4");//包装等级(1-不包;2-简包;3-普包;4-精包)	
						it.setPackage_fl("1");//是否包装(0-未包装;1-已包装)
					}
				}
				it.setOrd_use_cd(sciList.get(0).getPrdCode());//订单用途代码  
				String condition2 = "material_no = '"+ypd.getCoilno()+"'";
				List<QcmJudgeSurface> qcmList = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, condition2, "judge_time desc", 0, 1);
				if (qcmList!=null && qcmList.size()>0) {									
					it.setExtshape_quality(qcmList.get(0).getLevel_desc());//FA  FB外观质量等级
				}
				MesPackResult mpr = new MesPackResult();
				mpr.setCoil_no(ypd.getCoilno());
				List<MesPackResult> mprList = this.getMapper(MesPackResultMapper.class).findWithCondition(mpr, null, "create_time desc", 0, 0);
				if (mprList!=null && mprList.size()>0) {									
					it.setPackage_reg(mprList.get(0).getCreate_man());//包装人
					it.setPackage_dtime(new SimpleDateFormat("yyyy-MM-dd").format(mprList.get(0).getCreate_time()));//包装时间
				}
				it.setCur_prog_cd("DFA");
				it.setOrd_fl("1");
				//20200303 综合判定不合格的需要进行特殊处理
				if (it.getTot_dec_grd()!=null && "2".equals(it.getTot_dec_grd())) {
					//T.TOT_DEC_GRD='2',T.CUR_PROG_CD='CRC',T.ORD_FL='2',T.ORD_NO='',T.ORD_SEQ=''
					it.setTot_dec_grd("2");
					it.setCur_prog_cd("CRC");
					it.setOrd_fl("2");
					it.setOrd_no("");
					it.setOrd_seq("");
					it.setExtshape_quality("CP");//20200312综判不合格，外观等级直接给"CP"
				} else if (it.getTot_dec_grd()!=null && "1".equals(it.getTot_dec_grd())) {
					// 综判合格但是表面判定不合格的话，直接将表面判定置成最低合格登记FA：2022071201
					if (it.getExtshape_quality() != null && "CP".equals(it.getExtshape_quality())) {
						it.setExtshape_quality("FA");//FA  FB外观质量等级
					}
				}
				
				//20200629 处理轧制数据传到冷轧系统
				if (ypd.getCoilno().contains("L01") && "M0008".equals(ypd.getMachine_code())) {
					//t.ORD_FL='2',t.ORD_NO='',t.ORD_SEQ='',t.CUR_PROG_CD='CRC'
					it.setOrd_fl("2");
					it.setOrd_no("");
					it.setOrd_seq("");
					it.setCur_prog_cd("CRC");
				}
				
				ResultModel rm2 = this.getBean(IfSlmContractInfoServiceImpl.class).doInsertIfCoilC(it);
				if (rm2.getState()==null || !"200".equals(rm2.getState())) {
					throw new Exception("装车失败:"+rm2.getMsgInfo());
				}
				
				// 增加 ydm_hz_temp中间表数据：
				YdmHzTemp temp = new YdmHzTemp();
				temp.setCoilno(ypd.getCoilno());
				temp.setStorageattr(ypd.getStorageattr());
				temp.setProd_code(ypd.getProd_code());
				temp.setProd_name(ypd.getProd_name());
				temp.setStd_code(ypd.getStd_code());
				temp.setStd_name(ypd.getStd_name());
				temp.setUse_code(ypd.getUse_code());
				temp.setUse_name(ypd.getUse_name());
				temp.setPline_name(ypd.getPline_name());
				temp.setThick(ypd.getThick());
				temp.setWidth(ypd.getWidth());
				temp.setLength(ypd.getLength());
				temp.setDiameter_out(ypd.getDiameter_out());
				temp.setDiameter_inn(ypd.getDiameter_inn());
				temp.setQuantity(ypd.getQuantity());
				temp.setTheoryweight(ypd.getTheoryweight());
				temp.setFactweight(ypd.getFactweight());
				temp.setCustomer_no(ypd.getCustomer_no());
				temp.setCustomer_nm(ypd.getCustomer_nm());
				temp.setReceiv_no(ypd.getReceiv_no());
				temp.setReceiv_nm(ypd.getReceiv_nm());
				temp.setOrderno(ypd.getOrderno());
				temp.setProdorderno(ypd.getProdorderno());
				temp.setSteelcode(ypd.getSteelcode());
				temp.setJudgesteelcode(ypd.getJudgesteelcode());
				temp.setPacking_group(ypd.getPacking_group());
				temp.setChemresult(ypd.getChemresult());
				temp.setSurfaceresult(ypd.getSurfaceresult());
				temp.setWeightresult(ypd.getWeightresult());
				temp.setJudgeresult(ypd.getJudgeresult());
				temp.setPhysresult(ypd.getPhysresult());
				temp.setProducedate(ypd.getProducedate());
				temp.setIndate(ypd.getIndate());
				temp.setMemo(ypd.getMemo());
				temp.setCreater(ypd.getCreater());
				temp.setCreatedate(ypd.getCreatedate());
				temp.setUpdater(ypd.getUpdater());
				temp.setUpdatedate(ypd.getUpdatedate());
				temp.setState(ypd.getState());
				temp.setMaterailcoilno(ypd.getMaterailcoilno());
				temp.setChemid(ypd.getChemid());
				temp.setPhysid(ypd.getPhysid());
				temp.setObject_no_vt(ypd.getObject_no_vt());
				temp.setLzorderno(ypd.getLzorderno());
				temp.setUp_surface_result(ypd.getUp_surface_result());
				temp.setUd_surface_result(ypd.getUd_surface_result());
				temp.setUp_surface_result_id(ypd.getUp_surface_result_id());
				temp.setUd_surface_result_id(ypd.getUd_surface_result_id());
				temp.setChemresult_id(ypd.getChemresult_id());
				temp.setPhysresult_id(ypd.getPhysresult_id());
				temp.setObject_attr(ypd.getObject_attr());
				temp.setInspection_lot(ypd.getInspection_lot());
				temp.setMachine_code(ypd.getMachine_code());
				temp.setMachine_name(ypd.getMachine_name());
				temp.setDelivery_state_code(ypd.getDelivery_state_code());
				temp.setDelivery_state_desc(ypd.getDelivery_state_desc());
				temp.setButtressno(ypbList.get(0).getButtressno());// 垛位
				this.getMapper(YdmHzTempMapper.class).insert(temp);
				
				
				// 增加出库记录：
				// 修改卷的状态信息：
				// 增加物料进程数据：
				CommonPage<YdmProductDetail> ypdCp=new CommonPage<YdmProductDetail>();
				ypdCp.setObject(ypd);
				doOutStorageytg(ypdCp);

				// 脱单：这个待定：
				
				
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		MesOprLog mol = new MesOprLog("生产管理", "发送数据", "优特钢数据发送到卷板成功", username, opr_time, "coilno", null, null, null, "优特钢数据发送到卷板成功");
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
	
	/**
	 * 投料出库
	 * cp.object<YdmProductDetail>,ypd.setCoilno()
	 * @throws Exception 
	 * */
	public void doOutStorageytg(CommonPage<YdmProductDetail> cp) throws Exception {
		YdmProductDetail ypdo= new YdmProductDetail();
		ypdo.setCoilno(cp.getObject().getCoilno());	
		ypdo.setState("0");
		List<YdmProductDetail> list=this.getMapper(YdmProductDetailMapper.class).find(ypdo, 0, 0);
		String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		if(list!=null && list.size()>0) {
			for(YdmProductDetail ypd:list) {
				String lastChar = ypd.getCoilno().substring(ypd.getCoilno().length()-1);
				if (!"B".equals(lastChar) && !"H".equals(lastChar)) {
					if (ypd.getJudgeresult()==null || "".equals(ypd.getJudgeresult())) {
						throw new Exception("卷号【"+ypd.getCoilno()+"】没有综合判定，无法投料出库");
					}
				}
				
				//插入出库信息
				YdmProductOutlist ypo=new YdmProductOutlist();
				ypo.setOutbillno(this.getBean(YdmProductOutlistServiceImpl.class).createOUTBILLNO());
				ypo.setCreater(username);
				ypo.setCreatedate(now);
				ypo.setOuttype("500501");
				ypo.setOutdate(now);
				ypo.setOutoperator(username);
				ypo.setOutorder("2");
				ypo.setOutteam("3");

				ypo.setCoilno(ypd.getCoilno());
				//QmsApiServiceImpl.Copy(ypd, ypo);
				ypo.setCoiltype(ypd.getCoiltype());
				ypo.setMaterailtype(ypd.getMaterailtype());
				ypo.setSource(ypd.getSource());
				ypo.setMaterailsupplier(ypd.getMaterailsupplier());
				ypo.setIsbox(ypd.getIsbox());
				ypo.setBoxno(ypd.getBoxno());
				ypo.setDrawingno(ypd.getDrawingno());
				ypo.setBatchno(ypd.getBatchno());
				ypo.setHeatno(ypd.getBatchno());
				ypo.setSmpno(ypd.getSmpno());
				ypo.setManagementno(ypd.getManagementno());
				ypo.setStorageattr(ypd.getStorageattr());
				ypo.setProd_code(ypd.getProd_code());
				ypo.setProd_name(ypd.getProd_name());
				ypo.setStd_code(ypd.getStd_code());
				ypo.setStd_name(ypd.getStd_name());
				ypo.setUse_code(ypd.getUse_code());
				ypo.setUse_name(ypd.getUse_name());
				ypo.setPline_name(ypd.getPline_name());
				ypo.setPostid(ypd.getPostid());
				ypo.setThick(ypd.getThick());
				ypo.setWidth(ypd.getWidth());
				ypo.setLength(ypd.getLength());
				ypo.setDiameter_inn(ypd.getDiameter_inn());
				ypo.setDiameter_out(ypd.getDiameter_out());
				ypo.setQuantity(ypd.getQuantity());
				ypo.setTheoryweight(ypd.getTheoryweight());
				ypo.setCoreweight(ypd.getCoreweight());
				ypo.setGrossweight(ypd.getGrossweight());
				ypo.setPackweight(ypd.getPackweight());
				ypo.setFactweight(ypd.getFactweight());
				ypo.setCustomer_nm(ypd.getCustomer_nm());
				ypo.setCustomer_no(ypd.getCustomer_no());
				ypo.setReceiv_no(ypd.getReceiv_no());
				ypo.setReceiv_nm(ypd.getReceiv_nm());
				ypo.setOrderno(ypd.getOrderno());
				ypo.setProdorderno(ypd.getProdorderno());
				ypo.setSteelcode(ypd.getSteelcode());
				ypo.setJudgesteelcode(ypd.getJudgesteelcode());
				ypo.setPacking_group(ypd.getPacking_group());
				ypo.setChemresult(ypd.getChemresult());
				ypo.setSizeresult(ypd.getSizeresult());
				ypo.setSurfaceresult(ypd.getSurfaceresult());
				ypo.setWeightresult(ypd.getWeightresult());
				ypo.setJudgeresult(ypd.getJudgeresult());
				ypo.setPhysresult(ypd.getPhysresult());
				ypo.setSpyresult(ypd.getSpyresult());
				ypo.setProducedate(ypd.getProducedate());
				ypo.setProduceorder(ypd.getProduceorder());
				ypo.setProduceteam(ypd.getProduceteam());
				ypo.setIndate(ypd.getIndate());
				ypo.setInorder(ypd.getInorder());
				ypo.setInteam(ypd.getInteam());

				YdmProductButtresslist but = new YdmProductButtresslist();
				but.setCoilno(ypd.getCoilno());
				List<YdmProductButtresslist> butlist =	this.getMapper(YdmProductButtresslistMapper.class).find(but, 0, 0);
				if(butlist!=null&&butlist.size()>0) {
					ypo.setButtressno(butlist.get(0).getButtressno());
					ypo.setLocality((long)butlist.get(0).getLocality());
					ypo.setLayer((long) 1);
				}
				else {
					ypo.setButtressno(ypd.getButtressno());
				}
				
				// 加入物料属性：20230725刘侣
				ypo.setObj_attr_out(ypd.getObject_attr());
				// end
				
				this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
				//删除垛位信息
				if((ypd.getBoxno()!=null&&ypd.getBoxno()!="")||(ypd.getCoilno()!=null&&ypd.getCoilno()!="")){
					this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypd.getCoilno(),ypd.getBoxno());
				}
				
				//修改库存信息
				ypd.setUpdater(username);
				ypd.setUpdatedate(now);
				ypd.setState("5");
				this.getMapper(YdmProductDetailMapper.class).doUpdate(ypd);

				//调用生产计划模块物料跟踪接口
				PrcMaterielProcess pmp = new PrcMaterielProcess();
				pmp.setObject_no(ypd.getCoilno());
				pmp.setPrc_code("5BYS10");

				//这里的格式要和字符串日期的格式匹配，不然会抛出转换异常   
				SimpleDateFormat   dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
				Date date2 = dateFormat.parse(cp.getObject().getMemo());
				if(date2!=null&&!"".equals(date2)) {
					pmp.setCreate_time(date2);
				}
				else {
					pmp.setCreate_time(now);
				}
				pmp.setRemark("投料出库移送到冷轧进行酸轧工序");
				pmp.setCreate_man_name(username);
				this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
				//int tmp= this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
			}
		}
		else{
			throw new Exception("不在库不允许操作!");
		}
	}

	// 查询已发送到冷轧系统的数据：20240124刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel queryReceiveLz(CommonPage<YdmProductDetail> cp) {
//			Date now = new Date();
//			String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "查询冷轧移送到优特钢数据成功");
		
		try {
			
			// 先无条件查吧  条件之后再加：
			List<YdmHzTemp> hzList = this.getMapper(YdmHzTempMapper.class).queryReceiveLz();
			rm.setData(hzList);
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	// 接收冷轧系统数据：
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel receiveFromLzSys(CommonPage<YdmHzTemp> cp) {
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		ResultModel rm = new ResultModel("200", "优特钢接收卷板数据成功");
		
		try {
			
			List<YdmHzTemp> tempL = cp.getObjectList();
			
			if (tempL.size() <= 0) {
				throw new Exception("请勾选至少一条进行操作");
			}
			int i = 0;
			for (YdmHzTemp temp : tempL) {
				// 能提供的数据和xmlz.IF_RAW_MTR_COIL_M的数据差不多：
				// 需要确认的问题：1、传过来的卷号是什么样的；2、质量判定那些值哪里获取：
				
				// 1、增加库存表数据：
				YdmProductDetail ypd = new YdmProductDetail();
				ypd.setCoilno(temp.getCoilno()); // 这个卷号可能需要改动
				ypd.setStorageattr("500202");
				ypd.setProd_code(temp.getProd_code());
				ypd.setProd_name(temp.getProd_name());
				ypd.setStd_code(temp.getStd_code());
				ypd.setStd_name(temp.getStd_name());
				ypd.setThick(temp.getThick());
				ypd.setWidth(temp.getWidth());
				ypd.setLength(temp.getLength());
				ypd.setDiameter_out(temp.getDiameter_out());
				ypd.setDiameter_inn(temp.getDiameter_inn());
				ypd.setQuantity(1);
				ypd.setTheoryweight(temp.getTheoryweight());
				ypd.setFactweight(temp.getFactweight());
				
				// 牌号只有名称，所以得基础表获取：
				ComBaseSteel cbsQ = new ComBaseSteel();
				cbsQ.setSteel_name(temp.getSteelcode());
				List<ComBaseSteel> listSteel = this.getMapper(ComBaseSteelMapper.class).find(cbsQ, 0, 0);
				if (listSteel.size() > 0) {
					ypd.setSteelcode(listSteel.get(0).getSteel_name());
					ypd.setJudgesteelcode(listSteel.get(0).getSteel_name());
				}
				ypd.setChemresult("合格".equals(temp.getChemresult()) ? "40740101" : "不合格".equals(temp.getChemresult()) ? "40740102" : "判次".equals(temp.getChemresult()) ? "40740103" : "判废".equals(temp.getChemresult()) ? "40740104" : "0");
				ypd.setSizeresult("合格".equals(temp.getSizeresult()) ? "40740301" : "不合格".equals(temp.getSizeresult()) ? "40740302" : "判次".equals(temp.getSizeresult()) ? "40740303" : "判废".equals(temp.getSizeresult()) ? "40740304" : "0");
				ypd.setSurfaceresult("合格".equals(temp.getSurfaceresult()) ? "40740601" : "不合格".equals(temp.getSurfaceresult()) ? "40740602" : "判次".equals(temp.getSurfaceresult()) ? "40740603" : "判废".equals(temp.getSurfaceresult()) ? "40740604" : "0");
				ypd.setUp_surface_result("合格".equals(temp.getSurfaceresult()) ? "40740601" : "不合格".equals(temp.getSurfaceresult()) ? "40740602" : "判次".equals(temp.getSurfaceresult()) ? "40740603" : "判废".equals(temp.getSurfaceresult()) ? "40740604" : "0");
				ypd.setJudgeresult("合格".equals(temp.getJudgeresult()) ? "40740801" : "不合格".equals(temp.getJudgeresult()) ? "40740802" : "判次".equals(temp.getJudgeresult()) ? "40740803" : "判废".equals(temp.getJudgeresult()) ? "40740804" : "0");
				ypd.setProducedate(temp.getProducedate());
				ypd.setCreater(username);
				ypd.setCreatedate(now);
				ypd.setState("0");
				ypd.setMaterailcoilno(temp.getMaterailcoilno());
				ypd.setLzorderno(temp.getLzorderno());
				
				// 获取object_attr:
				List<YdmProductDetail> ypdL = this.getMapper(YdmHzTempMapper.class).queryObject_attr(temp.getMaterailcoilno());
				if (ypdL.size() > 0) {
					ypd.setObject_attr(ypdL.get(0).getObject_attr());
					
					ypd.setHeatno(ypdL.get(0).getHeatno());
					ypd.setUse_code(ypdL.get(0).getUse_code());
					ypd.setLz_thick(ypdL.get(0).getLz_thick());
					ypd.setLz_width(ypdL.get(0).getLz_width());
					
				}
				ypd.setDelivery_state_desc(temp.getDelivery_state_desc());
				ypd.setMachine_code("M0008");
				ypd.setMachine_name("轧机机组");
				
				// 以下是没法传过来的：
				ypd.setMemo("卷板生产完成移送过来的");
				ypd.setCoiltype("1");
				ypd.setMaterailtype(temp.getMaterailtype());
				ypd.setSource("0");
				
				
				ypd.setCic_is_lock("0");
				ypd.setPic_is_lock("0");
				ypd.setSic_is_lock("0");
				ypd.setDic_is_lock("0");
				ypd.setSfu_is_lock("0");
				ypd.setSfd_is_lock("0");
				ypd.setSfe_is_lock("0");
				
				this.getMapper(YdmProductDetailMapper.class).insert(ypd);
				
				
				// 2、增加入库记录：还得传垛位
				// 插入入库信息
				YdmProductInlist ypi = new YdmProductInlist();
				ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
				ypi.setCreatedate(now);
				ypi.setCreater(username);				
				ypi.setCoilno(ypd.getCoilno());
				ypi.setCoiltype(ypd.getCoiltype());
				ypi.setMaterailtype(ypd.getMaterailtype());
				ypi.setSource(ypd.getSource());
				ypi.setMaterailsupplier(ypd.getMaterailsupplier());
				ypi.setIsbox(ypd.getIsbox());
				ypi.setBoxno(ypd.getBoxno());
				ypi.setDrawingno(ypd.getDrawingno());
				ypi.setBatchno(ypd.getBatchno());
				ypi.setHeatno(ypd.getBatchno());
				ypi.setSmpno(ypd.getSmpno());
				ypi.setManagementno(ypd.getManagementno());
				ypi.setStorageattr(ypd.getStorageattr());
				ypi.setProd_code(ypd.getProd_code());
				ypi.setProd_name(ypd.getProd_name());
				ypi.setStd_code(ypd.getStd_code());
				ypi.setStd_name(ypd.getStd_name());
				ypi.setUse_code(ypd.getUse_code());
				ypi.setUse_name(ypd.getUse_name());
				ypi.setPline_name(ypd.getPline_name());
				ypi.setPostid(ypd.getPostid());
				ypi.setThick(ypd.getThick());
				ypi.setWidth(ypd.getWidth());
				ypi.setLength(ypd.getLength());
				ypi.setDiameter_inn(ypd.getDiameter_inn());
				ypi.setDiameter_out(ypd.getDiameter_out());
				ypi.setQuantity(ypd.getQuantity());
				ypi.setTheoryweight(ypd.getTheoryweight());
				ypi.setCoreweight(ypd.getCoreweight());
				ypi.setGrossweight(ypd.getGrossweight());
				ypi.setPackweight(ypd.getPackweight());
				ypi.setFactweight(ypd.getFactweight());
				ypi.setCustomer_nm(ypd.getCustomer_nm());
				ypi.setCustomer_no(ypd.getCustomer_no());
				ypi.setReceiv_no(ypd.getReceiv_no());
				ypi.setReceiv_nm(ypd.getReceiv_nm());
				ypi.setOrderno(ypd.getOrderno());
				ypi.setProdorderno(ypd.getProdorderno());
				ypi.setSteelcode(ypd.getSteelcode());
				ypi.setJudgesteelcode(ypd.getJudgesteelcode());
				ypi.setPacking_group(ypd.getPacking_group());
				ypi.setChemresult(ypd.getChemresult());
				ypi.setSizeresult(ypd.getSizeresult());
				ypi.setSurfaceresult(ypd.getSurfaceresult());
				ypi.setWeightresult(ypd.getWeightresult());
				ypi.setJudgeresult(ypd.getJudgeresult());
				ypi.setPhysresult(ypd.getPhysresult());
				ypi.setSpyresult(ypd.getSpyresult());
				ypi.setProducedate(ypd.getProducedate());
				ypi.setProduceorder(ypd.getProduceorder());
				ypi.setProduceteam(ypd.getProduceteam());
				ypi.setIndate(now);
				ypi.setInorder(ypd.getInorder());
				ypi.setInteam(ypd.getInteam());
				ypi.setOperator(username);
				ypi.setIntype("500401");//正常入库
				ypi.setButtressno(cp.getMemo1());//垛位
				ypi.setPosition(String.valueOf(Integer.valueOf(cp.getMemo2())+i));//位置	:批量操作，位置需要+1			
				ypi.setLocality(cp.getMemo3());//层数
				ypi.setMemo(cp.getMemo4());//备注
				ypi.setMachine_code(ypd.getMachine_code());//机台代码
				ypi.setMachine_name(ypd.getMachine_name());//机台名称
				
				// 加入物料属性：20230725刘侣
				ypi.setObj_attr_in(ypd.getObject_attr());
				// end
				
				this.getMapper(YdmProductInlistMapper.class).insert(ypi);
				// 插入垛位：
				// 删除原有的垛位，插入新的垛位信息				
				this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypd.getCoilno(), null);
				YdmProductButtresslist ypb = new YdmProductButtresslist();
				ypb.setCreater(username);
				ypb.setCreatedate(new Date());
				if (cp.getMemo5() != null && cp.getMemo5() != "") {
					ypb.setLayer(Integer.valueOf(cp.getMemo5()).intValue());
				} else {
					ypb.setLayer(1);
				}
				if (cp.getMemo3() != null && cp.getMemo3() != "")
					ypb.setLocality(Integer.valueOf(cp.getMemo3()).intValue()+ i);
				ypb.setButtressno(cp.getMemo2());
				ypb.setStorageattr(ypd.getStorageattr());
				ypb.setAreano(cp.getMemo1());
				ypb.setCoilno(ypd.getCoilno());
				ypb.setBoxno(ypd.getBoxno());
				this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb);
				
				// 3、入库物料进程：
				// 调用生产计划接口进行物料跟踪
				PrcMaterielProcess pmp = new PrcMaterielProcess();
				pmp.setObject_no(ypd.getCoilno());
				pmp.setPrc_code("5BYA05");
				pmp.setCreate_time(now);
				pmp.setRemark("接收入库");
				pmp.setCreate_man_name(username);
				PrcMaterielProcess pmp1 = new PrcMaterielProcess();
				pmp1.setObject_no(ypd.getCoilno());
				pmp1.setPrc_code("5BYA04");
				pmp1.setCreate_time(now);
				pmp1.setRemark("" + opr_time);
				pmp1.setCreate_man_name(username);
				int tmp1 = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp1);
				int tmp = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
				if (tmp1 == -1) {
					throw new Exception("物料跟踪失败");
				}
				if (tmp == -1) {
					throw new Exception("物料跟踪失败");
				}
				// 4、修改temp表状态为0：
				temp.setState("0");
				this.getMapper(YdmHzTempMapper.class).update(temp);
				
				i++;
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		MesOprLog mol = new MesOprLog("生产管理", "发送数据", "优特钢接收卷板数据成功", username, opr_time, "coilno", null, null, null, "优特钢接收卷板数据成功");
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		return rm;
	}
	
	// 二级库存指定：20240411刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel erjiInstorage(CommonPage<YdmProductDetail> cp) {
		Date now = new Date();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String memo = cp.getMemo1(); // 1:指定，0:取消指定
		ResultModel rm = new ResultModel("200", "操作成功");
		List<YdmProductDetail> ypds = cp.getObjectList();
		
		try {
			
			// 限定操作人：20240418刘侣
			if (!"兰雨姗".equals(username)) {
				throw new Exception("只能兰雨姗进行二级库存指定");
			}
			// end
			
			if (ypds.size() <= 0) {
				throw new Exception("请勾选至少一条进行操作！");
			}
			if (memo == null || "".equals(memo)) {
				throw new Exception("未传入指定或取消指定参数！");
			}
			// 进二级库存的卷的条件：卷必须在库且脱单状态，且不是二级库存状态
			for(YdmProductDetail ypd : ypds) {
				YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).findById(ypd.getCoilno());
				if (ypdQ == null) {
					throw new Exception("卷 " + ypd.getCoilno() + " 信息不存在");
				}
				if ("1".equals(memo)) {
					// 二级库存指定：
					if (!"0".equals(ypdQ.getState())) {
						throw new Exception("卷 " + ypd.getCoilno() + " 不在库");
					}
					if (ypdQ.getOrderno() != null) {
						throw new Exception("卷 " + ypd.getCoilno() + " 还未脱单");
					}
					if ("1".equals(ypdQ.getIs_kucun_new())) {
						throw new Exception("卷 " + ypd.getCoilno() + " 已经在二级库存");
					}
					ypdQ.setIs_kucun_new("1");
				} else {
					// 二级库存取消：
					if (!"0".equals(ypdQ.getState())) {
						throw new Exception("卷 " + ypd.getCoilno() + " 不在库");
					}
					if (ypdQ.getOrderno() != null) {
						throw new Exception("卷 " + ypd.getCoilno() + " 还未脱单");
					}
					if (ypdQ.getIs_kucun_new() == null || "0".equals(ypdQ.getIs_kucun_new())) {
						throw new Exception("卷 " + ypd.getCoilno() + " 不在二级库存");
					}
					ypdQ.setIs_kucun_new("0");
				}
				this.getMapper(YdmProductDetailMapper.class).update(ypdQ);
				MesOprLog mol = new MesOprLog("物流管理", "原料库成品库库存查询", "二级库存指定或取消", username, opr_time, ypd.getCoilno(), null, null, null, "二级库存"+("1".equals(ypdQ.getIs_kucun_new()) ? "指定" : "取消指定")+"成功");
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		
		return rm;
	}
	
	
	// 获取产出卷的交货状态：主要用于非计划卷的交货状态的确定 20240515 刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public String getDelStateFJH(String coilNo) {
//		ResultModel rm = new ResultModel("200", "操作成功");
		
		// 切记，只有返回了值才更新：！！！
		String res = "";
		
		try {
			if (coilNo == null || "".equals(coilNo)) {
				return "";
			}
			// 去掉原料卷：
			if (coilNo.length() <= 8) {
				return "";
			}
			
			String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(coilNo);
			if (coilNo.contains("T") || coilNo.contains("L") || coilNo.contains("S")) {
				// 查出该卷的投料卷：
				// 只有一种特殊情况：酸洗、酸洗退火的，类别都是酸洗   
				// 只有退火，轧机，酸洗需要：
				if (coilNo.contains("T")) {
					// 分为两种情况，一是上到工序未酸洗的，定为 酸洗，不是的话，就是退火
					if (prevcoil.contains("S")) {
						res = "S";
					} else {
						res = "T";
					}
				} else if (coilNo.contains("L")) {
					res = "L";
				} else if (coilNo.contains("S")) {
					res = "S";
				}
			} else {
				// 如果是分条，平整的话，那就获取投料卷的卷信息中的 交货状态字段：这样的话，
				// 酸洗-冷轧-退火-平整-分条 即使在分条或者平整这里，依然可以填入 退火 的交货状态：
				YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(prevcoil, null);
				res = ypdQ.getYsstate();
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	// 向产销系统发送装车数据：20240531刘侣
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel sendLoadData(String billNo) {
		ResultModel rm = new ResultModel("200", "操作成功");
		Date date = new Date();
		try {
			if (billNo == null || "".equals(billNo)) {
				throw new Exception("参数 提单号 不存在！！！");
			}
			SlmLadingBillHeat sh = this.getMapper(SlmLadingBillHeatMapper.class).findById(billNo);
			if (sh == null) {
				throw new Exception("提单：" + billNo + " 信息不存在!!!");
			}
			// 判断是否是火运提单：
			if ("1".equals(sh.getTrans_type())) {
				SendToCxSystem cxList = this.getMapper(SlmLadingBillHeatMapper.class).getSendToCxSystem(billNo);
				if (cxList == null) {
					throw new Exception("提单：" + billNo + " 不存在装车信息!!!");
				}
				
				// 写入前删除所有相同提单号的数据防止主键冲突：
				this.getMapper(SlmLadingBillHeatMapper.class).deleteCx(cxList.getBill_no());
				// 发送装车信息：
				this.getMapper(SlmLadingBillHeatMapper.class).sendToCx(cxList.getCreate_time(), cxList.getBill_no(), cxList.getContract_no(), cxList.getCustomer_name(), cxList.getJudgesteelcname(), cxList.getProd_name(), cxList.getLoad_theory_weight(), cxList.getLoad_fact_weight(), cxList.getQuantity(), cxList.getCarno(), "火运", "1");
				
				List<SlmLadingBillDetail> details = this.getMapper(SlmLadingBillHeatMapper.class).getSendToCxDetail(cxList.getBill_no());
				if (details.size() > 0) {
					// 写入前删除所有相同提单号的数据防止主键冲突：
					this.getMapper(SlmLadingBillHeatMapper.class).deleteCxDetail(cxList.getBill_no());
					// 发送装车明细信息：
					for (SlmLadingBillDetail de : details) {
						this.getMapper(SlmLadingBillHeatMapper.class).sendToCxDetail(date, de.getContract_no(), de.getOrder_no(), de.getBill_no(), de.getBoxno(), de.getCoilno(), de.getMemo(), de.getJudgesteelcname(), de.getThick(), de.getWidth(), de.getLen(), de.getTheoryweight(), de.getFactweight(), de.getCustomer_name(), de.getProd_name(), de.getMaterailcoilno());
					}
				}
			}
			
		} catch(Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//			rm.setState("500");
//			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	// 统一的废副品发运大标签：20241217
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel ffpPrintLabel(String billNo) {
		ResultModel rm = new ResultModel("200", "操作成功");
//		Date date = new Date();
		try {
			// 统一的废副品发运大标签：
			List<HashMap> label = this.getMapper(SlmLadingBillHeatMapper.class).getPrintLabel(billNo);
			rm.setData(label);
		} catch(Exception e) {
//			System.out.println(e.getMessage());
//			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	// 统一的废副品发运大标签：20250120
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel ffpPrintLabelFeiqi(String billNo) {
		ResultModel rm = new ResultModel("200", "操作成功");
//			Date date = new Date();
		try {
			// 统一的废副品发运大标签：
			List<HashMap> label = this.getMapper(SlmLadingBillHeatMapper.class).getPrintLabel(billNo);
			rm.setData(label);
		} catch(Exception e) {
//				System.out.println(e.getMessage());
//				e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	// 装车时根据车号和车牌颜色判断是否是环保车辆，不是则不允许装车出厂：20250304ll
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel isECOCar(String carno,String color) {
		ResultModel rm = new ResultModel("200", "是环保车辆");
		try {
			
			// 判断是否是环保车辆：
			// 1：黄牌，2：蓝牌，4：绿牌，5：黄绿牌
			String query = URLEncoder.encode(carno.trim(), "UTF-8");
			String url = "http://172.16.0.127:9093/api/Hbch/IsHbch?cCh=" + query + "&cCp=" + color;
			System.out.println(url);
			String result = Connecttt.getJsonParams(url);
			JsonObject resObj = new JsonParser().parse(result).getAsJsonObject();
			System.out.println(resObj.toString());
			String status = resObj.get("status").toString();
			if ("0".equals(status)) {
				rm.setState("500");
				rm.setMsgInfo("不是环保车辆（无法申请汽车成品出厂预报）");
			}
			
		} catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
}