/***文档注释***********************************************
 * 作者               :                   龙文航
 * 创建日期      :                   2017.11.22
 * 描述               :                   仓库管理-原料库在制品库成品库管理-入库查询
 * 注意事项      :                   后续修改从登陆获取班次班组
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/
package market.Lms.Warehouse.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import market.Api.Mes.impl.MesApiServiceImpl;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.vo.ComBaseCbYdd;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.IfRawMtrCoilMMapper;
import market.Lms.Warehouse.mapper.YdmBaseButtressconfigMapper;
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.YdmProductButtresslist;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Mes.Lengthwise.Performance.mapper.MesCrSlittingDMapper;
import market.Mes.Lengthwise.Performance.mapper.MesCrSlittingMMapper;
import market.Mes.Lengthwise.Performance.vo.MesCrSlittingD;
import market.Mes.Lengthwise.Plan.mapper.MesCrCrossCuttingDMapper;
import market.Mes.Lengthwise.Plan.vo.MesCrCrossCuttingD;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.Opr.mapper.MesInfoChangeMapper;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesInfoChange;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.impl.PlnProdorderGuaDanServiceImpl;
import market.Mes.OrderManager.Plan.impl.PlnProdorderStatisticServiceImpl;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.Pickle.Performance.mapper.MesPlmDMapper;
import market.Mes.Pickle.Performance.mapper.MesPlmMMapper;
import market.Mes.Pickle.Performance.vo.MesPlmD;
import market.Mes.Rolling.Performance.mapper.MesRcmDMapper;
import market.Mes.Rolling.Performance.mapper.MesRcmMMapper;
import market.Mes.Rolling.Performance.vo.MesRcmD;
import market.Mes.Tpm.mapper.MesTpmDMapper;
import market.Mes.Tpm.mapper.MesTpmMMapper;
import market.Mes.Tpm.vo.MesTpmD;
import market.Mes.anneal.mapper.MesCrAnnealMMapper;
import market.Mes.anneal.vo.MesCrAnnealM;
import market.Qms.qcm.mapper.QcmJudgeUltimateMapper;
import market.Qms.qcm.vo.QcmJudgeUltimate;
import market.Slm.FundManagement.impl.SlmFundFirstDetailServiceImpl;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;
import market.Slm.OrderManagement.impl.IfSlmContractInfoServiceImpl;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

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;

@SuppressWarnings("rawtypes")
@RemoteService(path = "YdmProductInlistService")
public class YdmProductInlistServiceImpl extends
		BaseServiceImpl<YdmProductInlist, Object> implements
		YdmProductInlistService {

	/**
	 * 入库查询 不使用
	 * */
	public ResultModel doQueryWeb(CommonPage<YdmProductInlist> cp) {
		ResultModel rm = new ResultModel();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		PageModel<YdmProductInlist> pm = new PageModel<YdmProductInlist>(pageIndex, pageSize);
		try {
			YdmProductInlist yp = cp.getObject();
			String sWhere = "1=1";
			if (cp.getStartTime() != null && cp.getStartTime() != "") {
				String starttime = cp.getStartTime();
				sWhere = " and INDATE>=to_date(concat(" + "'" + starttime + "'"
						+ ",' 00:00:00'),'yyyy-MM-dd HH24:MI:SS') ";
			}
			if (cp.getEndTime() != null && cp.getEndTime() != "") {
				String endtime = cp.getEndTime();
				sWhere = " and INDATE<=to_date(concat(" + "'" + endtime + "'"
						+ ",' 00:00:00'),'yyyy-MM-dd HH24:MI:SS') ";
			}
			if (cp.getObject().getCoilno() != null
					&& cp.getObject().getCoilno() != "") {
				String coilno = cp.getObject().getCoilno();
				sWhere = " and COILNO like '%" + coilno + "%'";
			}
			if (cp.getObject().getJudgesteelcode() != null
					&& cp.getObject().getJudgesteelcode() != "") {
				String judgesteelcodeString = cp.getObject().getJudgesteelcode();
				sWhere = " and JUDGESTEELCODE like '%" + judgesteelcodeString
						+ "%'";
			}
			if (cp.getMemo1() != null && cp.getMemo1() != "") {
				double hmin = Double.valueOf(cp.getMemo1()).doubleValue();
				sWhere = " and THICK>=" + hmin;
			}
			if (cp.getMemo2() != null && cp.getMemo2() != "") {
				double hmax = Double.valueOf(cp.getMemo2()).doubleValue();
				sWhere = " and THICK<=" + hmax;
			}
			if (cp.getMemo3() != null && cp.getMemo3() != "") {
				double wmin = Double.valueOf(cp.getMemo3()).doubleValue();
				sWhere = " and WIDTH>=" + wmin;
			}
			if (cp.getMemo4() != null && cp.getMemo4() != "") {
				double wmax = Double.valueOf(cp.getMemo4()).doubleValue();
				sWhere = " and WIDTH<=" + wmax;
			}
			pm.setRows(this.getMapper(YdmProductInlistMapper.class).findWithCondition(yp, sWhere, "INBILLNO",
							(pageIndex - 1) * pageSize, pageSize));
			pm.setTotal(this.getMapper(YdmProductInlistMapper.class).countWithCondition(yp, sWhere));
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 入库查询(入库管理 已入库查询) SQL实现 条件+汇总+分页
	 * */
	public ResultModel doQueryWebBySQL(CommonPage<YdmProductDetail> cp) {
		ResultModel rm = new ResultModel();
		int pageSize = cp.getPageSize();
		int pageIndex = cp.getPageIndex();
		PageModel<YdmProductInlist> pm = new PageModel<YdmProductInlist>(pageIndex, pageSize);
		try {
			String regex = "^(\\d+\\.?\\d*)$";
			boolean isMatch = true;
			Object hmin = "", hmax = "", wmin = "", wmax = "";
			if (cp.getMemo1() != null && !"".equals(cp.getMemo1())) {
				isMatch = Pattern.matches(regex, cp.getMemo1().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmin = Double.valueOf(cp.getMemo1()).doubleValue();
			}
			if (cp.getMemo2() != null && !"".equals(cp.getMemo2())) {
				isMatch = Pattern.matches(regex, cp.getMemo2().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmax = Double.valueOf(cp.getMemo2()).doubleValue();
			}
			if (cp.getMemo3() != null && !"".equals(cp.getMemo3())) {
				isMatch = Pattern.matches(regex, cp.getMemo3().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmin = Double.valueOf(cp.getMemo3()).doubleValue();
			}
			if (cp.getMemo4() != null && !"".equals(cp.getMemo4())) {
				isMatch = Pattern.matches(regex, cp.getMemo4().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmax = Double.valueOf(cp.getMemo4()).doubleValue();
			}
			/**
			 * 各机组入库管理，前端传参仓库Storageattr="",
			 * 控制各机组入库管理的入库查询只查询正常入库的数据 20200927 兰ys
			 */
			if (StringUtils.isEmpty(cp.getObject().getStorageattr())) {
				cp.getObject().setIntype("500401");
			}
			pm.setRows(this.getMapper(YdmProductInlistMapper.class).doQueryWebBySQLs(
					(pageIndex-1)*pageSize, pageIndex*pageSize, cp.getStartTime(), cp.getEndTime(),
							cp.getObject(),hmin, hmax,wmin, wmax));
			pm.setTotal(this.getMapper(YdmProductInlistMapper.class).doQueryWebBySQLCount(cp.getStartTime(), cp.getEndTime(),
					cp.getObject(),hmin, hmax,wmin, wmax));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	public ResultModel doQueryPzWgtChange(CommonPage<YdmProductDetail> cp){
		ResultModel rm = new ResultModel();
		YdmProductDetail ypd = cp.getObject();
		String condition = " state in ('0','-1')";
		if (StringUtils.isNotEmpty(ypd.getCoilno())) {
			condition += " and coilno like '%"+ypd.getCoilno()+"%'";
		}
		if (StringUtils.isNotEmpty(ypd.getMaterailcoilno())) {
			condition += " and materailcoilno like '%"+ypd.getMaterailcoilno()+"%'";
		}
		if (StringUtils.isNotEmpty(ypd.getMachine_code())) {
			condition += " and machine_code = '"+ypd.getMachine_code()+"'";
		}
		List<YdmProductDetail> ypdList = this.getMapper(YdmProductDetailMapper.class).findWithCondition(null, condition, "createdate desc,coilno", 0, 0);
		rm.setState("200");
		rm.setData(ypdList);
		return rm;
	}
	
	/**
	 * 生成主键
	 * @return
	 * @throws Exception
	 */
	public String createINBILLNO() throws Exception {
		try {
			String inbillno = "";
			List<HashMap> list = this.getMapper(YdmProductInlistMapper.class)
					.getNo("IN"+ (new SimpleDateFormat("yyyyMMdd").format(new Date())));
			inbillno = (String) list.get(0).get("MAXNO");
			return inbillno;
		} catch (Exception ex) {
			throw (ex);
		}
	}

	/**
	 * 入库管理-入库确认
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doConfirm(CommonPage<YdmProductDetail> cp) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		
		List<YdmProductDetail> list = cp.getObjectList();
		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);
		int i = 0;
		for (YdmProductDetail ypd : list) {
			if (ypd.getCoilno()==null) {
				continue;
			}
			String coilno = ypd.getCoilno();//卷号
			String storageattr = ypd.getStorageattr();//开始的仓库
			ypd = this.getMapper(YdmProductDetailMapper.class).findById(ypd.getCoilno());
			//  ************针对原料库的手持入库的特殊处理************************
			if (ypd==null || StringUtils.isEmpty(ypd.getMaterailcoilno())) {
				String condition = " materailcoilno = '"+coilno+"'";
				List<YdmProductDetail> ypdliList = this.getMapper(YdmProductDetailMapper.class).findWithCondition(null, condition, null, 0, 0);
				if (CollectionUtils.isNotEmpty(ypdliList)) {
					ypd = ypdliList.get(0);
				}
			}
			//  ***************************************************************
			if (!"-1".equals(ypd.getState()) && ypd.getStorageattr()!=null) {
				rm.setState("500");
				rm.setMsgInfo(ypd.getCoilno() + "_" + ypd.getMaterailcoilno() + " 不是待入库状态,无法进行入库操作！");
				return rm;
			}
			//仓库为null,默认是原料入库
			if (StringUtils.isEmpty(ypd.getStorageattr())) {
				//验证仓库是进原料库还是贸易库
				ypd.setStorageattr("500201");
				if (StringUtils.isNotEmpty(cp.getMemo1()) && cp.getMemo1().startsWith("1005")) {
					ypd.setStorageattr("500205");
				}
			}
			// 修改库存信息
			ypd.setSource("1");
			ypd.setState("0");
			ypd.setIndate(now);
			ypd.setCreater(username);
			ypd.setInorder(order);
			ypd.setInteam(team);
			ypd.setQuantity(1);
			ypd.setSteelcode(ypd.getJudgesteelcode());
			ypd.setPhysid(cp.getMemo1());
			ypd.setChemid(cp.getMemo2());
			//设置区域和垛位，返回给手持的前端
			YdmBaseButtressconfig ybb = this.getMapper(YdmBaseButtressconfigMapper.class).findById(cp.getMemo1());
			if (ybb!=null) {				
				ypd.setAreaname(ybb.getButtressname());
			}
			YdmBaseButtressconfig yb = this.getMapper(YdmBaseButtressconfigMapper.class).findById(cp.getMemo2());
			if (yb!=null) {				
				ypd.setButtressname(yb.getButtressname());
			}
			ypd.setPosition(cp.getMemo3());
			ypd.setLocality(cp.getMemo3());
			rm.setData(ypd);
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			// 调用生产计划接口进行物料跟踪
			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("物料跟踪失败");
			}
			// 插入入库信息
			YdmProductInlist ypi = new YdmProductInlist();
			ypi.setInbillno(this.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.setLocality("1");
			if (cp.getMemo3() != null && cp.getMemo3() != ""){
				ypi.setPosition(String.valueOf(Integer.valueOf(cp.getMemo3()).intValue() + i).toString());
			}				
			ypi.setMemo(cp.getMemo4());
			ypi.setButtressno(cp.getMemo2());
			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);
			
			
			// 原料待入库默认没有仓库：取消插入出库记录；20220517 刘侣
			//原料库和酸洗原料库
//			if ("500201".equals(storageattr)||"500208".equals(storageattr)) {
//				YdmProductOutlist ypo = new YdmProductOutlist();
//				ypo.setOuttype("500502");
//				ypo.setOutoperator(username);
//				ypo.setOutdate(now);
//				ypo.setOutorder(order);
//				ypo.setOutteam(team);
//				ypo.setCreater(username);
//				ypo.setCreatedate(now);
//				ypo.setOutbillno(this.getBean(YdmProductOutlistServiceImpl.class).createOUTBILLNO());
//				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("500205");
//				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());
//				ypo.setButtressno(ypd.getButtressno());
//				// 4.24
//				if (ypd.getLocality() != null && !ypd.getLocality().equals("")) {
//					ypo.setLocality((long) Integer.valueOf(ypd.getLocality()).intValue());
//				}
//				ypo.setLayer(ypd.getLayer());
//				//this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
//			}

			// 删除原有的垛位，插入新的垛位信息				
			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);
			i++;

			// 成品入库调生产接口
			/*if ("500203".equals(ypd.getStorageattr())&&ypd.getProdorderno()!= null&&!"".equals(ypd.getProdorderno())) {
					ResultModel rmValid = this.getBean(MesApiServiceImpl.class).YdmUpdateOrderStatisticsInfo(ypd.getProdorderno(),ypd.getCoilno(), "1");
				if (!"200".equals(rmValid.getState())) {
					throw new Exception(rmValid.getMsgInfo());
				}
			}*/
			
			// 成品   生产订单统计 统计量并修改生产订单状态
			try {
				if ("500203".equals(ypd.getStorageattr())) {
					this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(ypd.getCoilno(), 2, true);
				}
			} catch (Exception e) {
				throw new Exception("调用统计生产订单量接口出错");
			}
			
			
			// 原料库卷入库一体化卷自动执行挂单：
			if (ypd.getLzorderno() != null) {
				if (ypd.getCoilno() != null && ypd.getOrderno() == null && ypd.getCoilno().length() <= 8 && "0".equals(ypd.getState())) {
					// 校验订单是否存在且有效：
					String condition = "contract_no || contract_line_seq || order_seq = '"+ypd.getLzorderno() + ypd.getLzorderno().substring(ypd.getLzorderno().length() - 3)+"' and nvl(change_flag,0) <> '1'";
					List<SlmOrderInfo> orderL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
					PlnProdorder pp = new PlnProdorder();
					
					if (orderL == null || orderL.size() <= 0) {
						throw new Exception("订单：" + ypd.getLzorderno() + " 不存在");
					}
					
					pp.setOrder_no(orderL.get(0).getContract_no() + orderL.get(0).getContract_line_seq() + orderL.get(0).getOrder_seq());
					List<PlnProdorder> ppL = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 0);
					if (orderL != null && orderL.size() > 0 && ppL != null && ppL.size() > 0) {
						
						// 且生产订单状态不为：生产完成，发货完成，订单保留：0PAA50 0PAA60 0PAA20 ，这个逻辑先不加，20231024刘侣
//						if ("0PAA50" ppL.get(0).getStatus()) {
//							
//						}
						// end
						
						// 执行挂单：
						CommonPage<String[]> CP = new CommonPage<>();
						String[] arrs = {ypd.getCoilno()};
						CP.setObject(arrs);
						CP.setMemo1(ppL.get(0).getProd_order_no());
						ResultModel gdRes = this.getBean(PlnProdorderGuaDanServiceImpl.class).doRelationOrderAuto(CP);
						if ("500".equals(gdRes.getState())) {
							throw new Exception("订单：" + ypd.getLzorderno() + " 原料自动挂单失败" + gdRes.getMsgInfo());
						}
						// 成功，记录log：
						MesOprLog mol = new MesOprLog("物流管理", "原料自动脱挂单", "原料入库自动挂单", username, opr_time, ypd.getCoilno(), null, null, null, ppL.get(0).getOrder_no());
						this.getMapper(MesOprLogMapper.class).insert(mol);
					} else {
//						System.out.println("订单不存在：" + ypd.getLzorderno());
						throw new Exception("订单：" + ypd.getLzorderno() + " 不存在");
					}
				} else {
					throw new Exception("卷不满足条件：");
				}
			} else {
				throw new Exception("卷信息里：" + ypd.getLzorderno() + " 不存在");
			}
			
			
			
			// 如果是冷轧厂委托加工的轧硬卷入库，则给冷轧厂返写状态位：
			// 合同号一定是用WZ3开头，轧硬卷接收后更新字段：C_TBL02_COIL_COMM.ROUTE
			// 移送优特钢标识0待移送 1已移送未接收 2已接收 3已退回
			// 我移送给你之后这个字段会变成1 ，你接收之后更新成2
//			if ("500201".equals(ypd.getStorageattr()) && (ypd.getLzorderno().startsWith("WZ53") || ypd.getLzorderno().startsWith("WZ52") || ypd.getLzorderno().startsWith("WZ51"))) {
////				 向冷轧厂返写：
//				ResultModel rmFX = this.getBean(IfSlmContractInfoServiceImpl.class).doUpdateC_TBL02_COIL_COMM_ROUTE(ypd.getMaterailcoilno(), "2");
//				if (rmFX.getState()==null || !"200".equals(rmFX.getState())) {
//					throw new Exception("返写冷轧委托加工接收状态失败，请联系系统维护人员");
//				}
//				// 插入日志：
//				MesOprLog mol2 = new MesOprLog("物流管理", "入库管理", "入库", username, opr_time, ypd.getCoilno(), null, null, null, "冷轧厂加工委托卷子返写状态成功：2");
//				this.getMapper(MesOprLogMapper.class).insert(mol2);
//			}
			
			String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
			if ("1".equals(isOpen)) {
			
				// 记录成本异动点：20230811刘侣 20230824
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				
				// 当前产线：
				String currentMachine = "YT1";
				
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("55A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				
				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 = "YT1";
				
				cd.setSysId("IA");
				
				
				cd.setBeTransUnit("t");
				
				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.setBeTransWgt(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
				
				
				cd.setInvId(ypd.getMaterailcoilno());
				
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");

				// setSrcFac根据卷的物料属性去判断：20231031刘侣
				cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
				
				// 抛送热轧出库异动点：
				cd.setDataTypeIdx("O");
				cd.setLocNo(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
				cd.setManageip(cd.getInvId().startsWith("R") ? "热轧" : "酸轧");
				cd.setRefnoA("");
				cd.setOrderItem("");
				cd.setCrntMill(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
				cd.setExecJobFunc("N");
				cd.setLastMill(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
				cd.setProdTypeNo(cd.getInvId().startsWith("R") ? "HCR" : "CCR");
				cd.setAppId((cd.getInvId().startsWith("R") ? "热卷" : "酸轧") + "转出");
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				// end
				
				cd.setDataTypeIdx("N");
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setRefnoA(ypd.getMaterailcoilno()); // 投料卷号
				cd.setOrderItem(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setExecJobFunc("N");
				cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdTypeNo(cd.getInvId().startsWith("L") ? "CCR": "HCR");
				cd.setAppId("优特原料入库");
				
				// 存入表：
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				
				
			}
			
			MesOprLog mol = new MesOprLog("物流管理", "入库管理", "入库", username, opr_time, ypd.getCoilno(), null, null, null, null);
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		rm.setState("200");
		
		rm.setMsgInfo("入库确认成功");
		return rm;
	}
	
	/**
	 * 入库管理 撤销入库
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doCancel(CommonPage<YdmProductInlist> cp) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		
		try {
			List<YdmProductInlist> list = cp.getObjectList();
			for (YdmProductInlist ypi : list) {
				YdmProductDetail YPD = this.getMapper(YdmProductDetailMapper.class).doFind(ypi.getCoilno(), null);
				if ("2".equals(YPD.getState())) {
					rm.setData("500");
					rm.setMsgInfo("物料【"+YPD.getCoilno()+"】已经开提货单，请先撤销提货单！");
					return rm;
				}else if ("5".equals(YPD.getState())) {
					rm.setData("500");
					rm.setMsgInfo("物料【"+YPD.getCoilno()+"】已经出库，无法撤销入库！");
					return rm;
				}
				
				// 此时可能state：0
				// 原料库卷入库一体化卷自动执行脱单：
				if (YPD.getLzorderno() != null ) {
					if (YPD.getCoilno() != null && YPD.getOrderno() != null && YPD.getCoilno().length() <= 8 && "0".equals(YPD.getState()) && "500201".equals(YPD.getStorageattr())) {
						if (YPD.getLzorderno().equals(YPD.getOrderno().substring(0, YPD.getOrderno().length() - 3))) {
							// 校验订单是否存在且有效：
							String condition = "contract_no || contract_line_seq || order_seq = '"+YPD.getOrderno()+"' and nvl(change_flag,0) <> '1'";
							List<SlmOrderInfo> orderL = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
							PlnProdorder pp = new PlnProdorder();
							pp.setOrder_no(orderL.get(0).getContract_no() + orderL.get(0).getContract_line_seq() + orderL.get(0).getOrder_seq());
							List<PlnProdorder> ppL = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 0);
							if (orderL != null && orderL.size() > 0 && ppL != null && ppL.size() > 0) {
								// 执行脱单：
								// doMaterialReplace
								CommonPage<PlnMaterielDetail> oci = new CommonPage<>();
								List<PlnMaterielDetail> lpm = new ArrayList<>();
								PlnMaterielDetail pmd = new PlnMaterielDetail();
								pmd.setObject_no(YPD.getCoilno());
								lpm.add(pmd);
								oci.setObjectList(lpm);
								oci.setMemo1("原料撤销入库自动脱单，卷号：" + YPD.getCoilno() + " " + ppL.get(0).getOrder_no());
								
								ResultModel tdRes = this.getBean(SlmFundFirstDetailServiceImpl.class).tuodan(oci);
								
								if ("500".equals(tdRes.getState())) {
									throw new Exception("订单：" + ppL.get(0).getOrder_no() + " 原料自动脱单失败");
								}
								// 成功，记录log：
								MesOprLog mol = new MesOprLog("物流管理", "原料自动脱挂单", "原料撤销入库自动脱单", username, opr_time, YPD.getCoilno(), null, null, null, ppL.get(0).getOrder_no());
								this.getMapper(MesOprLogMapper.class).insert(mol);
							} else {
//								System.out.println("订单不存在：" + ppL.get(0).getOrder_no());
								throw new Exception("订单：" + ppL.get(0).getOrder_no() + " 不存在");
							}
						} else {
//							System.out.println("订单：" + YPD.getOrderno() + " 与冷轧订单不一致" + YPD.getLzorderno());
							throw new Exception("订单：" + YPD.getOrderno() + " 与冷轧订单不一致" + YPD.getLzorderno());
						}
						
					}
				}
				
				//删除入库信息
				if (ypi.getInbillno() != null && ypi.getInbillno() != "")
					this.getMapper(YdmProductInlistMapper.class).doDelete(ypi.getInbillno());
				//删除垛位信息
				if ((ypi.getBoxno() != null && ypi.getBoxno() != "") 
						|| (ypi.getCoilno() != null && ypi.getCoilno() != ""))
					this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypi.getCoilno(), ypi.getBoxno());
				//原料库和贸易外库的撤销入库，需要删除出库记录
				if ("500201".equals(ypi.getStorageattr())||"500205".equals(ypi.getStorageattr())) {
					this.getMapper(YdmProductOutlistMapper.class).doDeleteRecent(ypi.getCoilno(), "500502");
				}

				// 修改库存信息
				YdmProductDetail ypd = new YdmProductDetail();
				ypd.setCoilno(ypi.getCoilno());
				ypd.setBoxno(ypi.getBoxno());
				// "500201".equals(ypi.getStorageattr())|| 只允许贸易外库置为0状态：20230410刘侣
				if ("500205".equals(ypi.getStorageattr())) {
					ypd.setStorageattr("");
					ypd.setState("0");
				} else if ("500201".equals(ypi.getStorageattr())) {
					ypd.setStorageattr("");
					ypd.setState("-1");
				} else {
					ypd.setState("-1");
				}
				// end
				ypd.setUpdater(username);
				ypd.setUpdatedate(new Date());
				this.getMapper(YdmProductDetailMapper.class).update(ypd);
				//调用生产计划模块接口进行物料跟踪撤销
				PrcMaterielProcess pmp = new PrcMaterielProcess();
				pmp.setObject_no(ypd.getCoilno());
				pmp.setPrc_code("5BYA05");
				pmp.setKeep_sametime_status(0);
				pmp.setRemark("接收入库撤销");
				String tmp = this.getBean(MesApiServiceImpl.class).ARRAYLIST(pmp).getState();
				if(!"0".equals(tmp)) {
					//throw new Exception("实物["+ypd.getCoilno()+"]状态已发生改变，不能撤销！");
				}
				//20191205清除质量综合判定信息
				QcmJudgeUltimate qju = new QcmJudgeUltimate();
				qju.setMaterial_no(ypd.getCoilno());
				List<QcmJudgeUltimate> qjuList = this.getMapper(QcmJudgeUltimateMapper.class).find(qju, 0, 0);
				if (qjuList!=null && qjuList.size()>0) {
					for (QcmJudgeUltimate q : qjuList) {
						this.getMapper(QcmJudgeUltimateMapper.class).delete(q.getUtm_id());
					}
				}
				
				//成品库的   生产订单统计 统计量并修改生产订单状态
				try {
					if ("500203".equals(ypd.getStorageattr())) {
						this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(ypd.getCoilno(), 2, false);
					}
				} catch (Exception e) {
					throw new Exception("调用统计生产订单量接口出错");
				}
				
				// 如果是冷轧厂委托加工的轧硬卷入库，则给冷轧厂返写状态位：
				// 合同号一定是用WZ3开头，轧硬卷接收后更新字段：C_TBL02_COIL_COMM.ROUTE
				// 移送优特钢标识0待移送 1已移送未接收 2已接收 3已退回
				// 我移送给你之后这个字段会变成1 ，你接收之后更新成2
//				if ("500201".equals(ypd.getStorageattr()) && (ypd.getLzorderno().startsWith("WZ53") || ypd.getLzorderno().startsWith("WZ52") || ypd.getLzorderno().startsWith("WZ51"))) {
//					// 向冷轧厂返写：
//					ResultModel rmFX = this.getBean(IfSlmContractInfoServiceImpl.class).doUpdateC_TBL02_COIL_COMM_ROUTE(ypd.getMaterailcoilno(), "1");
//					if (rmFX.getState()==null || !"200".equals(rmFX.getState())) {
//						throw new Exception("返写冷轧委托加工接收状态失败，请联系系统维护人员");
//					}
//					// 插入日志：
//					MesOprLog mol2 = new MesOprLog("物流管理", "入库管理", "撤销入库", username, opr_time, ypd.getCoilno(), null, null, null, "冷轧厂加工委托卷子返写状态成功：1");
//					this.getMapper(MesOprLogMapper.class).insert(mol2);
//				}
				
				
				String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
				if ("1".equals(isOpen)) {
				
					// 记录成本异动点：20230811刘侣 20230824
					ComBaseCbYdd cd = new ComBaseCbYdd();
					cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
					cd.setInstDisp("01");
					cd.setDataTypeIdx("N");
					// 当前产线：
					String currentMachine = "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("55A");
					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 = "YT1";
					cd.setRefnoA(YPD.getMaterailcoilno()); // 投料卷号
					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("HCR");
					cd.setAppId("优特原料撤销入库");
					cd.setInvId(YPD.getMaterailcoilno());
					cd.setProdTypeNo(cd.getInvId().startsWith("L") ? "CCR": "HCR");
					cd.setInvQty("1");
					cd.setSrcFac("1");
					cd.setGrade("1"); // 正品　1　协议　3　次品　5
					cd.setProdClassNo("H");

					// setSrcFac根据卷的物料属性去判断：20231031刘侣
					cd.setSrcFac("507101".equals(YPD.getObject_attr()) ? "1" : "3");
					
					// 存入表：
					this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), YPD.getMaterailcoilno());
					
					// 抛送热轧出库异动点：
					cd.setDataTypeIdx("O");
					cd.setLocNo(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
					cd.setManageip(cd.getInvId().startsWith("R") ? "热轧" : "酸轧");
					cd.setRefnoA("");
					cd.setOrderItem("");
					cd.setCrntMill(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
					cd.setExecJobFunc("D");
					cd.setLastMill(cd.getInvId().startsWith("R") ? "RZ1" : "SZ1");
					cd.setProdTypeNo(cd.getInvId().startsWith("R") ? "HCR" : "CCR");
					cd.setAppId((cd.getInvId().startsWith("R") ? "热卷" : "酸轧") + "撤销转出");
					this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), YPD.getMaterailcoilno());
					// end
				}
				
				
				MesOprLog mol = new MesOprLog("物流管理", "入库管理", "撤销入库", username, opr_time, ypd.getCoilno(), null, null, null, null);
				this.getMapper(MesOprLogMapper.class).insert(mol);				
			}
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，撤销入库失败!");
			throw ex;
		}
		return rm;
	}

	/**
	 * 外购入库管理 入库确认(库操作) memo1，2传成分结果id和材质结果id,3传供应商代码
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doConfirmOut(CommonPage<YdmProductDetail> cp) 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);
		String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		YdmProductDetail ypd = cp.getObject();
		try {			
			// 插入库存信息
			IfRawMtrCoilM m = new IfRawMtrCoilM();
			ypd.setCreater(username);
			ypd.setCreatedate(now);
			ypd.setCoiltype("0");
			ypd.setSource("1");
			ypd.setState("0");
			ypd.setIndate(now);
			ypd.setInorder(order);
			ypd.setInteam(team);
			ypd.setSteelcode(ypd.getJudgesteelcode());
			if (cp.getMemo1() != null && cp.getMemo1() != "") {
				ypd.setChemid(cp.getMemo1());
				m.setChemid(cp.getMemo1());
			}
			if (cp.getMemo2() != null && cp.getMemo2() != "") {
				ypd.setPhysid(cp.getMemo2());
				m.setPhysid(cp.getMemo2());
			}
			this.getMapper(YdmProductDetailMapper.class).doInsert(ypd);
			// 调用生产计划模块接口进行物料跟踪
			PrcMaterielProcess pmp = new PrcMaterielProcess();
			Date date = new Date();
			pmp.setObject_no(ypd.getCoilno());
			pmp.setPrc_code("5BYA05");
			pmp.setCreate_time(date);
			pmp.setRemark("外购入库");
			pmp.setCreate_man_name(username);
			PrcMaterielProcess pmp1 = new PrcMaterielProcess();
			pmp1.setObject_no(ypd.getCoilno());
			pmp1.setPrc_code("5BYA04");
			pmp1.setCreate_time(date);
			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("物料跟踪失败");
			}
			// 插入原料主实绩
			m.setCreateOpr(username);
			m.setCreateTime(new Date());
			m.setStatus("1");
			m.setCoilNo(ypd.getCoilno());
			m.setCoilSource(ypd.getSource());
			m.setCoilSort(ypd.getMaterailtype());
			m.setSupplierCode(cp.getMemo3());
			m.setSupplierName(ypd.getMaterailsupplier());
			m.setHeatno(ypd.getHeatno());
			m.setPrdCode(ypd.getProd_code());
			m.setPrdName(ypd.getProd_name());
			m.setStdCode(ypd.getStd_code());
			m.setStdName(ypd.getStd_name());
			m.setSteelCode(ypd.getJudgesteelcode());
			m.setRemark(ypd.getMemo());
			m.setCoilThk(ypd.getThick());
			m.setCoilWdt(ypd.getWidth());
			m.setCoilLen(ypd.getLength());
			m.setCoilInnDia(ypd.getDiameter_inn());
			m.setCoilOutDia(ypd.getDiameter_out());
			m.setCoilThrWgt(ypd.getTheoryweight());
			m.setCoilActWgt(ypd.getFactweight());
			this.getMapper(IfRawMtrCoilMMapper.class).insert(m);
			// 插入入库信息
			YdmProductInlist ypi = new YdmProductInlist();
			ypi.setCreater(username);
			ypi.setCreatedate(new Date());
			ypi.setIntype("500406");
			ypi.setIndate(new Date());
			ypi.setInorder(order);
			ypi.setInteam(team);
			ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
			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.setOperator(username);
			ypi.setLocality("1");
			if (ypd.getLocality() != null && ypd.getLocality() != "")
				ypi.setPosition(ypd.getLocality());
			ypi.setMemo(ypd.getMemo());
			ypi.setButtressno(ypd.getButtressno());
			
			// 加入物料属性：20230725刘侣
			ypi.setObj_attr_in(ypd.getObject_attr());
			// end
			
			this.getMapper(YdmProductInlistMapper.class).insert(ypi);
			// 插入垛位信息
			YdmProductButtresslist ypb = new YdmProductButtresslist();
			ypb.setCreater(username);
			ypb.setCreatedate(new Date());
			ypb.setLayer(1);
			if (ypd.getLocality() != null && ypd.getLocality() != ""){
				ypb.setLocality(Integer.parseInt(ypd.getLocality()));
			}
			ypb.setButtressno(ypd.getButtressno());
			//判断现有垛位上是否存在物料
			String condition = " and buttressno = '"+ypb.getButtressno()+"' and layer = '"+ypb.getLayer()+"' and locality = '"+ypb.getLocality()+"'";
			int count = this.getMapper(YdmProductButtresslistMapper.class).countWithCondition(null, condition);
			if (count > 0) {
				throw new Exception("目标垛位已经存在物料信息，无法外购入库");
			}
			ypb.setStorageattr(ypd.getStorageattr());
			ypb.setAreano(ypd.getAreano());
			ypb.setCoilno(ypd.getCoilno());
			ypb.setBoxno(ypd.getBoxno());
			this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb);
			
			MesOprLog mol = new MesOprLog("物流管理", "外购入库管理", "入库确认", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);			
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("确认失败!");
			ex.printStackTrace();
			throw ex;
		}
		rm.setState("200");
		return rm;
	}

	/**
	 * 外购入库管理 撤销入库
	 * 
	 * @throws Exception
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doCancelOut(CommonPage<YdmProductInlist> cp) throws Exception {
		ResultModel rm = new ResultModel();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<YdmProductInlist> list = cp.getObjectList();
		for (YdmProductInlist ypi : list) {
			// 删除入库信息
			if (ypi.getInbillno() != null && ypi.getInbillno() != ""){
				this.getMapper(YdmProductInlistMapper.class).doDelete(ypi.getInbillno());
			}		
			// 删除垛位信息，库存信息
			if (StringUtils.isNotEmpty(ypi.getCoilno())) {
				this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypi.getCoilno(), ypi.getBoxno());
				// 调用生产计划模块接口进行物料跟踪撤销
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(ypi.getCoilno(),ypi.getBoxno());
				if (ypd != null && ypd.getCoilno() != null) {
					PrcMaterielProcess pmp = new PrcMaterielProcess();
					pmp.setObject_no(ypd.getCoilno());
					pmp.setPrc_code("5BYA05");
					pmp.setKeep_sametime_status(0);
					pmp.setRemark("外购入库撤销");
					this.getBean(MesApiServiceImpl.class).ARRAYLIST(pmp).getState();
					
					
					String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
					if ("1".equals(isOpen)) {
					
						// 记录成本异动点：20230811刘侣 20230824 外购入库撤销
						ComBaseCbYdd cd = new ComBaseCbYdd();
						cd.setCoilStus("0"); // 综判前算半成品，综判入库后算成品
						cd.setInstDisp("01");
						cd.setDataTypeIdx("O");
						// 当前产线：
						String currentMachine = "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("12AB");
						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 = "YT1";
						cd.setRefnoA(ypd.getMaterailcoilno()); // 投料卷号
						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("HCR");
						cd.setAppId("优特钢外购原料卷撤销入库");
						// 外购入库也抛原料卷号，20231214 董提出：
						cd.setInvId(ypd.getMaterailcoilno());
						cd.setInvQty("1");
						cd.setSrcFac("3");
						cd.setGrade("1"); // 正品　1　协议　3　次品　5
						cd.setProdClassNo("H");

						// setSrcFac根据卷的物料属性去判断：20231031刘侣
						cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
						
						// 存入表：
						this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
						// end
					}
					
					
				}
				MesOprLog mol = new MesOprLog("物流管理", "外购入库管理", "撤销入库", username, opr_time, ypi.getCoilno(), null, null, null, "原料卷号："+ypi.getMaterailcoilno());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				this.getMapper(YdmProductDetailMapper.class).doDelete(ypi.getCoilno(), ypi.getBoxno());
			}
		}
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 各机组入库管理
	 * @param cp	memo1：垛位   memo2：位置 memo3：层数
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doConfirmByMachine(CommonPage<YdmProductDetail> cp) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		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);	
		List<YdmProductDetail> list = cp.getObjectList();
		
		int i = 0;
		for (YdmProductDetail YPD : list) {
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(YPD.getCoilno());
			if (ypd==null) {
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】不存在，无法入库");
				rm.setState("500");
				return rm;
			}
			if (!"-1".equals(ypd.getState())) {
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】不是待入库状态，无法入库");
				rm.setState("500");
				return rm;
			}
			if (ypd.getStorageattr()==null || "".equals(ypd.getStorageattr())) {
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】仓库为空，无法入库");
				rm.setState("500");
				return rm;
			}
			if (ypd.getMachine_code()==null || "".equals(ypd.getMachine_code())) {
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】机台为空，无法入库");
				rm.setState("500");
				return rm;
			}
			// 等上线后解开：20191001
//			if (ypd.getJudgeresult()==null || "".equals(ypd.getJudgeresult())) {
//				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】综判为空，无法入库");
//				rm.setState("500");
//				return rm;
//			}
			// end
			
			//1. 修改库存信息
			if ("500202".equals(ypd.getStorageattr())) {
				YPD.setCoiltype("1");//中间卷
			}else if ("500203".equals(ypd.getStorageattr())) {
				YPD.setCoiltype("2");//成品卷
			}
			
			YPD.setState("0");
			YPD.setIndate(now);
			YPD.setInorder(order);
			YPD.setInteam(team);
			YPD.setQuantity(1);
//			YPD.setSteelcode(ypd.getJudgesteelcode());// 废掉20240815刘侣
			// 修改酸洗标识
			if ("M0010".equals(ypd.getMachine_code())) {
				YPD.setSx_valid_flg("1");
			}
			
			// 插入当前工序对应的交货状态：20240516 刘侣
			String deliveryState = this.getBean(SlmFundFirstDetailService.class).getDelStateFJH(ypd.getCoilno());
			YPD.setYsstate(deliveryState);
			
			this.getMapper(YdmProductDetailMapper.class).update(YPD);
			
			// 插入入库信息
			YdmProductInlist ypi = new YdmProductInlist();
			ypi.setInbillno(this.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());
			ypb.setButtressno(cp.getMemo1());//垛位
			ypb.setLocality(Integer.valueOf(cp.getMemo2())+i);//位置
			ypb.setLayer(Integer.valueOf(cp.getMemo3()));//层数
			ypb.setStorageattr(ypd.getStorageattr());
			YdmBaseButtressconfig ybb = this.getMapper(YdmBaseButtressconfigMapper.class).findById(ypb.getButtressno());
			if (ybb!=null) {
				ypb.setAreano(ybb.getSortcode());//区域
			}
			ypb.setCoilno(ypd.getCoilno());
			ypb.setBoxno(ypd.getBoxno());
			this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb);
						
			// 调用生产计划接口进行物料跟踪
			PrcMaterielProcess pmp = new PrcMaterielProcess();
			pmp.setObject_no(ypd.getCoilno());
			pmp.setPrc_code("5BYA05");
			pmp.setCreate_time(now);
			pmp.setRemark("正常入库:"+opr_time);
			pmp.setCreate_man_name(username);
			int tmp = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
			if (tmp == -1) {
				throw new Exception("物料跟踪失败");
			}
			
			// 优特属性的 头尾卷 和 边丝卷 不抛产出异动点：xuli 20231227 刘侣
			String lastChar = ypd.getCoilno().substring(ypd.getCoilno().length()-1);
			if ("507101".equals(ypd.getObject_attr()) && ("B".equals(lastChar) || "H".equals(lastChar))) {
				// 不抛送异动点：只记录操作记录；
			} else {
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("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(userId);
				cd.setActivityId("11A");
				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 = 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("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");
				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");

				// 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.setActivityId("11A");
				cd.setExecJobFunc("N");
				cd.setDataTypeIdx("O");
				cd.setProdTypeNo("CTR");
				cd.setCoilStus("0"); // 综判前算半成品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 + "产出");
				
				// 如果没有订单号，则取最后一次脱单的订单号：
				if (ypd.getOrderno() == null) {
					String lastord = this.getMapper(YdmProductDetailMapper.class).getLastOrd(ypd.getCoilno());
					cd.setOrderItem(lastord);
				}
				
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				
//				// 二抛：酸洗重量调整（如果有重量改了也抛送一条）：接收原料和上料之间不存在重量调整，所以不需要：20230913刘侣：还是需要这个节点的：20230918刘侣
				cd.setActivityId("11AA");
				cd.setExecJobFunc("N");
				cd.setDataTypeIdx("O");
				cd.setProdTypeNo("CTR");
				cd.setCoilStus("0"); // 综判前算半成品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
				cd.setAppId("优特" + currentMName + "重量调整");
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				
				// 入库后立马发送综判异动点：没有的直接给合格 20240509刘侣
				this.getBean(SlmFundFirstDetailService.class).receiveUltiYdd(ypd.getCoilno());
				
			}
			
			// 入库的时候检测是否存在综判数据，如果不存在，则让质量系统重新推送一遍数据过来：20231122刘侣
			if (ypd.getJudgeresult() == null || "".equals(ypd.getJudgeresult())) {
				ResultModel rejRes = this.getBean(SlmFundFirstDetailService.class).reAutoUltiJudgeRK(ypd.getCoilno());
				if (!"200".equals(rejRes.getState())) {
					throw new Exception(rejRes.getMsgInfo());
				}
			}
			
			MesOprLog mol = new MesOprLog("物流管理", "各机组入库管理", "入库确认", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			i++;
		}
		rm.setState("200");		
		rm.setMsgInfo("入库确认成功");
		return rm;
	}
	
	
	/**
	 * 根据卷号获取该卷的投料卷号
	 * 20230814刘侣
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public String doQueryTl(String coilNo) throws Exception {
		String no = "";
		if (coilNo == null || "".equals(coilNo)) {
			return "";
		}
		if (coilNo.contains("F")) {
			no = this.getMapper(MesCrSlittingDMapper.class).findM(coilNo);
		} else if (coilNo.contains("K")) { 
			no = this.getMapper(MesCrCrossCuttingDMapper.class).findM(coilNo);
		} else if (coilNo.contains("T")) { 
			no = this.getMapper(MesCrAnnealMMapper.class).findM(coilNo);
		} else if (coilNo.contains("P")) { 
			no = this.getMapper(MesTpmMMapper.class).findM(coilNo);
		} else if (coilNo.contains("L")) {
			no = this.getMapper(MesRcmMMapper.class).findM(coilNo);
		} else if (coilNo.contains("S")) {
			no = this.getMapper(MesPlmMMapper.class).findM(coilNo);
		} else {
			return coilNo;
		}
		return no;
	}
	
	
	/**
	 * 根据卷号获取该卷的产出卷信息
	 * 20230818刘侣
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public HashMap doQueryCchu(String coilNo) throws Exception {
		
		HashMap hm = new HashMap();
		if (coilNo == null || "".equals(coilNo)) {
			return hm;
		}
		
		// coilno, width,thick,length,orderno,steelcode,weight
		if (coilNo.contains("F")) {
			MesCrSlittingD no = this.getMapper(MesCrSlittingDMapper.class).findD(coilNo);
			hm.put("coilno", no.getCoil_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getCoil_act_wgt());
		} else if (coilNo.contains("K")) { 
			MesCrCrossCuttingD no = this.getMapper(MesCrCrossCuttingDMapper.class).findD(coilNo);
			hm.put("coilno", no.getPacking_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getPacking_net_wgt());
		} else if (coilNo.contains("T")) { 
			MesCrAnnealM no = this.getMapper(MesCrAnnealMMapper.class).findD(coilNo);
			hm.put("coilno", no.getCoil_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getCoil_act_wgt());
		} else if (coilNo.contains("P")) { 
			MesTpmD no = this.getMapper(MesTpmMMapper.class).findD(coilNo);
			hm.put("coilno", no.getCoil_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getCoil_act_wgt());
		} else if (coilNo.contains("L")) {
			MesRcmD no = this.getMapper(MesRcmMMapper.class).findD(coilNo);
			hm.put("coilno", no.getCoil_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getCoil_act_wgt());
		} else if (coilNo.contains("S")) {
			MesPlmD no = this.getMapper(MesPlmMMapper.class).findD(coilNo);
			hm.put("coilno", no.getCoil_no());
			hm.put("width", no.getAct_wdt());
			hm.put("thick", no.getAct_thk());
			hm.put("length", no.getAct_len());
			hm.put("orderno", no.getOrder_no());
			hm.put("steelcode", no.getSteel_code());
			hm.put("weight", no.getCoil_act_wgt());
		} else {
			return hm;
		}
		return hm;
	}
	
	
	/**
	 * 各机组入库的撤销入库
	 * @param cp
	 * @return测好
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doCancelConfirmByMachine(CommonPage<YdmProductInlist> cp) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		List<YdmProductInlist> list = cp.getObjectList();
		for (YdmProductInlist ypi : list) {
			YdmProductDetail YPD = this.getMapper(YdmProductDetailMapper.class).doFind(ypi.getCoilno(), null);
			if ("2".equals(YPD.getState())) {
				rm.setData("500");
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】已经开提货单，请先撤销提货单！");
				return rm;
			}else if ("5".equals(YPD.getState())) {
				rm.setData("500");
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】已经出库，无法撤销入库！");
				return rm;
			}else if ("6".equals(YPD.getState())) {
				rm.setData("500");
				rm.setMsgInfo("物料【"+YPD.getCoilno()+"】质量锁定，无法撤销入库！");
				return rm;
			}
			
			//1. 删除入库信息
			this.getMapper(YdmProductInlistMapper.class).doDelete(ypi.getInbillno());
			//2. 删除垛位信息
			this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypi.getCoilno(), YPD.getBoxno());			
			//3. 修改库存信息
			YdmProductDetail ypd = new YdmProductDetail();
			ypd.setCoilno(YPD.getCoilno());
			ypd.setBoxno(YPD.getBoxno());
			ypd.setState("-1");
			ypd.setUpdater(username);
			ypd.setUpdatedate(new Date());
			this.getMapper(YdmProductDetailMapper.class).doUpdate(ypd);			
			//4. 调用生产计划模块接口进行物料跟踪撤销
			PrcMaterielProcess pmp = new PrcMaterielProcess();
			pmp.setObject_no(ypd.getCoilno());
			pmp.setPrc_code("5BYA05");
			pmp.setKeep_sametime_status(0);
			pmp.setRemark("正常入库撤销");
			String tmp = this.getBean(MesApiServiceImpl.class).ARRAYLIST(pmp).getState();
			if(!"0".equals(tmp)) {
				throw new Exception("实物["+ypd.getCoilno()+"]状态已发生改变，不能撤销！");
			}
			
			// 优特属性的 头尾卷 和 边丝卷 不抛产出异动点：xuli 20240126 刘侣
			String lastChar = YPD.getCoilno().substring(YPD.getCoilno().length()-1);
			if ("507101".equals(YPD.getObject_attr()) && ("B".equals(lastChar) || "H".equals(lastChar))) {
				// 不抛送异动点：只记录操作记录；
				
			} else {
			
				// 先按照格式写道cyydd表里：新增一个接口调用，将备份库存表内的数据写进去；然后原来的定时接口传过去
				// 记录成本异动点：20230811刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus(("500203".equals(YPD.getStorageattr()) || "500210".equals(YPD.getStorageattr())) ? "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(userId);
				cd.setActivityId("11A");
				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 = 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("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("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");

				// setSrcFac根据卷的物料属性去判断：20231031刘侣
				cd.setSrcFac("507101".equals(YPD.getObject_attr()) ? "1" : "3");
				
				cd.setGrade("40740601".equals(YPD.getUp_surface_result()) ? "1" : "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.setActivityId("11A");
				cd.setExecJobFunc("D");
				cd.setDataTypeIdx("O");
				cd.setProdTypeNo("CTR");
				cd.setCoilStus("0"); // 综判前算半成品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 + "取消产出");
				
				// 如果没有订单号，则取最后一次脱单的订单号：
				if (YPD.getOrderno() == null) {
					String lastord = this.getMapper(YdmProductDetailMapper.class).getLastOrd(YPD.getCoilno());
					cd.setOrderItem(lastord);
				}
				
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), YPD.getMaterailcoilno());
				
				// 二抛：酸洗重量调整（如果有重量改了也抛送一条）：酸洗原料接收和上料直接不存在重量调整，所以不需要抛送重量调整：20230913刘侣：
				cd.setActivityId("11AA");
				cd.setExecJobFunc("D");
				cd.setDataTypeIdx("O");
				cd.setProdTypeNo("CTR");
				cd.setCoilStus("0"); // 综判前算半成品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
				cd.setAppId("优特" + currentMName + "取消重量调整");
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), YPD.getMaterailcoilno());
				
				// 撤销入库时发送 取消综判异动点：20240509刘侣
				this.getBean(SlmFundFirstDetailService.class).qXUltiYdd(YPD.getCoilno());
				
//				if ("500203".equals(YPD.getStorageattr())) {
//					cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
//					cd.setActivityId("40740601".equals(YPD.getUp_surface_result()) ? "11AC" : "11AZ");
//					cd.setAppId("优特" + currentMName + "取消综判");
//					cd.setProdTypeNo("CTR");
//					cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//					this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId());
//				}
				// end
			
			}

			MesOprLog mol = new MesOprLog("物流管理", "各机组入库管理", "撤销入库", username, opr_time, YPD.getCoilno(), null, null, null, "原料卷号："+YPD.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			
			//20191205清除质量综合判定信息
			String condition = "material_no = '"+ypi.getCoilno()+"'";
			List<QcmJudgeUltimate> qjuList = this.getMapper(QcmJudgeUltimateMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (qjuList!=null && qjuList.size()>0) {
				for (QcmJudgeUltimate q : qjuList) {
					this.getMapper(QcmJudgeUltimateMapper.class).delete(q.getUtm_id());
				}
			}

		}
		rm.setState("200");
		rm.setMsgInfo("撤销入库成功");
		return rm;
	}
	
	/**
	 * 入库管理 获取起始层高和位置
	 * */
	public ResultModel GetMaxLoc(CommonPage<YdmProductButtresslist> cp) {
		ResultModel rm = new ResultModel();
		try {
			List<YdmProductButtresslist> ypb = this.getMapper(
					YdmProductButtresslistMapper.class).GetMaxLoc(
					cp.getObject().getButtressno());
			int maxloc = 0, maxlayer = 0, colwidth = 0;
			if (ypb != null && ypb.size() > 0) {
				Object object1 = ypb.get(0).getMaxloc();
				Object object2 = ypb.get(0).getMaxlayer();
				Object object3 = ypb.get(0).getTcolwidth();
				if (object1 != null)
					maxloc = Integer.valueOf(object1.toString()).intValue();
				if (object2 != null)
					maxlayer = Integer.valueOf(object2.toString()).intValue();
				if (object3 != null)
					colwidth = Integer.valueOf(object3.toString()).intValue();
				//int max = maxloc;
				if (maxloc + 1 > colwidth) {
					rm.setMsgInfo("超出最大堆放位置");
					rm.setState("500");
				} else {
					maxloc += 1;
					HashMap<String, String> resultmap = new HashMap<String, String>();
					resultmap.put("inloc", String.valueOf(maxloc));
					resultmap.put("inlayer", String.valueOf(maxlayer));
					rm.setData(resultmap);
					rm.setState("200");
				}
			} else {
				rm.setState("600");
				rm.setMsgInfo("该货位不存在堆放记录!默认从1开始!");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("获取最大位置失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 手持-获取最高层位置
	 * 
	 * @param cp
	 * @return
	 */
	public ResultModel GetMaxLocApp(CommonPage<YdmProductButtresslist> cp) {
		ResultModel rm = new ResultModel();
		try {
			//获取当前垛位上已经存在的位置
			List<Integer> localityList = this.getMapper(YdmProductButtresslistMapper.class).getLocalityList(cp.getObject().getButtressno());
			// 垛位1.2.3.4.5.
			List<Integer> lists = this.getMapper(YdmProductButtresslistMapper.class).GetListIntApp(cp.getObject().getButtressno());
			if (lists==null || lists.size()<=0) {
				throw new Exception("选择的区域有问题，请检查垛位配置");
			}
			HashMap<Object, Object> resultmap = new HashMap<Object, Object>();
			resultmap.put("inlayer", "1");
			resultmap.put("ky", lists);
			if (localityList !=null && localityList.size() >0) {
				for (Integer loc : lists) {
					if (!localityList.contains(loc)) {						
						resultmap.put("inloc", String.valueOf(loc));
						break;
					}
				}
			}else {
				resultmap.put("inloc", "1");//位置1
			}
			rm.setData(resultmap);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("获取最大位置失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 入库管理 Y+Z<X
	 * */
	public ResultModel doCheck(CommonPage<YdmProductDetail> cp) {
		ResultModel rm = new ResultModel();
		try {
			List<YdmProductDetail> list = cp.getObjectList();
			List<YdmProductButtresslist> ypb = this.getMapper(
					YdmProductButtresslistMapper.class)
					.GetMaxLoc(cp.getMemo1());
			int maxloc = 0, maxlayer = 0, layer = 0, colwidth = 0, X, Y, Z;
			if (ypb != null && ypb.size() > 0) {
				Object object1 = ypb.get(0).getMaxloc();
				Object object2 = ypb.get(0).getMaxlayer();
				Object object3 = ypb.get(0).getTlayer();
				Object object4 = ypb.get(0).getTcolwidth();
				if (object1 != null)
					maxloc = Integer.valueOf(object1.toString()).intValue();
				if (object2 != null)
					maxlayer = Integer.valueOf(object2.toString()).intValue();
				if (object3 != null)
					layer = Integer.valueOf(object3.toString()).intValue();
				if (object4 != null)
					colwidth = Integer.valueOf(object4.toString()).intValue();
				X = layer * colwidth;
				Y = maxloc + (maxlayer - 1) * colwidth;
				Z = list.size();
				if (Y + Z < X)
					rm.setState("200");
				else {
					rm.setState("500");
					rm.setMsgInfo("超出最大堆放量:" + X);
				}
			} else {
				rm.setState("600");
				rm.setMsgInfo("该货位不存在堆放记录!默认位置为1!");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("判断失败!");
			ex.printStackTrace();
		}
		return rm;
	}



	

	/**
	 * 入库管理 检查在库
	 * */
	public ResultModel doCheckIN(CommonPage<YdmProductInlist> cp) {
		ResultModel rm = new ResultModel();
		try {
			List<YdmProductInlist> list = cp.getObjectList();
			String msg = "";
			boolean IN = false;
			int i = 1;
			for (YdmProductInlist ypi : list) {
				YdmProductDetail ypd = new YdmProductDetail();
				ypd.setCoilno(ypi.getCoilno());
				ypd.setBoxno(ypi.getBoxno());
				ypd.setStorageattr(ypi.getStorageattr());
				ypd.setState("0");
				List<YdmProductDetail> lypd = this.getMapper(
						YdmProductDetailMapper.class).find(ypd, 0, 0);
				if (lypd.size() > 0 && lypd != null) {
					msg += " " + i;
					IN = true;
				}
				i++;
			}
			if (IN)
				rm.setState("200");
			else {
				msg += "选取行的数据不在库，不允许操作!";
				rm.setMsgInfo(msg);
				rm.setState("500");
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，检查在库失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	
	/**
	 * 报表:成品库入库查询 SQL实现 条件+汇总+分页
	 * */
	public ResultModel doReportWebBySQL(CommonPage<YdmProductInlist> cp) {
		ResultModel rm = new ResultModel();
		int pageSize = cp.getPageSize();
		int pageIndex = cp.getPageIndex();
		PageModel<YdmProductInlist> pm = new PageModel<YdmProductInlist>(pageIndex, pageSize);
		try {
			String regex = "^(\\d+\\.?\\d*)$";
			boolean isMatch = true;
			Object hmin = "", hmax = "", wmin = "", wmax = "";
			if (cp.getMemo1() != null && cp.getMemo1() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo1().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmin = Double.valueOf(cp.getMemo1()).doubleValue();
			}
			if (cp.getMemo2() != null && cp.getMemo2() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo2().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmax = Double.valueOf(cp.getMemo2()).doubleValue();
			}
			if (cp.getMemo3() != null && cp.getMemo3() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo3().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmin = Double.valueOf(cp.getMemo3()).doubleValue();
			}
			if (cp.getMemo4() != null && cp.getMemo4() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo4().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmax = Double.valueOf(cp.getMemo4()).doubleValue();
			}
			pm.setRows(this.getMapper(YdmProductInlistMapper.class).doReportWebBySQL(
							(pageIndex - 1) * pageSize,
							(pageIndex - 1) * pageSize + pageSize,
							cp.getStartTime(), cp.getEndTime(),
							cp.getObject().getCoilno(),
							cp.getObject().getJudgesteelcode(), hmin, hmax, wmin,
							wmax, cp.getObject().getStorageattr(),
							cp.getObject().getIntype(),
							cp.getObject().getMaterailcoilno(),
							cp.getObject().getMaterailtype(),
							cp.getObject().getCustomer_no(),
							cp.getObject().getOrderno(),
							cp.getObject().getObject_attr(),
							cp.getObject()  ));
			pm.setTotal(this.getMapper(YdmProductInlistMapper.class).doReportWebBySQLCount(
							cp.getStartTime(), cp.getEndTime(),
							cp.getObject().getCoilno(),
							cp.getObject().getJudgesteelcode(), hmin, hmax, wmin,
							wmax, cp.getObject().getStorageattr(),
							cp.getObject().getIntype(),
							cp.getObject().getMaterailcoilno(),
							cp.getObject().getMaterailtype(),
							cp.getObject().getCustomer_no(),
							cp.getObject().getOrderno(),
							cp.getObject().getObject_attr(),
							cp.getObject()  ));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 恢复生产订单号和销售订单号
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doReCoverOrderno(CommonPage<YdmProductInlist> cp) 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<YdmProductInlist> ydiList = cp.getObjectList();
		
		if (CollectionUtils.isEmpty(ydiList)) {
			throw new Exception("请传入参数");
		}
		for (YdmProductInlist ypi : ydiList) {
			YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(ypi.getCoilno(), null);
			if (ypd==null) {
				rm.setState("500");
				rm.setMsgInfo("卷号【"+ypi.getCoilno()+"】信息未找到");
				return rm;
			}
			if (!"0".equals(ypd.getState())) {
				rm.setState("500");
				rm.setMsgInfo("卷号【"+ypd.getCoilno()+"】不是在库状态，无法恢复生产订单号");
				return rm;
			}
			if (StringUtils.isNotEmpty(ypd.getOrderno()) || StringUtils.isNotEmpty(ypd.getProdorderno())) {
				rm.setState("500");
				rm.setMsgInfo("卷号【"+ypd.getCoilno()+"】存在生产订单号或销售订单号，无需恢复");
				return rm;
			}
			if ("M0001".equals(ypd.getMachine_code()) || "M0002".equals(ypd.getMachine_code())) {//4mm + 12mm				
				MesCrSlittingD mcsd = this.getMapper(MesCrSlittingDMapper.class).findById(ypd.getCoilno());
				if (mcsd!=null) {
					ypd.setOrderno(mcsd.getOrder_no());
					ypd.setProdorderno(mcsd.getProd_order_no());
				}
			}else if ("M0003".equals(ypd.getMachine_code())) {//3mm
				MesCrCrossCuttingD mccd = this.getMapper(MesCrCrossCuttingDMapper.class).findById(ypd.getCoilno());
				if (mccd!=null) {
					ypd.setOrderno(mccd.getOrder_no());
					ypd.setProdorderno(mccd.getProd_order_no());
				}
			}else if ("M0004".equals(ypd.getMachine_code()) || "M0005".equals(ypd.getMachine_code()) 
					|| "M0006".equals(ypd.getMachine_code()) || "M0009".equals(ypd.getMachine_code())) {//退火
				//退火基本默认合格，不处理				
			}else if ("M0007".equals(ypd.getMachine_code())) {//平整
				MesTpmD mtd = this.getMapper(MesTpmDMapper.class).findById(ypd.getCoilno());
				if (mtd!=null) {
					ypd.setOrderno(mtd.getOrder_no());
					ypd.setProdorderno(mtd.getProd_order_no());
				}
			}else if ("M0008".equals(ypd.getMachine_code())) {//轧机
				MesRcmD mrd = this.getMapper(MesRcmDMapper.class).findById(ypd.getCoilno());
				if (mrd!=null) {
					ypd.setOrderno(mrd.getOrder_no());
					ypd.setProdorderno(mrd.getProd_order_no());
				}
			}else if ("M0010".equals(ypd.getMachine_code())) {//酸洗
				MesPlmD mpd = this.getMapper(MesPlmDMapper.class).findById(ypd.getCoilno());
				if (mpd!=null) {
					ypd.setOrderno(mpd.getOrder_no());
					ypd.setProdorderno(mpd.getProd_order_no());
				}
			}
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			
			MesOprLog mol = new MesOprLog("物流管理", "入库管理", "恢复订单", username, opr_time, ypd.getCoilno(), ypd.getOrderno(), null, null, "原料卷号："+ypd.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		rm.setState("200");
		rm.setMsgInfo("恢复订单号成功");
		return rm;
	}
	
	/**
	 * 调整入库时间
	 * @param cp [{"objectList":[{"inbillno":"入库单号"},{"inbillno":"OT2020040800021"}],"memo1":"2020-06-29 13:45:47"}]
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangeInDate(CommonPage<YdmProductInlist> cp) 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<YdmProductInlist> ydiList = cp.getObjectList();
		if (CollectionUtils.isEmpty(ydiList)) {
			throw new Exception("请传入参数");
		}
		if (StringUtils.isEmpty(cp.getMemo1())) {
			throw new Exception("请传入入库时间");
		}
		Date indate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cp.getMemo1());	//入库时间
		for (YdmProductInlist ypi : ydiList) {
			YdmProductInlist y = new YdmProductInlist();
			y.setInbillno(ypi.getInbillno());
			y.setIndate(indate);
			y.setMemo(username +":"+ opr_time +":调整入库时间");
			this.getMapper(YdmProductInlistMapper.class).update(y);	
			//日志
			MesOprLog mol = new MesOprLog("物流管理", "入库查询", "调整入库时间", username, opr_time, null, null, null, null, "出库单号:"+ypi.getInbillno()+"调整入库时间成："+cp.getMemo1());
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		rm.setState("200");
		rm.setMsgInfo("调整入库时间成功");
		return rm;
	}
	
	
	/**
	 *  平整机重量调整功能 zlz
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangePzWeight(CommonPage<YdmProductDetail> cp) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMdd").format(new Date());
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<YdmProductDetail> ypdList = cp.getObjectList();
		if (CollectionUtils.isEmpty(ypdList)) {
			throw new Exception("请传入参数");
		}
			 
		for (YdmProductDetail ypd : ypdList) {
			//判断是否在库或者待入库
			YdmProductDetail y = this.getMapper(YdmProductDetailMapper.class).findById(ypd.getCoilno());
			if (y==null || (!"0".equals(y.getState()) && !"-1".equals(y.getState()))) {
				rm.setState("500");
				rm.setMsgInfo("卷号【"+ypd.getCoilno()+"】不属于在库或待入库状态,无法操作");
				return rm;
			}
			//1.调整库存重量
			ypd.setTheoryweight(ypd.getFactweight());//平整的理重==实重
			ypd.setMemo(username + opr_time + "调整平整重量");
			this.getMapper(YdmProductDetailMapper.class).update(ypd);
			//2.调整生产重量
			MesTpmD mtd = new MesTpmD();
			mtd.setCoil_no(ypd.getCoilno());
			mtd.setCoil_act_wgt(ypd.getFactweight());//平整的理重==实重
			mtd.setCoil_thr_wgt(ypd.getFactweight());
			mtd.setMemo(username + opr_time + "调整平整重量");
			this.getMapper(MesTpmDMapper.class).update(mtd);
			//3.调整入库重量
			String condition = " coilno = '"+ypd.getCoilno()+"'";
			List<YdmProductInlist> ypiList = this.getMapper(YdmProductInlistMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (CollectionUtils.isNotEmpty(ypiList)) {
				for (YdmProductInlist ypi : ypiList) {
					ypi.setFactweight(ypd.getFactweight());
					ypi.setTheoryweight(ypd.getFactweight());//平整的理重==实重
					ypi.setMemo(username + opr_time + "调整平整重量");
					this.getMapper(YdmProductInlistMapper.class).update(ypi);
				}
			}
			// 写入调整表
			MesInfoChange mic = new MesInfoChange();
			mic.setCoil_no(ypd.getCoilno());
			mic.setOpr_man(username);
			mic.setOpr_time(now);
			mic.setOpr_info(username + opr_time + "调整平整重量,由"+y.getFactweight()+"调整成"+ypd.getFactweight());
			mic.setOrder_no(ypd.getOrderno());
			this.getMapper(MesInfoChangeMapper.class).insert(mic);
			
			MesOprLog mol = new MesOprLog("车间MES", "平整机调整管理", "重量调整", username, opr_time, ypd.getCoilno(), null, null, null, mic.getOpr_info());
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		rm.setState("200");
		rm.setMsgInfo("调整平整重量成功");
		return rm;
	}
	
}
