package com.prolog.rdc.tms.app.service.business.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.codingapi.tx.annotation.TxTransaction;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.app.constant.BussinessConstant;
import com.prolog.rdc.tms.app.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.app.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.app.constant.StatusConstant;
import com.prolog.rdc.tms.app.constant.enums.DispatchSelfPickHandleTypeEnum;
import com.prolog.rdc.tms.app.constant.enums.DriverReceiveStatusEnum;
import com.prolog.rdc.tms.app.constant.enums.IntelligentLockEnum;
import com.prolog.rdc.tms.app.constant.enums.ShipBillTypeEnum;
import com.prolog.rdc.tms.app.constant.enums.SignInStatusEnum;
import com.prolog.rdc.tms.app.dao.mapper.*;
import com.prolog.rdc.tms.app.model.dto.business.SelfPickUpPackageDTO;
import com.prolog.rdc.tms.app.model.dto.business.SelfPickUpShipBillDetailDTO;
import com.prolog.rdc.tms.app.model.dto.business.SelfWithdrawalConfirmQueryDTO;
import com.prolog.rdc.tms.app.model.dto.business.WaitForSelfWithdrawalDTO;
import com.prolog.rdc.tms.app.model.entity.*;
import com.prolog.rdc.tms.app.model.vo.business.*;
import com.prolog.rdc.tms.app.proxy.MainDataProxy;
import com.prolog.rdc.tms.app.service.business.ShipbillNodeTrackingService;
import com.prolog.rdc.tms.app.service.business.ShipbillOperateLogService;
import com.prolog.rdc.tms.app.service.business.WaitForSelfWithdrawalService;
import com.prolog.rdc.tms.app.util.BusinessFlowUtil;
import com.prolog.rdc.tms.app.util.MessageUtil;
import com.prolog.rdc.tms.app.util.PublicMethods;
import com.prolog.rdc.tms.app.util.StrategyUtil;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessMatchingDTO;
import com.prolog.rdc.tms.model.dto.basicData.ItemCheckDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleAndDriverDTO;
import com.prolog.rdc.tms.model.dto.message.SendMessageDTO;
import com.prolog.rdc.tms.model.entity.SysParamConfigModel;
import com.prolog.rdc.tms.model.enums.MessageOrderTypeEnum;
import com.prolog.rdc.tms.model.enums.MessageTypeEnum;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalOpenVO;
import com.prolog.rdc.tms.model.vo.basicData.ItemCheckVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleAndVehicleVO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 待自提实现层
 *
 * @author xyf
 * @since 2022/4/18 12:43
 */
@Service
@Slf4j
public class WaitForSelfWithdrawalServiceImpl implements WaitForSelfWithdrawalService {

	@Autowired
	private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

	@Autowired
	private MaindataFeign maindataTmsResource;

	@Autowired
	private TmsShipbillDetailMapper tmsShipbillDetailMapper;

	@Autowired
	private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

	@Autowired
	private TmsShipbillPackageMapper tmsShipbillPackageMapper;

	@Autowired
	private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

	@Autowired
	private TmsShipbillTransportLogMapper tmsShipbillTransportLogMapper;

	@Autowired
	private TmsShipbillNodeTrackingMapper tmsShipbillNodeTrackingMapper;

	@Autowired
	private BusinessFlowUtil businessFlowUtil;

	@Autowired
	private TmsShipbillOperateLogMapper tmsShipbillOperateLogMapper;

	@Autowired
	private ShipbillOperateLogService shipbillOperateLogService;

	@Autowired
	private ShipbillNodeTrackingService shipbillNodeTrackingService;

	@Autowired
	private MainDataProxy mainDataProxy;

	@Autowired
	private StrategyUtil strategyUtil;

	/**
	 * 主界面分页查询
	 *
	 * @param
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<WaitForSelfWithdrawalDTO> queryShipbill(WaitForSelfWithdrawalQueryVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 权限控制
		if (!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY) &&
				!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_GYS) &&
				!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_HZ) &&
				!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_KH) ) {
			throw new PrologException("当前人员没有操作权限");
		}
		// 添加查询条件
		vo.setUserType(user.getUserType());
		vo.setEnterpriseId(user.getEnterpriseId());
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			// 自有账号
			vo.setDepts(user.getDepts().stream().toArray(String[]::new));
			if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {
				vo.setIsDept(StatusConstant.IS_DEPT_YES);
			} else {
				vo.setIsDept(StatusConstant.IS_DEPT_NO);
				// 其它权限
				// 货主
				vo.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
				// 客户
				vo.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
				// 供应商
				vo.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
				// 仓库
				vo.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
			}
		} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_HZ)) {// 货主账号
			vo.setCargoOwnerUserId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_GYS)) {// 供应商账号
			vo.setSupplierUserId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_KH)) {// 客户账号
			vo.setCustomerUserId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		} else {
			throw new PrologException("当前人员没有操作权限！");
		}
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		List<WaitForSelfWithdrawalDTO> waitForSelfWithdrawalDTOList = tmsShipbillHeaderMapper.queryWaitForSelfWithdrawal(vo);
		// 行号
		int id = 1;
		// 订单业务类型
		List<Map<String, Object>> data2 = Lists.newArrayList();
		RestMessage<List<Map<String, Object>>> restMessage2 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_BUSINESS_TYPE, null, null, null);
		if (!restMessage2.isSuccess()) {
			throw new RuntimeException("订单业务类型翻译失败!");
		} else {
			data2 = restMessage2.getData();
		}
		for (WaitForSelfWithdrawalDTO selfWithdrawalDTO : waitForSelfWithdrawalDTOList) {
			selfWithdrawalDTO.setId(id);
			id++;
			selfWithdrawalDTO.setOrderBusinessTypeName(PublicMethods.change(data2, String.valueOf(selfWithdrawalDTO.getOrderBusinessType())));

			StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
			// 目的地
			consigneeProvinceCityDistrict.append(selfWithdrawalDTO.getConsigneeProvinceName());
			consigneeProvinceCityDistrict.append(selfWithdrawalDTO.getConsigneeCityName());
			consigneeProvinceCityDistrict.append(selfWithdrawalDTO.getConsigneeDistrictName());
			selfWithdrawalDTO.setConsigneeProvinceCityDistrict(consigneeProvinceCityDistrict.toString());
			// 始发地
			StringBuffer shipperProvinceCityDistrict = new StringBuffer();
			shipperProvinceCityDistrict.append(selfWithdrawalDTO.getShipperProvinceName());
			shipperProvinceCityDistrict.append(selfWithdrawalDTO.getShipperCityName());
			shipperProvinceCityDistrict.append(selfWithdrawalDTO.getShipperDistrictName());
			selfWithdrawalDTO.setShipperProvinceCityDistrict(shipperProvinceCityDistrict.toString());

			// 发货方类型
			if (DataDictionaryConstant.SHIPPER_TYPE_KH.equals(selfWithdrawalDTO.getShipperType())) {
				// 发货方名称
				selfWithdrawalDTO.setShipperName(selfWithdrawalDTO.getShipperUnitName() + DataDictionaryConstant.Line_SYMBOL + selfWithdrawalDTO.getShipperName());
			}

			// 收货方电话
			StringBuffer tel = new StringBuffer();
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 start
			if (ToolKits.isNotEmpty(selfWithdrawalDTO.getConsigneePhoneNumber())) {
				tel.append(selfWithdrawalDTO.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(selfWithdrawalDTO.getConsigneeLandlineNumber())) {
				tel.append(selfWithdrawalDTO.getConsigneeLandlineNumber());
			}
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 end
			if (ToolKits.isNotEmpty(tel.toString())) {
				selfWithdrawalDTO.setConsigneeTel(tel.toString());
			}

			// 收货方类型
			if (DataDictionaryConstant.CONSIGNEE_TYPE_KH.equals(selfWithdrawalDTO.getConsigneeType())) {
				// 收货方名称
				selfWithdrawalDTO.setConsigneeName(selfWithdrawalDTO.getConsigneeUnitName() + DataDictionaryConstant.Line_SYMBOL + selfWithdrawalDTO.getConsigneeName());
			} else if (DataDictionaryConstant.CONSIGNEE_TYPE_GYS.equals(selfWithdrawalDTO.getConsigneeType())) {
				// 收货方名称
				selfWithdrawalDTO.setConsigneeName(selfWithdrawalDTO.getConsigneeName() + DataDictionaryConstant.Line_SYMBOL + selfWithdrawalDTO.getShipperName());
			}

			// 获取包裹信息
			Criteria criteriaPkg = Criteria.forClass(TmsShipbillPackageModel.class);
			Restriction r1 = Restrictions.eq(TmsShipbillPackageModel::getShipbillId, selfWithdrawalDTO.getShipbillId());
			Restriction r2 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, user.getEnterpriseId());
			criteriaPkg.setRestriction(Restrictions.and(r1, r2));
			criteriaPkg.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));

			List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteriaPkg);

			List<SelfPickUpPackageDTO> loadingPackageDTOList = Lists.newArrayList();
			for (TmsShipbillPackageModel packageModel : tmsShipbillPackageModels) {
				SelfPickUpPackageDTO packageDTO = new SelfPickUpPackageDTO();
				BeanUtils.copyProperties(packageModel, packageDTO);
				loadingPackageDTOList.add(packageDTO);
			}
			selfWithdrawalDTO.setSelfPickUpPackageDTOS(loadingPackageDTOList);

			if (loadingPackageDTOList.size() == 0) {
				// 获取商品信息
				Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
				criteriaDetail.setRestriction(Restrictions.and(r1, r2));
				criteriaDetail.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
				List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);

				//匹配业务规则
				TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
				BeanUtils.copyProperties(selfWithdrawalDTO, model);
				StrategyBusinessMatchingDTO businessData = strategyUtil.shipbillMatchBusinessRule(model, tmsShipbillDetailModels);
				if (ToolKits.isNotEmpty(businessData) && businessData.getApplyPcsSelect().intValue() == 1) {
					selfWithdrawalDTO.setShowApplyPcs(businessData.getApplyPcsEnable());
				}
				if (ToolKits.isNotEmpty(businessData) && businessData.getInventoryCheckSelect().intValue() == 1) {
					selfWithdrawalDTO.setInventoryCheck(businessData.getInventoryCheckEnable());
				}

				List<SelfPickUpShipBillDetailDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					SelfPickUpShipBillDetailDTO detailDTO = new SelfPickUpShipBillDetailDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				selfWithdrawalDTO.setSelfPickUpShipBillDetailDTOS(detailDTOList);
			}

			if (ToolKits.isEmpty(selfWithdrawalDTO.getShowApplyPcs())) {
				selfWithdrawalDTO.setShowApplyPcs(Integer.valueOf(10));
			}
			if (ToolKits.isEmpty(selfWithdrawalDTO.getInventoryCheck())) {
				selfWithdrawalDTO.setInventoryCheck(Integer.valueOf(10));
			}
		}
		// 分页重组
		Page<WaitForSelfWithdrawalDTO> page = PageUtils.getPage(waitForSelfWithdrawalDTOList);
		if (waitForSelfWithdrawalDTOList instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<WaitForSelfWithdrawalDTO> p0 = (com.github.pagehelper.Page<WaitForSelfWithdrawalDTO>) waitForSelfWithdrawalDTOList;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}
		return page;
	}

	/**
	 * 商品查询
	 *
	 * @param itemQueryVO
	 * @return
	 */
	public List<SelfPickUpShipBillDetailDTO> queryShipbillDetail_(WaitForSelfItemQueryVO itemQueryVO) {
		ToolKits.isParamNull(itemQueryVO, "商品查询请求不为空");
		ToolKits.isParamNull(itemQueryVO.getShipbillId(), "运单ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 权限控制
		if (!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			throw new PrologException("当前人员没有操作权限");
		}
		// 获取商品信息
		Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
		Restriction r1 = Restrictions.eq(TmsShipbillPackageModel::getShipbillId, itemQueryVO.getShipbillId());
		Restriction r2 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, user.getEnterpriseId());

		criteriaDetail.setRestriction(Restrictions.and(r1, r2));
		criteriaDetail.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);

