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

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
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.util.MessageUtil;
import com.prolog.rdc.tms.model.dto.basicConfigure.ShipbillMatchCarrierDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ShipbillMatchLineDTO;
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.ShipbillMatchCarrierVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ShipbillMatchLineVO;
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 org.springframework.util.Assert;

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.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.dao.mapper.TmsLoadingBillDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillHeaderMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillNodeTrackingMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillOperateLogMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillPackageMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillTransportLogMapper;
import com.prolog.rdc.tms.app.model.dto.business.PendingRVShipBillDetailDTO;
import com.prolog.rdc.tms.app.model.dto.business.PendingReviewPackageDTO;
import com.prolog.rdc.tms.app.model.dto.business.PendingReviewQueryDTO;
import com.prolog.rdc.tms.app.model.entity.ShipbillNodeTracking;
import com.prolog.rdc.tms.app.model.entity.TmsLoadingBillDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillOperateLogModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillPackageModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillTransLogModel;
import com.prolog.rdc.tms.app.model.vo.business.PendingDispatchVO;
import com.prolog.rdc.tms.app.model.vo.business.PendingReviewQueryVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillGoBackVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillNodeTrackingSaveNewVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillOperateLogSaveNewVO;
import com.prolog.rdc.tms.app.service.business.PendingDispatchService;
import com.prolog.rdc.tms.app.service.business.PendingReviewService;
import com.prolog.rdc.tms.app.service.business.ShipbillNodeTrackingService;
import com.prolog.rdc.tms.app.service.business.ShipbillOperateLogService;
import com.prolog.rdc.tms.model.dto.basicConfigure.ShipbillFitBusinessFlowDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategySplitMatchingDTO;
import com.prolog.rdc.tms.model.dto.basicData.CustomerCarrierDTO;
import com.prolog.rdc.tms.model.dto.basicData.ItemCheckDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsBaseBranchDTO;
import com.prolog.rdc.tms.model.vo.basicConfigure.BusinessFlowShipbillVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.StrategySplitMatchingVO;
import com.prolog.rdc.tms.model.vo.basicData.CustomerCarrierVO;
import com.prolog.rdc.tms.model.vo.basicData.ItemCheckVO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;

/**
 * 调度管理-待审核实现层
 *
 * @author lhb
 * @since 2022-04-11 14:45:00
 */
@Service
@Slf4j
public class PendingReviewServiceImpl implements PendingReviewService {
	@Autowired
	private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

	@Autowired
	private TmsShipbillDetailMapper tmsShipbillDetailMapper;

	@Autowired
	private TmsShipbillPackageMapper tmsShipbillPackageMapper;

	@Autowired
	private MaindataFeign maindataTmsResource;

	@Autowired
	private TmsShipbillNodeTrackingMapper tmsShipbillNodeTrackingMapper;

	@Autowired
	private PendingDispatchService pendingDispatchService;

	@Autowired
	private TmsShipbillTransportLogMapper tmsShipbillTransportLogMapper;

	@Autowired
	private TmsShipbillOperateLogMapper tmsShipbillOperateLogMapper;

	@Autowired
	private ShipbillOperateLogService shipbillOperateLogService;

	@Autowired
	private ShipbillNodeTrackingService shipbillNodeTrackingService;

	@Autowired
	private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

