package market.Slm.DeliveryManagement.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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

import market.Api.Mes.impl.MesApiServiceImpl;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Logistics.impl.SpmDeliveryServiceImpl;
import market.Lms.Logistics.impl.SpmTransportDetailServiceImpl;
import market.Lms.Logistics.mapper.SpmDeliveryDetailMapper;
import market.Lms.Logistics.mapper.SpmDeliveryMapper;
import market.Lms.Logistics.mapper.SpmDistrbuteMainMapper;
import market.Lms.Logistics.mapper.SpmTransportDetailMapper;
import market.Lms.Logistics.vo.SpmDelivery;
import market.Lms.Logistics.vo.SpmDeliveryDetail;
import market.Lms.Logistics.vo.SpmDistrbuteMain;
import market.Lms.Logistics.vo.SpmTransportDetail;
import market.Lms.Warehouse.impl.YdmProductInlistServiceImpl;
import market.Lms.Warehouse.impl.YdmProductOutlistServiceImpl;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.mapper.YdmProductOutlistMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.service.SlmLadingBillDetailService;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

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

@RemoteService(path="SlmLadingBillDetailService")
public class SlmLadingBillDetailServiceImpl extends BaseServiceImpl<SlmLadingBillDetail,Object> implements SlmLadingBillDetailService {

	/**
	 * 查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmLadingBillDetail> sum){
		ResultModel rm=new ResultModel();
		try{
			SlmLadingBillDetail detail=sum.getObject();
			/*int pageIndex=sum.getPageIndex();
			int pageSize=sum.getPageSize();*/
			// List<SlmLadingBillDetail> list=this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(detail, null, " create_time desc", (pageIndex-1)*pageSize, pageIndex*pageSize);
			List<SlmLadingBillDetail> list = this.getMapper(SlmLadingBillDetailMapper.class).findBillDetail(detail);
			for(SlmLadingBillDetail details:list){
				String order_no=details.getContract_no()+details.getContract_line_seq()+details.getOrder_seq();
				details.setOrder_no(order_no);
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}

