/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2020-05-08
 * 描述            ：出厂证接口
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Lms.Logistics.impl;
import static market.Api.Mes.impl.RestfulHttpClient.getClient;

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

import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Api.Mes.impl.RestfulHttpClient;
import market.Com.mapper.PbModelDbMapper;
import market.Com.vo.CommonPage;
import market.Com.vo.PassportInfo;
import market.Com.vo.ResultModel;
import market.Lms.Logistics.mapper.LmsPassportinfoCancelMapper;
import market.Lms.Logistics.mapper.LmsPassportinfoMapper;
import market.Lms.Logistics.mapper.SpmDeliveryMapper;
import market.Lms.Logistics.mapper.SpmDistrbuteMainMapper;
import market.Lms.Logistics.mapper.SpmTransportDetailMapper;
import market.Lms.Logistics.service.LmsPassportinfoService;
import market.Lms.Logistics.vo.LmsPassportinfoCancel;
import market.Lms.Logistics.vo.SpmDelivery;
import market.Lms.Logistics.vo.SpmDistrbuteMain;
import market.Lms.Warehouse.impl.YdmProductInlistServiceImpl;
import market.Lms.Warehouse.impl.YdmProductMoveServiceImpl;
import market.Lms.Warehouse.impl.YdmProductOutlistServiceImpl;
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.YdmProductMoveMapper;
import market.Lms.Warehouse.mapper.YdmProductOutlistMapper;
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.YdmProductMove;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Slm.CustomerInformation.impl.SlmCustomerTransSolutionServiceImpl;
import market.Slm.CustomerInformation.mapper.SlmCustomerInfoMapper;
import market.Slm.CustomerInformation.vo.SlmCustomerInfo;
import market.Slm.CustomerInformation.vo.SlmCustomerTransSolution;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;
import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@Service("LmsPassportinfoService")
@RemoteService(path="LmsPassportinfoService")
public class LmsPassportinfoServiceImpl extends BaseServiceImpl<PassportInfo,Object> implements LmsPassportinfoService {
	