	/**
	 * 待审核查询
	 *
	 * @param pendingReviewVO
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<PendingReviewQueryDTO> pendingReviewQuery(PendingReviewQueryVO pendingReviewVO) {
		ToolKits.isParamNull(pendingReviewVO, "待审核查询请求不为空");
		ToolKits.isParamNull(pendingReviewVO.getPageNum(), "当前页码不为空");
		ToolKits.isParamNull(pendingReviewVO.getPageSize(), "每页条数不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 添加查询条件
		Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
		Restriction r1 = ToolKits.isEmpty(pendingReviewVO.getOrderBusinessType()) ? null : Restrictions.eq(TmsShipbillHeaderModel::getOrderBusinessType, pendingReviewVO.getOrderBusinessType());
		Restriction r2 = ToolKits.isEmpty(pendingReviewVO.getEstimatedPickupStartTime()) ? null : Restrictions.ge(TmsShipbillHeaderModel::getEstimatedPickupStartTime, pendingReviewVO.getEstimatedPickupStartTime());
		Restriction r3 = ToolKits.isEmpty(pendingReviewVO.getEstimatedPickupEndTime()) ? null : Restrictions.le(TmsShipbillHeaderModel::getEstimatedPickupEndTime, pendingReviewVO.getEstimatedPickupEndTime());
		Restriction r24 = ToolKits.isEmpty(pendingReviewVO.getConsigneeUnitName()) ? null : Restrictions.like(TmsShipbillHeaderModel::getConsigneeUnitName, "%" + pendingReviewVO.getConsigneeUnitName() + "%");
		Restriction r25 = ToolKits.isEmpty(pendingReviewVO.getLineName()) ? null : Restrictions.like(TmsShipbillHeaderModel::getLineName, "%" + pendingReviewVO.getLineName() + "%");

		Restriction r4 = null;
		if (!ToolKits.isEmpty(pendingReviewVO.getShipperAddress())) {
			Restriction r5 = Restrictions.like(TmsShipbillHeaderModel::getShipperProvinceName, "%" + pendingReviewVO.getShipperAddress() + "%");
			Restriction r6 = Restrictions.like(TmsShipbillHeaderModel::getShipperCityName, "%" + pendingReviewVO.getShipperAddress() + "%");
			r4 = Restrictions.or(r5, r6);
		}

		Restriction r7 = null;
		if (!ToolKits.isEmpty(pendingReviewVO.getConsigneeAddress())) {
			Restriction r8 = Restrictions.like(TmsShipbillHeaderModel::getConsigneeProvinceName, "%" + pendingReviewVO.getConsigneeAddress() + "%");
			Restriction r9 = Restrictions.like(TmsShipbillHeaderModel::getConsigneeCityName, "%" + pendingReviewVO.getConsigneeAddress() + "%");
			r7 = Restrictions.or(r8, r9);
		}
		Restriction r10 = Restrictions.eq(TmsShipbillHeaderModel::getEnterpriseId, user.getEnterpriseId());

		Restriction r13 = null;
		Restriction r14 = null;
		Restriction r15 = null;
		Restriction r29 = null;
		// 权限控制
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			// 自有账号
			// 拆单状态 0未拆单
			Restriction r30 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
			// 承运商拆单类型 1未拆单
			Restriction r31 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
			Restriction r32 = Restrictions.and(r30, r31);
			// 承运商拆单类型 2拆分主单
			Restriction r33 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
			// 承运商拆单类型 2中转主单
			Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
			r29 = Restrictions.or(r32, r33, r34);
			// 判断是否为部门权限
			Integer[] stsArr = { DataDictionaryConstant.SHIPBILL_STATUS_YTJ, DataDictionaryConstant.SHIPBILL_STATUS_WZ, DataDictionaryConstant.SHIPBILL_STATUS_WS };
			r13 = Restrictions.in(TmsShipbillHeaderModel::getStatus, stsArr);
			if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
				r14 = Restrictions.in(TmsShipbillHeaderModel::getDepartmentId, user.getDepts().stream().toArray(String[]::new));
			} else {
				r14 = Restrictions.in(TmsShipbillHeaderModel::getDepartmentId, user.getDepts().stream().toArray(String[]::new));
				Restriction r16 = Restrictions.in(TmsShipbillHeaderModel::getCargoOwnerId, user.getConsignors().stream().toArray(Long[]::new));

				Restriction r17 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, user.getWarehouses().stream().toArray(Long[]::new));
				Restriction r18 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, user.getSuppliers().stream().toArray(Long[]::new));
				Restriction r19 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, user.getCustomers().stream().toArray(Long[]::new));

				Restriction r47 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getWarehouses().stream().toArray(Long[]::new));
				Restriction r48 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getSuppliers().stream().toArray(Long[]::new));
				Restriction r49 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getCustomers().stream().toArray(Long[]::new));

				Restriction r20 = Restrictions.or(r17, r18, r19,r47,r48,r49);
				r15 = Restrictions.and(r16, r20);
			}
		} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
			// 承运商账号
			r29 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
			// 查询调度类型为承运商的运单
			Restriction r21 = Restrictions.eq(TmsShipbillHeaderModel::getCarrierId, Long.valueOf(user.getLoginUserCompanyInfo().getId()));
			Restriction r22 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK);
			Restriction r23 = Restrictions.eq(TmsShipbillHeaderModel::getCarrierShipbillStatus, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
			r15 = Restrictions.and(r21, r22, r23);
		} else {
			throw new PrologException("当前人员没有操作权限！");
		}

		Restriction r50 = ToolKits.isEmpty(pendingReviewVO.getShipbillNo()) ? null : Restrictions.eq(TmsShipbillHeaderModel::getShipbillNo, pendingReviewVO.getShipbillNo());
		Restriction r51 = ToolKits.isEmpty(pendingReviewVO.getOrderNo()) ? null : Restrictions.eq(TmsShipbillHeaderModel::getOrderNo, pendingReviewVO.getOrderNo());

		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r7, r10, r13, r14, r15, r24, r25, r29, r50, r51));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));

		PageUtils.startPage(pendingReviewVO.getPageNum(), pendingReviewVO.getPageSize());
		List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

		// 响应对象集合
		List<PendingReviewQueryDTO> pendingReviewDTOs = Lists.newArrayList();

		for (TmsShipbillHeaderModel tmsShipbillHeaderModel : tmsShipbillHeaderModels) {
			PendingReviewQueryDTO pendingReviewDTO = new PendingReviewQueryDTO();
			BeanUtils.copyProperties(tmsShipbillHeaderModel, pendingReviewDTO);
			StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
			// 目的地
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeProvinceName()) ? "" : tmsShipbillHeaderModel.getConsigneeProvinceName());
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeCityName()) ? "" : tmsShipbillHeaderModel.getConsigneeCityName());
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeDistrictName()) ? "" : tmsShipbillHeaderModel.getConsigneeDistrictName());
			pendingReviewDTO.setConsigneeProvinceCityDistrict(consigneeProvinceCityDistrict.toString());
			// 始发地
			StringBuffer shipperProvinceCityDistrict = new StringBuffer();
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperProvinceName()) ? "" : tmsShipbillHeaderModel.getShipperProvinceName());
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperCityName()) ? "" : tmsShipbillHeaderModel.getShipperCityName());
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperDistrictName()) ? "" : tmsShipbillHeaderModel.getShipperDistrictName());
			pendingReviewDTO.setShipperProvinceCityDistrict(shipperProvinceCityDistrict.toString());

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

			// 收货方电话
			StringBuffer tel = new StringBuffer();
			if (ToolKits.isNotEmpty(pendingReviewDTO.getConsigneePhoneNumber())) {
				tel.append(pendingReviewDTO.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(pendingReviewDTO.getConsigneeLandlineNumber())) {
				tel.append(pendingReviewDTO.getConsigneeLandlineNumber());
			}
			if (ToolKits.isNotEmpty(tel.toString())) {
				pendingReviewDTO.setConsigneeTel(tel.toString());
			}

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

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

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

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

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

				List<PendingRVShipBillDetailDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					PendingRVShipBillDetailDTO detailDTO = new PendingRVShipBillDetailDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				pendingReviewDTO.setShipBillDetailDTOS(detailDTOList);
			}
			pendingReviewDTOs.add(pendingReviewDTO);
		}
		// 分页重组
		Page<PendingReviewQueryDTO> page = PageUtils.getPage(pendingReviewDTOs);
		if (tmsShipbillHeaderModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsShipbillHeaderModel> p0 = (com.github.pagehelper.Page<TmsShipbillHeaderModel>) tmsShipbillHeaderModels;
			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 shipbillIds
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void reviewShipbillData(List<String> shipbillIds) {
		ToolKits.isParamNull(shipbillIds, "运单审核请求不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 当前时间
		Date date = DateUtil.date();

		autoReviewShipbillData(shipbillIds, user, date);
	}

	/**
	 * 自动运单审核
	 *
	 * @param shipbillIds
	 * @return
	 */
	@Override
	public void autoReviewShipbillData(List<String> shipbillIds, UserEntity user, Date date) {
		for (String id : shipbillIds) {
			ToolKits.isParamNull(id, "运单ID不为空");
			// 更新
			TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
			ShipbillNodeTracking nodeModel = new ShipbillNodeTracking();
			TmsShipbillOperateLogModel logModel = new TmsShipbillOperateLogModel();

			if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
				// 自有账号
				if (!DataDictionaryConstant.SHIPBILL_STATUS_YTJ.equals(tmsShipbillHeaderModel.getStatus())) {
					throw new PrologException("运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】非待调度状态,审核失败");
				}
				tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
				nodeModel.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_RE);
				logModel.setOperateEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_RE);
			} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
				// 承运商账号
				if (!DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT.equals(tmsShipbillHeaderModel.getCarrierShipbillStatus())) {
					throw new PrologException("运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】非待调度状态,审核失败");
				}
				tmsShipbillHeaderModel.setCarrierShipbillStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_AUDITED);
				nodeModel.setNodeEvent(DataDictionaryConstant.CARRIER_SHIPBILL_NODE_STATUSNAME_RE);
				logModel.setOperateEvent(DataDictionaryConstant.CARRIER_SHIPBILL_NODE_STATUSNAME_RE);
			}

			// 运单审核
			tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
			tmsShipbillHeaderModel.setUpdatetime(date);
			tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

			// 运单节点保存
			// 获取节点ID
			RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_NODE_TRACKING_ID, "L");
			if (!restMessage.isSuccess()) {
				throw new RuntimeException("生成节点ID失败");
			}
			String nodeId = restMessage.getData();
			nodeModel.setId(nodeId);
			nodeModel.setNodeDate(date);
			nodeModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
			nodeModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
			nodeModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			nodeModel.setUserId(user.getUserid());
			nodeModel.setUserName(user.getNickname());
			nodeModel.setEnterpriseId(user.getEnterpriseId());
			nodeModel.setEnterpriseName(user.getEnterpriseName());
			nodeModel.setCreateperson(user.getNickname());
			nodeModel.setCreatetime(date);
			tmsShipbillNodeTrackingMapper.save(nodeModel);

			// 运单日志保存
			// 获取日志ID
			RestMessage<String> logRestMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_OPERATE_LOG_ID, "L");
			if (!logRestMessage.isSuccess()) {
				throw new RuntimeException("生成日志ID失败");
			}
			String logId = logRestMessage.getData();
			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.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
			logModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
			logModel.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
			logModel.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);

			tmsShipbillOperateLogMapper.save(logModel);

			// 更新运输记录表的审核时间
			Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
			Restriction r1 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
			Restriction r2 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, user.getEnterpriseId());
			criteriaTransLog.setRestriction(Restrictions.and(r1, r2));

			Map<String, Object> mapUpdate = Maps.newHashMap();
			mapUpdate.put("updateperson", user.getNickname());
			mapUpdate.put("updatetime", date);
			mapUpdate.put("reviewDt", date);
			if (tmsShipbillHeaderModel.getDeliveryMethodType().equals(DataDictionaryConstant.DELIVERY_METHOD_TYPE_ZT)) {
				mapUpdate.put("disDt", date);
				mapUpdate.put("disCheckDt", date);
			}
			tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransLog);

			// 运单匹配唯一承运方是否自动调度
			TmsShipbillHeaderModel shipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
			boolean autoSplit = false;
			if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
				if (shipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_REVIEW_SPLIT)) {
					autoSplit = true;
				}
			}
			// 自动拆分
			List<TmsShipbillHeaderModel> autoDispatchOjbs = Lists.newArrayList();
			if (autoSplit) {
				autoDispatchOjbs.addAll(autoSplit(id, date, user));
			}
			// 自动拆分做了时，子单参加调度，没有自动拆分时，原单参加自动调度
			if (ToolKits.isEmpty(autoDispatchOjbs)) {
				autoDispatchOjbs.add(shipbillHeaderModel);
			}
			for (TmsShipbillHeaderModel headerModel : autoDispatchOjbs) {
				// 收货方类型是客户时，自动调度
				if (!DataDictionaryConstant.CONSIGNEE_TYPE_KH.equals(headerModel.getConsigneeType())) {
					continue;
				}
				if (!DataDictionaryConstant.DELIVERY_METHOD_TYPE_SEND.equals(shipbillHeaderModel.getDeliveryMethodType())) {
					continue;
				}
				if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
					if (!shipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_REVIEW_DISPATCH)) {
						continue;
					}
				} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
					if (!shipbillHeaderModel.getCarrierFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_REVIEW_DISPATCH)) {
						continue;
					}
				}
				List<ShipbillMatchCarrierVO> matchCarrierVOS = Lists.newArrayList();
				ShipbillMatchCarrierVO carrierVO = new ShipbillMatchCarrierVO();
				BeanUtils.copyProperties(headerModel, carrierVO);
				carrierVO.setShipperAgingTime(headerModel.getEstimatedPickupStartTime());
				carrierVO.setPickupStartTime(headerModel.getEstimatedPickupStartTime());
				matchCarrierVOS.add(carrierVO);
				RestMessage<Map<String, ShipbillMatchCarrierDTO>> shipbillMatchRs = maindataTmsResource.shipbillMatchCarrierExecute(matchCarrierVOS);
				if (!shipbillMatchRs.isSuccess()) {
					throw new RuntimeException("承运方匹配策略适配失败:" + shipbillMatchRs.getMessage());
				}
				Map<String, ShipbillMatchCarrierDTO> rsCarriers = shipbillMatchRs.getData();
				ShipbillMatchCarrierDTO carrierDTO = rsCarriers.get(headerModel.getShipbillId());
				log.info("自动调度策略:" + JSON.toJSONString(rsCarriers));
				PendingDispatchVO pendingDispatchVO = new PendingDispatchVO();

				if (ToolKits.isNotEmpty(carrierDTO) && ToolKits.isNotEmpty(carrierDTO.getCarrierId())) {
					// 唯一匹配承运方
					// 承运方类型
					pendingDispatchVO.setCarrierType(carrierDTO.getCarrierType());
					if (DataDictionaryConstant.LINE_CARRIER_TYPE_SJ.equals(carrierDTO.getCarrierType())) {
						// 司机ID
						pendingDispatchVO.setDriverId(carrierDTO.getCarrierId());
						pendingDispatchVO.setDriverCode(carrierDTO.getCarrierCode());
						pendingDispatchVO.setDriverName(carrierDTO.getCarrierName());
						// 送货员
						pendingDispatchVO.setDeliverymanId(carrierDTO.getDeliverymanId());
						pendingDispatchVO.setDeliverymanCode(carrierDTO.getDeliverymanCode());
						pendingDispatchVO.setDeliverymanName(carrierDTO.getDeliverymanName());
						pendingDispatchVO.setDeliverymanPhoneNumber(carrierDTO.getDeliverymanPhoneNumber());
						// 车辆
						pendingDispatchVO.setVehicleId(carrierDTO.getVehicleId());
						pendingDispatchVO.setVehicleCode(carrierDTO.getVehicleCode());
						pendingDispatchVO.setVehicleName(carrierDTO.getVehicleName());
						pendingDispatchVO.setVehiclePlateNumber(carrierDTO.getVehiclePlateNumber());
						pendingDispatchVO.setVehicleAscription(carrierDTO.getVehicleAscription());
						// 车型
						pendingDispatchVO.setVehicleTypeId(carrierDTO.getVehicleTypeId());
						pendingDispatchVO.setVehicleTypeCode(carrierDTO.getVehicleTypeCode());
						pendingDispatchVO.setVehicleTypeName(carrierDTO.getVehicleTypeName());
						// 车辆的设备
						if (ToolKits.isNotEmpty(carrierDTO.getVehicleDeviceId())) {
							pendingDispatchVO.setVehicleDeviceId(String.valueOf(carrierDTO.getVehicleDeviceId()));
							pendingDispatchVO.setVehicleDeviceCode(carrierDTO.getVehicleDeviceCode());
							pendingDispatchVO.setVehicleDeviceName(carrierDTO.getVehicleDeviceName());
						}
						if (ToolKits.isNotEmpty(carrierDTO.getContainerId())) {
							pendingDispatchVO.setContainerId(carrierDTO.getContainerId());
							pendingDispatchVO.setContainerCode(carrierDTO.getContainerCode());
							pendingDispatchVO.setContainerName(carrierDTO.getContainerName());
						}
						if (ToolKits.isNotEmpty(carrierDTO.getVehicleTypeCategory())) {
							pendingDispatchVO.setVehicleTypeCategory(String.valueOf(carrierDTO.getVehicleTypeCategory()));
						}
						if (ToolKits.isNotEmpty(carrierDTO.getVehicleAffiliationId())) {
							pendingDispatchVO.setVehicleAffiliationId(String.valueOf(carrierDTO.getVehicleAffiliationId()));
							pendingDispatchVO.setVehicleAffiliationCode(String.valueOf(carrierDTO.getVehicleAffiliationCode()));
							pendingDispatchVO.setVehicleAffiliationName(String.valueOf(carrierDTO.getVehicleAffiliationName()));
						}
					} else {
						// 承运商ID
						pendingDispatchVO.setCarrierId(Long.valueOf(carrierDTO.getCarrierId()));
						pendingDispatchVO.setCarrierCode(carrierDTO.getCarrierCode());
						pendingDispatchVO.setCarrierName(carrierDTO.getCarrierName());
					}
					// 司机手机号
					pendingDispatchVO.setDriverPhoneNumber(carrierDTO.getDriverPhoneNumber());
					// 车牌号
					pendingDispatchVO.setVehiclePlateNumber(carrierDTO.getVehiclePlateNumber());

					pendingDispatchVO.setVehicleId(carrierDTO.getVehicleId());
					pendingDispatchVO.setVehicleCode(carrierDTO.getVehicleCode());
					pendingDispatchVO.setVehicleName(carrierDTO.getVehicleName());
					List<String> ids = Lists.newArrayList();
					ids.add(headerModel.getShipbillId());
					pendingDispatchVO.setShipbillIds(ids);
					// 自动调度
					pendingDispatchService.autoDispatch(pendingDispatchVO, user, date);
				}
			}
			MessageTypeEnum messageTypeEnum = MessageTypeEnum.SELF_AUDIT;
			if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
				messageTypeEnum = MessageTypeEnum.CARRIER_AUDIT;
			}
			MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), messageTypeEnum.getCode(), Lists.newArrayList(id)));
		}
	}

	/**
	 * 运单待审核-回退
	 *
	 * @param vo
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void goBackShipbill(ShipbillGoBackVO vo) {
		ToolKits.isParamNull(vo.getBackType(), "回退类型不为空");
		ToolKits.isParamNull(vo.getShipbillIdList(), "运单ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 当前时间
		Date date = DateUtil.date();

		for (String id : vo.getShipbillIdList()) {
			ToolKits.isParamNull(id, "运单ID不为空");
			// 更新
			TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
			Restriction r3 = null;
			ShipbillNodeTracking nodeModel = new ShipbillNodeTracking();
			TmsShipbillOperateLogModel logModel = new TmsShipbillOperateLogModel();

			if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
				// 自有账号
				Assert.isTrue(tmsShipbillHeaderModel.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_YTH, "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】已回退");
				// 运单状态更新为5已回退
				tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTH);
				r3 = Restrictions.eq("status", DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

				logModel.setOperateEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_HT);
				logModel.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
				logModel.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTH);
				nodeModel.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_HT);
				nodeModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTH);
			} else if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
				// 承运商账号
				Assert.isTrue(tmsShipbillHeaderModel.getCarrierShipbillStatus() != DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK, "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】已回退");
				// 运单状态更新为5已回退
				tmsShipbillHeaderModel.setCarrierShipbillStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK);
				r3 = Restrictions.eq("status", DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);

				nodeModel.setNodeEvent(DataDictionaryConstant.CARRIER_SHIPBILL_STATUSNAME_YTH);
				nodeModel.setStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK);

				logModel.setOperateEvent(DataDictionaryConstant.CARRIER_SHIPBILL_STATUSNAME_YTH);
				logModel.setOldStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
				logModel.setNewStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK);
			}
			tmsShipbillHeaderModel.setBackReason(vo.getBackReason());
			tmsShipbillHeaderModel.setBackType(vo.getBackType());
			tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
			tmsShipbillHeaderModel.setUpdatetime(date);
			tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

			// 运单确认节点删除
			Criteria criteria = Criteria.forClass(ShipbillNodeTracking.class);
			Restriction r1 = Restrictions.eq("shipbillId", id);
			Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteria.setRestriction(Restrictions.and(r1, r2, r3));
			tmsShipbillNodeTrackingMapper.deleteByCriteria(criteria);

			// 运单日志保存
			// 获取日志ID
			RestMessage<String> logRestMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_OPERATE_LOG_ID, "L");
			if (!logRestMessage.isSuccess()) {
				throw new RuntimeException("生成日志ID失败");
			}
			String logId = logRestMessage.getData();
			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.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
			logModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
			tmsShipbillOperateLogMapper.save(logModel);

			// 运单节点保存
			// 获取节点ID
			RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_NODE_TRACKING_ID, "L");
			if (!restMessage.isSuccess()) {
				throw new RuntimeException("生成节点ID失败:" + restMessage.getMessage());
			}
			String nodeId = restMessage.getData();
			nodeModel.setId(nodeId);
			nodeModel.setNodeDate(date);
			nodeModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
			nodeModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
			nodeModel.setUserId(user.getUserid());
			nodeModel.setUserName(user.getNickname());
			nodeModel.setEnterpriseId(user.getEnterpriseId());
			nodeModel.setEnterpriseName(user.getEnterpriseName());
			nodeModel.setCreateperson(user.getNickname());
			nodeModel.setCreatetime(date);
			tmsShipbillNodeTrackingMapper.save(nodeModel);
		}
	}

	/**
	 * 智能拆分
	 *
	 * @param shipbillId
	 * @return
	 */
	public List<TmsShipbillHeaderModel> autoSplit(String shipbillId, Date date, UserEntity user) {
		// 返回数据
		List<TmsShipbillHeaderModel> smartSplitDTOS = Lists.newArrayList();

		// 获取商品集合
		Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
		Restriction r1 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, shipbillId);
		criteriaDetail.setRestriction(r1);
		List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);
		// 运单没有商品
		if (ToolKits.isEmpty(tmsShipbillDetailModels)) {
			return smartSplitDTOS;
		}
		// 查询对应运单
		TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);

		// 获取拆分策略
		StrategySplitMatchingVO strategySplitMatchingVO = new StrategySplitMatchingVO();
		BeanUtils.copyProperties(tmsShipbillHeaderModel, strategySplitMatchingVO);
		RestMessage<List<StrategySplitMatchingDTO>> restMessage = maindataTmsResource.matchingExecute(strategySplitMatchingVO);
		if (!restMessage.isSuccess()) {
			return smartSplitDTOS;
		}

		// 策略集合
		List<StrategySplitMatchingDTO> strategySplitMatchingDTOS = restMessage.getData();

		// 如果为空跳过
		if (ToolKits.isEmpty(strategySplitMatchingDTOS) || strategySplitMatchingDTOS.size() > 1) {
			return smartSplitDTOS;
		}
		StrategySplitMatchingDTO strategyDTO = strategySplitMatchingDTOS.get(0);

		// 拆分完的明细集合
		Map<Object, List<TmsShipbillDetailModel>> map = Maps.newHashMap();
		// 拆分的不足单子
		List<TmsShipbillDetailModel> modelSplitIns = Lists.newArrayList();
		// 库存足的单子
		List<TmsShipbillDetailModel> modelNotIns = Lists.newArrayList();
		// 获取库存不足单子
		List<TmsShipbillDetailModel> modelIns = Lists.newArrayList();

		switch (strategyDTO.getRuleCode().intValue()) {
		case 1: // 按商品品类拆分
			try {
				map = tmsShipbillDetailModels.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getItemCategoryId));
				if (map.size() == 1) {
					map.clear();
				}
			} catch (Exception e) {
			}
			break;
		case 2:// 按包装类型拆分
			try {
				map = tmsShipbillDetailModels.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getPackType));
				if (map.size() == 1) {
					map.clear();
				}
			} catch (Exception e) {
			}
			break;
		case 3:// 按货物温层拆分
			try {
				map = tmsShipbillDetailModels.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getCargoThermosphere));
				if (map.size() == 1) {
					map.clear();
				}
			} catch (Exception e) {
			}
			break;
		case 4:// 按数量、库存数量拆分
				// 获取库存不足单子
			try {
				modelIns = tmsShipbillDetailModels.stream().filter(o -> (o.getPcs().intValue() > o.getInventoryPcs().intValue() && ToolKits.isNotEmpty(o.getInventoryPcs()) && o.getInventoryPcs().intValue() > 0)).collect(Collectors.toList());
			} catch (Exception e) {
			}
			// 没有库存不足的就不拆分
			if (ToolKits.isEmpty(modelIns)) {
				break;
			}
			// 获取库存足的单子
			modelNotIns = tmsShipbillDetailModels.stream().filter(o -> o.getPcs().intValue() < o.getInventoryPcs().intValue()).collect(Collectors.toList());

			for (TmsShipbillDetailModel model : modelIns) {
				TmsShipbillDetailModel model1 = new TmsShipbillDetailModel();
				TmsShipbillDetailModel model2 = new TmsShipbillDetailModel();
				BeanUtils.copyProperties(model, model1);
				BeanUtils.copyProperties(model, model2);
				model1.setPcs(new BigDecimal(model.getInventoryPcs()));
				model2.setPcs(model.getPcs().subtract(new BigDecimal(model.getInventoryPcs())));
				model2.setInventoryPcs(0);

				// 计算商品的体积，重量
				ItemCheckVO itemCheckVO = new ItemCheckVO();
				itemCheckVO.setItemId(model.getItemId());
				RestMessage<ItemCheckDTO> itemRestMessage = maindataTmsResource.getItem(itemCheckVO);

				if (!itemRestMessage.isSuccess()) {
					throw new PrologException("获取商品服务失败:" + itemRestMessage.getMessage());
				}
				if (ToolKits.isEmpty(itemRestMessage.getData())) {
					throw new PrologException("未找到对应商品【" + model.getItemName() + "】");
				}
				ItemCheckDTO itemCheckDTO = itemRestMessage.getData();

				if (ToolKits.isNotEmpty(itemCheckDTO.getWeight())) {
					model1.setWeight(itemCheckDTO.getWeight().multiply(model1.getPcs()));
					model2.setWeight(itemCheckDTO.getWeight().multiply(model2.getPcs()));
				}
				if (ToolKits.isNotEmpty(itemCheckDTO.getVolume())) {
					model1.setVolume(itemCheckDTO.getVolume().multiply(model1.getPcs()));
					model2.setVolume(itemCheckDTO.getVolume().multiply(model2.getPcs()));
				}
				modelNotIns.add(model1);
				modelSplitIns.add(model2);
			}
			// 封装到map集合
			// 库存足
			map.put("modelSplitIns", modelNotIns);
			// 库存不足
			map.put("modelSplitInsNo", modelSplitIns);
			break;
		case 5:// 按默认存放仓库、数量、库存数量拆分
			Map<Long, List<TmsShipbillDetailModel>> collect = Maps.newHashMap();
			try {
				collect = tmsShipbillDetailModels.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getBranchId));
			} catch (Exception e) {
				break;
			}
			for (Long l : collect.keySet()) {
				List<TmsShipbillDetailModel> list = collect.get(l);
				// 获取库存不足单子
				List<TmsShipbillDetailModel> modelInsList = list.stream().filter(o -> (o.getPcs().intValue() > o.getInventoryPcs().intValue() && ToolKits.isNotEmpty(o.getInventoryPcs()) && o.getInventoryPcs().intValue() > 0)).collect(Collectors.toList());
				// 库存足,有分组的也拆分
				if (ToolKits.isEmpty(modelInsList)) {
					if (collect.size() > 1) {
						map.put(l + "-Ins-U-Flow", list);
					}

					continue;
				}
				// 获取库存足的单子
				List<TmsShipbillDetailModel> modelNotInsList = list.stream().filter(o -> o.getPcs().intValue() < o.getInventoryPcs().intValue()).collect(Collectors.toList());

				// 拆分的不足单子
				List<TmsShipbillDetailModel> modelSplitInsList = Lists.newArrayList();
				for (TmsShipbillDetailModel model : modelInsList) {

					TmsShipbillDetailModel model1 = new TmsShipbillDetailModel();
					TmsShipbillDetailModel model2 = new TmsShipbillDetailModel();
					BeanUtils.copyProperties(model, model1);
					BeanUtils.copyProperties(model, model2);
					model1.setPcs(new BigDecimal(model.getInventoryPcs()));
					model2.setPcs(model.getPcs().subtract(new BigDecimal(model.getInventoryPcs())));
					model2.setInventoryPcs(0);

					// 计算商品的体积，重量
					ItemCheckVO itemCheckVO = new ItemCheckVO();
					itemCheckVO.setItemId(model.getItemId());
					RestMessage<ItemCheckDTO> itemRestMessage = maindataTmsResource.getItem(itemCheckVO);

					if (!itemRestMessage.isSuccess()) {
						throw new PrologException("获取商品服务失败");
					}
					if (ToolKits.isEmpty(itemRestMessage.getData())) {
						throw new PrologException("未找到对应商品[商品:" + model.getItemName() + "]");
					}
					ItemCheckDTO itemCheckDTO = itemRestMessage.getData();

					if (ToolKits.isNotEmpty(itemCheckDTO.getWeight())) {
						model1.setWeight(itemCheckDTO.getWeight().multiply(model1.getPcs()));
						model2.setWeight(itemCheckDTO.getWeight().multiply(model2.getPcs()));
					}
					if (ToolKits.isNotEmpty(itemCheckDTO.getVolume())) {
						model1.setVolume(itemCheckDTO.getVolume().multiply(model1.getPcs()));
						model2.setVolume(itemCheckDTO.getVolume().multiply(model2.getPcs()));
					}
					modelNotInsList.add(model1);
					modelSplitInsList.add(model2);
				}
				// 封装到map集合
				// 库存足的运单
				map.put(l + "-SplitIns-U-Flow", modelNotInsList);
				// 库存不足的运单
				map.put(l + "-SplitInsNo-U-Flow", modelSplitInsList);
			}
			break;
		case 6:// 按默认存放仓库拆分
			Map<Long, List<TmsShipbillDetailModel>> collect6 = Maps.newHashMap();
			try {
				collect6 = tmsShipbillDetailModels.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getBranchId));
			} catch (Exception e) {
				break;
			}
			if (collect6.size() > 1) {
				for (Long l : collect6.keySet()) {
					List<TmsShipbillDetailModel> list6 = collect6.get(l);
					map.put(l + "-Ins-U-Flow", list6);
				}
			}
			break;
		case 7:// 按运单明细关键字拆分
			String splitKey = strategyDTO.getShipbillDetailSplitKey();
			if (ToolKits.isNotEmpty(splitKey)) {
				List<String> keyList = Arrays.stream(splitKey.split(",")).distinct().collect(Collectors.toList());
				List<TmsShipbillDetailModel> noMatchShipbillDetails = tmsShipbillDetailModels.stream().filter(t -> ToolKits.isEmpty(t.getMemo())).collect(Collectors.toList());

				List<TmsShipbillDetailModel> matchShipbillDetails = Lists.newArrayList();

				tmsShipbillDetailModels = tmsShipbillDetailModels.stream().filter(t -> ToolKits.isNotEmpty(t.getMemo())).collect(Collectors.toList());

				Map<String, List<TmsShipbillDetailModel>> collect7 = Maps.newHashMap();
				if (ToolKits.isNotEmpty(tmsShipbillDetailModels)) {
					for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
						boolean match = false;
						for (String key : keyList) {
							if (detailModel.getMemo().contains(key)) {
								detailModel.setUpdateperson(key);
								matchShipbillDetails.add(detailModel);
								match = true;
								break;
							}
						}
						if (!match) {
							noMatchShipbillDetails.add(detailModel);
						}
					}
					collect7 = matchShipbillDetails.stream().collect(Collectors.groupingBy(TmsShipbillDetailModel::getUpdateperson));
				}
				if (ToolKits.isNotEmpty(noMatchShipbillDetails)) {
					if (collect7.size() > 0) {
						for (String l : collect7.keySet()) {
							List<TmsShipbillDetailModel> list7 = collect7.get(l);
							map.put(l + "-key-split", list7);
						}
						map.put("no" + "-key-split", noMatchShipbillDetails);
					}
				} else {
					if (collect7.size() > 1) {
						for (String l : collect7.keySet()) {
							List<TmsShipbillDetailModel> list7 = collect7.get(l);
							map.put(l + "-key-split", list7);
						}
					}
				}
			}
			break;
		}
		if (ToolKits.isEmpty(map)) {
			return smartSplitDTOS;
		}
		int index = 1;
		RestMessage<SysParamConfigModel> restMessageShipbillId = maindataTmsResource.getValue(DataDictionaryConstant.SHIPBILL_ID_CREATE_RULE);
		if (!restMessageShipbillId.isSuccess()) {
			throw new RuntimeException("获取运单ID生成规则的系统参数失败!");
		}
		SysParamConfigModel sysParamConfigModel = restMessageShipbillId.getData();
		for (Object obj : map.keySet()) {
			List<TmsShipbillDetailModel> list = map.get(obj);
			if (ToolKits.isEmpty(list)) {
				continue;
			}
			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(tmsShipbillHeaderModel.getShipbillId());
				buffNo1.append(DataDictionaryConstant.SUB_SHIPBILL_NO);
				buffNo1.append(DataDictionaryConstant.SPLIT_SHIPBILL_NO);
				buffNo1.append(index);
				subShipbillId = buffNo1.toString();
				index++;
			}

			// 商品总件数
			BigDecimal goodsTotalPcs = new BigDecimal(0);
			// 商品总体积
			BigDecimal goodsTotalVolume = new BigDecimal(0);
			// 商品总重量
			BigDecimal goodsTotalWeight = new BigDecimal(0);

			BigDecimal zero = new BigDecimal(0);

			// 保存拆分子单的运单汇总
			TmsShipbillHeaderModel subTmsShipbillHeaderModel = new TmsShipbillHeaderModel();
			BeanUtils.copyProperties(tmsShipbillHeaderModel, subTmsShipbillHeaderModel);
			Long branchId = list.get(0).getBranchId();
			if (obj.toString().contains("U-Flow")) {
				// 取新仓库信息
				RestMessage<TmsBaseBranchDTO> restMessageBranch = maindataTmsResource.viewBranch(branchId);
				if (restMessageBranch.isSuccess()) {
					TmsBaseBranchDTO tmsBaseBranchDTO = restMessageBranch.getData();
					// 重新设定发货方数据
					// 发货方类型
					subTmsShipbillHeaderModel.setShipperType(DataDictionaryConstant.SHIPPER_TYPE_CK);
					// 发货方单位ID
					subTmsShipbillHeaderModel.setShipperUnitId(tmsBaseBranchDTO.getId());
					subTmsShipbillHeaderModel.setShipperUnitCode(tmsBaseBranchDTO.getCode());
					subTmsShipbillHeaderModel.setShipperUnitName(tmsBaseBranchDTO.getName());
					// 发货方ID
					subTmsShipbillHeaderModel.setShipperId(tmsBaseBranchDTO.getId());
					subTmsShipbillHeaderModel.setShipperCode(tmsBaseBranchDTO.getCode());
					subTmsShipbillHeaderModel.setShipperName(tmsBaseBranchDTO.getName());

					// 发货方联系人
					subTmsShipbillHeaderModel.setShipperContact(tmsBaseBranchDTO.getContact());
					// 发货方手机号
					subTmsShipbillHeaderModel.setShipperPhoneNumber(tmsBaseBranchDTO.getPhoneNumber());
					// 发货方座机号
					subTmsShipbillHeaderModel.setShipperLandlineNumber(tmsBaseBranchDTO.getLandlineNumber());

					subTmsShipbillHeaderModel.setShipperEmail(tmsBaseBranchDTO.getEmail());

					subTmsShipbillHeaderModel.setShipperRelatedPhoneNumber(tmsBaseBranchDTO.getPhoneNumber());
					// 发货方省编码
					subTmsShipbillHeaderModel.setShipperProvince(tmsBaseBranchDTO.getProvince());
					// 发货方省名称
					subTmsShipbillHeaderModel.setShipperProvinceName(tmsBaseBranchDTO.getProvinceName());
					// 发货方市编码
					subTmsShipbillHeaderModel.setShipperCity(tmsBaseBranchDTO.getCity());
					subTmsShipbillHeaderModel.setShipperCityName(tmsBaseBranchDTO.getCityName());
					// 发货方区/县编码
					subTmsShipbillHeaderModel.setShipperDistrict(tmsBaseBranchDTO.getDistrict());
					subTmsShipbillHeaderModel.setShipperDistrictName(tmsBaseBranchDTO.getDistrictName());

					// 发货方详细地址
					subTmsShipbillHeaderModel.setShipperAddress(tmsBaseBranchDTO.getAddress());

					// 发货方经度
					subTmsShipbillHeaderModel.setShipperLongitude(tmsBaseBranchDTO.getLongitude());
					// 发货方纬度
					subTmsShipbillHeaderModel.setShipperLatitude(tmsBaseBranchDTO.getLatitude());
					subTmsShipbillHeaderModel.setShipperMemo(tmsBaseBranchDTO.getMemo());

					// 重新适配新业务流程,取流程失败时，此运单不做拆分
					ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(subTmsShipbillHeaderModel, 2);
					if (ToolKits.isEmpty(flowData) || ToolKits.isEmpty(flowData.getFlowConfig())) {
						return smartSplitDTOS;
					}
					subTmsShipbillHeaderModel.setFlowConfig(flowData.getFlowConfig());
				}
				if (strategyDTO.getRematchLine().equals(DataDictionaryConstant.REMATCH_LINE_YES)) {
					// 子单重新匹配线路
					ShipbillMatchLineDTO lineData = shipbillMatchLine(subTmsShipbillHeaderModel);
					if (ToolKits.isNotEmpty(lineData) && ToolKits.isNotEmpty(lineData.getLineId())) {
						// 订单绑定线路
						subTmsShipbillHeaderModel.setLineId(lineData.getLineId());
						subTmsShipbillHeaderModel.setLineCode(lineData.getLineCode());
						subTmsShipbillHeaderModel.setLineName(lineData.getLineName());
						subTmsShipbillHeaderModel.setLineDirection(lineData.getLineDirection());
						subTmsShipbillHeaderModel.setShippingOrder(lineData.getShippingOrder());
						subTmsShipbillHeaderModel.setPickUpOrder(lineData.getPickUpOrder());
					}
				}
			}

			// 保存每个子单中的明细信息
			int idx = 1;
			for (TmsShipbillDetailModel detailModel : list) {
				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 计算件重体 20220913 start
				ItemCheckVO itemCheckVO = new ItemCheckVO();
				itemCheckVO.setItemId(detailModel.getItemId());
				RestMessage<ItemCheckDTO> restMessage3 = maindataTmsResource.getItem(itemCheckVO);
				if (!restMessage3.isSuccess()) {
					throw new RuntimeException("取商品资料信息失败:" + restMessage3.getMessage());
				}
				ItemCheckDTO rsItemInfo = restMessage3.getData();
				// STD-DEVELOP20220823 lhb 计算件重体 20220913 end

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

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

				subTmsShipbillDetailModel.setCreateperson(user.getNickname());
				subTmsShipbillDetailModel.setCreatetime(date);
				subTmsShipbillDetailModel.setUpdateperson(user.getNickname());
				subTmsShipbillDetailModel.setUpdatetime(date);
				// STD-DEVELOP20220823 lhb 计算件重体 20220913 start
				subTmsShipbillDetailModel.setWeight(detailModel.getPcs().multiply(rsItemInfo.getWeight()));
				subTmsShipbillDetailModel.setVolume(detailModel.getPcs().multiply(rsItemInfo.getVolume()));
				// STD-DEVELOP20220823 lhb 计算件重体 20220913 end
				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 计算件重体 20220913 start
				if (ToolKits.isNotEmpty(subTmsShipbillDetailModel.getPcs())) {
					goodsTotalPcs = goodsTotalPcs.add(subTmsShipbillDetailModel.getPcs());
				}
				if (ToolKits.isNotEmpty(subTmsShipbillDetailModel.getVolume())) {
					goodsTotalVolume = goodsTotalVolume.add(subTmsShipbillDetailModel.getVolume());
				}
				if (ToolKits.isNotEmpty(subTmsShipbillDetailModel.getWeight())) {
					goodsTotalWeight = goodsTotalWeight.add(subTmsShipbillDetailModel.getWeight());
				}
				// STD-DEVELOP20220823 lhb 计算件重体 20220913 end
			}

			subTmsShipbillHeaderModel.setShipbillId(subShipbillId);
			subTmsShipbillHeaderModel.setShipbillNo(subShipbillId);
			// 运单状态
			subTmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
			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);

				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.setOperateDate(date);
			subShipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_EVENT_NAME_SPLIT_SUB);
			subShipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
			subShipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);

			subShipbillOperateLogSaveVO.setUserId(user.getUserid());
			subShipbillOperateLogSaveVO.setUserName(user.getNickname());
			subShipbillOperateLogSaveVO.setEnterpriseId(user.getEnterpriseId());
			subShipbillOperateLogSaveVO.setEnterpriseName(user.getEnterpriseName());
			shipbillOperateLogService.addShipbillOperateLogNewData(subShipbillOperateLogSaveVO);

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

			shipbillNodeTrackingSaveVO.setUserId(user.getUserid());
			shipbillNodeTrackingSaveVO.setUserName(user.getNickname());
			shipbillNodeTrackingSaveVO.setEnterpriseId(user.getEnterpriseId());
			shipbillNodeTrackingSaveVO.setEnterpriseName(user.getEnterpriseName());
			shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveVO);

			smartSplitDTOS.add(subTmsShipbillHeaderModel);
		}
		// 修改主单
		if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
			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);
			}
		} else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
			tmsShipbillHeaderModel.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_ED);
			// 原始主单被拆分时，拆单类型更新为2拆分主单，子单被拆分时，不更新拆单类型
			if (ToolKits.isEmpty(tmsShipbillHeaderModel.getCarrierSplitOrderType()) || DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN.equals(tmsShipbillHeaderModel.getCarrierSplitOrderType())) {
				tmsShipbillHeaderModel.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
			}

			// STD-DEVELOP20220823 lhb 承运商拆分完善 20220916 start
			// 更新装车单明细
			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
		}
		tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
		tmsShipbillHeaderModel.setUpdatetime(date);
		tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

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

		shipbillOperateLogSaveVO.setUserId(user.getUserid());
		shipbillOperateLogSaveVO.setUserName(user.getNickname());
		shipbillOperateLogSaveVO.setEnterpriseId(user.getEnterpriseId());
		shipbillOperateLogSaveVO.setEnterpriseName(user.getEnterpriseName());
		shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveVO);

		List<String> shipbillIds = Lists.newArrayList();
		shipbillIds.add(shipbillId);
		pendingDispatchService.updatePlanBill(shipbillIds,user);

		return smartSplitDTOS;
	}

	/**
	 * 生成运输记录表
	 */
	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);
	}

	/**
	 * 运单匹配业务流程
	 *
	 * @param model
	 * @return
	 */
	public ShipbillFitBusinessFlowDTO shipbillMatchBusinessFlow(TmsShipbillHeaderModel model, Integer flowType) {
		// 新增后自动提交判定
		BusinessFlowShipbillVO matchFlowVO = new BusinessFlowShipbillVO();
		// 流程类型
		matchFlowVO.setFlowType(flowType);
		// 配送方式
		matchFlowVO.setDeliveryMethodType(model.getDeliveryMethodType());
		// 发货方类型
		matchFlowVO.setShipperType(model.getShipperType());
		// 发货方单位ID
		matchFlowVO.setShipperUnitId(model.getShipperUnitId());
		// 收货方类型
		matchFlowVO.setConsigneeType(model.getConsigneeType());
		// 收货方单位ID
		matchFlowVO.setConsigneeUnitId(model.getConsigneeUnitId());
		// 订单类型
		matchFlowVO.setOrderType(model.getOrderType());
		// 订单业务类型
		matchFlowVO.setOrderBusinessType(model.getOrderBusinessType());
		// 运输模式
		matchFlowVO.setTransportType(model.getTransportType());
		// 温度要求
		matchFlowVO.setTemperatureRequirement(model.getTemperatureRequirement());
		// 货主ID
		matchFlowVO.setCargoOwnerId(model.getCargoOwnerId());
		RestMessage<ShipbillFitBusinessFlowDTO> matchRs = maindataTmsResource.shipbillMatchFlowQuery(matchFlowVO);
		if (!matchRs.isSuccess()) {
			return null;
		}
		return matchRs.getData();
	}

	/**
	 * 运单匹配线路
	 *
	 * @param model
	 * @return
	 */
	public ShipbillMatchLineDTO shipbillMatchLine(TmsShipbillHeaderModel model) {
		// 新增后自动提交判定
		ShipbillMatchLineVO matchLineVO = new ShipbillMatchLineVO();
		// 配送方式
		matchLineVO.setDeliveryMethodType(model.getDeliveryMethodType());
		// 发货方类型
		matchLineVO.setShipperType(model.getShipperType());
		// 发货方单位ID
		matchLineVO.setShipperUnitId(model.getShipperUnitId());
		matchLineVO.setShipperProvince(model.getShipperProvince());
		matchLineVO.setShipperCity(model.getShipperCity());
		matchLineVO.setShipperDistrict(model.getShipperDistrict());
		// 收货方类型
		matchLineVO.setConsigneeType(model.getConsigneeType());
		// 收货方单位ID
		matchLineVO.setConsigneeUnitId(model.getConsigneeUnitId());
		matchLineVO.setConsigneeId(model.getConsigneeId());
		matchLineVO.setConsigneeProvince(model.getConsigneeProvince());
		matchLineVO.setConsigneeCity(model.getConsigneeCity());
		matchLineVO.setConsigneeDistrict(model.getConsigneeDistrict());
		// 订单类型
		matchLineVO.setOrderType(model.getOrderType());
		// 订单业务类型
		matchLineVO.setOrderBusinessType(model.getOrderBusinessType());
		// 运输模式
		matchLineVO.setTransportType(model.getTransportType());
		// 温度要求
		matchLineVO.setTemperatureRequirement(model.getTemperatureRequirement());
		// 货主ID
		matchLineVO.setCargoOwnerId(model.getCargoOwnerId());

		matchLineVO.setDepartmentId(model.getDepartmentId());
		matchLineVO.setEnterpriseId(model.getEnterpriseId());

		RestMessage<ShipbillMatchLineDTO> matchRs = maindataTmsResource.shipbillMatchLineExecute(matchLineVO);
		if (!matchRs.isSuccess()) {
			throw new PrologException("运单【" + model.getShipbillNo() + "】调用maindata服务运单匹配线路策略失败");
		}
		return matchRs.getData();
	}
}
