/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.11.27
 * 描述               :        			订单信息
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/

package market.Mes.OrderManager.Plan.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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.Com.mapper.ComBaseInfoMapper;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.impl.YdmProductDetailBfServiceImpl;
import market.Lms.Warehouse.impl.YdmProductInlistServiceImpl;
import market.Lms.Warehouse.impl.YdmProductOutlistServiceImpl;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.mapper.YdmProductOutlistMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Mes.Lengthwise.Plan.mapper.PlnMatReplaceLogMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.Lengthwise.Plan.vo.PlnMatReplaceLog;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
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.service.PlnProdorderGuaDanService;
import market.Mes.OrderManager.Plan.vo.PlnOrderStatistic;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.OrderManager.Plan.vo.PlnProdorderStatistic;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.FundManagement.impl.SlmFundFirstDetailServiceImpl;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;

import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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.service.HomeService;

@RemoteService(path = "PlnProdorderGuaDanService")
public class PlnProdorderGuaDanServiceImpl extends BaseServiceImpl<PlnProdorder, Object> implements PlnProdorderGuaDanService {

	/**
	 * 挂单管理：查询生产订单信息
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryWaitGuaDan(CommonPage<PlnProdorder> cp) {
		ResultModel rm = new ResultModel();
		PlnProdorder pp = cp.getObject();
		try {
			String sWhere = "";
			// 假如为1则为下发产生时间 为2交货时间
			if ("1".equals(cp.getMemo1())) {
				sWhere += " and ((t1.status>='0PAA12' and t1.send_time between to_date('" + cp.getStartTime()
						+ "','yyyy-MM-dd HH24:mi:ss') and to_date('" + cp.getEndTime()
						+ "','yyyy-MM-dd HH24:mi:ss')) or (t1.status>='0PAA10' and t1.create_time between to_date('"
						+ cp.getStartTime() + "','yyyy-MM-dd HH24:mi:ss') and to_date('" + cp.getEndTime()
						+ "','yyyy-MM-dd HH24:mi:ss'))) ";
			} else if ("2".equals(cp.getMemo1())) {
				sWhere += " and t1.deliver_date between to_date('" + cp.getStartTime().substring(0, 10)
						+ "','yyyy-MM-dd') and to_date('" + cp.getEndTime().substring(0, 10) + "','yyyy-MM-dd') ";
			}
			// 不显示满足溢
			if ("1".equals(cp.getMemo2())) {
				sWhere += " and nvl2(t1.delivery_error_min, case when ((t1.estimate_weight - t1.delivery_error_min) < "
						+ "(case when  t1.order_nature in ('1','2','3') or t1.whole_coil = '1' "
						+ "then nvl(t2.unscheduled,0) "
						+ "else nvl(t2.cl_undsn,0)+nvl(t2.lw_undsn,0)+nvl(t2.pc_undsn,0)+nvl(t2.an_undsn,0)+nvl(t2.sr_undsn,0)+nvl(t2.rl_undsn,0)"
						+ " end)) then 1 else 0 end, 1) = 1 ";
			} else {
				sWhere += " and ((t1.order_nature in ('1', '3') or t1.whole_coil = '1') and t2.unscheduled is not null"
						+ " or (t2.cl_undsn||t2.lw_undsn||t2.pc_undsn||t2.an_undsn||t2.sr_undsn||t2.rl_undsn is not null))";
			}
			if (pp != null) {
				//销售订单号
				if (pp.getOrder_no() != null && !"".equals(pp.getOrder_no().trim())) {
					sWhere += " and t1.order_no like '%" + pp.getOrder_no().trim() + "%' ";
				}
				//生产订单号
				if (pp.getProd_order_no() != null && !"".equals(pp.getProd_order_no().trim())) {
					sWhere += " and t1.prod_order_no like '%" + pp.getProd_order_no().trim() + "%' ";
				}
				//牌号
				if (pp.getSteel_name() != null && !"".equals(pp.getSteel_name().trim())) {
					sWhere += " and t1.steel_name like '%" + pp.getSteel_name().trim() + "%' ";
				}
				//首工序
				if (pp.getWhole_process_names()!=null && !"".equals(pp.getWhole_process_names())) {
					sWhere += " and t1.whole_process_names like '"+pp.getWhole_process_names()+"%' ";
				}
			}
			List<HashMap> hmList = this.getMapper(PlnProdorderMapper.class).doQueryWaitGuaDan(pp, sWhere);
			rm.setState("200");
			rm.setData(hmList);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}

		return rm;
	}
	
	/**
	 * 自动挂单管理：查询生产订单信息
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryWaitGuaDanAuto(CommonPage<PlnProdorder> cp) {
		ResultModel rm = new ResultModel();
		PlnProdorder pp = cp.getObject();
		try {
			String sWhere = "";
			// 假如为1则为下发产生时间 为2交货时间
			if ("1".equals(cp.getMemo1())) {
				sWhere += " and t1.create_time between to_date('"
						+ cp.getStartTime() + "','yyyy-MM-dd HH24:mi:ss') and to_date('" + cp.getEndTime()
						+ "','yyyy-MM-dd HH24:mi:ss') ";
			}
//			// 不显示满足溢
//			if ("1".equals(cp.getMemo2())) {
//				sWhere += " and nvl2(t1.delivery_error_min, case when ((t1.estimate_weight - t1.delivery_error_min) < "
//						+ "(case when  t1.order_nature in ('1','2','3') or t1.whole_coil = '1' "
//						+ "then nvl(t2.unscheduled,0) "
//						+ "else nvl(t2.cl_undsn,0)+nvl(t2.lw_undsn,0)+nvl(t2.pc_undsn,0)+nvl(t2.an_undsn,0)+nvl(t2.sr_undsn,0)+nvl(t2.rl_undsn,0)"
//						+ " end)) then 1 else 0 end, 1) = 1 ";
//			} else {
//				sWhere += " and ((t1.order_nature in ('1', '3') or t1.whole_coil = '1') and t2.unscheduled is not null"
//						+ " or (t2.cl_undsn||t2.lw_undsn||t2.pc_undsn||t2.an_undsn||t2.sr_undsn||t2.rl_undsn is not null))";
//			}
			if (pp != null) {
				//销售订单号
				if (pp.getOrder_no() != null && !"".equals(pp.getOrder_no().trim())) {
					sWhere += " and t1.order_no like '%" + pp.getOrder_no().trim() + "%' ";
				}
				//生产订单号
				if (pp.getProd_order_no() != null && !"".equals(pp.getProd_order_no().trim())) {
					sWhere += " and t1.prod_order_no like '%" + pp.getProd_order_no().trim() + "%' ";
				}
				//牌号
				if (pp.getSteel_name() != null && !"".equals(pp.getSteel_name().trim())) {
					sWhere += " and t1.steel_name like '%" + pp.getSteel_name().trim() + "%' ";
				}
				//首工序
				if (pp.getWhole_process_names()!=null && !"".equals(pp.getWhole_process_names())) {
					sWhere += " and t1.whole_process_names like '"+pp.getWhole_process_names()+"%' ";
				}
			}
			List<HashMap> hmList = this.getMapper(PlnProdorderMapper.class).doQueryWaitGuaDan(pp, sWhere);
			rm.setState("200");
			rm.setData(hmList);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}

		return rm;
	}
	
	/**
	 * 挂单管理：查询库存信息
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryYpdGuaDan(CommonPage<YdmProductDetail> cp) {
		ResultModel rm=new ResultModel();
		YdmProductDetail ypd = cp.getObject();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		String thickmax = cp.getMemo3();//厚度上限
		String thickmin = cp.getMemo4();//厚度下限
		PageModel<HashMap> pm = new PageModel<HashMap>(pageIndex,pageSize);
		try {			
			// 匹配采购订单号
			if (ypd.getOrderno()!=null && !"".equals(ypd.getOrderno())) {
				ResultModel rms =this.getBean(MesApiServiceImpl.class).getPurchaseContractNoInfo(ypd.getOrderno());
				if (rms.getData()==null) {
					ypd.setLzorderno(null);
				}else {
					ypd.setLzorderno(rms.getData().toString());
				}
			}
			
			// 拆分订单所挂物料锁定在原订单范围内
			String condition = null;
			/*if (cp.getObject().getMaterailorderno()!=null&&!"".equals(cp.getObject().getMaterailorderno())) {
				List<PlnProdorder> lppq = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " order_no = '"+cp.getObject().getMaterailorderno()+"'", null, 0, 1);
				// 是拆分订单
				if (CollectionUtils.isNotEmpty(lppq) && lppq.get(0).getIs_split() != null && "1".equals(lppq.get(0).getIs_split())) {
					// 获取原订单数据
					List<PlnProdorder> lppo = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " ord_pk = '"+lppq.get(0).getP_order_no()+"'", null, 0, 1);
					if (CollectionUtils.isNotEmpty(lppo)) {						
						condition = " (select distinct object_no from pln_mat_replace_log where order_no = '"+lppo.get(0).getOrder_no()+"')";
					}
				}
			}*/
			if((cp.getObject().getJudgesteelcode()==null||"".equals(cp.getObject().getJudgesteelcode()))&&cp.getObject().getSteelcode()!=null&&!"".equals(cp.getObject().getSteelcode()))
				cp.getObject().setJudgesteelcode(cp.getObject().getSteelcode());