	/**
	 * 查询出厂证信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryLmsPassportInfo(CommonPage<PassportInfo> cp) throws Exception{
		ResultModel rm = new ResultModel();
		PassportInfo lpi = cp.getObject();
		String condition = "1=1";
		if (StringUtils.isNotEmpty(cp.getStartTime())) {//
			condition += " and to_date(created,'yyyy-MM-dd HH24:mi:ss') >= to_date('"+cp.getStartTime()+"','yyyy-MM-dd HH24:mi:ss')";
		}
		if (StringUtils.isNotEmpty(cp.getEndTime())) {//
			condition += " and to_date(created,'yyyy-MM-dd HH24:mi:ss') <= to_date('"+cp.getEndTime()+"','yyyy-MM-dd HH24:mi:ss')";
		}
		if (StringUtils.isNotEmpty(lpi.getCoilList())) {//卷号
			condition += " and coillist like '%"+lpi.getCoilList()+"%'";
		}
		if (StringUtils.isNotEmpty(lpi.getPlateNumber())) {//车号
			condition += " and platenumber like '%"+lpi.getPlateNumber()+"%'";
		}
		if (StringUtils.isNotEmpty(lpi.getStandard())) {//牌号
			condition += " and standard like '%"+lpi.getStandard()+"%'";
		}
		if (StringUtils.isNotEmpty(lpi.getForecast())) {//发运号
			condition += " and forecast like '%"+lpi.getForecast()+"%'";
		}
		List<PassportInfo> list = this.getMapper(LmsPassportinfoMapper.class).findWithCondition(null, condition, "created desc", 0, 0);
		if (CollectionUtils.isNotEmpty(list)) {
			for (PassportInfo pi : list) {
				if ("1".equals(pi.getIs_send())) {
					pi.setIs_send("已下发");
				}
			}
		}
		rm.setData(list);
		rm.setMsgInfo("200");
		return rm;
	}
	
	/**
	 * 新增出厂证信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddPassportInfo(CommonPage<PassportInfo> 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);
		PassportInfo pp = cp.getObject();//装车信息
		String billno = cp.getMemo1();//提货单号 
		
		PassportInfo ppi = new PassportInfo();
		ppi.setCategoryId("108");//必填，中冶新材为107，优特钢带为108
		ppi.setPlanDate(new SimpleDateFormat("yyyy/MM/dd").format(now));//计划出厂日期 字符串，yyyy/mm/dd
		// 改为使用前端传过来的选择的车牌颜色：2023010701 刘侣
		ppi.setPlateType(cp.getMemo6() == null ? "1" : cp.getMemo6());//车牌颜色 1—黄牌，2—蓝牌，3—厂牌，先用黄牌1
		// end
		ppi.setLowerLimit(-0.005);//允许上限:千分之五   百分之二
		ppi.setUpperLimit(+0.005);//允许上限
		ppi.setAmountUnit(null);//数量单位
		if (billno!=null && !"".equals(billno)) {	
			this.getMapper(LmsPassportinfoMapper.class).delete("Y"+billno);//先删除再新增
			//1. 装车界面出库
			ppi.setForecast("Y"+billno);//
			List<SpmDistrbuteMain> carnoList = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, "deliveryno='"+billno+"'", null, 0, 1);
			if (carnoList!=null && carnoList.size()>0) {			
				ppi.setPlateNumber(carnoList.get(0).getCarno());//车牌
			}			
			List<SlmLadingBillDetail> slbdList = this.getMapper(SpmDeliveryMapper.class).doQuaryCarInfo(billno);
			if (slbdList!=null && slbdList.size()>0) {
				SlmLadingBillDetail slbd = slbdList.get(0);
				ppi.setTicket(slbd.getBill_no());//
				ppi.setProduct(StringUtils.isEmpty(slbd.getProd_name())?"头尾板":slbd.getProd_name());//产品名称
				ppi.setStandard(slbd.getSteel_name());//规格型号(牌号)
				
			}
			slbdList = this.getMapper(SpmDeliveryMapper.class).doQuaryCarInfo1(billno);
			if (slbdList!=null && slbdList.size()>0) {
				SlmLadingBillDetail slbd = slbdList.get(0);
				ppi.setPlanWeight(slbd.getFactweight());//装车重量
				ppi.setAmount(slbd.getLoad_num());//装车数量==把数量组装到了理重重量字段中
			}			
			SlmLadingBillHeat slbd = this.getMapper(SlmLadingBillHeatMapper.class).findById(billno);
			if (slbd!=null) {			
				ppi.setAcceptUnit(slbd.getReciver_unit_name());//提货单位
				ppi.setDischarge(slbd.getReciver_address());//卸货地点
				SlmCustomerTransSolution solution=this.getBean(SlmCustomerTransSolutionServiceImpl.class).doQueryOne(slbd.getSolutions_no());
				if(solution!=null){
					ppi.setAcceptor(solution.getConsignee_name());//提货人
				}    		
			}			
			Double packWeight = this.getMapper(SpmDeliveryMapper.class).doQuaryPackWeight(billno); //包装重量
			packWeight = (packWeight==null?0d:packWeight);
			ppi.setPackage_weight(packWeight+"");//包装重量
			ppi.setGrass_weight(0+"");//草支垫重量默认为0
			if (StringUtils.isNotEmpty(cp.getMemo2())) {//memo2中传草支垫重量(kg)
				ppi.setGrass_weight(Double.parseDouble(cp.getMemo2())/1000 + "");//草支垫重量
			}
			ppi.setDeduction(packWeight + Double.parseDouble(ppi.getGrass_weight()));//过磅扣重 = 包装重量 + 草支垫重量
			//全是废副品库，则设置废次材
	    	int count = this.getMapper(SpmDeliveryMapper.class).doQuaryCarInfo2(billno);
	    	if (count == 0) {
	    		ppi.setProduct("废次材");
				ppi.setUpperLimit(null);
				ppi.setLowerLimit(null);
			}
	    	
	    	if ("1".equals(slbd.getTrans_type())) {
	    		// 如果是火运提单：20240521刘侣
				// 然后再根据 ticket 提单号，将提单信息发往产销系统：
				this.getBean(SlmFundFirstDetailService.class).sendLoadData(billno);
	    	}
	    	
	    	//日志
	    	MesOprLog mol = new MesOprLog("物流管理", "装车管理", "装车自动新增出厂证", username, opr_time, null, null, billno, null, null);
	    	this.getMapper(MesOprLogMapper.class).insert(mol);
		}else {
			//2.  转运出库(客户，运输方案)：小票
			String ticket = new SimpleDateFormat("yyyyMMdd").format(now)+"YT";
			String condition = "TICKET like '"+ticket+"%'";
			List<PassportInfo> piList = this.getMapper(LmsPassportinfoMapper.class).findWithCondition(null, condition, "TICKET desc", 0, 1);
			if (piList==null || piList.size()<=0) {
				ticket += "0001";
			}else {
				 String maxTicket = piList.get(0).getTicket();
				 Integer iSeq = Integer.parseInt(maxTicket.substring(maxTicket.length()-4)) + 1;
				 ticket += String.format("%04d", iSeq);
			}
			ppi.setTicket(ticket);//出厂证号  与纸质单据保持一致
			ppi.setForecast("Y"+ticket);//同车序号  必须唯一；代表一次装车    	
			ppi.setPlateNumber(pp.getPlateNumber());//车牌号码
			ppi.setStandard(pp.getStandard());//规格型号(牌号)
			ppi.setProduct(pp.getProduct()==null?"*":pp.getProduct());//产品名称为空
			ppi.setPlanWeight(pp.getPlanWeight());//装车重量
			ppi.setAmount(pp.getAmount());//装车数量==把数量组装到了理重重量字段中
			ppi.setCoilList(pp.getCoilList());//卷号集合
			ppi.setWeightlist(pp.getWeightlist());
			ppi.setCustomer_no(pp.getCustomer_no());//客户
			ppi.setCustomer_nm(pp.getCustomer_nm());
			SlmCustomerInfo sci = this.getMapper(SlmCustomerInfoMapper.class).findById(pp.getCustomer_no());
			if (sci!=null) {
				ppi.setAcceptor(sci.getCorporation_man());//提货人
				ppi.setAcceptUnit(sci.getCustomer_name());
				ppi.setDischarge(sci.getAddress());//卸货地点
			}
			ppi.setSolutions_no(pp.getSolutions_no());
			ppi.setOrder_no(pp.getOrder_no());
			//根据卷号，设置订单规格和规格重量
			String[] coilStr = pp.getCoilList().split(",");
			List<String> coilList = Arrays.asList(coilStr);			
			List<PassportInfo> ppiList = this.getMapper(YdmProductDetailMapper.class).doQuaryLmsPassPortInfoSpecWeight(coilList);
			if (CollectionUtils.isNotEmpty(ppiList)) {
				String spec = "";
				String specWeight = "";
				for (PassportInfo p : ppiList) {
					spec = spec + p.getSpec() + ",";
					specWeight = specWeight + p.getSpec_weight() + ",";
				}
				spec = spec.substring(0, spec.length()-1);
				specWeight = specWeight.substring(0, specWeight.length()-1);
				ppi.setSpec(spec);//规格
				ppi.setSpec_weight(specWeight);//规格集合
			}
			//获取包装重量
			Double packWeight = this.getMapper(SpmDeliveryMapper.class).doQuaryPackWeight_WK(coilList);
			ppi.setPackage_weight(packWeight+"");//包装重量
			ppi.setGrass_weight(0+"");
			ppi.setDeduction(packWeight);//过磅扣重(T)
			//日志
			MesOprLog mol = new MesOprLog("物流管理", "转运出厂证管理", "新增", username, opr_time, null, null, ticket, null, null);
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
    	ppi.setNote(null);
    	ppi.setCreator(username);
    	ppi.setCreated(new SimpleDateFormat("yyy/MM/dd HH:mm:ss").format(now));
    	ppi.setSourceUnit("优特钢带");
    	//20200803 对碎边丝处理：统一废次材，不设上下限
    	if ("碎边丝".equals(ppi.getStandard()) || "头尾板".equals(ppi.getStandard()) || "头尾卷".equals(ppi.getStandard())) {
			ppi.setProduct("废次材");
			ppi.setUpperLimit(null);
			ppi.setLowerLimit(null);
		}    	
    	this.getMapper(LmsPassportinfoMapper.class).insert(ppi);
    	rm.setState("200");
		return rm;
	}
	
	/**
	 * 废副品提单新增出厂证信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddPassportInfoF(CommonPage<PassportInfo> 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 billno = cp.getMemo1();//提货单号 
		
		PassportInfo ppi = new PassportInfo();
		ppi.setCategoryId("108");//必填，中冶新材为107，优特钢带为108
		ppi.setPlanDate(new SimpleDateFormat("yyyy/MM/dd").format(now));//计划出厂日期 字符串，yyyy/mm/dd
		// 改为使用前端传过来的选择的车牌颜色：2023010701 刘侣
		ppi.setPlateType(cp.getMemo6() == null ? "1" : cp.getMemo6());//车牌颜色 1—黄牌，2—蓝牌，3—厂牌，先用黄牌1
		// end
		ppi.setLowerLimit(-0.005);//允许上限:千分之五   百分之二
		ppi.setUpperLimit(+0.005);//允许上限
		ppi.setAmountUnit(null);//数量单位
		if (billno!=null && !"".equals(billno)) {	
			this.getMapper(LmsPassportinfoMapper.class).delete("Y"+billno);//先删除再新增
			//1. 装车界面出库
			ppi.setForecast("Y"+billno);//
			List<SpmDistrbuteMain> carnoList = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, "deliveryno='"+billno+"'", null, 0, 1);
			if (carnoList!=null && carnoList.size()>0) {			
				ppi.setPlateNumber(carnoList.get(0).getCarno());//车牌
			}			
			List<SlmLadingBillDetail> slbdList = this.getMapper(SpmDeliveryMapper.class).doQuaryCarInfo(billno);
			if (slbdList!=null && slbdList.size()>0) {
				SlmLadingBillDetail slbd = slbdList.get(0);
				ppi.setTicket(slbd.getBill_no());//
				ppi.setProduct("头尾板");//产品名称
				ppi.setStandard(slbd.getSteel_name());//规格型号(牌号)
				
			}
			
			
			slbdList = this.getMapper(SpmDeliveryMapper.class).doQuaryCarInfoF(billno);
			if (slbdList!=null && slbdList.size()>0) {
				SlmLadingBillDetail slbd = slbdList.get(0);
				ppi.setPlanWeight(slbd.getFactweight());//装车重量
				ppi.setAmount(slbd.getLoad_num());//装车数量==把数量组装到了理重重量字段中
			}			
			SlmLadingBillHeat slbd = this.getMapper(SlmLadingBillHeatMapper.class).findById(billno);
			if (slbd!=null) {			
				ppi.setAcceptUnit(slbd.getReciver_unit_name());//提货单位
				ppi.setDischarge(slbd.getReciver_address());//卸货地点
				SlmCustomerTransSolution solution=this.getBean(SlmCustomerTransSolutionServiceImpl.class).doQueryOne(slbd.getSolutions_no());
				if(solution!=null){
					ppi.setAcceptor(solution.getConsignee_name());//提货人
				}    		
			}		
			// 头尾边丝一律裸包
			Double packWeight = this.getMapper(SpmDeliveryMapper.class).doQuaryPackWeight(billno); //包装重量
			packWeight = (packWeight==null?0d:packWeight);
			ppi.setPackage_weight(packWeight+"");//包装重量
			ppi.setGrass_weight(0+"");//草支垫重量默认为0
			if (StringUtils.isNotEmpty(cp.getMemo2())) {//memo2中传草支垫重量(kg)
				ppi.setGrass_weight(Double.parseDouble(cp.getMemo2())/1000 + "");//草支垫重量
			}
			ppi.setDeduction(packWeight + Double.parseDouble(ppi.getGrass_weight()));//过磅扣重 = 包装重量 + 草支垫重量
			//全是废副品库，则设置废次材
	    	
	    		ppi.setProduct("废次材");
				ppi.setUpperLimit(null);
				ppi.setLowerLimit(null);
			
	    	
//	    	if ("1".equals(slbd.getTrans_type())) {
//	    		// 如果是火运提单：20240521刘侣
//				// 然后再根据 ticket 提单号，将提单信息发往产销系统：
//				this.getBean(SlmFundFirstDetailService.class).sendLoadData(billno);
//	    	}
	    	
	    	//日志
	    	MesOprLog mol = new MesOprLog("物流管理", "废副品装车管理", "装车自动新增出厂证", username, opr_time, null, null, billno, null, null);
	    	this.getMapper(MesOprLogMapper.class).insert(mol);
		}
    	ppi.setNote(null);
    	ppi.setCreator(username);
    	ppi.setCreated(new SimpleDateFormat("yyy/MM/dd HH:mm:ss").format(now));
    	ppi.setSourceUnit("优特钢带");
    	//20200803 对碎边丝处理：统一废次材，不设上下限
//    	if ("碎边丝".equals(ppi.getStandard()) || "头尾板".equals(ppi.getStandard()) || "头尾卷".equals(ppi.getStandard())) {
			ppi.setProduct("废次材");
			ppi.setUpperLimit(null);
			ppi.setLowerLimit(null);
//		}    	
    	this.getMapper(LmsPassportinfoMapper.class).insert(ppi);
    	rm.setState("200");
		return rm;
	}
	
	
	/**
	 * 装车操作
	 * @param cp  memo5传草支垫重量
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doLoadPassportInfo(CommonPage<PassportInfo> 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<PassportInfo> piList = cp.getObjectList();
		String carno = cp.getMemo1();//车号
		
		if (CollectionUtils.isNotEmpty(piList)) {
			for (PassportInfo pi : piList) {
				PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById(pi.getForecast());
				if (lpi!=null) {
					// 如果下发过门禁，那么就需要将删除门禁后才能再次装车：
					if ("1".equals(lpi.getIs_send())) {
						throw new Exception("已经下发了门禁，需要删除门禁后才能再次装车！！！");
					}
					lpi.setPlateNumber(carno);
					lpi.setPlanDate(new SimpleDateFormat("yyyy/MM/dd").format(now));
					lpi.setCreated(new SimpleDateFormat("yyy/MM/dd HH:mm:ss").format(now));
					if (StringUtils.isNotEmpty(cp.getMemo5())) {
						lpi.setGrass_weight(Double.parseDouble(cp.getMemo5())/1000 + "");//草支垫重量
						lpi.setDeduction(Double.parseDouble(lpi.getPackage_weight()) + Double.parseDouble(cp.getMemo5())/1000);//过磅扣重
					}
					this.getMapper(LmsPassportinfoMapper.class).update(lpi);
					//日志
					MesOprLog mol = new MesOprLog("物流管理", "转运出厂证管理", "装车", username, opr_time, null, null,pi.getForecast(), null, null);
					this.getMapper(MesOprLogMapper.class).insert(mol);
				}
			}
		}
		rm.setState("200");
		rm.setMsgInfo("装车成功");
		return rm;
	}
	
	/**
	 * 门禁下发
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSendPassportInfo(CommonPage<PassportInfo> 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<PassportInfo> piList = cp.getObjectList();
		
		if (CollectionUtils.isNotEmpty(piList)) {
			for (PassportInfo pi : piList) {
				PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById("Y"+pi.getTicket());
				if (lpi!=null) {
					try {
						// 如果已经下发了门禁，就提示需要删除门禁后才能再次下发：
						if ("1".equals(lpi.getIs_send())) {
							throw new Exception("已经下发了门禁，需要删除门禁后才能再次下发");
						}
						//日志
						MesOprLog mol = new MesOprLog("物流管理", "装车管理/转运出厂证管理", "门禁下发", username, opr_time, null, null, pi.getTicket(), null, null);
						this.getMapper(MesOprLogMapper.class).insert(mol);
						//逻辑处理
						lpi.setPlanDate(new SimpleDateFormat("yyyy/MM/dd").format(now));//计划出厂日期
						lpi.setCreated(new SimpleDateFormat("yyy/MM/dd HH:mm:ss").format(now));//计划出厂日期
						rm = this.getBean(LmsApiServiceImpl.class).insertPassport(lpi, 0, 5);
						if ("200".equals(rm.getState())) {
							lpi.setCreator(username);//录入人  
							lpi.setIs_send("1");//标识已发送门禁
							this.getMapper(LmsPassportinfoMapper.class).update(lpi);
							
						}else {
							throw new Exception(rm.getMsgInfo() + ","+ rm.getErrorInfo());
						}
					} catch (Exception e) {
						throw new Exception(e.getMessage());
					}									
				} else {
					// 如果门禁数据为空，直接报错：20230509刘侣
					throw new Exception("提单：" + pi.getTicket() + " 门禁数据为空，请联系管理员(可能本应是一次结算)");
					// end
				}
			}
		}
		return rm;
	}
	
	
	/**
	 * 删除门禁
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeletePassportInfo(CommonPage<SpmDelivery> 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 billno = "Y"+cp.getMemo1();
		String cancel_reason = cp.getMemo2();//作废原因
		
		if (StringUtils.isEmpty(cancel_reason)) {
			rm.setState("500");
			rm.setMsgInfo("未填写撤销原因！");
			return rm;
		}
    	rm = this.getBean(LmsApiServiceImpl.class).cancelPassport(billno, cancel_reason, username);
    	if ("200".equals(rm.getState())) {
			rm.setState("200");
			rm.setMsgInfo("作废成功");			
			//调整下发标识
			LmsPassportinfoCancel lpic = new LmsPassportinfoCancel();
			PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById(billno);
			lpi.setIs_send("0");//标识没有发送门禁
			this.getMapper(LmsPassportinfoMapper.class).update(lpi);//删除装车车号
			// 20210308 新增作废出厂证信息
			BeanUtils.copyProperties(lpic, lpi);//复制
			lpic.setDelele_man(username);
			lpic.setDelele_time(new SimpleDateFormat("yyyyMMddHHmmss").format(now));
			lpic.setDelete_reason(cancel_reason);
			this.getMapper(LmsPassportinfoCancelMapper.class).delete(billno);//先删除，防止主键冲突
			this.getMapper(LmsPassportinfoCancelMapper.class).insert(lpic);
    	}
    	//日志
    	MesOprLog mol = new MesOprLog("物流管理", "装车管理/转运出厂证管理", "删除门禁", username, opr_time, null, null, billno, null, null);
    	this.getMapper(MesOprLogMapper.class).insert(mol);
		return rm;
	}
	
	/**
	 * 彻底删除出厂证信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRemovePassportInfo(CommonPage<SpmDelivery> 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 billno = "Y"+cp.getMemo1();
		
		PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById(billno);
		if (lpi==null) {
			throw new Exception("未找到发运号【"+billno+"】对应的转运出厂信息，请重新查询");
		}
		//控制只能本人删除
		if (!lpi.getCreator().equals(username)) {
			throw new Exception("发运号【"+billno+"】非本人创建，无法彻底删除");
		}
		
		// 检测是否已经下发了门禁：是则需要先撤销门禁；20231014刘侣
		if (lpi.getIs_send() != null && "1".equals(lpi.getIs_send())) {
			throw new Exception("发运号【"+billno+"】已经下发门禁，需要先删除门禁。");
		}
		// end;
		
    	this.getMapper(LmsPassportinfoMapper.class).delete(billno);
    	//日志
    	MesOprLog mol = new MesOprLog("物流管理", "转运出厂证管理", "彻底删除", username, opr_time, null, null, billno, null, null);
    	this.getMapper(MesOprLogMapper.class).insert(mol);
    	rm.setMsgInfo("彻底删除成功");
		return rm;
	}
	
	/**
	 * 查询出厂证信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryPassportInfo(CommonPage<SpmDelivery> cp) throws Exception{
		List<SpmDelivery> list = cp.getObjectList();
		List<String> strList = new ArrayList<>();
		for (SpmDelivery sd : list) {
			strList.add("Y"+sd.getDeliveryno());
		}
    	ResultModel rm = this.getBean(LmsApiServiceImpl.class).queryPassportInfo(strList);
		return rm;
	}
	
	/**
	 * 获取当前车次的过磅重量
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel queryPassportWeight(CommonPage<SpmDelivery> cp) throws Exception{
		String carno = cp.getMemo1();
		List<String> strList = new ArrayList<>();
		strList.add(carno);
		ResultModel rm = this.getBean(LmsApiServiceImpl.class).queryPassportWeight(strList);
		return rm;
	}
	
	/**
	 * 获取转库仓库
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryStorageattrForLpi(CommonPage<SpmDelivery> cp) throws Exception{
		ResultModel rm = new ResultModel();
		YdmBaseButtressconfig ybb = new YdmBaseButtressconfig();
		ybb.setSortcode("1005");
		List<YdmBaseButtressconfig> list = this.getMapper(YdmBaseButtressconfigMapper.class).findWithCondition(ybb, null, "buttressno", 0, 0);
		rm.setData(list);
		rm.setState("200");
		return rm;
	}

	
	/**
	 * 以发运号查询铁前MES出厂信息
	 * @param listForecastNo 发运号数组
	 * @return
	 */
	public ResultModel queryPassportInfo(List<String> listForecastNo){
		ResultModel rm = new ResultModel();
		try {
			String url = "http://172.16.0.18:9090/ZyTg/services/Passport/sv?forecastList=";
			String params = "";
			for(String forecastNo:listForecastNo){
				params+=forecastNo+"','";
			}
			if (StringUtils.isNotBlank(params) && params.length() > 3){
				params = params.substring(0,params.length()-3);
			}
			url += "'"+params+"'";
			RestfulHttpClient.HttpResponse response = getClient(url)
					.get()
					.addHeader("Content-Type", "application/json; charset=utf-8")
					//.addQueryParam("forecastList",params)
					.request();
			if (response.getCode() == 200) {
				String result = response.getContent();
				rm.setData(JSONArray.fromObject(result));
				rm.setState("200");
				rm.setMsgInfo("查询成功！");
			} else {
				rm.setState("500");
				rm.setMsgInfo("查询失败！");
				rm.setErrorInfo(response.getContent());
			}
		}catch (Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 转外库，打印大标签
	 * 20211011 不要打印大标签了
	 * @param cp
	 * @return
	 */
	@Deprecated
	public ResultModel doQueryPrintLabelInfo(CommonPage<PassportInfo> cp){
		ResultModel rm = new ResultModel();
		List<PassportInfo> piList = cp.getObjectList();
		for (PassportInfo pi : piList) {
			PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById(pi.getForecast());//发运号：Y+。。。
			if (lpi==null || StringUtils.isEmpty(lpi.getCoilList())) {
				continue;
			}
			List<String> coilList = Arrays.asList(lpi.getCoilList().split(","));
			for (String coilno : coilList) {//获取卷号
				String sql = "t.prod_name,cbs.steel_name,t.std_name,t.heatno,t.coilno|| '（' || t.materailcoilno || '）' as packing_no,t.coilno,"
						+ " to_char(t.thick, 'FM90.009') || '*' ||to_char(t.width, 'FM9990.0') as prod_spec, to_char(t.producedate,'yyyy-MM-dd') wrk_date,t.orderno,"
						+ " t.receiv_nm,sci.register_address, t.factweight, decode(t.produceorder,'1', '甲', '2', '乙', '3', '丙', '4', '丁') wrk_grp, "
						+ " 'CoilNo:' || t.coilno || ' Dimension:' || to_char(t.thick, 'FM90.00') || '*' || to_char(t.width, 'FM9990.0') || ' SteelGrade:' || cbs.steel_name ||' Date:' || to_char(t.producedate,'yyyy-MM-dd') || ' Weight:' ||t.factweight as barcode"
						+ " from ydm_product_detail t"
						+ " left join slm_customer_info sci on t.customer_no = sci.customer_no"
						+ " left join com_base_steel cbs on t.judgesteelcode = cbs.steel_code "
						+ " where t.coilno = '"+coilno+"'";
				this.getMapper(PbModelDbMapper.class).doQueryHashMap(sql);
			}
		}
		return rm;
	}
	
	/**
	 * 转库出厂证管理：移送至贸易库
	 * @param cp
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doMoveToStorage500205(CommonPage<PassportInfo> 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);
		List<PassportInfo> piList = cp.getObjectList();
		
		for (PassportInfo pi : piList) {
			PassportInfo lpi = this.getMapper(LmsPassportinfoMapper.class).findById("Y"+pi.getTicket());//发运号：Y+。。。
			if (lpi==null || StringUtils.isEmpty(lpi.getCoilList()) || "1".equals(lpi.getIs_move())) {
				rm.setState("500");
				rm.setMsgInfo("请核对【"+pi.getTicket()+"】对应的出厂证信息是否正确");
				return rm;
			}
			
			//统一的装车单号
			String billno=this.getBean(YdmProductMoveServiceImpl.class).createBILLNO();
			List<String> coilList = Arrays.asList(lpi.getCoilList().split(","));
			for (String coilno : coilList) {//获取卷号
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(coilno);
				if (ypd == null) {
					continue;
				}
				//0、获取原垛位信息
				String condition = " coilno = '"+coilno+"'";
				List<YdmProductButtresslist> ypbList = this.getMapper(YdmProductButtresslistMapper.class).findWithCondition(null, condition, "createdate desc", 0, 1);
				//1、新增出库记录
				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(ypd.getStorageattr());
				ypo.setProd_code(ypd.getProd_code());
				ypo.setProd_name(ypd.getProd_name());
				ypo.setStd_code(ypd.getStd_code());
				ypo.setStd_name(ypd.getStd_name());
				ypo.setUse_code(ypd.getUse_code());
				ypo.setUse_name(ypd.getUse_name());
				ypo.setPline_name(ypd.getPline_name());
				ypo.setPostid(ypd.getPostid());
				ypo.setThick(ypd.getThick());
				ypo.setWidth(ypd.getWidth());
				ypo.setLength(ypd.getLength());
				ypo.setDiameter_inn(ypd.getDiameter_inn());
				ypo.setDiameter_out(ypd.getDiameter_out());
				ypo.setQuantity(ypd.getQuantity());
				ypo.setTheoryweight(ypd.getTheoryweight());
				ypo.setCoreweight(ypd.getCoreweight());
				ypo.setGrossweight(ypd.getGrossweight());
				ypo.setPackweight(ypd.getPackweight());
				ypo.setFactweight(ypd.getFactweight());
				ypo.setCustomer_nm(ypd.getCustomer_nm());
				ypo.setCustomer_no(ypd.getCustomer_no());
				ypo.setReceiv_no(ypd.getReceiv_no());
				ypo.setReceiv_nm(ypd.getReceiv_nm());
				ypo.setOrderno(ypd.getOrderno());
				ypo.setProdorderno(ypd.getProdorderno());
				ypo.setSteelcode(ypd.getSteelcode());
				ypo.setJudgesteelcode(ypd.getJudgesteelcode());
				ypo.setPacking_group(ypd.getPacking_group());
				ypo.setChemresult(ypd.getChemresult());
				ypo.setSizeresult(ypd.getSizeresult());
				ypo.setSurfaceresult(ypd.getSurfaceresult());
				ypo.setWeightresult(ypd.getWeightresult());
				ypo.setJudgeresult(ypd.getJudgeresult());
				ypo.setPhysresult(ypd.getPhysresult());
				ypo.setSpyresult(ypd.getSpyresult());
				ypo.setProducedate(ypd.getProducedate());
				ypo.setProduceorder(ypd.getProduceorder());
				ypo.setProduceteam(ypd.getProduceteam());
				ypo.setIndate(ypd.getIndate());
				ypo.setInorder(ypd.getInorder());
				
				// 加入物料属性：20230725刘侣
				ypo.setObj_attr_out(ypd.getObject_attr());
				// end
				
				ypo.setInteam(ypd.getInteam());
				if (CollectionUtils.isNotEmpty(ypbList)) {					
					ypo.setButtressno(ypbList.get(0).getButtressno());
					ypo.setLocality((long)ypbList.get(0).getLocality());
					ypo.setLayer((long)ypbList.get(0).getLayer());
				}
				this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
				//2.1、删除原垛位信息
				this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypd.getCoilno(), ypd.getBoxno());	
				//2.2、新增贸易外库的垛位信息()
				YdmProductButtresslist ypb=new YdmProductButtresslist();	
				String condString = "buttressname = '"+lpi.getSolutions_no()+"' and sortcode = '1011' and validflag = '1'";
				List<YdmBaseButtressconfig> ybbList = this.getMapper(YdmBaseButtressconfigMapper.class).findWithCondition(null, condString, null, 0, 1);
				if (CollectionUtils.isNotEmpty(ybbList)) {
					ypb.setAreano(ybbList.get(0).getButtressno());
					ypb.setButtressno(ybbList.get(0).getButtressno()+"001");
					ypb.setLocality(1);//默认1层1位置
					ypb.setLayer(1);					
				}
				ypb.setStorageattr("500205");
				ypb.setCoilno(ypd.getCoilno());
				ypb.setBoxno(ypd.getBoxno());
				ypb.setCreatedate(now);
				ypb.setCreater(username);
				this.getMapper(YdmProductButtresslistMapper.class).insert(ypb);
				//3、新增贸易外库的入库记录
				YdmProductInlist ypi=new YdmProductInlist();
				ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
				ypi.setCreater(username);
				ypi.setCreatedate(now);
				ypi.setIndate(now);
				ypi.setOperator(username);
				ypi.setIntype("500404");//移送接收入库
				ypi.setMemo(cp.getMemo4());
				ypi.setButtressno(ypb.getButtressno());
				ypi.setPosition("1");//默认1层1位置		
				ypi.setLocality("1");
				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("500205");//入库仓库为贸易外库500205
				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.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.setInorder(order);
				ypi.setInteam(team);
				
				// 加入物料属性：20230725刘侣
				ypi.setObj_attr_in(ypd.getObject_attr());
				// end
				
				this.getMapper(YdmProductInlistMapper.class).insert(ypi);				
				//5、新增移库操作
				YdmProductMove ypm=new YdmProductMove();
				ypm.setMovebillno(this.getBean(YdmProductMoveServiceImpl.class).createMOVEBILLNO());
				ypm.setOutbillno(ypo.getOutbillno());
				ypm.setInbillno(ypi.getInbillno());
				ypm.setBillno(billno);
				ypm.setMovedate(now);
				ypm.setMoveoperator(username);
				ypm.setCreatedate(now);
				ypm.setCreater(username);
				ypm.setCarno("8");
				ypm.setIsaccept("1");
				ypm.setRemanagementno("20171218221814830158");
				ypm.setRestorageattr("500205");
				ypm.setAcceptdate(now);
				ypm.setCoilno(ypd.getCoilno());
				ypm.setCoiltype(ypd.getCoiltype());
				ypm.setMaterailtype(ypd.getMaterailtype());
				ypm.setSource(ypd.getSource());
				ypm.setMaterailsupplier(ypd.getMaterailsupplier());
				ypm.setIsbox(ypd.getIsbox());
				ypm.setBoxno(ypd.getBoxno());
				ypm.setDrawingno(ypd.getDrawingno());
				ypm.setBatchno(ypd.getBatchno());
				ypm.setHeatno(ypd.getBatchno());
				ypm.setSmpno(ypd.getSmpno());
				ypm.setManagementno(ypd.getManagementno());
				ypm.setStorageattr(ypd.getStorageattr());
				ypm.setProd_code(ypd.getProd_code());
				ypm.setProd_name(ypd.getProd_name());
				ypm.setStd_code(ypd.getStd_code());
				ypm.setStd_name(ypd.getStd_name());
				ypm.setUse_code(ypd.getUse_code());
				ypm.setUse_name(ypd.getUse_name());
				ypm.setPline_name(ypd.getPline_name());
				ypm.setPostid(ypd.getPostid());
				ypm.setThick(ypd.getThick());
				ypm.setWidth(ypd.getWidth());
				ypm.setLength(ypd.getLength());
				ypm.setDiameter_inn(ypd.getDiameter_inn());
				ypm.setDiameter_out(ypd.getDiameter_out());
				ypm.setQuantity(ypd.getQuantity());
				ypm.setTheoryweight(ypd.getTheoryweight());
				ypm.setCoreweight(ypd.getCoreweight());
				ypm.setGrossweight(ypd.getGrossweight());
				ypm.setPackweight(ypd.getPackweight());
				ypm.setFactweight(ypd.getFactweight());
				ypm.setCustomer_nm(ypd.getCustomer_nm());
				ypm.setCustomer_no(ypd.getCustomer_no());
				ypm.setReceiv_no(ypd.getReceiv_no());
				ypm.setReceiv_nm(ypd.getReceiv_nm());
				ypm.setOrderno(ypd.getOrderno());
				ypm.setProdorderno(ypd.getProdorderno());
				ypm.setSteelcode(ypd.getSteelcode());
				ypm.setJudgesteelcode(ypd.getJudgesteelcode());
				ypm.setPacking_group(ypd.getPacking_group());
				ypm.setChemresult(ypd.getChemresult());
				ypm.setSizeresult(ypd.getSizeresult());
				ypm.setSurfaceresult(ypd.getSurfaceresult());
				ypm.setWeightresult(ypd.getWeightresult());
				ypm.setJudgeresult(ypd.getJudgeresult());
				ypm.setPhysresult(ypd.getPhysresult());
				ypm.setSpyresult(ypd.getSpyresult());
				ypm.setProducedate(ypd.getProducedate());
				ypm.setProduceorder(ypd.getProduceorder());
				ypm.setProduceteam(ypd.getProduceteam());
				ypm.setIndate(ypd.getIndate());
				ypm.setInorder(ypd.getInorder());
				ypm.setInteam(ypd.getInteam());
				if (CollectionUtils.isNotEmpty(ypbList)) {					
					ypm.setArea(this.getMapper(YdmBaseButtressconfigMapper.class).findById(ypbList.get(0).getAreano()).getButtressname());//区域
					ypm.setButtressname(this.getMapper(YdmBaseButtressconfigMapper.class).findById(ypbList.get(0).getButtressno()).getButtressname());//垛位
					ypm.setLocation(ypbList.get(0).getLocality()+"");//位置
				}				
				this.getMapper(YdmProductMoveMapper.class).insert(ypm);
				//4、库存修改
				ypd.setStorageattr("500205");
				ypd.setUpdatedate(now);
				ypd.setUpdater(username);
				this.getMapper(YdmProductDetailMapper.class).update(ypd);
				//5、修改移库标识
				lpi.setIs_move("1");
				this.getMapper(LmsPassportinfoMapper.class).update(lpi);
				//6、日志
				MesOprLog mol = new MesOprLog("物流管理", "转库出厂证管理", "移送贸易库", username, opr_time, ypd.getCoilno(), null, null, null, "自动移送至贸易外库");
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
		}
		rm.setState("200");
		rm.setMsgInfo("移送贸易外库成功");
		return rm;
	}
}