		List<SelfPickUpShipBillDetailDTO> detailDTOList = Lists.newArrayList();
		for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
			SelfPickUpShipBillDetailDTO detailDTO = new SelfPickUpShipBillDetailDTO();
			BeanUtils.copyProperties(detailModel, detailDTO);
			detailDTOList.add(detailDTO);
		}
		return detailDTOList;
	}

	/**
	 * 自提确认
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void selfWithdrawalConfirm(SelfWithdrawalConfirmVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vo.getShipbills(), "请选择要操作的运单");

		if (!user.getUserType().equals(BussinessConstant.USER_TYPE_ZY) &&
				!user.getUserType().equals(BussinessConstant.USER_TYPE_SJ) &&
				!user.getUserType().equals(BussinessConstant.USER_TYPE_SHY)) {
			throw new PrologException("当前人员没有操作权限");
		}

		StringBuffer nodeEvent = new StringBuffer();
		nodeEvent.append("自提确认");
		nodeEvent.append(" 自提时间:");
		nodeEvent.append(DateUtil.formatDateTime(vo.getSelfWithdrawalDate()));
		nodeEvent.append(" 自提人:");
		nodeEvent.append(vo.getSelfWithdrawalPerson());
		nodeEvent.append(" 联系方式:");
		nodeEvent.append(vo.getContactTel());
		if (ToolKits.isNotEmpty(vo.getVehiclePlateNumber())) {
			nodeEvent.append(" 车牌号：");
			nodeEvent.append(vo.getVehiclePlateNumber());
		}
		if (ToolKits.isNotEmpty(vo.getIdCrad())) {
			nodeEvent.append(" 身份证:");
			nodeEvent.append(vo.getIdCrad());
		}
		Date date = DateUtil.date();
		Map<String, Object> updateLoadingHeaderMap = Maps.newHashMap();
		updateLoadingHeaderMap.put("status", DataDictionaryConstant.SHIPBILL_STATUS_END);
		updateLoadingHeaderMap.put("updatetime", date);
		updateLoadingHeaderMap.put("updateperson", user.getNickname());
		// STD-DEVELOP20220823 lhb bwc0823003 20220825 start
		for (String id : vo.getShipbills()) {
			// STD-DEVELOP20220823 lhb bwc0823003 20220825 end
			TmsShipbillHeaderModel tmsShipbillHeader = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
			if (ToolKits.isEmpty(tmsShipbillHeader)) {
				throw new PrologException("运单【" + id + "】不存在");
			}
			if (tmsShipbillHeader.getStatus().intValue() > DataDictionaryConstant.SHIPBILL_STATUS_HD_ZT.intValue()) {
				throw new PrologException("运单【" + id + "】已经自提确认了");
			}
			Map<String, Object> queryMap = Maps.newHashMap();
			queryMap.put("shipbillId", id);
			// 自提车辆登记校验
			List<TmsLoadingBillDetailModel> tmsLoadingBillDetails = tmsLoadingBillDetailMapper.findByMap(queryMap, TmsLoadingBillDetailModel.class);
			if (tmsShipbillHeader.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_SELF_PICKUP_VEH_REG) && ToolKits.isEmpty(tmsLoadingBillDetails)) {
				throw new PrologException("运单【" + id + "】还没有做自提车辆登记，不能自提确认!");
			}
			if (ToolKits.isNotEmpty(tmsShipbillHeader)) {
				// 修改运单明细的商品信息
				Criteria criteriaShipbillDetail = Criteria.forClass(TmsShipbillDetailModel.class);
				Restriction r11 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, tmsShipbillHeader.getShipbillId());
				Restriction r12 = Restrictions.eq(TmsShipbillDetailModel::getEnterpriseId, user.getEnterpriseId());
				Restriction r13 = Restrictions.gt(TmsShipbillDetailModel::getPcs, BigDecimal.valueOf(0));
				criteriaShipbillDetail.setRestriction(Restrictions.and(r11, r12, r13));
				List<TmsShipbillDetailModel> shipbillDetailModels =  tmsShipbillDetailMapper.findByCriteria(criteriaShipbillDetail);
				BigDecimal totalDeliveryPcs = new BigDecimal(0);
				BigDecimal totalDeliveryVolume = new BigDecimal(0);
				BigDecimal totalDeliveryWeight = new BigDecimal(0);

				if (ToolKits.isNotEmpty(shipbillDetailModels)) {
					for (TmsShipbillDetailModel shipbillDetailModel : shipbillDetailModels) {
						shipbillDetailModel.setDeliveryPcs(shipbillDetailModel.getPcs());
						shipbillDetailModel.setPcs(new BigDecimal(0));
						shipbillDetailModel.setVolume(new BigDecimal(0));
						shipbillDetailModel.setWeight(new BigDecimal(0));
						tmsShipbillDetailMapper.update(shipbillDetailModel);

						ItemCheckVO itemCheckVO = new ItemCheckVO();
						itemCheckVO.setItemId(shipbillDetailModel.getItemId());
						RestMessage<ItemCheckDTO> restMessage3 = maindataTmsResource.getItem(itemCheckVO);
						if (!restMessage3.isSuccess()) {
							throw new RuntimeException("取商品资料信息失败:" + restMessage3.getMessage());
						}
						ItemCheckDTO rsItemInfo = restMessage3.getData();

						BigDecimal fatherDeliveryPcs = new BigDecimal(0);
						BigDecimal fatherDeliveryVolume = new BigDecimal(0);
						BigDecimal fatherDeliveryWeight = new BigDecimal(0);

						fatherDeliveryPcs = fatherDeliveryPcs.add(shipbillDetailModel.getDeliveryPcs());
						fatherDeliveryVolume = fatherDeliveryVolume.add(shipbillDetailModel.getDeliveryPcs().multiply(rsItemInfo.getVolume()));
						fatherDeliveryWeight = fatherDeliveryWeight.add(shipbillDetailModel.getDeliveryPcs().multiply(rsItemInfo.getWeight()));

						totalDeliveryPcs = totalDeliveryPcs.add(shipbillDetailModel.getDeliveryPcs());
						totalDeliveryVolume = totalDeliveryVolume.add(shipbillDetailModel.getDeliveryPcs().multiply(rsItemInfo.getVolume()));
						totalDeliveryWeight = totalDeliveryWeight.add(shipbillDetailModel.getDeliveryPcs().multiply(rsItemInfo.getWeight()));

						// 主单对应的运单明细
						String fatherShipbillIdForDetail = tmsShipbillHeader.getShipbillId();
						while (ToolKits.isNotEmpty(fatherShipbillIdForDetail)) {
							fatherShipbillIdForDetail = updateFatherShipbillDetail(fatherShipbillIdForDetail, shipbillDetailModel,fatherDeliveryPcs, date, user,rsItemInfo);
						}
					}
				}

				Integer oldStatus = tmsShipbillHeader.getStatus();
				if (ToolKits.isNotEmpty(tmsLoadingBillDetails) && tmsLoadingBillDetails.size() > 0) {
					// 更新调度明细
					TmsLoadingBillDetailModel tmsLoadingBillDetail = tmsLoadingBillDetails.get(0);
					tmsLoadingBillDetail.setUpdateperson(user.getNickname());
					tmsLoadingBillDetail.setUpdatetime(date);
					tmsLoadingBillDetail.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_END);
					tmsLoadingBillDetail.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);
					tmsLoadingBillDetailMapper.update(tmsLoadingBillDetail);

					// 更新调度表
					tmsLoadingBillHeaderMapper.updateMapById(tmsLoadingBillDetail.getLoadingBillId(), updateLoadingHeaderMap, TmsLoadingBillHeaderModel.class);
				}

				// 更新运单
				Map<String, Object> mapShipbillHeadUpdate = Maps.newHashMap();
				tmsShipbillHeader.setUpdateperson(user.getNickname());
				tmsShipbillHeader.setUpdatetime(date);
				tmsShipbillHeader.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_END);
				tmsShipbillHeader.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);

				mapShipbillHeadUpdate.put("status", DataDictionaryConstant.SHIPBILL_STATUS_END);
				mapShipbillHeadUpdate.put("updateperson", user.getNickname());
				mapShipbillHeadUpdate.put("updatetime", date);
				mapShipbillHeadUpdate.put("transportStatus", DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);
				Criteria criteriaHead = Criteria.forClass(TmsShipbillHeaderModel.class);
				Restriction r23 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_HD_ZT);
				Restriction r24 = Restrictions.eq(TmsShipbillHeaderModel::getShipbillId, tmsShipbillHeader.getShipbillId());
				criteriaHead.setRestriction(Restrictions.and(r23, r24));
				long upCnt = tmsShipbillHeaderMapper.updateMapByCriteria(mapShipbillHeadUpdate, criteriaHead);
				if (upCnt == 0) {
					throw new PrologException("运单【" + tmsShipbillHeader.getShipbillNo() + "】非待自提确认状态,确认失败");
				}

				// 更新运单运输记录
				Map<String, Object> queryMap2 = Maps.newHashMap();
				queryMap2.put("shipbillId", id);
				List<TmsShipbillTransLogModel> tmsShipbillTransportLogs = tmsShipbillTransportLogMapper.findByMap(queryMap2, TmsShipbillTransLogModel.class);
				if (ToolKits.isNotEmpty(tmsShipbillTransportLogs) && tmsShipbillTransportLogs.size() > 0) {
					TmsShipbillTransLogModel tmsShipbillTransportLog = tmsShipbillTransportLogs.get(0);
					tmsShipbillTransportLog.setSelfPickUpTime(vo.getSelfWithdrawalDate());
					tmsShipbillTransportLog.setSelfPickUpPerson(vo.getSelfWithdrawalPerson());// 自提人
					tmsShipbillTransportLog.setSelfPickUpTel(vo.getContactTel());// 自提人联系方式
					tmsShipbillTransportLog.setVehiclePlateNumber(vo.getVehiclePlateNumber());
					tmsShipbillTransportLog.setIdCard(vo.getIdCrad());
					tmsShipbillTransportLogMapper.update(tmsShipbillTransportLog);
				}

				// 运单节点保存
				// 获取节点ID
				RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_NODE_TRACKING_ID, "L");
				if (!restMessage.isSuccess()) {
					throw new RuntimeException("生成节点ID失败");
				}
				String nodeId = restMessage.getData();

				// 节点记录
				ShipbillNodeTracking model = new ShipbillNodeTracking();
				model.setId(nodeId);
				model.setNodeDate(vo.getSelfWithdrawalDate());
				model.setShipbillId(tmsShipbillHeader.getShipbillId());
				model.setShipbillNo(tmsShipbillHeader.getShipbillId());
				model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_END);
				model.setNodeEvent(nodeEvent.toString());
				model.setPicUrl(vo.getPicUrl());
				model.setUserId(user.getUserid());
				model.setUserName(user.getNickname());
				model.setEnterpriseId(user.getEnterpriseId());
				model.setEnterpriseName(user.getEnterpriseName());
				model.setCreateperson(user.getNickname());
				model.setCreatetime(date);
				tmsShipbillNodeTrackingMapper.save(model);

				// 运单日志保存
				// 获取日志ID
				RestMessage<String> logRestMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_OPERATE_LOG_ID, "L");
				if (!logRestMessage.isSuccess()) {
					throw new RuntimeException("生成日志ID失败");
				}
				String logId = logRestMessage.getData();

				TmsShipbillOperateLogModel logModel = new TmsShipbillOperateLogModel();
				logModel.setId(logId);
				logModel.setOperateDate(date);
				logModel.setUserId(user.getUserid());
				logModel.setUserName(user.getNickname());
				logModel.setEnterpriseId(user.getEnterpriseId());
				logModel.setEnterpriseName(user.getEnterpriseName());
				logModel.setCreateperson(user.getNickname());
				logModel.setCreatetime(date);
				logModel.setUpdateperson(user.getNickname());
				logModel.setUpdatetime(date);
				logModel.setShipbillId(tmsShipbillHeader.getShipbillId());
				logModel.setShipbillNo(tmsShipbillHeader.getShipbillId());
				logModel.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_DZT);
				logModel.setOldStatus(oldStatus);
				logModel.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_END);
				tmsShipbillOperateLogMapper.save(logModel);

			} else {
				throw new PrologException("自提确认的运单【" + id + "】在运单表中不存在");
			}
			MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.SELF_CONFIRM.getCode(), Lists.newArrayList(id)));
		}
	}

	/**
	 * 同步更新父运单商品明细
	 *
	 * @param shipbillId
	 * @param date
	 * @param user
	 * @return
	 */
	public String updateFatherShipbillDetail(String shipbillId, TmsShipbillDetailModel subShipbillDetailModel, BigDecimal totalDeliveryPcs, Date date, UserEntity user, ItemCheckDTO rsItemInfo) {
		// 查询运单
		TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);
		// 判断是否为原始单号
		if (ToolKits.isNotEmpty(tmsShipbillHeaderModel.getFatherShipbillId()) && !tmsShipbillHeaderModel.getFatherShipbillId().equals(shipbillId)) {
			// 查找父级单号
			TmsShipbillHeaderModel fatherShipbillHeaderModel = tmsShipbillHeaderMapper.findById(tmsShipbillHeaderModel.getFatherShipbillId(), TmsShipbillHeaderModel.class);

			Criteria criteriaShipbillDetail = Criteria.forClass(TmsShipbillDetailModel.class);
			Restriction r11 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, fatherShipbillHeaderModel.getShipbillId());
			Restriction r12 = Restrictions.eq(TmsShipbillDetailModel::getEnterpriseId, user.getEnterpriseId());
			Restriction r13 = Restrictions.eq(TmsShipbillDetailModel::getItemId, subShipbillDetailModel.getItemId());
			Restriction r14 = Restrictions.gt(TmsShipbillDetailModel::getPcs, BigDecimal.valueOf(0));
			criteriaShipbillDetail.setRestriction(Restrictions.and(r11, r12,r13,r14));
			List<TmsShipbillDetailModel> shipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaShipbillDetail);

			if (ToolKits.isEmpty(shipbillDetailModels)) {
				throw new PrologException("运单【" + shipbillId + "】的父运单的运单商品明细【" + subShipbillDetailModel.getItemName() + "】不存在");
			}

			BigDecimal detailDeliveryPcs = totalDeliveryPcs;
			for (TmsShipbillDetailModel fatherShipbillDetailModel : shipbillDetailModels) {
				if (detailDeliveryPcs.intValue() <= 0) {
					break;
				}
				if (fatherShipbillDetailModel.getPcs().intValue() >= detailDeliveryPcs.intValue()) {
					fatherShipbillDetailModel.setDeliveryPcs(fatherShipbillDetailModel.getDeliveryPcs().add(detailDeliveryPcs));

					// 剩余件数
					fatherShipbillDetailModel.setUpdateperson(user.getNickname());
					fatherShipbillDetailModel.setUpdatetime(date);
					fatherShipbillDetailModel.setPcs(fatherShipbillDetailModel.getOrigPcs().subtract(fatherShipbillDetailModel.getClosingPcs()).subtract(fatherShipbillDetailModel.getDeliveryPcs()));
					fatherShipbillDetailModel.setVolume(fatherShipbillDetailModel.getPcs().multiply(rsItemInfo.getVolume()));
					fatherShipbillDetailModel.setWeight(fatherShipbillDetailModel.getPcs().multiply(rsItemInfo.getWeight()));
					tmsShipbillDetailMapper.update(fatherShipbillDetailModel);
					detailDeliveryPcs = BigDecimal.valueOf(0);
					break;
				} else {
					fatherShipbillDetailModel.setDeliveryPcs(fatherShipbillDetailModel.getDeliveryPcs().add(fatherShipbillDetailModel.getPcs()));
					detailDeliveryPcs = detailDeliveryPcs.subtract(fatherShipbillDetailModel.getPcs());

					// 剩余件数
					fatherShipbillDetailModel.setUpdateperson(user.getNickname());
					fatherShipbillDetailModel.setUpdatetime(date);
					fatherShipbillDetailModel.setPcs(fatherShipbillDetailModel.getOrigPcs().subtract(fatherShipbillDetailModel.getClosingPcs()).subtract(fatherShipbillDetailModel.getDeliveryPcs()));
					fatherShipbillDetailModel.setVolume(fatherShipbillDetailModel.getPcs().multiply(rsItemInfo.getVolume()));
					fatherShipbillDetailModel.setWeight(fatherShipbillDetailModel.getPcs().multiply(rsItemInfo.getWeight()));
					tmsShipbillDetailMapper.update(fatherShipbillDetailModel);
				}
			}
			if (detailDeliveryPcs.intValue() > 0) {
				throw new PrologException("运单【" + shipbillId + "】的商品【" + subShipbillDetailModel.getItemName() + "】的件数>父运单的件数");
			}
			// 更新运单
			if (ToolKits.isEmpty(fatherShipbillHeaderModel.getTotalDeliveryPcs())) {
				fatherShipbillHeaderModel.setTotalDeliveryPcs(totalDeliveryPcs);
			} else {
				fatherShipbillHeaderModel.setTotalDeliveryPcs(fatherShipbillHeaderModel.getTotalDeliveryPcs().add(totalDeliveryPcs));
			}

			fatherShipbillHeaderModel.setTotalDeliveryVolume(fatherShipbillHeaderModel.getTotalDeliveryPcs().multiply(rsItemInfo.getVolume()));
			fatherShipbillHeaderModel.setTotalDeliveryWeight(fatherShipbillHeaderModel.getTotalDeliveryPcs().multiply(rsItemInfo.getWeight()));

			if (ToolKits.isEmpty(fatherShipbillHeaderModel.getDepartureTime())) {
				fatherShipbillHeaderModel.setDepartureTime(new Date());
			}
			fatherShipbillHeaderModel.setTotalPcs(fatherShipbillHeaderModel.getTotalPcs().subtract(totalDeliveryPcs));
			fatherShipbillHeaderModel.setTotalVolume(fatherShipbillHeaderModel.getTotalPcs().multiply(rsItemInfo.getVolume()));
			fatherShipbillHeaderModel.setTotalWeight(fatherShipbillHeaderModel.getTotalPcs().multiply(rsItemInfo.getWeight()));
			fatherShipbillHeaderModel.setActualTotalPcs(fatherShipbillHeaderModel.getTotalPcs());
			fatherShipbillHeaderModel.setActualTotalVolume(fatherShipbillHeaderModel.getTotalVolume());
			fatherShipbillHeaderModel.setActualTotalWeight(fatherShipbillHeaderModel.getTotalWeight());

			fatherShipbillHeaderModel.setUpdateperson(user.getNickname());
			fatherShipbillHeaderModel.setUpdatetime(date);
			tmsShipbillHeaderMapper.update(fatherShipbillHeaderModel);

			return fatherShipbillHeaderModel.getShipbillId();
		}
		return null;
	}

	/**
	 * 自提车辆登记
	 *
	 * @param vehicleRegisterVO
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void vehicleRegister(SelfPickUpVehicleRegisterVO vehicleRegisterVO) {
		log.info("自提登记开始处理:" + JSON.toJSONString(vehicleRegisterVO));
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vehicleRegisterVO.getSelfPickUpRegisterShipbillList(), "请选择要操作的运单");
		Date date = DateUtil.date();

		String dispatchSelfpickHandleType = mainDataProxy.getSystemParamByCode(DispatchSelfPickHandleTypeEnum.ENUM_NAME);
		// 拆分后需要自提登记的运单
		List<SelfPickUpRegisterShipbillVO> selfPickUpRegisterShipbills = vehicleRegisterVO.getSelfPickUpRegisterShipbillList();
		selfPickUpRegisterShipbills = selfPickUpRegisterShipbills.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(
						Comparator.comparing(
								SelfPickUpRegisterShipbillVO::getShipbillId))), ArrayList::new));
		log.info("自提登记开始处理入参去重:" + JSON.toJSONString(selfPickUpRegisterShipbills));
		List<String> selfRegShipbills = Lists.newArrayList();
		for (SelfPickUpRegisterShipbillVO registerShipbillVO : selfPickUpRegisterShipbills) {
			// 首先，按商品申请数量拆分
			// 自提登记商品明细
			List<SelfPickUpShipBillDetailVO> selfRegDetails = Lists.newArrayList();
			// 不自提登记商品明细
			List<SelfPickUpShipBillDetailVO> noSelfRegDetails = Lists.newArrayList();
			List<String> splitShipbills = Lists.newArrayList();
			if (ToolKits.isNotEmpty(registerShipbillVO.getSelfPickUpShipBillDetailDTOS())) {
				for (SelfPickUpShipBillDetailVO itemVO : registerShipbillVO.getSelfPickUpShipBillDetailDTOS()) {
					if (ToolKits.isEmpty(itemVO.getPcs()) || ToolKits.isEmpty(itemVO.getInventoryPcs()) || ToolKits.isEmpty(itemVO.getApplyPcs())) {
						itemVO.setApplyPcs(0);
						noSelfRegDetails.add(itemVO);
						continue;
					}
					if (itemVO.getApplyPcs().intValue() == 0) {
						noSelfRegDetails.add(itemVO);
						continue;
					}
					if (itemVO.getApplyPcs().intValue() > itemVO.getPcs().intValue()) {
						throw new PrologException("商品申请数量不能大于商品数量");
					}
					if (DispatchSelfPickHandleTypeEnum.VALID.getCode().equals(dispatchSelfpickHandleType) ||
							DispatchSelfPickHandleTypeEnum.VALID_AND_QTY.getCode().equals(dispatchSelfpickHandleType)) {
						if (registerShipbillVO.getInventoryCheck().intValue() == 10) {
							if (itemVO.getApplyPcs().intValue() > itemVO.getInventoryPcs().intValue()) {
								throw new PrologException("商品申请数量不能大于库存数量");
							}
						}
					}
					if (itemVO.getApplyPcs().intValue() == itemVO.getPcs().intValue()) {
						selfRegDetails.add(itemVO);
						continue;
					}
					// 自提商品明细
					SelfPickUpShipBillDetailVO selfRegItem = new SelfPickUpShipBillDetailVO();
					BeanUtils.copyProperties(itemVO, selfRegItem);
					selfRegItem.setPcs(BigDecimal.valueOf(itemVO.getApplyPcs()));
					selfRegDetails.add(selfRegItem);
					// 不自提商品明细
					SelfPickUpShipBillDetailVO noSelfRegItem = new SelfPickUpShipBillDetailVO();
					BeanUtils.copyProperties(itemVO, noSelfRegItem);
					noSelfRegItem.setPcs(BigDecimal.valueOf(itemVO.getPcs().intValue() - itemVO.getApplyPcs().intValue()));
//					noSelfRegItem.setInventoryPcs(itemVO.getInventoryPcs().intValue() - itemVO.getApplyPcs().intValue());
					BigDecimal inventoryPcs = NumberUtil.sub(itemVO.getInventoryPcs(), itemVO.getApplyPcs());
					inventoryPcs = NumberUtil.isGreater(inventoryPcs, BigDecimal.ZERO) ? inventoryPcs : BigDecimal.ZERO;
					noSelfRegItem.setInventoryPcs(inventoryPcs.intValue());
					noSelfRegDetails.add(noSelfRegItem);
				}

				// 按商品拆分运单
				if (ToolKits.isNotEmpty(selfRegDetails) && ToolKits.isNotEmpty(noSelfRegDetails)) {
					SelfRegSplitVO splitVO = new SelfRegSplitVO();
					splitVO.setShipbillId(registerShipbillVO.getShipbillId());
					Map<String, List<SelfPickUpShipBillDetailVO>> goodsMap = Maps.newHashMap();

					goodsMap.put("selfReg", selfRegDetails);
					goodsMap.put("selfRegNo", noSelfRegDetails);

					splitVO.setSplitGoodsMap(goodsMap);
					// 拆分处理
					splitShipbills.addAll(goodsSplit(splitVO, date, user));
				}
			}

			if (ToolKits.isEmpty(splitShipbills)) {
				selfRegShipbills.add(registerShipbillVO.getShipbillId());
			} else {
				selfRegShipbills.addAll(splitShipbills);
			}
		}

		// 校验司机车辆信息
		VehicleAndVehicleVO vehicleAndVehicleVO = new VehicleAndVehicleVO();
		vehicleAndVehicleVO.setDriverName(vehicleRegisterVO.getSelfWithdrawalPerson());
		vehicleAndVehicleVO.setPhoneNumber(vehicleRegisterVO.getContactTel());
		vehicleAndVehicleVO.setVehiclePlateNumber(vehicleRegisterVO.getVehiclePlateNumber());
		RestMessage<VehicleAndDriverDTO> VehicleRestMessage = maindataTmsResource.vehicleAutomaticExecute(vehicleAndVehicleVO);
		if (!VehicleRestMessage.isSuccess()) {
			throw new ParameterException("自提车辆信息校验失败:" + VehicleRestMessage.getMessage());
		}
		// 车辆司机信息
		VehicleAndDriverDTO vehicleAndDriverDTO = VehicleRestMessage.getData();

		// 获取装车单ID
		RestMessage<String> restMessage1 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_LOADING_BILL_HEADER_ID, "L");
		if (!restMessage1.isSuccess()) {
			throw new RuntimeException("生成装车单ID失败");
		}
		String loadingBillId = restMessage1.getData();

		Criteria criteriaTransport = Criteria.forClass(TmsShipbillTransLogModel.class);
		Map<String, Object> transportLogMap = Maps.newHashMap();
		transportLogMap.put("updateperson", user.getNickname());
		transportLogMap.put("updatetime", date);

		// 总件数
		BigDecimal goodsTotalPcs = new BigDecimal(0);
		// 总体积
		BigDecimal goodsTotalVolume = new BigDecimal(0);
		// 总重量
		BigDecimal goodsTotalWeight = new BigDecimal(0);
		for (String shipbillId : selfRegShipbills) {
			log.info("自提登记运单:" + JSON.toJSONString(selfRegShipbills));
			TmsShipbillHeaderModel headerModel = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);
			if (!headerModel.getStatus().equals(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW)) {
				log.info("运单【" + headerModel.getShipbillNo() + "】已自提登记");
				throw new PrologException("运单【" + headerModel.getShipbillNo() + "】已自提登记");
			}
			if (!headerModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_SELF_PICKUP_VEH_REG)) {
				// 流程没有自提车辆登记
				log.info("运单【" + shipbillId + "】没有配置车辆自提登记的流程，不能做车辆自提登记");
				throw new PrologException("运单【" + shipbillId + "】没有配置车辆自提登记的流程，不能做车辆自提登记");
			}
			// 重复自提登记
			Criteria criteriaLoadingBillDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
			Restriction r2 = Restrictions.eq(TmsLoadingBillDetailModel::getShipbillId, shipbillId);
			criteriaLoadingBillDetail.setRestriction(Restrictions.and(r2));
			List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModels = tmsLoadingBillDetailMapper.findByCriteria(criteriaLoadingBillDetail);
			if (ToolKits.isNotEmpty(tmsLoadingBillDetailModels)) {
				log.info("运单【" + shipbillId + "】已自提登记");
				throw new PrologException("运单【" + shipbillId + "】已自提登记");
			}

			// 登记信息保存到运输记录表中
			transportLogMap.put("selfPickUpPerson", vehicleRegisterVO.getSelfWithdrawalPerson());
			transportLogMap.put("selfPickUpTel", vehicleRegisterVO.getContactTel());
			transportLogMap.put("updatetime", date);
			transportLogMap.put("updateperson", user.getNickname());
			if (ToolKits.isNotEmpty(vehicleRegisterVO.getVehiclePlateNumber())) {
				transportLogMap.put("vehiclePlateNumber", vehicleRegisterVO.getVehiclePlateNumber());
			}
			if (ToolKits.isNotEmpty(vehicleRegisterVO.getIdCrad())) {
				transportLogMap.put("idCard", vehicleRegisterVO.getIdCrad());
			}
			if (ToolKits.isNotEmpty(vehicleRegisterVO.getMemo())) {
				transportLogMap.put("selfPickUpMemo", vehicleRegisterVO.getMemo());
			}
			Restriction r1 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, shipbillId);
			criteriaTransport.setRestriction(r1);
			tmsShipbillTransportLogMapper.updateMapByCriteria(transportLogMap, criteriaTransport);

			Map<String, Object> mapShipbillHeadUpdate = Maps.newHashMap();
			mapShipbillHeadUpdate.put("updateperson", user.getNickname());
			mapShipbillHeadUpdate.put("updatetime", date);

			// STD-DEVELOP20220823 lhb bwc0825001 20220905 自提登记审批 start
			boolean matched = approvalOpen(headerModel, DataDictionaryConstant.APPROVAL_FLOW_TYPE_ZT_REG, user);
			if (matched) {
				// 开启自提登记审批流
				headerModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_HD_ZT_APPROVAL);
				mapShipbillHeadUpdate.put("status", DataDictionaryConstant.SHIPBILL_STATUS_HD_ZT_APPROVAL);
				headerModel.setUpdatetime(date);
				headerModel.setUpdateperson(user.getNickname());
				Criteria criteriaHead = Criteria.forClass(TmsShipbillHeaderModel.class);
				Restriction r23 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
				Restriction r24 = Restrictions.eq(TmsShipbillHeaderModel::getShipbillId, headerModel.getShipbillId());
				criteriaHead.setRestriction(Restrictions.and(r23, r24));
				long upCnt = tmsShipbillHeaderMapper.updateMapByCriteria(mapShipbillHeadUpdate, criteriaHead);
				if (upCnt == 0) {
					log.info("运单【" + headerModel.getShipbillNo() + "】非待自提登记状态,登记失败");
					throw new PrologException("运单【" + headerModel.getShipbillNo() + "】非待自提登记状态,登记失败");
				}
				continue;
			}
			// STD-DEVELOP20220823 lhb bwc0825001 20220905 自提登记审批 end
			// 运单节点表
			// 获取节点ID
			RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_NODE_TRACKING_ID, "L");
			if (!restMessage.isSuccess()) {
				throw new RuntimeException("生成节点ID失败");
			}
			String id = restMessage.getData();

			// 节点记录
			ShipbillNodeTracking model = new ShipbillNodeTracking();
			model.setId(id);
			model.setNodeDate(date);
			model.setShipbillId(shipbillId);
			model.setShipbillNo(shipbillId);
			model.setStatus(headerModel.getStatus());
			model.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_SELF_PICK_VEH_REG);
			model.setUserId(user.getUserid());
			model.setUserName(user.getNickname());
			model.setEnterpriseId(user.getEnterpriseId());
			model.setEnterpriseName(user.getEnterpriseName());
			model.setCreateperson(user.getNickname());
			model.setCreatetime(date);
			tmsShipbillNodeTrackingMapper.save(model);

			goodsTotalPcs = headerModel.getTotalPcs();
			goodsTotalVolume = ToolKits.isEmpty(headerModel.getTotalVolume()) ? BigDecimal.ZERO : headerModel.getTotalVolume();
			goodsTotalWeight = ToolKits.isEmpty(headerModel.getTotalWeight()) ? BigDecimal.ZERO : headerModel.getTotalWeight();

			// 判定下一步流程
			int status = businessFlowUtil.judgmentNextFlowSts(headerModel.getFlowConfig(), DataDictionaryConstant.FLOW_CONFIG_SELF_PICKUP_VEH_REG);

			// 生成调度单明细表
			TmsLoadingBillDetailModel loadingBillDetailModel = new TmsLoadingBillDetailModel();
			RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_LOADING_BILL_DETAIL_ID, "L");
			if (!restMessage2.isSuccess()) {
				throw new RuntimeException("生成装车单明细ID失败");
			}
			String loadingBillDetailId = restMessage2.getData();

			BeanUtils.copyProperties(headerModel, loadingBillDetailModel);

			loadingBillDetailModel.setStatus(status);
			loadingBillDetailModel.setId(loadingBillDetailId);
			loadingBillDetailModel.setLoadingBillId(loadingBillId);
			loadingBillDetailModel.setLoadingBillNo(loadingBillId);
			loadingBillDetailModel.setEnterpriseId(user.getEnterpriseId());
			loadingBillDetailModel.setEnterpriseName(user.getEnterpriseName());
			loadingBillDetailModel.setCreateperson(user.getNickname());
			loadingBillDetailModel.setCreatetime(date);
			loadingBillDetailModel.setUpdateperson(user.getNickname());
			loadingBillDetailModel.setUpdatetime(date);
			loadingBillDetailModel.setCarrierId(vehicleAndDriverDTO.getDriver().getDriverId());
			loadingBillDetailModel.setCarrierCode(vehicleAndDriverDTO.getDriver().getDriverCode());
			loadingBillDetailModel.setCarrierName(vehicleRegisterVO.getSelfWithdrawalPerson());
			loadingBillDetailModel.setCarrierType(DataDictionaryConstant.LINE_CARRIER_TYPE_ZT);
			loadingBillDetailModel.setShippingOrder(Integer.valueOf(1));
			// 保存调度单明细
			tmsLoadingBillDetailMapper.save(loadingBillDetailModel);

			// 更新运单表
			headerModel.setStatus(status);
			headerModel.setUpdateperson(user.getNickname());
			headerModel.setUpdatetime(date);
			tmsShipbillHeaderMapper.update(headerModel);

			// 保存调度表
			TmsLoadingBillHeaderModel loadingBillHeaderModel = new TmsLoadingBillHeaderModel();
			loadingBillHeaderModel.setSiteNumber(Integer.valueOf(1));
			loadingBillHeaderModel.setCustomerNumber(Integer.valueOf(1));
			loadingBillHeaderModel.setTotalPcs(goodsTotalPcs);
			loadingBillHeaderModel.setTotalVolume(goodsTotalVolume);
			loadingBillHeaderModel.setTotalWeight(goodsTotalWeight);
			loadingBillHeaderModel.setActualTotalPcs(goodsTotalPcs);
			loadingBillHeaderModel.setActualTotalVolume(goodsTotalVolume);
			loadingBillHeaderModel.setActualTotalWeight(goodsTotalWeight);
			// 运单数
			loadingBillHeaderModel.setShipbillNumber(Integer.valueOf(1));
			loadingBillHeaderModel.setDriverId(vehicleAndDriverDTO.getDriver().getDriverId());
			loadingBillHeaderModel.setDriverCode(vehicleAndDriverDTO.getDriver().getDriverCode());
			loadingBillHeaderModel.setCarrierId(vehicleAndDriverDTO.getDriver().getDriverId());
			loadingBillHeaderModel.setCarrierCode(vehicleAndDriverDTO.getDriver().getDriverCode());
			loadingBillHeaderModel.setCarrierName(vehicleRegisterVO.getSelfWithdrawalPerson());
			loadingBillHeaderModel.setDeliverymanName(vehicleRegisterVO.getSelfWithdrawalPerson());
			loadingBillHeaderModel.setDriverName(vehicleRegisterVO.getSelfWithdrawalPerson());
			loadingBillHeaderModel.setDriverPhoneNumber(vehicleRegisterVO.getContactTel());
			loadingBillHeaderModel.setVehicleId(ToolKits.isEmpty(vehicleAndDriverDTO.getVehicle()) ? null : vehicleAndDriverDTO.getVehicle().getVehicleId());
			loadingBillHeaderModel.setVehicleCode(ToolKits.isEmpty(vehicleAndDriverDTO.getVehicle()) ? null : vehicleAndDriverDTO.getVehicle().getVehicleCode());
			loadingBillHeaderModel.setVehicleName(ToolKits.isEmpty(vehicleAndDriverDTO.getVehicle()) ? null : vehicleAndDriverDTO.getVehicle().getVehicleName());
			loadingBillHeaderModel.setVehiclePlateNumber(vehicleRegisterVO.getVehiclePlateNumber());
			// 调度类型
			loadingBillHeaderModel.setScheduleType(DataDictionaryConstant.SCHEDULE_TYPE_ZY);
			// 承运方类型
			loadingBillHeaderModel.setCarrierType(DataDictionaryConstant.LINE_CARRIER_TYPE_ZT);
			loadingBillHeaderModel.setLoadingBillId(loadingBillId);
			loadingBillHeaderModel.setLoadingBillNo(loadingBillId);
			loadingBillHeaderModel.setLoadingBillDate(date);
			// 自提
			loadingBillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_YSH);
			loadingBillHeaderModel.setEnterpriseId(user.getEnterpriseId());
			loadingBillHeaderModel.setEnterpriseName(user.getEnterpriseName());
			loadingBillHeaderModel.setCreatetime(date);
			loadingBillHeaderModel.setCreateperson(user.getNickname());
			loadingBillHeaderModel.setUpdateperson(user.getNickname());
			loadingBillHeaderModel.setUpdatetime(date);

			loadingBillHeaderModel.setLoadingBillDate(date);
			loadingBillHeaderModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
			tmsLoadingBillHeaderMapper.save(loadingBillHeaderModel);

			// 运单日志保存
			ShipbillOperateLogSaveNewVO shipbillOperateLogSaveNewVO = new ShipbillOperateLogSaveNewVO();
			shipbillOperateLogSaveNewVO.setShipbillId(shipbillId);
			shipbillOperateLogSaveNewVO.setShipbillNo(shipbillId);
			shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_DZT_DJ);
			shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			shipbillOperateLogSaveNewVO.setNewStatus(status);
			shipbillOperateLogSaveNewVO.setOperateDate(date);
			shipbillOperateLogSaveNewVO.setEnterpriseId(user.getEnterpriseId());
			shipbillOperateLogSaveNewVO.setEnterpriseName(user.getEnterpriseName());
			shipbillOperateLogSaveNewVO.setUserId(user.getUserid());
			shipbillOperateLogSaveNewVO.setUserName(user.getNickname());
			shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);
			MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.SELF_VEHICLE_REGISTER.getCode(), Lists.newArrayList(shipbillId)));
		}
	}

	/**
	 * 自提确认查询
	 *
	 * @param vo
	 * @return
	 */
	@Override
	public SelfWithdrawalConfirmQueryDTO ConfirmQuery(SelfWithdrawalConfirmQueryVO vo) {

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vo, "请选择要操作的运单");

		Criteria criteria = Criteria.forClass(TmsShipbillTransLogModel.class);
		Restriction r1 = Restrictions.in(TmsShipbillTransLogModel::getShipbillId, vo.getIds().stream().toArray(String[]::new));
		Restriction r2 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));

		List<TmsShipbillTransLogModel> logModels = tmsShipbillTransportLogMapper.findByCriteria(criteria);
		SelfWithdrawalConfirmQueryDTO confirmQueryDTO = new SelfWithdrawalConfirmQueryDTO();
		if (ToolKits.isNotEmpty(logModels)) {
			// STD-DEVELOP20220823 lhb bwc0823003 20220908 start
			Long driverNameSize = logModels.stream().map(TmsShipbillTransLogModel::getSelfPickUpPerson).distinct().count();
			Long driverPhoneSize = logModels.stream().map(TmsShipbillTransLogModel::getSelfPickUpTel).distinct().count();
			Long plateNumSize = logModels.stream().map(TmsShipbillTransLogModel::getVehiclePlateNumber).distinct().count();

			if (driverNameSize > 1 || driverPhoneSize > 1 || plateNumSize > 1) {
				throw new PrologException("请勾选相同司机、司机电话、车辆的运单");
			}
			confirmQueryDTO.setSelfWithdrawalPerson(logModels.get(0).getSelfPickUpPerson());
			confirmQueryDTO.setIdCrad(logModels.get(0).getIdCard());
			confirmQueryDTO.setContactTel(logModels.get(0).getSelfPickUpTel());
			confirmQueryDTO.setVehiclePlateNumber(logModels.get(0).getVehiclePlateNumber());
			// STD-DEVELOP20220823 lhb bwc0823003 20220908 end
		}
		return confirmQueryDTO;
	}

	// 商品拆分
	public List<String> goodsSplit(SelfRegSplitVO splitVO, Date date, UserEntity user) {
		ToolKits.isParamNull(splitVO, "自提登记拆分请求不为空");
		List<String> selfRegShipbills = Lists.newArrayList();
		// 原运单更新
		TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(splitVO.getShipbillId(), TmsShipbillHeaderModel.class);

		if (tmsShipbillHeaderModel.getSplitOrderStatus().equals(DataDictionaryConstant.SPLIT_ORDER_STATUS_ED)) {
			throw new PrologException("运单【"+tmsShipbillHeaderModel.getShipbillId()+"】已拆分,或者已自提登记");
		}
		Map<String, Object> mapShipbillHeadUpdate = Maps.newHashMap();
		Restriction r23 = Restrictions.eq(TmsShipbillHeaderModel::getSplitOrderStatus, DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
		mapShipbillHeadUpdate.put("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_ED);
		tmsShipbillHeaderModel.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_ED);
		// 原始主单被拆分时，拆单类型更新为2拆分主单，子单被拆分时，不更新拆单类型
		if (ToolKits.isEmpty(tmsShipbillHeaderModel.getSplitOrderType()) || DataDictionaryConstant.SPLIT_ORDER_TYPE_UN.equals(tmsShipbillHeaderModel.getSplitOrderType())) {
			tmsShipbillHeaderModel.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_SPLIT_MASTER);
			mapShipbillHeadUpdate.put("splitOrderType", DataDictionaryConstant.SPLIT_ORDER_TYPE_SPLIT_MASTER);
		}

		tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
		tmsShipbillHeaderModel.setUpdatetime(date);
		mapShipbillHeadUpdate.put("updateperson", user.getNickname());
		mapShipbillHeadUpdate.put("updatetime", date);
		Criteria criteriaHead = Criteria.forClass(TmsShipbillHeaderModel.class);
		Restriction r24 = Restrictions.eq(TmsShipbillHeaderModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
		criteriaHead.setRestriction(Restrictions.and(r23, r24));
		long upCnt = tmsShipbillHeaderMapper.updateMapByCriteria(mapShipbillHeadUpdate, criteriaHead);
		if (upCnt == 0) {
			throw new PrologException("运单【" + tmsShipbillHeaderModel.getShipbillId() + "】已拆分,或者已自提登记");
		}

		// STD-DEVELOP20220823 lhb 承运商拆分完善 20220916 start
		if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
			// 更新装车单明细
			Map<String, Object> mapLoadingDetailUpdate = Maps.newHashMap();
			mapLoadingDetailUpdate.put("updateperson", user.getNickname());
			mapLoadingDetailUpdate.put("updatetime", date);
			mapLoadingDetailUpdate.put("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_ED);
			if (ToolKits.isEmpty(tmsShipbillHeaderModel.getCarrierSplitOrderType()) || DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN.equals(tmsShipbillHeaderModel.getCarrierSplitOrderType())) {
				mapLoadingDetailUpdate.put("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
			}
			Criteria criteriaLoadingDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
			Restriction r21 = Restrictions.eq(TmsLoadingBillDetailModel::getCarrierShipbillStatus, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_AUDITED);
			Restriction r22 = Restrictions.eq(TmsLoadingBillDetailModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
			criteriaLoadingDetail.setRestriction(Restrictions.and(r21, r22));
			tmsLoadingBillDetailMapper.updateMapByCriteria(mapLoadingDetailUpdate, criteriaLoadingDetail);
		}
		// STD-DEVELOP20220823 lhb 承运商拆分完善 20220916 end

		// 原运单日志保存
		ShipbillOperateLogSaveNewVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveNewVO();
		shipbillOperateLogSaveVO.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
		shipbillOperateLogSaveVO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
		shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_EVENT_NAME_SPLIT);
		shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
		shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
		shipbillOperateLogSaveVO.setOperateDate(date);
		shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveVO);

		// 拆分成多个子单
		RestMessage<SysParamConfigModel> restMessageShipbillId = maindataTmsResource.getValue(DataDictionaryConstant.SHIPBILL_ID_CREATE_RULE);
		if (!restMessageShipbillId.isSuccess()) {
			throw new RuntimeException("获取运单ID生成规则的系统参数失败!");
		}
		SysParamConfigModel sysParamConfigModel = restMessageShipbillId.getData();
		int index = 1;
		Map<String, List<SelfPickUpShipBillDetailVO>> maps = splitVO.getSplitGoodsMap();
		for (String splitType : maps.keySet()) {
			// 运单汇总ID
			String subShipbillId = "";
			// 运单ID生成规则
			if (DataDictionaryConstant.SHIPBILL_ID_CREATE_RULE_AUTO.equals(sysParamConfigModel.getValue())) {
				// 获取运单汇总ID
				RestMessage<String> restMessageAutoCreateShipbillId = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
				if (!restMessageAutoCreateShipbillId.isSuccess()) {
					throw new RuntimeException("生成运单汇总ID失败");
				}
				subShipbillId = restMessageAutoCreateShipbillId.getData();
			} else {
				StringBuffer buffNo1 = new StringBuffer(splitVO.getShipbillId());
				buffNo1.append(DataDictionaryConstant.SUB_SHIPBILL_NO);
				buffNo1.append(DataDictionaryConstant.SPLIT_SHIPBILL_NO);
				buffNo1.append(index);
				subShipbillId = buffNo1.toString();
			}
			// 商品总件数
			BigDecimal goodsTotalPcs = new BigDecimal(0);
			// 商品总体积
			BigDecimal goodsTotalVolume = new BigDecimal(0);
			// 商品总重量
			BigDecimal goodsTotalWeight = new BigDecimal(0);

			BigDecimal zero = new BigDecimal(0);

			// 保存每个子单中的明细信息
			for (SelfPickUpShipBillDetailVO splitGoodsDetailVO : maps.get(splitType)) {
				TmsShipbillDetailModel subTmsShipbillDetailModel = new TmsShipbillDetailModel();
				// 运单明细ID
				RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
				if (!restMessage2.isSuccess()) {
					throw new RuntimeException("生成运单明细ID失败");
				}
				String subShipbillDetailId = restMessage2.getData();

				// STD-DEVELOP20220823 lhb 计算件重体 20220909 start
				ItemCheckVO itemCheckVO = new ItemCheckVO();
				itemCheckVO.setItemId(splitGoodsDetailVO.getItemId());
				RestMessage<ItemCheckDTO> restMessage3 = maindataTmsResource.getItem(itemCheckVO);
				if (!restMessage3.isSuccess()) {
					throw new RuntimeException("取商品资料信息失败:" + restMessage3.getMessage());
				}
				ItemCheckDTO rsItemInfo = restMessage3.getData();
				// STD-DEVELOP20220823 lhb 计算件重体 20220909 end

				TmsShipbillDetailModel detailModel = tmsShipbillDetailMapper.findById(splitGoodsDetailVO.getId(), TmsShipbillDetailModel.class);
				if (ToolKits.isEmpty(detailModel)) {
					throw new PrologException("运单【" + splitVO.getShipbillId() + "】的商品【" + splitGoodsDetailVO.getItemName() + "】信息不存在");
				}

				BeanUtils.copyProperties(detailModel, subTmsShipbillDetailModel);
				// ID
				subTmsShipbillDetailModel.setId(subShipbillDetailId);
				// 运单ID
				subTmsShipbillDetailModel.setShipbillId(subShipbillId);
				// 运单编号
				subTmsShipbillDetailModel.setShipbillNo(subShipbillId);

				subTmsShipbillDetailModel.setPcs(splitGoodsDetailVO.getPcs());
				// STD-DEVELOP20220823 lhb 计算件重体 20220909 start
				subTmsShipbillDetailModel.setWeight(splitGoodsDetailVO.getPcs().multiply(rsItemInfo.getWeight()));
				subTmsShipbillDetailModel.setVolume(splitGoodsDetailVO.getPcs().multiply(rsItemInfo.getVolume()));
				// STD-DEVELOP20220823 lhb 计算件重体 20220909 end

				subTmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
				subTmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());

				subTmsShipbillDetailModel.setCreateperson(user.getNickname());
				subTmsShipbillDetailModel.setCreatetime(date);
				subTmsShipbillDetailModel.setUpdateperson(user.getNickname());
				subTmsShipbillDetailModel.setUpdatetime(date);
				subTmsShipbillDetailModel.setOrigPcs(subTmsShipbillDetailModel.getPcs());
				subTmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
				subTmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
				subTmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
				tmsShipbillDetailMapper.save(subTmsShipbillDetailModel);

				// STD-DEVELOP20220823 lhb 计算件重体 20220909 start
				goodsTotalPcs = goodsTotalPcs.add(subTmsShipbillDetailModel.getPcs());
				goodsTotalVolume = goodsTotalVolume.add(subTmsShipbillDetailModel.getVolume());
				goodsTotalWeight = goodsTotalWeight.add(subTmsShipbillDetailModel.getWeight());
				// STD-DEVELOP20220823 lhb 计算件重体 20220909 end
			}

			// 保存拆分子单的运单汇总
			TmsShipbillHeaderModel subTmsShipbillHeaderModel = new TmsShipbillHeaderModel();
			BeanUtils.copyProperties(tmsShipbillHeaderModel, subTmsShipbillHeaderModel);

			subTmsShipbillHeaderModel.setShipbillNo(subShipbillId);
			subTmsShipbillHeaderModel.setShipbillId(subShipbillId);
			if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
				// 拆单状态 0未拆单
				subTmsShipbillHeaderModel.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
				// 拆单类型 3拆分子单
				subTmsShipbillHeaderModel.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_SPLIT_SUB);
				// 拆单状态 0未拆单
				subTmsShipbillHeaderModel.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
				// 拆单类型 3拆分子单
				subTmsShipbillHeaderModel.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
			} else {
				// 拆单状态 0未拆单
				subTmsShipbillHeaderModel.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
				// 拆单类型 3拆分子单
				subTmsShipbillHeaderModel.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_SUB);
				// 拆单状态 0未拆单
				subTmsShipbillHeaderModel.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
				// 拆单类型 3拆分子单
				subTmsShipbillHeaderModel.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
			}
			// 父级运单ID
			subTmsShipbillHeaderModel.setFatherShipbillId(tmsShipbillHeaderModel.getShipbillId());
			// 父级运单编号
			subTmsShipbillHeaderModel.setFatherShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
			// 原始运单ID
			String originalShipbillId = tmsShipbillHeaderModel.getOriginalShipbillId() == null ? tmsShipbillHeaderModel.getShipbillId() : tmsShipbillHeaderModel.getOriginalShipbillId();
			subTmsShipbillHeaderModel.setOriginalShipbillId(originalShipbillId);
			// 原始运单编号
			String originalShipbillNo = tmsShipbillHeaderModel.getOriginalShipbillNo() == null ? tmsShipbillHeaderModel.getShipbillNo() : tmsShipbillHeaderModel.getOriginalShipbillNo();
			subTmsShipbillHeaderModel.setOriginalShipbillNo(originalShipbillNo);
			// 总件数
			subTmsShipbillHeaderModel.setTotalPcs(goodsTotalPcs);
			// 总体积
			subTmsShipbillHeaderModel.setTotalVolume(goodsTotalVolume);
			// 总重量
			subTmsShipbillHeaderModel.setTotalWeight(goodsTotalWeight);
			// 实际总件数
			subTmsShipbillHeaderModel.setActualTotalPcs(goodsTotalPcs);
			// 实际总体积
			subTmsShipbillHeaderModel.setActualTotalVolume(goodsTotalVolume);
			// 实际总重量
			subTmsShipbillHeaderModel.setActualTotalWeight(goodsTotalWeight);
			// 包裹整件数
			subTmsShipbillHeaderModel.setPackageWholePiece(zero);
			// 包裹拼箱数
			subTmsShipbillHeaderModel.setPackageLclPiece(zero);
			// 包裹总体积
			subTmsShipbillHeaderModel.setPackageTotalVolume(zero);
			// 包裹总重量
			subTmsShipbillHeaderModel.setPackageTotalWeight(zero);

			subTmsShipbillHeaderModel.setCreateperson(user.getNickname());
			subTmsShipbillHeaderModel.setCreatetime(date);
			subTmsShipbillHeaderModel.setUpdateperson(user.getNickname());
			subTmsShipbillHeaderModel.setUpdatetime(date);
			subTmsShipbillHeaderModel.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
			subTmsShipbillHeaderModel.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
			subTmsShipbillHeaderModel.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());
			subTmsShipbillHeaderModel.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
			tmsShipbillHeaderMapper.save(subTmsShipbillHeaderModel);

			// 运输记录
			saveTransportLog(subTmsShipbillHeaderModel.getShipbillId(), date, subTmsShipbillHeaderModel.getEstimatedPickupStartTime());

			// 子运单日志保存
			ShipbillOperateLogSaveNewVO subShipbillOperateLogSaveVO = new ShipbillOperateLogSaveNewVO();
			subShipbillOperateLogSaveVO.setShipbillId(subTmsShipbillHeaderModel.getShipbillId());
			subShipbillOperateLogSaveVO.setShipbillNo(subTmsShipbillHeaderModel.getShipbillNo());
			subShipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_EVENT_NAME_SPLIT_SUB);
			subShipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			subShipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			subShipbillOperateLogSaveVO.setOperateDate(date);
			shipbillOperateLogService.addShipbillOperateLogNewData(subShipbillOperateLogSaveVO);

			// 运单节点保存
			ShipbillNodeTrackingSaveNewVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveNewVO();
			shipbillNodeTrackingSaveVO.setShipbillId(subShipbillId);
			shipbillNodeTrackingSaveVO.setShipbillNo(subShipbillId);
			shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_REW);
			shipbillNodeTrackingSaveVO.setNodeDate(date);
			shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveVO);
			index++;

			if (splitType.equals("selfReg")) {
				selfRegShipbills.add(subTmsShipbillHeaderModel.getShipbillId());
			}
		}
		return selfRegShipbills;
	}

	/**
	 * 生成运输记录表
	 */
	public void saveTransportLog(String shipbillId, Date date, Date pickUpStartDt) {
		TmsShipbillTransLogModel logModel = new TmsShipbillTransLogModel();
		RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_TRANSPORT_LOG_ID, "L");
		if (!restMessage.isSuccess()) {
			throw new RuntimeException("生成运输记录ID失败");
		}
		String id = restMessage.getData();
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		logModel.setId(id);
		logModel.setShipbillId(shipbillId);
		logModel.setShipbillNo(shipbillId);

		logModel.setOrderDt(date);
		logModel.setCommitDt(date);
		logModel.setReviewDt(date);
		logModel.setEstimatedPickupStartTime(pickUpStartDt);
		logModel.setEnterpriseId(user.getEnterpriseId());
		logModel.setEnterpriseName(user.getEnterpriseName());
		logModel.setCreateperson(user.getNickname());
		logModel.setCreatetime(date);
		logModel.setUpdateperson(user.getNickname());
		logModel.setUpdatetime(date);

		tmsShipbillTransportLogMapper.save(logModel);
	}

	// STD-DEVELOP20220823 lhb bwc0825001 20220905 自提登记审批流 start
	// 自提登记审核匹配审批流程
	public Boolean approvalOpen(TmsShipbillHeaderModel model, Integer approvalFlowType, UserEntity user) {
		// 封装判断所需数据
		ApprovalOpenVO approvalOpenVO = new ApprovalOpenVO();
		approvalOpenVO.setApprovalFlowType(approvalFlowType);
		approvalOpenVO.setApprovalObjectId(model.getShipbillId());
		approvalOpenVO.setApprovalObjectCode(model.getShipbillNo());
		approvalOpenVO.setApprovalObjectName(model.getShipbillNo());
		approvalOpenVO.setInitiatedUserId(user.getUserid());
		approvalOpenVO.setInitiatedUserName(user.getNickname());

		// 配送方式
		approvalOpenVO.setDeliveryMethodType(model.getDeliveryMethodType());
		// 发货方类型
		approvalOpenVO.setShipperType(model.getShipperType());
		// 发货方单位ID
		approvalOpenVO.setShipperUnitId(model.getShipperUnitId());
		// 收货方类型
		approvalOpenVO.setConsigneeType(model.getConsigneeType());
		// 收货方单位ID
		approvalOpenVO.setConsigneeUnitId(model.getConsigneeUnitId());
		// 订单类型
		approvalOpenVO.setOrderType(model.getOrderType());
		// 订单业务类型
		approvalOpenVO.setOrderBusinessType(model.getOrderBusinessType());
		// 运输模式
		approvalOpenVO.setTransportType(model.getTransportType());
		// 温度要求
		approvalOpenVO.setTemperatureRequirement(model.getTemperatureRequirement());
		// 货主ID
		approvalOpenVO.setCargoOwnerId(model.getCargoOwnerId());
		// 部门ID
		approvalOpenVO.setDepartmentId(model.getDepartmentId());

		RestMessage<Boolean> restMessage1 = maindataTmsResource.openExecute(approvalOpenVO);
		if (!restMessage1.isSuccess()) {
			throw new RuntimeException("调用maindata服务是否开启审批流接口失败:" + restMessage1.getMessage());
		}
		return restMessage1.getData();
	}
	// STD-DEVELOP20220823 lhb bwc0825001 20220905 自提登记审批流 end
}