	/**
	 * 查询-有效
	 * */
	public ResultModel doQueryValidWeb(CommonPage<SlmLadingBillDetail> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillDetail detail=sum.getObject();
		try{
			List<SlmLadingBillDetail> list=this.getMapper(SlmLadingBillDetailMapper.class).doQueryValid(detail);
			List<SlmLadingBillDetail> temp_list=new ArrayList<SlmLadingBillDetail>();
			for(SlmLadingBillDetail details:list){
				double weight=details.getTheoryweight()==null?0:details.getTheoryweight();
				if(weight==0 && !(details.getCoilno().contains("F") && details.getCoilno().contains("H"))){
				}else{
					temp_list.add(details);
				}
			}
			rm.setData(temp_list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}

	/**
	 * 删除
	 * */
	public ResultModel doDeleteWeb(CommonPage<SlmLadingBillDetail> sum){
		ResultModel rm=new ResultModel();
		try{
			SlmLadingBillDetail detail=sum.getObject();
			this.getMapper(SlmLadingBillDetailMapper.class).delete(detail.getDetail_no());
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}

	public String doAdd(SlmLadingBillDetail detail) {
		String msg=null;
		try{
			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()); //操作时间
			int count = this.getMapper(SlmLadingBillDetailMapper.class).countWithCondition(null," LINE_NO like concat('"+detail.getLine_no()+"','%')")+1;
			detail.setDetail_no(detail.getLine_no()+String.format("%03d", count));
			detail.setCreate_man_no(userId);
			detail.setCreate_man_name(userName);
			detail.setCreate_time(new Date());
			this.getMapper(SlmLadingBillDetailMapper.class).insert(detail);
			// 新增提单明细成功时增加日志：
			//日志
			MesOprLog mol = new MesOprLog("销售管理", "汽运提货单管理", "新增提货单明细", userName, opr_time, detail.getCoilno(), null, detail.getBill_no(), null, "转库费单价：" + detail.getZkf_u_price() + ", 资金占用费单价：" + detail.getZj_u_price() + ", 额外加价总额：" + detail.getExtra_money());
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}catch(Exception e){
			msg="提单明细新增错误："+e.getMessage();
		}
		return msg;
	}

	public List<SlmLadingBillDetail> doQuery(SlmLadingBillDetail detail) {
		return this.getMapper(SlmLadingBillDetailMapper.class).findBillDetail(detail);
	}

	public void doDelete(SlmLadingBillDetail details) {
		this.getMapper(SlmLadingBillDetailMapper.class).doDelete(details.getDetail_no());
	}
	
	/**
	 * 20200909 华pan 新增提货单导出功能
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQuerySlbdForReport(CommonPage<SlmLadingBillDetail> cp){
		ResultModel rm=new ResultModel();
		SlmLadingBillDetail slbd = cp.getObject();
		try{
			String conditon = "";
			if (StringUtils.isNotEmpty(slbd.getCustomer_no())) {
				conditon += " and t.customer_no = '"+slbd.getCustomer_no()+"'";
			}
			if (StringUtils.isNotEmpty(slbd.getCoilno())) { //卷号
				conditon += " and t.coilno like '%"+ slbd.getCoilno()+"%'";
			}
			if (StringUtils.isNotEmpty(slbd.getMaterailcoilno())) { //原料卷号
				conditon += " and t.materailcoilno like '%"+slbd.getMaterailcoilno()+"%'";
			}
			if (StringUtils.isNotEmpty(slbd.getBill_no())) { //提货单号
				conditon += " and t.bill_no like '%"+slbd.getBill_no()+"%'";
			}
			if (StringUtils.isNotEmpty(slbd.getContract_no())) { //合同号
				conditon += " and t.contract_no like '%"+slbd.getContract_no()+"%'";
			}
			if (StringUtils.isNotEmpty(cp.getStartTime())) { //开始时间
				conditon += " and slbh.create_time >= to_date('"+cp.getStartTime()+" 00:00:00','yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(cp.getEndTime())) {//结束时间
				conditon += " and slbh.create_time <= to_date('"+cp.getEndTime()+" 23:59:59','yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(slbd.getValid_status())) {//提货单状态
				conditon += " and slbh.valid_status = '"+slbd.getValid_status()+"'";
			}
			List<HashMap> hmList = this.getMapper(SlmLadingBillDetailMapper.class).doQuerySlbdForReport(conditon);
			rm.setData(hmList);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 一次结算功能
	 * @param detail
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doFirstSettleBill(CommonPage<SlmLadingBillHeat> cp) {
		ResultModel rm = new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(now);		
		// *** 防止数据量过大，先第一步进行判断
		List<SlmLadingBillHeat> paramList = cp.getObjectList();
		List<SlmLadingBillHeat> slbhList = new ArrayList<SlmLadingBillHeat>();
		for (SlmLadingBillHeat param : paramList) {
			SlmLadingBillHeat slbh = this.getMapper(SlmLadingBillHeatMapper.class).findById(param.getBill_no());			
			if (slbh!=null) {
				if (!"1".equals(slbh.getValid_status()) || "0".equals(slbh.getValid_flag())) {
					rm.setState("500");
					rm.setMsgInfo("提单【"+param.getBill_no()+"】的状态不是【编辑】或者【提单无效】，无法一次结算");
					return rm;
				}
				if (!slbh.getSolutions_name().contains("到优特")) {
					rm.setState("500");
					rm.setMsgInfo("提单【"+param.getBill_no()+"】的运输方案不含【到优特】，无法一次结算");
					return rm;
				}
				if (Math.abs((slbh.getCreate_time().getTime()-now.getTime())/1000) < 10) {
					rm.setState("500");
					rm.setMsgInfo("操作过快，请稍候。。。。。。");
					return rm;
				}
				slbhList.add(slbh);
			}
		}
		
		//开始处理业务逻辑
		try{
			for (SlmLadingBillHeat slbh : slbhList) {
				//1.提单状态直接转换至【实际关闭】
				slbh.setValid_status("11");		//实际关闭
				slbh.setUpdate_man_no(userId);
				slbh.setUpdate_man_name(userName);
				slbh.setUpdate_time(now);
				slbh.setMemo("一次结算");
				slbh.setIssuer_time(now);
				slbh.setIssuer_man_name(userName);
				slbh.setIssuer_man_no(userId);
				this.getMapper(SlmLadingBillHeatMapper.class).update(slbh);
				//理货单号
				String distrbuteno = this.getBean(SpmDeliveryServiceImpl.class).createDistrbuteNO();
				//装车单号
				String outbillno = this.getBean(SpmTransportDetailServiceImpl.class).createOutBillNo();
				//同车序号
				String carSeq = this.getMapper(SpmDeliveryMapper.class).getCode(new SimpleDateFormat("yyyyMMdd").format(new Date()));
				//2.提单行处理：
				String condition = " and bill_no = '"+slbh.getBill_no()+"'";
				List<SlmLadingBillLine> slblList = this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, condition, "line_no desc", 0, 0);
				for (SlmLadingBillLine slbl : slblList) {
					//2.1 反写实际支数和实际重量
					SlmLadingBillLine SLBL = this.getMapper(SlmLadingBillLineMapper.class).doQuaryRebackForLine(slbl.getLine_no());
					this.getMapper(SlmLadingBillLineMapper.class).update(SLBL);
					//2.2 新增SpmDeliveryDetail
					SpmDeliveryDetail sdd = new SpmDeliveryDetail();
					sdd.setDeliveryno(slbh.getBill_no());
					sdd.setLineNo(slbl.getLine_no());
					sdd.setDistrbutequantity(SLBL.getActual_quantity().intValue());
					sdd.setDisTheoryWeight(SLBL.getDis_theory_weight());
					sdd.setDisFactWeight(SLBL.getDis_fact_weight());
					sdd.setQuantity(SLBL.getActual_quantity().intValue());
					sdd.setLoadFactWeight(SLBL.getActual_weight());
					sdd.setLoadTheoryWeight(SLBL.getDis_theory_weight());
					sdd.setStarttime(slbh.getEffect_start_time());
					sdd.setOvertime(slbh.getEffect_end_time());
					sdd.setCloser(userName);
					sdd.setClosetime(now);
					sdd.setState("3");//已装车
					sdd.setReceiver(userName);
					sdd.setReceivetime(now);
					sdd.setCarno("8");
					sdd.setPlanStartTime(slbh.getEffect_start_time());
					sdd.setPlanEndTime(slbh.getEffect_end_time());
					sdd.setCreater(userName);
					sdd.setCreatedate(now);
					// 销售出厂-提货单实绩表(从)
					this.getMapper(SpmDeliveryDetailMapper.class).insert(sdd);
					
					// 一次结算时将订单由 生产/缴库 改成 发货：20230720刘侣
					SlmOrderInfo orderYC=new SlmOrderInfo();
					orderYC.setContract_no(slbl.getContract_no());
					orderYC.setContract_line_seq(slbl.getContract_line_seq());
					orderYC.setOrder_seq(slbl.getOrder_seq());
					List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(orderYC,0,0);
					if(order_list.size()>0){
						orderYC=order_list.get(0);
						if(orderYC!=null&&("103409".equals(orderYC.getOrder_flag_no())||"103408".equals(orderYC.getOrder_flag_no()))){
							orderYC.setP_order_flag_no(orderYC.getOrder_flag_no());
							orderYC.setP_order_flag_name(orderYC.getOrder_flag_name());
							orderYC.setOrder_flag_no("103410");
							orderYC.setOrder_flag_name("发货");
							this.getMapper(SlmOrderInfoMapper.class).update(orderYC);
						}
					}
					// end
					
					// 一次结算时计算当前订单内的所有一次结算重量是否达到订单要求的90%：20231007 刘侣
					PlnProdorder pp = new PlnProdorder();
					pp.setOrder_no(slbl.getOrder_no());
					List<PlnProdorder> ppL = this.getMapper(PlnProdorderMapper.class).find(pp, 0, 0);
					if (ppL != null && ppL.size() > 0 && order_list.size() > 0) {
						// 获取订单内所有一次结算重量：
						Double ycW = this.getMapper(SlmLadingBillHeatMapper.class).getYCW(slbl.getOrder_no());
						
						if (order_list.get(0).getEstimate_weight() != null) {
							if (ycW >= order_list.get(0).getEstimate_weight() * 0.9) {
								// 订单一次结算总量大于等于订单总量的90%：修改生产订单状态为发货完成：
								ppL.get(0).setStatus("0PAA50");
								this.getMapper(PlnProdorderMapper.class).update(ppL.get(0));
							}
						}
					}
					// end
					
					//3.提单明细处理
					condition = " and line_no = '"+slbl.getLine_no()+"'";
					List<SlmLadingBillDetail> slbdList = this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, condition, "coilno desc", 0, 0);
					if (CollectionUtils.isNotEmpty(slbdList)) {
						for (SlmLadingBillDetail slbd : slbdList) {
							//3.0 修改
							
							//3.2 新增SpmTransportDetail 销售出厂-装车单从表
							SpmTransportDetail std = new SpmTransportDetail();
							std.setOutbillno(outbillno);
							std.setDistrbuteno(distrbuteno);
							std.setBillNo(slbd.getBill_no());//特别注意，这里的billNO
							std.setLineNo(slbd.getLine_no());
							std.setLoaddate(now);
							std.setLoadoperator(userName);
							YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(slbd.getCoilno());
							if (ypd!=null) {
								
								// 限制已经一次结算过，不允许再次一次结算20230224刘侣
								if("507102".equals(ypd.getObject_attr())) {
									throw new Exception("卷号：" + slbd.getCoilno() + " 已经是客户属性，不允许再次做一次结算。");
								}
								// end
								
								//3.1 转换客户属性(一次结算，物料不进行出库操作)						
								ypd.setObject_attr("507102");
								ypd.setState("0");
								ypd.setUpdatedate(now);
								ypd.setUpdater(userName);
								this.getMapper(YdmProductDetailMapper.class).update(ypd);
								
								// 一次结算记录出入库表的物料属性：20230726刘侣：以后没有成本模块了，这个也就没啥意义了20230816刘侣
//								YdmProductOutlist ypo=new YdmProductOutlist();
//								ypo.setCreater(userName);
//								ypo.setCreatedate(now);
//								ypo.setOutbillno(this.getBean(YdmProductOutlistServiceImpl.class).createOUTBILLNO());
//								ypo.setOuttype("");//一次结算的出库，暂时不知道
//								ypo.setOutdate(now);
//								ypo.setOutoperator(userName);
//								ypo.setCoilno(ypd.getCoilno());
//								ypo.setCoiltype(ypd.getCoiltype());
//								ypo.setMaterailtype(ypd.getMaterailtype());
//								ypo.setSource(ypd.getSource());
//								ypo.setMaterailsupplier(ypd.getMaterailsupplier());
//								ypo.setIsbox(ypd.getIsbox());
//								ypo.setBoxno(ypd.getBoxno());
//								ypo.setDrawingno(ypd.getDrawingno());
//								ypo.setBatchno(ypd.getBatchno());
//								ypo.setHeatno(ypd.getBatchno());
//								ypo.setSmpno(ypd.getSmpno());
//								ypo.setManagementno(ypd.getManagementno());
//								ypo.setStorageattr(ypd.getStorageattr());
//								ypo.setProd_code(ypd.getProd_code());
//								ypo.setProd_name(ypd.getProd_name());
//								ypo.setStd_code(ypd.getStd_code());
//								ypo.setStd_name(ypd.getStd_name());
//								ypo.setUse_code(ypd.getUse_code());
//								ypo.setUse_name(ypd.getUse_name());
//								ypo.setPline_name(ypd.getPline_name());
//								ypo.setPostid(ypd.getPostid());
//								ypo.setThick(ypd.getThick());
//								ypo.setWidth(ypd.getWidth());
//								ypo.setLength(ypd.getLength());
//								ypo.setDiameter_inn(ypd.getDiameter_inn());
//								ypo.setDiameter_out(ypd.getDiameter_out());
//								ypo.setQuantity(ypd.getQuantity());
//								ypo.setTheoryweight(ypd.getTheoryweight());
//								ypo.setCoreweight(ypd.getCoreweight());
//								ypo.setGrossweight(ypd.getGrossweight());
//								ypo.setPackweight(ypd.getPackweight());
//								ypo.setFactweight(ypd.getFactweight());
//								ypo.setCustomer_nm(ypd.getCustomer_nm());
//								ypo.setCustomer_no(ypd.getCustomer_no());
//								ypo.setReceiv_no(ypd.getReceiv_no());
//								ypo.setReceiv_nm(ypd.getReceiv_nm());
//								ypo.setOrderno(ypd.getOrderno());
//								ypo.setProdorderno(ypd.getProdorderno());
//								ypo.setSteelcode(ypd.getSteelcode());
//								ypo.setJudgesteelcode(ypd.getJudgesteelcode());
//								ypo.setPacking_group(ypd.getPacking_group());
//								ypo.setChemresult(ypd.getChemresult());
//								ypo.setSizeresult(ypd.getSizeresult());
//								ypo.setSurfaceresult(ypd.getSurfaceresult());
//								ypo.setWeightresult(ypd.getWeightresult());
//								ypo.setJudgeresult(ypd.getJudgeresult());
//								ypo.setPhysresult(ypd.getPhysresult());
//								ypo.setSpyresult(ypd.getSpyresult());
//								ypo.setButtressno(ypd.getButtressno());				 
//								if(ypd.getLocality()!=null){					
//									ypo.setLocality(Long.valueOf(ypd.getLocality()));
//								}
//								ypo.setMemo("一次结算原地出库记录");
//								
//								// 加入物料属性：20230725刘侣
//								ypo.setObj_attr_out("507101");
//								
//								this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
								
								// 一次结算原地入库记录：以后没有成本模块了，这个也就没啥意义了20230816刘侣
//								YdmProductInlist ypi = new YdmProductInlist();
//								ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
//								ypi.setCreatedate(now);
//								ypi.setCreater(userName);				
//								ypi.setCoilno(ypd.getCoilno());
//								ypi.setCoiltype(ypd.getCoiltype());
//								ypi.setMaterailtype(ypd.getMaterailtype());
//								ypi.setSource(ypd.getSource());
//								ypi.setMaterailsupplier(ypd.getMaterailsupplier());
//								ypi.setIsbox(ypd.getIsbox());
//								ypi.setBoxno(ypd.getBoxno());
//								ypi.setDrawingno(ypd.getDrawingno());
//								ypi.setBatchno(ypd.getBatchno());
//								ypi.setHeatno(ypd.getBatchno());
//								ypi.setSmpno(ypd.getSmpno());
//								ypi.setManagementno(ypd.getManagementno());
//								ypi.setStorageattr(ypd.getStorageattr());
//								ypi.setProd_code(ypd.getProd_code());
//								ypi.setProd_name(ypd.getProd_name());
//								ypi.setStd_code(ypd.getStd_code());
//								ypi.setStd_name(ypd.getStd_name());
//								ypi.setUse_code(ypd.getUse_code());
//								ypi.setUse_name(ypd.getUse_name());
//								ypi.setPline_name(ypd.getPline_name());
//								ypi.setPostid(ypd.getPostid());
//								ypi.setThick(ypd.getThick());
//								ypi.setWidth(ypd.getWidth());
//								ypi.setLength(ypd.getLength());
//								ypi.setDiameter_inn(ypd.getDiameter_inn());
//								ypi.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.setOperator(userName);
//								//ypi.setButtressno("100106001");//虚拟区
//								ypi.setLocality("1");
//								ypi.setPosition("1");
//								ypi.setMemo("一次结算原地入库记录");
//								ypi.setMachine_code(ypd.getMachine_code());
//								ypi.setMachine_name(ypd.getMachine_name());
//								
//								// 加入物料属性：20230725刘侣
//								ypi.setObj_attr_in("507102");
//							
//								this.getMapper(YdmProductInlistMapper.class).insert(ypi);
								// end
								
								//3.2 调用物料进行跟踪
								PrcMaterielProcess pmp = new PrcMaterielProcess();
								pmp.setObject_no(ypd.getCoilno());
								pmp.setPrc_code("5BYS10");
								pmp.setCreate_time(now);
								pmp.setRemark("一次结算装车出库");
								pmp.setCreate_man_name(userName);
								PrcMaterielProcess pmp1 = new PrcMaterielProcess();
								pmp1.setObject_no(ypd.getCoilno());
								pmp1.setPrc_code("5BYZ10");
								pmp1.setCreate_time(now);
								pmp1.setRemark("一次结算"+time);
								pmp1.setCreate_man_name(userName);
								this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp1);
								this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
								
								std.setObjectno(ypd.getCoilno());
								std.setObjectnotype(ypd.getCoiltype());
								std.setMaterailtype(ypd.getMaterailtype());
								std.setSource(ypd.getSource());					
								std.setBatchno(ypd.getBatchno());
								std.setHeatno(ypd.getHeatno());
								std.setSmpNo(ypd.getSmpno());
								std.setManagementno(ypd.getManagementno());
								std.setStorageattr(ypd.getStorageattr());
								std.setPrdCode(ypd.getProd_code());
								std.setPrdName(ypd.getProd_name());
								std.setStdCode(ypd.getStd_code());
								std.setStdName(ypd.getStd_name());
								std.setUsgCode(ypd.getUse_code());
								std.setUsgName(ypd.getUse_name());
								std.setHeight(ypd.getThick());
								std.setWidth(ypd.getWidth());
								std.setLength(ypd.getLength());
								std.setDiameter(ypd.getDiameter_out());
								std.setInterdiameter(ypd.getDiameter_inn());
								std.setQuantity(1);
								std.setTheoryweight(ypd.getTheoryweight());
								std.setFactweight(ypd.getFactweight());
								std.setCustomerNo(ypd.getCustomer_no());
								std.setCustomerNm(ypd.getCustomer_nm());
								std.setReceivNo(ypd.getReceiv_no());
								std.setReceivNm(ypd.getReceiv_nm());
								std.setOrderno(ypd.getOrderno());
								std.setProdorderno(ypd.getProdorderno());
								std.setSteelcode(ypd.getSteelcode());
								std.setJudgesteelcode(ypd.getJudgesteelcode());
								std.setChemresult(ypd.getChemresult());
								std.setSizeresult(ypd.getSizeresult());							
								std.setSurfaceresult(ypd.getSurfaceresult());
								std.setWeightresult(ypd.getWeightresult());
								std.setJudgeresult(ypd.getJudgeresult());
								std.setPhysresult(ypd.getPhysresult());
								std.setProducedate(ypd.getProducedate());
								std.setProduceteam(ypd.getProduceteam());
								std.setProduceorder(ypd.getProduceorder());
								std.setInteam(ypd.getInteam());
								std.setIndate(ypd.getIndate());
								std.setState("1");
							} else {
								// 直接抛错，来防止一次结算不改变卷子属性成客户20230224刘侣
								throw new Exception("卷号：" + slbd.getCoilno() + " 未查询到，请联系管理员；");
								// end
							}
							std.setOutlistno(null);//一次结算，物料不进行出库操作
							std.setCreater(userName);
							std.setCreatedate(now);
							this.getMapper(SpmTransportDetailMapper.class).doInsert(std);							
						}
					}
				}
				//3.新增Spm_Delivery
				SlmLadingBillHeat SLBH = this.getMapper(SlmLadingBillLineMapper.class).doQuaryRebackForBill(slbh.getBill_no());
				SpmDelivery sd = new SpmDelivery();
				sd.setDeliveryno(slbh.getBill_no());
				sd.setDistrbutequantity(SLBH.getQuantity());
				sd.setDisTheoryWeight(SLBH.getDis_theory_weight());
				sd.setDisFactWeight(SLBH.getDis_fact_weight());
				sd.setQuantity(SLBH.getQuantity());
				sd.setLoadTheoryWeight(SLBH.getDis_theory_weight());
				sd.setLoadFactWeight(Double.parseDouble(SLBH.getFact_weight()));
				sd.setStarttime(slbh.getEffect_start_time());
				sd.setOvertime(slbh.getEffect_end_time());
				sd.setReceiver(userName);
				sd.setReceivetime(now);
				sd.setCloser(userName);
				sd.setClosetime(now);
				sd.setIssuer_time(now);
				sd.setState("6");//实际关闭
				sd.setPlanStartTime(slbh.getEffect_start_time());
				sd.setPlanEndTime(slbh.getEffect_end_time());
				sd.setCreater(userName);
				sd.setCreatedate(now);
				sd.setCar_seq(carSeq);//同车序号
				this.getMapper(SpmDeliveryMapper.class).insert(sd);
				//自动脱单
				this.getMapper(YdmProductDetailMapper.class).doTuoDan(sd.getDeliveryno());
				//4. 新增SpmDistrbuteMain理货单主表
				SpmDistrbuteMain sdm = new SpmDistrbuteMain();
				sdm.setDistrbuteno(distrbuteno);//理货单号：主键
				sdm.setDeliveryno(slbh.getBill_no());
				sdm.setLineNo(null);
				sdm.setOutbillno(outbillno);
				sdm.setDistrbutequantity(SLBH.getQuantity());
				sdm.setDisFactWeight(SLBH.getDis_fact_weight());
				sdm.setDisTheoryWeight(SLBH.getDis_theory_weight());
				sdm.setQuantity(SLBH.getQuantity());
				sdm.setLoadfactweight(Double.parseDouble(SLBH.getFact_weight()));//实际重量
				sdm.setLoadtheoryweight(SLBH.getDis_theory_weight());
				sdm.setStarttime(slbh.getEffect_start_time());
				sdm.setOvertime(slbh.getEffect_end_time());
				sdm.setCloser(userName);
				sdm.setClosetime(now);
				sdm.setState("2");
				sdm.setCarno("8");//一次结算：装8
				sdm.setLoadstore("500203");//固定，整个表都是500203
				sdm.setPlanStartTime(slbh.getEffect_start_time());
				sdm.setPlanEndTime(slbh.getEffect_end_time());
				sdm.setCreater(userName);
				sdm.setCreatedate(now);
				this.getMapper(SpmDistrbuteMainMapper.class).insert(sdm);
				
				// 对每个提货单号进行检测，看是否生成了spm几个表的数据：如果一次结算失败spm几个表是没有数据的：2023109刘侣
				List<SpmDistrbuteMain> sdmL = this.getMapper(SpmDistrbuteMainMapper.class).findWithCondition(null, " DELIVERYNO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (sdmL == null || sdmL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmDistrbuteMain");
				}
				List<SpmTransportDetail> ssdL = this.getMapper(SpmTransportDetailMapper.class).findWithCondition(null, " BILL_NO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (ssdL == null || ssdL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmTransportDetail");
				}
				List<SpmDelivery> sdlL = this.getMapper(SpmDeliveryMapper.class).findWithCondition(null, " DELIVERYNO = '"+slbh.getBill_no()+"'", null, 0, 0);
				if (sdlL == null || sdlL.size() == 0) {
					throw new Exception("一次结算失败，请等待两分钟后重试 SpmDelivery");
				}
				// end
			}
		}catch(Exception e){
			// 如果有trycatch，则需要设置手动20230304 刘侣
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			// end
			rm.setState("500");
			rm.setMsgInfo("一次结算失败："+e.getMessage());
			return rm;
		}
		rm.setState("200");
		rm.setMsgInfo("一次结算成功");
		return rm;
	}
	
}