			pm.setRows(this.getMapper(YdmProductDetailMapper.class).doQueryYpdGuaDan(
					(pageIndex-1)*pageSize, pageIndex*pageSize, ypd, condition, thickmax, thickmin));
			pm.setTotal(this.getMapper(YdmProductDetailMapper.class).doQueryYpdGuaDanCount(0, 0, ypd, condition, 
					thickmax, thickmin));
			rm.setData(pm);
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，查询失败!");
			ex.printStackTrace();
		}
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 自动挂单管理：查询库存信息
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryYpdGuaDanAuto(CommonPage<YdmProductDetail> cp) {
		ResultModel rm=new ResultModel();
		YdmProductDetail ypd = cp.getObject();
		
		try {			
			if (ypd == null) {
				throw new Exception("请传入object参数");
			}
			String orderno = ypd.getOrderno();
			if (orderno == null || "".equals(orderno)) {
				throw new Exception("请传入订单号");
			}
			
			rm.setData(this.getMapper(YdmProductDetailMapper.class).doQueryYpdGuaDanAuto(orderno));
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，查询失败!");
			ex.printStackTrace();
		}
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 需加工挂单前判断：20230214刘侣
	 * @param CP
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel gdBeforeJudge(CommonPage<String[]> CP) throws Exception{
		ResultModel rm=new ResultModel();
		rm.setState("200");
		rm.setMsgInfo("1"); // 可以正常挂单
		// 厂内合同和非需加工订单不需要做报错返回：
		//验证生产订单号是否存在
		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("生产订单已经锁定[订单变更中],不允许挂单!");
		}
		
		// 合同是否是厂内合同 101603
		if ("101603".equals(pp.getContract_type_no())) {
			rm.setState("200");
			rm.setMsgInfo("1"); // 可以正常挂单
		}
		
		if (!"2".equals(pp.getOrder_nature())) {
			rm.setState("200");
			rm.setMsgInfo("1"); // 可以正常挂单
		}
		// 非厂内合同且是需加工：判断是否之前做过一次结算：
		//实物卷号数组
		String[] sCoilNo=CP.getObject();
		for(String CoilNo:sCoilNo){
			if (CoilNo != null && CoilNo.length() > 9) {
				// 非未生产的卷：
				// 挂单管理，当前挂的需加工的话，需要判断卷子是否之前做过一次结算；20230214刘侣
				// flag_c = true 厂内合同: 非厂内合同且是需加工
				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 + "之前还没做一次结算，不能挂需加工订单");
					rm.setState("200");
					rm.setMsgInfo("0"); // 提示是否继续挂单
				}
				
				// end
			}
			
		}
		
		return rm;
	}
	
	/**
	 * 挂单管理：挂单操作
	 * @param CP
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRelationOrder(CommonPage<String[]> CP) throws Exception{
		
	    String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		Date now = new Date();
		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;
		}
		
		// 验证生产订单状态是否为订单保留：20230908刘侣
		if ("0PAA60".equals(lpp.get(0).getStatus())) {
			throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许挂单");
		}
		if ("0PAA70".equals(lpp.get(0).getStatus())) {
			throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许挂单");
		}
		
		pp = lpp.get(0);//生产订单号唯一约束
		// 验证生产订单是否锁定
		if ("2".equals(pp.getFinished_status())) {
			throw new Exception("生产订单已经锁定[订单变更中],不允许挂单!");
		}
		
		// 合同是否是厂内合同 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;
				}
				

				// 挂单管理，当前挂的需加工的话，需要判断卷子是否之前做过一次结算；20230214刘侣 注释掉，已经在其他地方实现了；
				// flag_c = true 厂内合同: 非厂内合同且是需加工
//				if (!flag_c && "2".equals(pp.getOrder_nature()) && CoilNo.length() > 8 && CP.getMemo4() ) {
//					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
				
				// 牌号不对，提示需要做强制挂单：
				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;
					}
					// 判断实物，和订单原料卷的宽，如果实物比订单值小，则报错退出
//					if (ypd.getWidth().doubleValue() < pp.getWidth().doubleValue()) {
//						throw new Exception("实物卷的宽比订单要求值小，不能上料！");
//					}
				}
				
				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());
//						detail.setJudgesteelcode(lpp.get(0).getSteel_code());
						this.getMapper(YdmProductDetailMapper.class).update(detail);
//					}else {						
//						rm.setState("500");
//						rm.setMsgInfo("牌号不匹配，请选择检验牌号强制挂单！");
//						return rm;
//					}
				}
				
				
				//如果不是强制挂单，需要验证信息
				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())) {
									// 去掉这个限制lanyushan：20231113刘侣
//									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("未找到实物厚度，不能上料！");
					}
					
//					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());
//					}

					
					
					//毛重交货的需要验证客户信息是否一致
//					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() + "]");
//					}
				}
				
				// 生成设计信息
				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());
					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++);
					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);
					
					// 生成物料附加信息
					this.getBean(MesApiDesignInfoImpl.class).addMaterielExinfo(lpp.get(0), pmdetail.get(0), processpoint.slitting_code);
					
					// 拆分订单如果还需继续生产,判断是否需要移动库存 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 如果成品库 需加工订单，运输方案到优特
					if("500203".equals(ypd.getStorageattr()) && "2".equals(pp.getOrder_nature()) && solution!=null && solution.contains("到优特")) {
						ResultModel rmChange = 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));
							}
						}
						y.setMemo("需加工挂单重新入原料库!!!");
						this.getMapper(YdmProductDetailMapper.class).update(y);
						this.getMapper(YdmProductDetailMapper.class).kctbYdd(y.getCoilno());
						// 从成品库入原料库后抛送取消综判异动点：20240425刘侣
						this.getBean(SlmFundFirstDetailServiceImpl.class).cancelUltiYdd(y.getCoilno());
					}					
				} catch (Exception e) {
					// 如果有trycatch，则需要设置手动20230703 刘侣
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					// end
					throw new Exception(e.getMessage());
				}
				
				ResultModel rejRes = this.getBean(SlmFundFirstDetailService.class).reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				this.getBean(SlmFundFirstDetailService.class).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());
//						detail.setJudgesteelcode(lpp.get(0).getSteel_code());
						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());
//						}
					}				
					//判断实物，和订单原料卷的宽、重量信息，如果实物比订单值小，则报错退出
//					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);
				
				ResultModel rejRes = this.getBean(SlmFundFirstDetailService.class).reAutoUltiJudge(CoilNo);
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
				
				this.getBean(SlmFundFirstDetailService.class).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;
	}
	
	
	/**
	 * 挂单管理：挂单操作
	 * @param CP
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRelationOrderAuto(CommonPage<String[]> CP) throws Exception{
		
	    String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		Date now = new Date();
		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;
		}
		
		// 验证生产订单状态是否为订单保留：20230908刘侣
		if ("0PAA60".equals(lpp.get(0).getStatus())) {
			throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许挂单");
		}
		if ("0PAA70".equals(lpp.get(0).getStatus())) {
			throw new Exception("生产订单["+lpp.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许挂单");
		}
		
		pp = lpp.get(0);//生产订单号唯一约束
		// 验证生产订单是否锁定
		if ("2".equals(pp.getFinished_status())) {
			throw new Exception("生产订单已经锁定[订单变更中],不允许挂单!");
		}
		
		// 合同是否是厂内合同 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;
				}
				

				// 挂单管理，当前挂的需加工的话，需要判断卷子是否之前做过一次结算；20230214刘侣 注释掉，已经在其他地方实现了；
				// flag_c = true 厂内合同: 非厂内合同且是需加工
//				if (!flag_c && "2".equals(pp.getOrder_nature()) && CoilNo.length() > 8 && CP.getMemo4() ) {
//					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
				
				// 牌号不对，提示需要做强制挂单：
				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;
					}
					// 判断实物，和订单原料卷的宽，如果实物比订单值小，则报错退出
//					if (ypd.getWidth().doubleValue() < pp.getWidth().doubleValue()) {
//						throw new Exception("实物卷的宽比订单要求值小，不能上料！");
//					}
				}
				
				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());
//						detail.setJudgesteelcode(lpp.get(0).getSteel_code());
						this.getMapper(YdmProductDetailMapper.class).update(detail);
//					}else {						
//						rm.setState("500");
//						rm.setMsgInfo("牌号不匹配，请选择检验牌号强制挂单！");
//						return rm;
//					}
				}
				
				
				//如果不是强制挂单，需要验证信息
				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())) {
									// 去掉这个限制lanyushan：20231113刘侣
//									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("未找到实物厚度，不能上料！");
					}
					
//					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());
//					}

					
					
					//毛重交货的需要验证客户信息是否一致
//					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() + "]");
//					}
				}
				
				// 生成设计信息
				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());
					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++);
					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);
					
					// 生成物料附加信息
					this.getBean(MesApiDesignInfoImpl.class).addMaterielExinfo(lpp.get(0), pmdetail.get(0), processpoint.slitting_code);
					
					// 拆分订单如果还需继续生产,判断是否需要移动库存 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 如果成品库 需加工订单，运输方案到优特
					if("500203".equals(ypd.getStorageattr()) && "2".equals(pp.getOrder_nature()) && solution!=null && solution.contains("到优特")) {
						ResultModel rmChange = 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));
							}
						}
						y.setMemo("需加工挂单重新入原料库!!!");
						this.getMapper(YdmProductDetailMapper.class).update(y);
						this.getMapper(YdmProductDetailMapper.class).kctbYdd(y.getCoilno());
						// 从成品库入原料库后抛送取消综判异动点：20240425刘侣
						this.getBean(SlmFundFirstDetailServiceImpl.class).cancelUltiYdd(y.getCoilno());
					}					
				} catch (Exception e) {
					// 如果有trycatch，则需要设置手动20230703 刘侣
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					// end
					throw new Exception(e.getMessage());
				}
				
				this.getBean(SlmFundFirstDetailService.class).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());
//						}
					}				
					//判断实物，和订单原料卷的宽、重量信息，如果实物比订单值小，则报错退出
//					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.getBean(SlmFundFirstDetailService.class).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;
	}
	
	
	
	public ResultModel doChangeStorageattr(YdmProductDetail ypd,String opr,String order,String team,Date oprTime){
		ResultModel rm = new ResultModel();
		try {
			
			
			
			//1.新增成品库出库记录
			YdmProductOutlist ypo=new YdmProductOutlist();
			ypo.setCreater(opr);
			ypo.setCreatedate(oprTime);
			ypo.setOutbillno(this.getBean(YdmProductOutlistServiceImpl.class).createOUTBILLNO());
			ypo.setOuttype("500513");//挂单出库
			ypo.setOutdate(oprTime);
			ypo.setOutoperator(opr);
			ypo.setCoilno(ypd.getCoilno());
			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.setButtressno(ypd.getButtressno());				 
			if(ypd.getLocality()!=null){					
				ypo.setLocality(Long.valueOf(ypd.getLocality()));
			}
			ypo.setMemo("需加工挂单成品库出库");
			
			// 加入物料属性：20230725刘侣
			ypo.setObj_attr_out(ypd.getObject_attr());
			// end
			
			this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
			//2.仓库调整
			ypd.setStorageattr("500201");//物料由成品库转到原料库
			ypd.setIs_change_storage("1");
			ypd.setObject_attr("507102");//物料属性转换为“ 客户”
			ypd.setMemo("需加工挂单重新入原料库");
			ypd.setSource("0");
			ypd.setState("0");
			ypd.setBill_no("");//清除提单信息
			ypd.setLine_no("");	
			ypd.setIs_can_load("");// 将卷子可发运状态取消20230210刘侣
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			this.getMapper(YdmProductDetailMapper.class).kctbYdd(ypd.getCoilno());
			
			//3.生成原料库入库信息
			YdmProductInlist ypi = new YdmProductInlist();
			ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
			ypi.setCreatedate(oprTime);
			ypi.setCreater(opr);				
			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.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(oprTime);
			ypi.setInorder(order);
			ypi.setInteam(team);
			ypi.setOperator(opr);
			ypi.setIntype("500413");
			//ypi.setButtressno("100106001");//虚拟区
			ypi.setLocality("1");
			ypi.setPosition("1");
			ypi.setMemo("挂单自动入库:"+ypd.getMemo());
			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);
			//调用生产计划模块物料跟踪接口
			PrcMaterielProcess pmp = new PrcMaterielProcess();
			pmp.setObject_no(ypd.getCoilno());
			pmp.setPrc_code("5BYS10");
			pmp.setCreate_time(oprTime);
			pmp.setRemark("物料挂单，成品库自动出库");
			pmp.setCreate_man_name(opr);
			int tmp = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
			if (tmp == -1) {
				throw new Exception("物料跟踪失败");
			}
			PrcMaterielProcess pmp1 = new PrcMaterielProcess();
			pmp1.setObject_no(ypd.getCoilno());
			pmp1.setPrc_code("5BYA05");
			pmp1.setCreate_time(oprTime);
			pmp1.setRemark("物料挂单，原料库自动入库");
			pmp1.setCreate_man_name(opr);
			int tmp1 = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp1);
			if (tmp1 == -1) {
				throw new Exception("物料跟踪失败");
			}
			//二次确定调整仓库
			ypd.setStorageattr("500201");
			ypd.setMemo("需加工挂单重新入原料库++");
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			
			// 由成品库回到原料库插入一个异动点：xuli需求 20231228刘侣  一体化需要暂时注释：xuli需求 20240126
//			this.getBean(SlmFundFirstDetailServiceImpl.class).hYlkPYdd(ypd.getCoilno());
			
			rm.setState("200");
			return rm;
		} catch (Exception e) {
			rm.setData("500");
			rm.setMsgInfo(e.getMessage());
			return rm;
		}
	}
	
}
