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

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.prolog.common.util.DateUtils;
import com.prolog.common.util.ToolKits;
import com.prolog.cs.platform.power.model.Organization;
import com.prolog.framework.authority.util.HystrixVarUtil;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
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.constant.BussinessConstant;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.constant.StatusConstant;
import com.prolog.rdc.tms.constant.enums.DriverReceiveStatusEnum;
import com.prolog.rdc.tms.constant.enums.ShipBillTypeEnum;
import com.prolog.rdc.tms.constant.enums.SignInStatusEnum;
import com.prolog.rdc.tms.constant.enums.intelligent.IntelligentLockEnum;
import com.prolog.rdc.tms.dao.mapper.ShipbillRouteDataMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLoadingBillDetailMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLoadingBillHeaderMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillDetailMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillDetailTempMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillHeaderMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillHeaderTempMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillPackageDetailMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillPackageMapper;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillTransportLogMapper;
import com.prolog.rdc.tms.dao.mapper.TmsVehicleGpsMapper;
import com.prolog.rdc.tms.model.ShipbillRouteDataModel;
import com.prolog.rdc.tms.model.dto.ExportShipbillDTO;
import com.prolog.rdc.tms.model.dto.IntfErrorLogDTO;
import com.prolog.rdc.tms.model.dto.LmsTmsZoneDTO;
import com.prolog.rdc.tms.model.dto.LmsTmsZoneMinDTO;
import com.prolog.rdc.tms.model.dto.ShipAndLoadingBillDTO;
import com.prolog.rdc.tms.model.dto.ShipBillExportDTO;
import com.prolog.rdc.tms.model.dto.ShipBillTemperatureDTO;
import com.prolog.rdc.tms.model.dto.ShipbillAddressResolutionPageDTO;
import com.prolog.rdc.tms.model.dto.ShipbillAndLoadingbillInfoDTO;
import com.prolog.rdc.tms.model.dto.ShipbillApprovalInfoDTO;
import com.prolog.rdc.tms.model.dto.ShipbillBusinessRuleDTO;
import com.prolog.rdc.tms.model.dto.ShipbillDetailApprovalDTO;
import com.prolog.rdc.tms.model.dto.ShipbillDetailPageDTO;
import com.prolog.rdc.tms.model.dto.ShipbillDetailViewByIdDTO;
import com.prolog.rdc.tms.model.dto.ShipbillDetailViewDTO;
import com.prolog.rdc.tms.model.dto.ShipbillHeaderPageDTO;
import com.prolog.rdc.tms.model.dto.ShipbillPackageViewDTO;
import com.prolog.rdc.tms.model.dto.ShipbillPrintHeadDTO;
import com.prolog.rdc.tms.model.dto.ShipbillPrintTableDTO;
import com.prolog.rdc.tms.model.dto.ShipbillTrackingDTO;
import com.prolog.rdc.tms.model.dto.ShipbillViewDTO;
import com.prolog.rdc.tms.model.dto.ShipbillViewlByIdDTO;
import com.prolog.rdc.tms.model.dto.StrategyBusinessTemperatureDTO;
import com.prolog.rdc.tms.model.dto.UploadFileDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ShipbillFitBusinessFlowDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ShipbillMatchLineDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SignconfigPopDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessMatchingDTO;
import com.prolog.rdc.tms.model.dto.basicData.ApprovalLogDTO;
import com.prolog.rdc.tms.model.dto.basicData.ApprovalNodeSelDTO;
import com.prolog.rdc.tms.model.dto.basicData.BranchByEncodingNameDTO;
import com.prolog.rdc.tms.model.dto.basicData.CargoOwnerByEncodingNameDTO;
import com.prolog.rdc.tms.model.dto.basicData.CargoOwnerPageDTO;
import com.prolog.rdc.tms.model.dto.basicData.CarriersByEncodingNameDTO;
import com.prolog.rdc.tms.model.dto.basicData.ImportMatchingDataDTO;
import com.prolog.rdc.tms.model.dto.basicData.ItemByEncodingNameDTO;
import com.prolog.rdc.tms.model.dto.basicData.ItemCheckDTO;
import com.prolog.rdc.tms.model.dto.basicData.ItemPagingQueryDTO;
import com.prolog.rdc.tms.model.dto.basicData.LineByCustomerQueryDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsBaseBranchDTO;
import com.prolog.rdc.tms.model.dto.intransit.TmsVehicleGpsDTO;
import com.prolog.rdc.tms.model.dto.message.SendMessageDTO;
import com.prolog.rdc.tms.model.entity.SysRefdatadModel;
import com.prolog.rdc.tms.model.entity.TmsLoadingBillDetailModel;
import com.prolog.rdc.tms.model.entity.TmsLoadingBillHeaderModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillDetailModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillDetailTempModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillHeaderTempModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillPackageModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillPkgDetailModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillTransLogModel;
import com.prolog.rdc.tms.model.entity.TmsVehicleGpsModel;
import com.prolog.rdc.tms.model.enums.MessageOrderTypeEnum;
import com.prolog.rdc.tms.model.enums.MessageTypeEnum;
import com.prolog.rdc.tms.model.vo.ImportLogUpdateVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillDetailVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillHeaderVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillPackageHeaderVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillPackageVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillPkgDetailVO;
import com.prolog.rdc.tms.model.vo.LmsTmsZoneQueryVO;
import com.prolog.rdc.tms.model.vo.ShipbillAddressResolutionPageVO;
import com.prolog.rdc.tms.model.vo.ShipbillAdvancedQueryVO;
import com.prolog.rdc.tms.model.vo.ShipbillApprovalInfoVO;
import com.prolog.rdc.tms.model.vo.ShipbillApprovalInvalidVO;
import com.prolog.rdc.tms.model.vo.ShipbillApprovalRetractVO;
import com.prolog.rdc.tms.model.vo.ShipbillApprovalSubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillApprovalVO;
import com.prolog.rdc.tms.model.vo.ShipbillCopySubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillCopyVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailApprovalSubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailCopySubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailCopyVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailModifySubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailModifyVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailPageVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailSaveVO;
import com.prolog.rdc.tms.model.vo.ShipbillDetailSubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillExportAllVO;
import com.prolog.rdc.tms.model.vo.ShipbillExportPageVO;
import com.prolog.rdc.tms.model.vo.ShipbillHeaderPageVO;
import com.prolog.rdc.tms.model.vo.ShipbillHeaderSaveVO;
import com.prolog.rdc.tms.model.vo.ShipbillHeaderSubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillLocationVO;
import com.prolog.rdc.tms.model.vo.ShipbillModifySubmitVO;
import com.prolog.rdc.tms.model.vo.ShipbillModifyVO;
import com.prolog.rdc.tms.model.vo.ShipbillNodeTrackingSaveVO;
import com.prolog.rdc.tms.model.vo.ShipbillOperateLogSaveNewVO;
import com.prolog.rdc.tms.model.vo.ShipbillOperateLogSaveVO;
import com.prolog.rdc.tms.model.vo.ShipbillParseAddressVO;
import com.prolog.rdc.tms.model.vo.ShipbillPrintVO;
import com.prolog.rdc.tms.model.vo.ShipbillTrackVO;
import com.prolog.rdc.tms.model.vo.ShipbillViewIdVO;
import com.prolog.rdc.tms.model.vo.ShipbillViewVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalBusinessNodeVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalOpenVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.BusinessFlowShipbillVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ShipbillMatchLineVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SignconfigPopVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.StrategyBusinessItemVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.StrategyBusinessMatchingVO;
import com.prolog.rdc.tms.model.vo.basicData.BranchByEncodingNameVO;
import com.prolog.rdc.tms.model.vo.basicData.CargoOwnerByEncodingNameVO;
import com.prolog.rdc.tms.model.vo.basicData.CargoOwnerPageVO;
import com.prolog.rdc.tms.model.vo.basicData.CarriersByEncodingNameVO;
import com.prolog.rdc.tms.model.vo.basicData.ImportMatchingDataVO;
import com.prolog.rdc.tms.model.vo.basicData.ItemByEncodingNameVO;
import com.prolog.rdc.tms.model.vo.basicData.ItemPagingQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.LineByCustomerQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseBranchQueryVO;
import com.prolog.rdc.tms.model.vo.xlsimport.ShipbillImportVO;
import com.prolog.rdc.tms.proxy.MainDataProxy;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;
import com.prolog.rdc.tms.rmi.feign.UserFeign;
import com.prolog.rdc.tms.service.DispatchService;
import com.prolog.rdc.tms.service.PendingReviewService;
import com.prolog.rdc.tms.service.ShipbillNodeTrackingService;
import com.prolog.rdc.tms.service.ShipbillOperateLogService;
import com.prolog.rdc.tms.service.ShipbillService;
import com.prolog.rdc.tms.util.ConvertorUtil;
import com.prolog.rdc.tms.util.DataUtils;
import com.prolog.rdc.tms.util.FileUtils;
import com.prolog.rdc.tms.util.MessageUtil;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单管理实现层
 *
 * @author :zhangsj
 * @version :1.0.0
 * @className :ShipbillServiceImpl
 * @creationTime :2022/03/31
 * @description :
 * @modifier :zhangsj
 * @modifyTime :2022/03/31
 * @reviseRemarks:
 */
@Slf4j
@Service
public class ShipbillServiceImpl implements ShipbillService {

    @Autowired
    private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

    @Autowired
    private MaindataFeign maindataTmsResource;

    @Autowired
    private TmsShipbillDetailMapper tmsShipbillDetailMapper;

    @Autowired
    private ShipbillNodeTrackingService shipbillNodeTrackingService;

    @Autowired
    private ShipbillOperateLogService shipbillOperateLogService;

    @Autowired
    private TmsShipbillHeaderTempMapper tmsShipbillHeaderTempMapper;

    @Autowired
    private TmsShipbillDetailTempMapper tmsShipbillDetailTempMapper;

    @Autowired
    private UserFeign userTmsResource;

    @Autowired
    private DispatchService dispatchService;

    @Autowired
    private TmsShipbillTransportLogMapper tmsShipbillTransportLogMapper;

    @Autowired
    private PendingReviewService pendingReviewService;

    @Autowired
    private TmsShipbillPackageMapper tmsShipbillPackageMapper;

    @Autowired
    private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

    @Autowired
    private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

    @Autowired
    private ConvertorUtil convertorUtil;

    @Autowired
    private TmsVehicleGpsMapper tmsVehicleGpsMapper;

    @Autowired
    private MainDataProxy mainDataProxy;

    @Autowired
    @Qualifier("messageAndImportExecutor")
    private ThreadPoolTaskExecutor executor;

    @SuppressWarnings("all")
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ShipbillService shipbillService;

    @Autowired
    private TmsShipbillPackageDetailMapper tmsShipbillPackageDetailMapper;

    @Autowired
    private ShipbillRouteDataMapper shipbillRouteDataMapper;

    /**
     * 运单汇总查询
     *
     * @param shipbillHeaderPageVO
     * @return
     */
    @SuppressWarnings("resource")
    @Override
    public Page<ShipbillHeaderPageDTO> pageShipbillHeaderData(ShipbillHeaderPageVO shipbillHeaderPageVO) {
        ToolKits.isParamNull(shipbillHeaderPageVO, "运单汇总查询请求不为空！");
        ToolKits.isParamNull(shipbillHeaderPageVO.getPageNum(), "当前页码不为空");
        ToolKits.isParamNull(shipbillHeaderPageVO.getPageSize(), "每页条数不为空");

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

        // 数据字典翻译数据集合
        List<SignconfigPopDTO> data9 = Lists.newArrayList();
        // 标记配置
        SignconfigPopVO signconfigPopVO = new SignconfigPopVO();
        RestMessage<List<SignconfigPopDTO>> restMessage9 = maindataTmsResource.getSignConfig(signconfigPopVO);
        if (!restMessage9.isSuccess()) {
            throw new RuntimeException("标记配置查询失败!");
        } else {
            data9 = restMessage9.getData();
        }
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT, // 签到时间点单位
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, // 配送方式
                DataDictionaryConstant.TRANSPORT_TYPE, // 运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, // 温度要求
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.ORDER_TYPE, // 订单类型
                DataDictionaryConstant.SHIPBILL_STATUS, // 运单状态
                DataDictionaryConstant.CARRIER_SHIPBILL_STATUS, // 承运商运单状态
                DataDictionaryConstant.LINE_DIRECTION, // 线路方向
                DataDictionaryConstant.ORDER_BUSINESS_TYPE // 订单业务类型
        });

        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = ToolKits.isEmpty(shipbillHeaderPageVO.getShipbillNo()) ? null : Restrictions.like("shipbillNo", "%" + shipbillHeaderPageVO.getShipbillNo() + "%");
        Restriction r2 = ToolKits.isEmpty(shipbillHeaderPageVO.getCargoOwnerName()) ? null : Restrictions.like("cargoOwnerName",
                "%" + shipbillHeaderPageVO.getCargoOwnerName() + "%");
        Restriction r3 = ToolKits.isEmpty(shipbillHeaderPageVO.getOrderNo()) ? null : Restrictions.like("orderNo", "%" + shipbillHeaderPageVO.getOrderNo() + "%");
        Restriction r4 = ToolKits.isEmpty(shipbillHeaderPageVO.getOrderStartDate()) ? null : Restrictions.ge("orderDate", shipbillHeaderPageVO.getOrderStartDate());
        Restriction r5 = ToolKits.isEmpty(shipbillHeaderPageVO.getOrderEndDate()) ? null : Restrictions.le("orderDate", shipbillHeaderPageVO.getOrderEndDate());
        Restriction r6 = ToolKits.isEmpty(shipbillHeaderPageVO.getOrderBusinessType()) ? null : Restrictions.eq("orderBusinessType", shipbillHeaderPageVO.getOrderBusinessType());
        Restriction r7 = ToolKits.isEmpty(shipbillHeaderPageVO.getCreateStartTime()) ? null : Restrictions.ge("createtime", shipbillHeaderPageVO.getCreateStartTime());
        Restriction r8 = ToolKits.isEmpty(shipbillHeaderPageVO.getCreateEndTime()) ? null : Restrictions.le("createtime", shipbillHeaderPageVO.getCreateEndTime());

        Restriction r10 = Restrictions.eq("enterpriseId", user.getEnterpriseId());

        // 权限控制
        Restriction r9 = null;
        Restriction r11 = null;
        Restriction r12 = null;
        Restriction r13 = null;
        Restriction r14 = null;
        Restriction r15 = null;
        Restriction r16 = null;
        Restriction r30 = null;
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 拆单状态 0未拆单
            Restriction r31 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            // 承运商拆单类型 1未拆单
            Restriction r32 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
            Restriction r33 = Restrictions.and(r31, r32);
            // 承运商拆单类型 2拆分主单
            Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
            // 承运商拆单类型 2中转主单
            Restriction r35 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
            r30 = Restrictions.or(r33, r34, r35);
            // 判断是否为部门权限
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
                    DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
            } else {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
                // 其它权限
                // 货主
                r12 = Restrictions.in("cargoOwnerId", user.getConsignors().toArray());
                // 客户
                r13 = Restrictions.in("consigneeUnitId", user.getCustomers().toArray());
                // 供应商
                r14 = Restrictions.in("consigneeUnitId", user.getSuppliers().toArray());
                // 仓库
                r15 = Restrictions.in("consigneeUnitId", user.getWarehouses().toArray());

                Restriction r23 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getWarehouses().stream().toArray(Long[]::new));
                Restriction r24 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getSuppliers().stream().toArray(Long[]::new));
                Restriction r25 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getCustomers().stream().toArray(Long[]::new));

                r16 = Restrictions.or(r13, r14, r15, r23, r24, r25);
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            r30 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
            // 运单状态
            r9 = Restrictions.eq("status", DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK);
            // 承运商账号
            r11 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            // 承运商运单状态
            r12 = Restrictions.in("carrierShipbillStatus", new Integer[]{DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK,
             DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED,
                    DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_DISPATCHED});
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
            // 货主账号
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            r11 = Restrictions.eq(TmsShipbillHeaderModel::getCargoOwnerId, Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        } else {
            throw new BizException("当前人员没有操作权限！");
        }

        Restriction r17 = null;
        if (ToolKits.isNotEmpty(shipbillHeaderPageVO.getShipperLocation()) && shipbillHeaderPageVO.getShipperLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("shipperLongitude");
            Restriction r19 = Restrictions.isnull("shipperLatitude");
            r17 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillHeaderPageVO.getShipperLocation()) && shipbillHeaderPageVO.getShipperLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("shipperLongitude");
            Restriction r19 = Restrictions.isNotNull("shipperLatitude");
            r17 = Restrictions.and(r18, r19);
        }
        Restriction r20 = null;
        if (ToolKits.isNotEmpty(shipbillHeaderPageVO.getConsigneeLocation()) && shipbillHeaderPageVO.getConsigneeLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("consigneeLongitude");
            Restriction r19 = Restrictions.isnull("consigneeLatitude");
            r20 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillHeaderPageVO.getConsigneeLocation()) && shipbillHeaderPageVO.getConsigneeLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("consigneeLongitude");
            Restriction r19 = Restrictions.isNotNull("consigneeLatitude");
            r20 = Restrictions.and(r18, r19);
        }

        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r16, r17, r20, r30));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));

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

        List<ShipbillHeaderPageDTO> list = Lists.newArrayList();
        for (TmsShipbillHeaderModel model : tmsShipbillHeaderModels) {
            ShipbillHeaderPageDTO dto = new ShipbillHeaderPageDTO();
            BeanUtils.copyProperties(model, dto);
            // 收货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude())) {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_WDW);
            }
            // 发货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getShipperLongitude()) && ToolKits.isNotEmpty(model.getShipperLatitude())) {
                dto.setShipperPositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setShipperPositioning(StatusConstant.POSITIONING_WDW);
            }

            // 类型翻译
            dto.setOrderTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(dto.getOrderType())));
            dto.setOrderBusinessTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(dto.getOrderBusinessType())));
            dto.setDeliveryMethodTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(dto.getDeliveryMethodType())));
            dto.setTransportTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(dto.getTransportType())));
            dto.setTemperatureRequirementName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(dto.getTemperatureRequirement())));
            dto.setShipperTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(dto.getShipperType())));
            dto.setConsigneeTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(dto.getConsigneeType())));
            dto.setLineDirectionName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_DIRECTION, String.valueOf(dto.getLineDirection())));
            dto.setShipperSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PICK_UP_SIGN_TIME, String.valueOf(dto.getShipperSignTime())));
            dto.setShipperSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getShipperSignTimeUnit())));

            dto.setConsigneeSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_SIGN_TIME, String.valueOf(dto.getConsigneeSignTime())));
            dto.setConsigneeSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getConsigneeSignTimeUnit())));

            if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
                dto.setStatus(model.getCarrierShipbillStatus());
                dto.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS, String.valueOf(model.getCarrierShipbillStatus())));
            } else {
                dto.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPBILL_STATUS, String.valueOf(dto.getStatus())));
            }

            // 获取背景颜色和字体颜色
            Signconfig:
            for (SignconfigPopDTO signconfigPopDTO : data9) {
                // 标记类型匹配
                switch (signconfigPopDTO.getType()) {
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_DDLX: // 订单类型
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            // 判断是否匹配
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getOrderTypeName()) ? dto.getOrderTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                // 匹配上结束循环
                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_YWLX: // 业务类型
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getOrderBusinessTypeName()) ? dto.getOrderBusinessTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_WDYQ: // 配送方式
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getTemperatureRequirementName()) ? dto.getTemperatureRequirementName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_PSFS: // 订单备注
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getDeliveryMethodTypeName()) ? dto.getDeliveryMethodTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_DDBZ:
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getMemo()) ? dto.getMemo() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                }
            }

            list.add(dto);
        }

        // 分页重组
        Page<ShipbillHeaderPageDTO> page = PageUtils.getPage(list);
        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 advancedQueryVO
     * @return
     */
    @SuppressWarnings("resource")
    @Override
    public Page<ShipbillHeaderPageDTO> pageAdvanced(ShipbillAdvancedQueryVO advancedQueryVO) {
        ToolKits.isParamNull(advancedQueryVO, "运单汇总查询请求不为空！");
        ToolKits.isParamNull(advancedQueryVO.getPageNum(), "当前页码不为空");
        ToolKits.isParamNull(advancedQueryVO.getPageSize(), "每页条数不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();
        List<Map<String, Object>> data3 = Lists.newArrayList();
        List<Map<String, Object>> data4 = Lists.newArrayList();
        List<Map<String, Object>> data5 = Lists.newArrayList();
        List<Map<String, Object>> data6 = Lists.newArrayList();
        List<Map<String, Object>> data7 = Lists.newArrayList();
        List<Map<String, Object>> data8 = Lists.newArrayList();
        List<SignconfigPopDTO> data9 = Lists.newArrayList();

        // 订单类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 订单业务类型
        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();
        }
        // 配送方式
        RestMessage<List<Map<String, Object>>> restMessage3 = maindataTmsResource.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
        if (!restMessage3.isSuccess()) {
            throw new RuntimeException("配送方式翻译失败!");
        } else {
            data3 = restMessage3.getData();
        }
        // 运输类型(运输模式)
        RestMessage<List<Map<String, Object>>> restMessage4 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
        if (!restMessage4.isSuccess()) {
            throw new RuntimeException("运输类型(运输模式)翻译失败!");
        } else {
            data4 = restMessage4.getData();
        }
        // 温度要求
        RestMessage<List<Map<String, Object>>> restMessage5 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);
        if (!restMessage5.isSuccess()) {
            throw new RuntimeException("温度要求翻译失败!");
        } else {
            data5 = restMessage5.getData();
        }
        // 发货方类型
        RestMessage<List<Map<String, Object>>> restMessage6 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
        if (!restMessage6.isSuccess()) {
            throw new RuntimeException("发货方类型翻译失败!");
        } else {
            data6 = restMessage6.getData();
        }
        // 收货方类型
        RestMessage<List<Map<String, Object>>> restMessage7 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
        if (!restMessage7.isSuccess()) {
            throw new RuntimeException("收货方类型翻译失败!");
        } else {
            data7 = restMessage7.getData();
        }

        // 运单状态
        RestMessage<List<Map<String, Object>>> restMessage8 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPBILL_STATUS, null, null, null);
        if (!restMessage8.isSuccess()) {
            throw new RuntimeException("运单状态翻译失败!");
        } else {
            data8 = restMessage8.getData();
        }

        // 标记配置
        SignconfigPopVO signconfigPopVO = new SignconfigPopVO();
        RestMessage<List<SignconfigPopDTO>> restMessage9 = maindataTmsResource.getSignConfig(signconfigPopVO);
        if (!restMessage9.isSuccess()) {
            throw new RuntimeException("标记配置查询失败!");
        } else {
            data9 = restMessage9.getData();
        }

        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT // 签到时间点单位
        });

        // 判断账号类型
        // 用户类型
        advancedQueryVO.setUserType(user.getUserType());
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 判断是否为部门权限
            Integer[] statusList = new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH};
            advancedQueryVO.setStatusList(statusList);
            advancedQueryVO.setDepts(user.getDepts().stream().toArray(String[]::new));
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                advancedQueryVO.setIsDept("YES");
            } else {
                advancedQueryVO.setIsDept("NO");
                // 其它权限
                // 货主
                advancedQueryVO.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
                // 客户
                advancedQueryVO.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
                // 供应商
                advancedQueryVO.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
                // 仓库
                advancedQueryVO.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
            // 货主账号
            Integer[] statusList = new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH};
            advancedQueryVO.setStatusList(statusList);
            advancedQueryVO.setUnitId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            // 承运商账号 单位ID
            advancedQueryVO.setUnitId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            // 承运商运单状态
            Integer[] carrierStsList = new Integer[]{DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE,
                    DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED};
            advancedQueryVO.setCarrierStatusList(carrierStsList);
        } else {
            throw new BizException("当前人员没有操作权限！");
        }
        // 获取高级查询配置
        String conditions = null;
        RestMessage<String> restMessageAdvancedCfg = maindataTmsResource.getQueryConfiguration(DataDictionaryConstant.BIZ_TYPE_BILL);
        if (!restMessageAdvancedCfg.isSuccess()) {
            // throw new RuntimeException("订单类型翻译失败!");
        } else {
            conditions = restMessageAdvancedCfg.getData();
        }
        advancedQueryVO.setEnterpriseId(user.getEnterpriseId());
        advancedQueryVO.setSql(conditions);

        PageUtils.startPage(advancedQueryVO.getPageNum(), advancedQueryVO.getPageSize());
        List<ShipbillHeaderPageDTO> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.shipbillAdvancedQuery(advancedQueryVO);

        List<ShipbillHeaderPageDTO> list = Lists.newArrayList();
        for (ShipbillHeaderPageDTO model : tmsShipbillHeaderModels) {
            ShipbillHeaderPageDTO dto = new ShipbillHeaderPageDTO();
            BeanUtils.copyProperties(model, dto);
            // 收货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude())) {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_WDW);
            }
            // 发货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getShipperLongitude()) && ToolKits.isNotEmpty(model.getShipperLatitude())) {
                dto.setShipperPositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setShipperPositioning(StatusConstant.POSITIONING_WDW);
            }

            // 类型翻译
            dto.setOrderTypeName(PublicMethods.change(data1, String.valueOf(dto.getOrderType())));
            dto.setOrderBusinessTypeName(PublicMethods.change(data2, String.valueOf(dto.getOrderBusinessType())));
            dto.setDeliveryMethodTypeName(PublicMethods.change(data3, String.valueOf(dto.getDeliveryMethodType())));
            dto.setTransportTypeName(PublicMethods.change(data4, String.valueOf(dto.getTransportType())));
            dto.setTemperatureRequirementName(PublicMethods.change(data5, String.valueOf(dto.getTemperatureRequirement())));
            dto.setShipperTypeName(PublicMethods.change(data6, String.valueOf(dto.getShipperType())));
            dto.setConsigneeTypeName(PublicMethods.change(data7, String.valueOf(dto.getConsigneeType())));
            dto.setStatusName(PublicMethods.change(data8, String.valueOf(dto.getStatus())));

            dto.setShipperSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PICK_UP_SIGN_TIME, String.valueOf(dto.getShipperSignTime())));
            dto.setShipperSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getShipperSignTimeUnit())));

            dto.setConsigneeSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_SIGN_TIME, String.valueOf(dto.getConsigneeSignTime())));
            dto.setConsigneeSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getConsigneeSignTimeUnit())));

            // 获取背景颜色和字体颜色
            Signconfig:
            for (SignconfigPopDTO signconfigPopDTO : data9) {
                // 标记类型匹配
                switch (signconfigPopDTO.getType()) {
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_DDLX: // 订单类型
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            // 判断是否匹配
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getOrderTypeName()) ? dto.getOrderTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                // 匹配上结束循环
                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_YWLX: // 业务类型
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                                    : "", ToolKits.isNotEmpty(dto.getOrderBusinessTypeName()) ? dto.getOrderBusinessTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_WDYQ: // 配送方式
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
 : "", ToolKits.isNotEmpty(dto.getTemperatureRequirementName()) ? dto.getTemperatureRequirementName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_PSFS: // 订单备注
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                                    : "", ToolKits.isNotEmpty(dto.getDeliveryMethodTypeName()) ? dto.getDeliveryMethodTypeName() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                    case DataDictionaryConstant.SIGNCONFIG_TYPE_DDBZ:
                        if (ToolKits.isNotEmpty(signconfigPopDTO.getMatching())) {
                            if (PublicMethods.compare(signconfigPopDTO.getMatching(), ToolKits.isNotEmpty(signconfigPopDTO.getStoredValue()) ? signconfigPopDTO.getStoredValue()
                            : "", ToolKits.isNotEmpty(dto.getMemo()) ? dto.getMemo() : "")) {
                                dto.setBackground(ToolKits.isEmpty(signconfigPopDTO.getBackground()) ? "" : signconfigPopDTO.getBackground());
                                dto.setColor(ToolKits.isEmpty(signconfigPopDTO.getColor()) ? "" : signconfigPopDTO.getColor());

                                // 返回前端所需标记ID
                                dto.setSignConfigId(signconfigPopDTO.getId());

                                break Signconfig;
                            }
                        }
                        break;
                }
            }

            list.add(dto);
        }

        // 分页重组
        Page<ShipbillHeaderPageDTO> page = PageUtils.getPage(list);
        if (tmsShipbillHeaderModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<ShipbillHeaderPageDTO> p0 = (com.github.pagehelper.Page<ShipbillHeaderPageDTO>) 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 shipbillHeaderSaveVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSaveShipbillHeaderData(ShipbillHeaderSaveVO shipbillHeaderSaveVO) {
        ToolKits.isParamNull(shipbillHeaderSaveVO, "运单保存请求不为空！");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getCargoOwnerId(), "货主ID不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getCargoOwnerCode(), "货主编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getCargoOwnerName(), "货主名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillHeaderSaveVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillHeaderSaveVO.getDepartmentName(), "所属部门名称不为空");

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

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

        // 获取运单汇总ID
        RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("生成运单汇总ID失败");
        }
        String id = restMessage.getData();

        TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillHeaderSaveVO, model);

        // 汇总赋值
        model.setShipbillId(id);
        model.setShipbillNo(id);
        model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        model.setSource(DataDictionaryConstant.SOURCE_ADD);
        model.setEnterpriseId(user.getEnterpriseId());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setOrderDate(ToolKits.isEmpty(model.getOrderDate()) ? date : model.getOrderDate());
        model.setCreateperson(user.getNickname());
        model.setCreatetime(date);
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);
        model.setReturnOrderFlag(ToolKits.isEmpty(shipbillHeaderSaveVO.getReturnOrderFlag()) ? StatusConstant.WHETHER_NO : shipbillHeaderSaveVO.getReturnOrderFlag());

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        // 运单明细对象集合
        List<TmsShipbillDetailModel> detailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillHeaderSaveVO.getDetails())) {
            // 设置明细行号
            Integer seqno = 1;
            for (ShipbillDetailSaveVO shipbillDetailSaveVO : shipbillHeaderSaveVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailSaveVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(seqno);
                tmsShipbillDetailModel.setShipbillId(id);
                tmsShipbillDetailModel.setShipbillNo(id);
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(user.getNickname());
                tmsShipbillDetailModel.setCreatetime(date);
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);

                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));

                // 行号自增长
                seqno++;
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                // 运单明细保存
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);
                detailModels.add(tmsShipbillDetailModel);
            }
        }
        // 运单业务流程匹配
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);
        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());

        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
        model.setPickUpOrder(1);
        model.setShippingOrder(2);
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_LINE_STRATEGY)) {
            updateShipBillLine(model, "CR");
        }
        model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
        model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
        model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());

        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(model, detailModels, user);
        }
        model.setStagingLocations(detailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
        // 运单汇总表保存
        model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
        tmsShipbillHeaderMapper.save(model);

        // 运单节点保存
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        shipbillNodeTrackingSaveVO.setShipbillId(id);
        shipbillNodeTrackingSaveVO.setShipbillNo(id);
        shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_SC);
        shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

        // 运单操作日志保存
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
        shipbillOperateLogSaveVO.setShipbillId(id);
        shipbillOperateLogSaveVO.setShipbillNo(id);
        shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_CSH + " 匹配业务流程：" + flowData.getFlowName());
        shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

        // 初期化订单运输记录表
        saveTransportLog(id, date, DataDictionaryConstant.ACTION_SAVE, model.getEstimatedPickupStartTime());

        // 保存自动提交判定
        if (model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
            List<String> list = Lists.newArrayList();
            list.add(model.getShipbillId());
            try {
                // 调用提交处理
                autoSubmit(list, user, date);
            } catch (Exception e) {
                throw new PrologException("运单保存自动提交处理失败", e);
            }

        }

        return id;
    }

    /**
     * 运单保存提交
     *
     * @param shipbillHeaderSubmitVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSubmitShipbillHeaderData(ShipbillHeaderSubmitVO shipbillHeaderSubmitVO) {
        ToolKits.isParamNull(shipbillHeaderSubmitVO, "运单保存提交请求不为空！");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerId(), "货主ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerCode(), "货主编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerName(), "货主名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentName(), "所属部门名称不为空");

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

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

        // 获取运单汇总ID
        RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("生成运单汇总ID失败");
        }
        String id = restMessage.getData();

        TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillHeaderSubmitVO, model);

        // 发货方为仓库，收货方为 客户，能匹配上 线路，则自动 将匹配的线路 填入
        /*
         * if (shipbillHeaderSubmitVO.getShipperType().equals(DataDictionaryConstant.
         * SHIPPER_TYPE_CK) &&
         * shipbillHeaderSubmitVO.getConsigneeType().equals(DataDictionaryConstant.
         * CONSIGNEE_TYPE_KH)) { LineByCustomerQueryVO lineByCustomerQueryVO = new
         * LineByCustomerQueryVO();
         * lineByCustomerQueryVO.setCustomerId(shipbillHeaderSubmitVO.getConsigneeUnitId
         * ());
         * lineByCustomerQueryVO.setConsigneeId(shipbillHeaderSubmitVO.getConsigneeId())
         * ; RestMessage<LineByCustomerQueryDTO> restMessage1 =
         * maindataTmsResource.getLineByCustomerExecute(lineByCustomerQueryVO); if
         * (restMessage1.isSuccess()) { if (ToolKits.isNotEmpty(restMessage1.getData()))
         * { model.setLineId(restMessage1.getData().getLineId());
         * model.setLineCode(restMessage1.getData().getLineCode());
         * model.setLineName(restMessage1.getData().getLineName()); } } else { throw new
         * ParameterException(restMessage1.getMessage()); } }
         */

        // 汇总赋值
        model.setShipbillId(id);
        model.setShipbillNo(id);
        model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
        model.setSource(DataDictionaryConstant.SOURCE_ADD);
        model.setEnterpriseId(user.getEnterpriseId());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setOrderDate(ToolKits.isEmpty(model.getOrderDate()) ? date : model.getOrderDate());
        model.setCreateperson(user.getNickname());
        model.setCreatetime(date);

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);
        model.setReturnOrderFlag(ToolKits.isEmpty(shipbillHeaderSubmitVO.getReturnOrderFlag()) ? StatusConstant.WHETHER_NO : shipbillHeaderSubmitVO.getReturnOrderFlag());

        // 运单明细对象集合
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillHeaderSubmitVO.getDetails())) {
            for (ShipbillDetailSubmitVO shipbillDetailSubmitVO : shipbillHeaderSubmitVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailSubmitVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailSubmitVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailSubmitVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailSubmitVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailSubmitVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(Integer.parseInt(tmsShipbillDetailId));
                tmsShipbillDetailModel.setShipbillId(id);
                tmsShipbillDetailModel.setShipbillNo(id);
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(user.getNickname());
                tmsShipbillDetailModel.setCreatetime(date);
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);

                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

                tmsShipbillDetailModels.add(tmsShipbillDetailModel);
            }
        }
        model.setPickUpOrder(1);
        model.setShippingOrder(2);
        // 运单匹配业务流程
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);
        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());

        // 根据业务规则,修改运单
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(model, tmsShipbillDetailModels, user);
        }
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_LINE_STRATEGY)) {
            updateShipBillLine(model, "CRS");
        }
        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);

        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);

        Boolean data = false;
        // 封装判断所需数据
        ApprovalOpenVO approvalOpenVO = new ApprovalOpenVO();
        approvalOpenVO.setApprovalFlowType(DataDictionaryConstant.APPROVAL_FLOW_TYPE_SHIPBILL);
        approvalOpenVO.setApprovalObjectId(id);
        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());
        }
        data = restMessage1.getData();

        // 声明节点实体
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        // 声明日志实体
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();

        if (data) {
            // 修改主表状态为待审核
            model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_CSH_YTJ_APPROVAL + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
            model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
            model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());

            // 封装运单汇总临时表
            TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = new TmsShipbillHeaderTempModel();
            BeanUtils.copyProperties(model, tmsShipbillHeaderTempModel);

            // 封装运单明细临时表
            tmsShipbillDetailModels.forEach(o -> {
                TmsShipbillDetailTempModel tmsShipbillDetailTempModel = new TmsShipbillDetailTempModel();
                BeanUtils.copyProperties(o, tmsShipbillDetailTempModel);
                // 运单明细临时表保存
                tmsShipbillDetailTempMapper.save(tmsShipbillDetailTempModel);
            });
            // 运单汇总表新增
            model.setStagingLocations(tmsShipbillDetailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
            model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
            tmsShipbillHeaderMapper.save(model);

            // 运单汇总临时表保存
            tmsShipbillHeaderTempMapper.save(tmsShipbillHeaderTempModel);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(id);
            shipbillNodeTrackingSaveVO.setShipbillNo(id);
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_CSH_YTJ_APPROVAL);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(id);
            shipbillOperateLogSaveVO.setShipbillNo(id);
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
        } else {
            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YTJ + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
            model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
            model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());
            // 运单汇总表新增
            model.setStagingLocations(tmsShipbillDetailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
            model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
            tmsShipbillHeaderMapper.save(model);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(id);
            shipbillNodeTrackingSaveVO.setShipbillNo(id);
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(id);
            shipbillOperateLogSaveVO.setShipbillNo(id);
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

            // 初期化订单运输记录表
            saveTransportLog(id, date, DataDictionaryConstant.ACTION_COMMIT, model.getEstimatedPickupStartTime());

            // 判定提交后是否自动审核
            if (flowData.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                // 调用审核处理
                List<String> ids = Lists.newArrayList();
                ids.add(id);
                pendingReviewService.reviewShipbillData(ids);
            }
        }
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.SELF_SUBMIT;
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            messageTypeEnum = MessageTypeEnum.CARRIER_SUBMIT;
        }
        MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), messageTypeEnum.getCode(), Lists.newArrayList(id)));
        return id;
    }

    /**
     * 运单批量提交
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitShipbillData(List<String> ids) throws Exception {
        ToolKits.isParamNull(ids, "运单批量提交请求不为空");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 当前时间
        Date date = DateUtil.date();
        try {
            autoSubmit(ids, user, date);
        } catch (Exception e) {
            throw new PrologException("运单批量提交处理失败", e);
        }
    }

    public void autoSubmit(List<String> ids, UserEntity user, Date date) {
        List<String> reviewObjs = Lists.newArrayList();
        for (String id : ids) {
            ToolKits.isParamNull(id, "运单ID不为空");

            // 更新
            TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);

            // 查询明细数据
            Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
            Restriction r1 = Restrictions.eq("shipbillId", id);
            criteria.setRestriction(r1);
            List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);
            if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_BUSINESS_STRATEGY)) {
                // 根据业务规则,修改运单
                updateShipbillHeaderByBusinessRule(tmsShipbillHeaderModel, tmsShipbillDetailModels, user);
            }
            // 运单匹配线路
            if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_LINE_STRATEGY)) {
                updateShipBillLine(tmsShipbillHeaderModel, "CRS");
            }
            if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY) || user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
                Assert.isTrue(tmsShipbillHeaderModel.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_YTJ, "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】已提交");
                Assert.isTrue(tmsShipbillHeaderModel.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_DSH, "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】在审核中");
            } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
                Assert.isTrue(tmsShipbillHeaderModel.getCarrierShipbillStatus() != DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT,
                 "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】已提交");
            }

            Boolean data = false;
            if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY) || user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
                // 封装判断所需数据
                ApprovalOpenVO approvalOpenVO = new ApprovalOpenVO();
                approvalOpenVO.setApprovalFlowType(DataDictionaryConstant.APPROVAL_FLOW_TYPE_SHIPBILL);
                approvalOpenVO.setApprovalObjectId(id);
                approvalOpenVO.setApprovalObjectCode(tmsShipbillHeaderModel.getShipbillNo());
                approvalOpenVO.setApprovalObjectName(tmsShipbillHeaderModel.getShipbillNo());
                approvalOpenVO.setInitiatedUserId(user.getUserid());
                approvalOpenVO.setInitiatedUserName(user.getNickname());

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

                RestMessage<Boolean> restMessage1 = maindataTmsResource.openExecute(approvalOpenVO);
                if (!restMessage1.isSuccess()) {
                    throw new RuntimeException("调用maindata服务是否开启审批流接口失败" + restMessage1.getMessage());
                }
                data = restMessage1.getData();
            }

            // 声明节点实体
            ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
            // 声明日志实体
            ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();

            if (data) {
                // 修改主表状态为待审核
                tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

                tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
                tmsShipbillHeaderModel.setUpdatetime(date);
                // 节点状态
                shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);
                shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ_APPROVAL);
                // 日志状态
                shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YTJ_APPROVAL);
                shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

                // 封装运单汇总临时表
                TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = new TmsShipbillHeaderTempModel();
                BeanUtils.copyProperties(tmsShipbillHeaderModel, tmsShipbillHeaderTempModel);

                tmsShipbillHeaderTempMapper.save(tmsShipbillHeaderTempModel);
                // 封装运单明细临时表
                tmsShipbillDetailModels.forEach(o -> {
                    TmsShipbillDetailTempModel tmsShipbillDetailTempModel = new TmsShipbillDetailTempModel();
                    BeanUtils.copyProperties(o, tmsShipbillDetailTempModel);

                    // 运单明细临时表保存
                    tmsShipbillDetailTempMapper.save(tmsShipbillDetailTempModel);
                });

                // 运单汇总表更新
                tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);
            } else {
                // 运单提交
                if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY) || user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
                    tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

                    // 日志状态
                    shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YTJ);
                    shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                    shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

                    // 节点状态
                    shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
                    shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
                    // 判定提交后是否自动审核
                    if (tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                        reviewObjs.add(id);
                    }
                } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
                    tmsShipbillHeaderModel.setCarrierShipbillStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
                    // 日志状态
                    shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.CARRIER_SHIPBILL_STATUSNAME_YTJ);
                    shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED);
                    shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
                    // 节点状态
                    shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
                    shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.CARRIER_SHIPBILL_NODE_STATUSNAME_TJ);
                    // 判定提交后是否自动审核
                    if (tmsShipbillHeaderModel.getCarrierFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                        reviewObjs.add(id);
                    }
                }
                tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
                tmsShipbillHeaderModel.setUpdatetime(date);
                // 运单汇总表更新
                tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

                Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
                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("commitDt", date);
                tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransLog);
            }

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());

            shipbillOperateLogSaveVO.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
            // 节点保存
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

            MessageTypeEnum messageTypeEnum = MessageTypeEnum.SELF_SUBMIT;
            if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
                messageTypeEnum = MessageTypeEnum.CARRIER_SUBMIT;
            }
            MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), messageTypeEnum.getCode(), Lists.newArrayList(id)));
        }

        // 提交后，调用自动审核处理
        if (ToolKits.isNotEmpty(reviewObjs)) {
            pendingReviewService.autoReview(reviewObjs, user, date);
        }
    }

    /**
     * 运单明细查询
     *
     * @param shipbillDetailPageVO
     * @return
     */
    @SuppressWarnings("resource")
    @Override
    public Page<ShipbillDetailPageDTO> pageShipbillDetailData(ShipbillDetailPageVO shipbillDetailPageVO) {
        ToolKits.isParamNull(shipbillDetailPageVO.getShipbillId(), "运单ID不为空");
        ToolKits.isParamNull(shipbillDetailPageVO.getPageNum(), "当前页码不为空");
        ToolKits.isParamNull(shipbillDetailPageVO.getPageSize(), "每页条数不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();

        // 包装类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.PACK_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 货物温层
        RestMessage<List<Map<String, Object>>> restMessage2 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CARGO_THERMOSPHERE, null, null, null);
        if (!restMessage2.isSuccess()) {
            throw new RuntimeException("货物温层翻译失败!");
        } else {
            data2 = restMessage2.getData();
        }

        // 根据运单ID查询明细数据
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillDetailPageVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().asc(new String[]{"seqno"}));

        PageUtils.startPage(shipbillDetailPageVO.getPageNum(), shipbillDetailPageVO.getPageSize());
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);

        // 返回数据集
        List<ShipbillDetailPageDTO> list = Lists.newArrayList();

        for (TmsShipbillDetailModel tmsShipbillDetailModel : tmsShipbillDetailModels) {
            ShipbillDetailPageDTO dto = new ShipbillDetailPageDTO();
            BeanUtils.copyProperties(tmsShipbillDetailModel, dto);

            // 数据字典翻译
            dto.setPackTypeName(PublicMethods.change(data1, String.valueOf(dto.getPackType())));
            dto.setCargoThermosphereName(PublicMethods.change(data2, String.valueOf(dto.getCargoThermosphere())));

            list.add(dto);
        }

        // 分页重组
        Page<ShipbillDetailPageDTO> page = PageUtils.getPage(list);
        if (tmsShipbillDetailModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsShipbillDetailModel> p0 = (com.github.pagehelper.Page<TmsShipbillDetailModel>) tmsShipbillDetailModels;
            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 shipbillViewVO
     * @return
     */
    @Override
    public ShipbillViewDTO viewShipbillData(ShipbillViewVO shipbillViewVO) {
        ToolKits.isParamNull(shipbillViewVO, "运单查看请求不为空");
        ToolKits.isParamNull(shipbillViewVO.getShipbillId(), "运单ID不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();
        List<Map<String, Object>> data3 = Lists.newArrayList();
        List<Map<String, Object>> data4 = Lists.newArrayList();
        List<Map<String, Object>> data5 = Lists.newArrayList();
        List<Map<String, Object>> data6 = Lists.newArrayList();
        List<Map<String, Object>> data7 = Lists.newArrayList();
        List<Map<String, Object>> data8 = Lists.newArrayList();
        List<Map<String, Object>> data9 = Lists.newArrayList();

        // 订单类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 订单业务类型
        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();
        }
        // 配送方式
        RestMessage<List<Map<String, Object>>> restMessage3 = maindataTmsResource.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
        if (!restMessage3.isSuccess()) {
            throw new RuntimeException("配送方式翻译失败!");
        } else {
            data3 = restMessage3.getData();
        }
        // 运输类型(运输模式)
        RestMessage<List<Map<String, Object>>> restMessage4 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
        if (!restMessage4.isSuccess()) {
            throw new RuntimeException("运输类型(运输模式)翻译失败!");
        } else {
            data4 = restMessage4.getData();
        }
        // 温度要求
        RestMessage<List<Map<String, Object>>> restMessage5 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);
        if (!restMessage5.isSuccess()) {
            throw new RuntimeException("温度要求翻译失败!");
        } else {
            data5 = restMessage5.getData();
        }
        // 发货方类型
        RestMessage<List<Map<String, Object>>> restMessage6 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
        if (!restMessage6.isSuccess()) {
            throw new RuntimeException("发货方类型翻译失败!");
        } else {
            data6 = restMessage6.getData();
        }
        // 收货方类型
        RestMessage<List<Map<String, Object>>> restMessage7 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
        if (!restMessage7.isSuccess()) {
            throw new RuntimeException("收货方类型翻译失败!");
        } else {
            data7 = restMessage7.getData();
        }
        // 包装类型
        RestMessage<List<Map<String, Object>>> restMessage8 = maindataTmsResource.getDropDownById(DataDictionaryConstant.PACK_TYPE, null, null, null);
        if (!restMessage8.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data8 = restMessage8.getData();
        }
        // 货物温层
        RestMessage<List<Map<String, Object>>> restMessage9 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CARGO_THERMOSPHERE, null, null, null);
        if (!restMessage9.isSuccess()) {
            throw new RuntimeException("货物温层翻译失败!");
        } else {
            data9 = restMessage9.getData();
        }
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT // 签到时间点单位
        });
        // 查询运单汇总信息
        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillViewVO.getShipbillId(), TmsShipbillHeaderModel.class);

        ShipbillViewDTO dto = new ShipbillViewDTO();
        BeanUtils.copyProperties(model, dto);

        // 类型翻译
        dto.setOrderTypeName(PublicMethods.change(data1, String.valueOf(dto.getOrderType())));
        dto.setOrderBusinessTypeName(PublicMethods.change(data2, String.valueOf(dto.getOrderBusinessType())));
        dto.setDeliveryMethodTypeName(PublicMethods.change(data3, String.valueOf(dto.getDeliveryMethodType())));
        dto.setTransportTypeName(PublicMethods.change(data4, String.valueOf(dto.getTransportType())));
        dto.setTemperatureRequirementName(PublicMethods.change(data5, String.valueOf(dto.getTemperatureRequirement())));
        dto.setShipperTypeName(PublicMethods.change(data6, String.valueOf(dto.getShipperType())));
        dto.setConsigneeTypeName(PublicMethods.change(data7, String.valueOf(dto.getConsigneeType())));

        dto.setShipperSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PICK_UP_SIGN_TIME, String.valueOf(dto.getShipperSignTime())));
        dto.setShipperSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getShipperSignTimeUnit())));
        dto.setConsigneeSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_SIGN_TIME, String.valueOf(dto.getConsigneeSignTime())));
        dto.setConsigneeSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getConsigneeSignTimeUnit())));

        // 运单明细数据集
        List<ShipbillDetailViewDTO> shipbillDetailViewDTOS = Lists.newArrayList();

        // 查询运单明细
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillViewVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().asc(new String[]{"seqno"}));
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(tmsShipbillDetailModels)) {
            for (TmsShipbillDetailModel tmsShipbillDetailModel : tmsShipbillDetailModels) {
                ShipbillDetailViewDTO detailDTO = new ShipbillDetailViewDTO();
                BeanUtils.copyProperties(tmsShipbillDetailModel, detailDTO);

                // 数据字典翻译
                detailDTO.setPackTypeName(PublicMethods.change(data8, String.valueOf(detailDTO.getPackType())));
                detailDTO.setCargoThermosphereName(PublicMethods.change(data9, String.valueOf(detailDTO.getCargoThermosphere())));

                shipbillDetailViewDTOS.add(detailDTO);
            }
            dto.setShipbillDetailViewDTOS(shipbillDetailViewDTOS);
        }

        return dto;
    }

    /**
     * 点击运单查看
     *
     * @param shipbillViewIdVO
     * @return
     */
    @Override
    public ShipbillViewlByIdDTO viewShipbilllByIdData(ShipbillViewIdVO shipbillViewIdVO) {
        ToolKits.isParamNull(shipbillViewIdVO, "点击运单查看请求不为空");
        ToolKits.isParamNull(shipbillViewIdVO.getShipbillId(), "运单ID不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();
        List<Map<String, Object>> data3 = Lists.newArrayList();
        List<Map<String, Object>> data4 = Lists.newArrayList();
        List<Map<String, Object>> data5 = Lists.newArrayList();
        List<Map<String, Object>> data6 = Lists.newArrayList();
        List<Map<String, Object>> data7 = Lists.newArrayList();
        List<Map<String, Object>> data8 = Lists.newArrayList();
        List<Map<String, Object>> data9 = Lists.newArrayList();
        List<Map<String, Object>> data10 = Lists.newArrayList();

        // 订单类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 订单业务类型
        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();
        }
        // 配送方式
        RestMessage<List<Map<String, Object>>> restMessage3 = maindataTmsResource.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
        if (!restMessage3.isSuccess()) {
            throw new RuntimeException("配送方式翻译失败!");
        } else {
            data3 = restMessage3.getData();
        }
        // 运输类型(运输模式)
        RestMessage<List<Map<String, Object>>> restMessage4 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
        if (!restMessage4.isSuccess()) {
            throw new RuntimeException("运输类型(运输模式)翻译失败!");
        } else {
            data4 = restMessage4.getData();
        }
        // 温度要求
        RestMessage<List<Map<String, Object>>> restMessage5 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);
        if (!restMessage5.isSuccess()) {
            throw new RuntimeException("温度要求翻译失败!");
        } else {
            data5 = restMessage5.getData();
        }
        // 发货方类型
        RestMessage<List<Map<String, Object>>> restMessage6 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
        if (!restMessage6.isSuccess()) {
            throw new RuntimeException("发货方类型翻译失败!");
        } else {
            data6 = restMessage6.getData();
        }
        // 收货方类型
        RestMessage<List<Map<String, Object>>> restMessage7 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
        if (!restMessage7.isSuccess()) {
            throw new RuntimeException("收货方类型翻译失败!");
        } else {
            data7 = restMessage7.getData();
        }
        // 包装类型
        RestMessage<List<Map<String, Object>>> restMessage8 = maindataTmsResource.getDropDownById(DataDictionaryConstant.PACK_TYPE, null, null, null);
        if (!restMessage8.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data8 = restMessage8.getData();
        }
        // 货物温层
        RestMessage<List<Map<String, Object>>> restMessage9 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CARGO_THERMOSPHERE, null, null, null);
        if (!restMessage9.isSuccess()) {
            throw new RuntimeException("货物温层翻译失败!");
        } else {
            data9 = restMessage9.getData();
        }

        // 包裹类型
        RestMessage<List<Map<String, Object>>> restMessage10 = maindataTmsResource.getDropDownById(DataDictionaryConstant.PACKAGE_TYPE, null, null, null);
        if (!restMessage10.isSuccess()) {
            throw new RuntimeException("包裹类型翻译失败!");
        } else {
            data10 = restMessage10.getData();
        }
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT // 签到时间点单位
        });
        // 查询运单汇总信息
        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillViewIdVO.getShipbillId(), TmsShipbillHeaderModel.class);

        ShipbillViewlByIdDTO dto = new ShipbillViewlByIdDTO();
        BeanUtils.copyProperties(model, dto);

        // 类型翻译
        dto.setOrderTypeName(PublicMethods.change(data1, String.valueOf(dto.getOrderType())));
        dto.setOrderBusinessTypeName(PublicMethods.change(data2, String.valueOf(dto.getOrderBusinessType())));
        dto.setDeliveryMethodTypeName(PublicMethods.change(data3, String.valueOf(dto.getDeliveryMethodType())));
        dto.setTransportTypeName(PublicMethods.change(data4, String.valueOf(dto.getTransportType())));
        dto.setTemperatureRequirementName(PublicMethods.change(data5, String.valueOf(dto.getTemperatureRequirement())));
        dto.setShipperTypeName(PublicMethods.change(data6, String.valueOf(dto.getShipperType())));
        dto.setConsigneeTypeName(PublicMethods.change(data7, String.valueOf(dto.getConsigneeType())));

        dto.setShipperSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PICK_UP_SIGN_TIME, String.valueOf(dto.getShipperSignTime())));
        dto.setShipperSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getShipperSignTimeUnit())));
        dto.setConsigneeSignTimeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_SIGN_TIME, String.valueOf(dto.getConsigneeSignTime())));
        dto.setConsigneeSignTimeUnitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SIGN_TIME_UNIT, String.valueOf(dto.getConsigneeSignTimeUnit())));

        StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
        // 目的地
        consigneeProvinceCityDistrict.append(dto.getConsigneeProvinceName());
        consigneeProvinceCityDistrict.append(dto.getConsigneeCityName());
        consigneeProvinceCityDistrict.append(dto.getConsigneeDistrictName());
        dto.setConsigneeProvinceCity(consigneeProvinceCityDistrict.toString());

        // 始发地
        StringBuffer shipperProvinceCityDistrict = new StringBuffer();
        shipperProvinceCityDistrict.append(dto.getShipperProvinceName());
        shipperProvinceCityDistrict.append(dto.getShipperCityName());
        shipperProvinceCityDistrict.append(dto.getShipperDistrictName());
        dto.setShipperProvinceCity(shipperProvinceCityDistrict.toString());

        // 运单明细数据集
        List<ShipbillDetailViewByIdDTO> shipbillDetailViewByIdDTOS = Lists.newArrayList();

        // 查询运单明细
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillViewIdVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().asc(new String[]{"seqno"}));
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(tmsShipbillDetailModels)) {
            for (TmsShipbillDetailModel tmsShipbillDetailModel : tmsShipbillDetailModels) {
                ShipbillDetailViewByIdDTO detailDTO = new ShipbillDetailViewByIdDTO();
                BeanUtils.copyProperties(tmsShipbillDetailModel, detailDTO);

                // 数据字典翻译
                detailDTO.setPackTypeName(PublicMethods.change(data8, String.valueOf(detailDTO.getPackType())));
                detailDTO.setCargoThermosphereName(PublicMethods.change(data9, String.valueOf(detailDTO.getCargoThermosphere())));
                detailDTO.setPlanDeliveryPcs(ToolKits.isEmpty(tmsShipbillDetailModel.getPlanDeliveryPcs()) ? BigDecimal.ZERO : tmsShipbillDetailModel.getPlanDeliveryPcs());
                detailDTO.setPlanDeliveryVolume(NumberUtil.mul(detailDTO.getPlanDeliveryPcs(), tmsShipbillDetailModel.getUnitVolume()));
                detailDTO.setPlanDeliveryWeight(NumberUtil.mul(detailDTO.getPlanDeliveryPcs(), tmsShipbillDetailModel.getUnitWeight()));

                detailDTO.setDeliveryPcs(ToolKits.isEmpty(tmsShipbillDetailModel.getDeliveryPcs()) ? BigDecimal.ZERO : tmsShipbillDetailModel.getDeliveryPcs());
                detailDTO.setDeliveryVolume(NumberUtil.mul(detailDTO.getDeliveryPcs(), tmsShipbillDetailModel.getUnitVolume()));
                detailDTO.setDeliveryWeight(NumberUtil.mul(detailDTO.getDeliveryPcs(), tmsShipbillDetailModel.getUnitWeight()));
                shipbillDetailViewByIdDTOS.add(detailDTO);
            }
            dto.setShipbillDetailViewByIdDTOS(shipbillDetailViewByIdDTOS);
        }

        // 运单包裹数据集
        List<ShipbillPackageViewDTO> shipbillPackageViewDTOs = Lists.newArrayList();

        // 查询运单包裹
        Criteria criteria1 = Criteria.forClass(TmsShipbillPackageModel.class);
        Restriction r11 = Restrictions.eq("shipbillId", shipbillViewIdVO.getShipbillId());
        Restriction r12 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria1.setRestriction(Restrictions.and(r11, r12));
        criteria1.setOrder(Order.newInstance().asc(new String[]{"updatetime"}));
        List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteria1);
        if (ToolKits.isNotEmpty(tmsShipbillPackageModels)) {
            for (TmsShipbillPackageModel tmsShipbillPackageModel : tmsShipbillPackageModels) {
                ShipbillPackageViewDTO shipbillPackageViewDTO = new ShipbillPackageViewDTO();
                BeanUtils.copyProperties(tmsShipbillPackageModel, shipbillPackageViewDTO);

                // 数据字典翻译
                shipbillPackageViewDTO.setPackageTypeName(PublicMethods.change(data10, String.valueOf(shipbillPackageViewDTO.getPackageType())));

                shipbillPackageViewDTOs.add(shipbillPackageViewDTO);
            }
            dto.setPackages(shipbillPackageViewDTOs);
        }

        return dto;
    }

    /**
     * 运单批量作废
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void invalidShipbillData(List<String> ids) throws Exception {
        ToolKits.isParamNull(ids, "运单批量作废请求不为空");

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

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

        for (String id : ids) {
            ToolKits.isParamNull(id, "运单ID不为空");

            // 更新
            TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
            Assert.isTrue(tmsShipbillHeaderModel.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_ZF, "运单【" + tmsShipbillHeaderModel.getShipbillNo() + "】已作废");

            // 运单作废
            tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_ZF);
            tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
            tmsShipbillHeaderModel.setUpdatetime(date);
            tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

            // 运单节点保存
            ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
            shipbillNodeTrackingSaveVO.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_ZF);
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_ZF);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 运单日志保存
            ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
            shipbillOperateLogSaveVO.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_ZF);
            shipbillOperateLogSaveVO.setOldStatus(tmsShipbillHeaderModel.getStatus());
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_ZF);
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
        }
    }

    /**
     * 运单修改保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void modifyShipbillHeaderData(ShipbillModifyVO shipbillModifyVO) throws Exception {
        ToolKits.isParamNull(shipbillModifyVO, "运单修改保存请求不为空！");
        ToolKits.isParamNull(shipbillModifyVO.getShipbillId(), "订单ID不为空");
        ToolKits.isParamNull(shipbillModifyVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillModifyVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillModifyVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillModifyVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillModifyVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillModifyVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillModifyVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillModifyVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillModifyVO.getDepartmentName(), "所属部门名称不为空");

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

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

        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillModifyVO.getShipbillId(), TmsShipbillHeaderModel.class);
        Assert.isTrue(model.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_DSH, "运单【" + model.getShipbillNo() + "】在审核中");
        BeanUtils.copyProperties(shipbillModifyVO, model);

        // 发货方为仓库，收货方为 客户，能匹配上 线路，则自动 将匹配的线路 填入
        if (shipbillModifyVO.getShipperType().equals(DataDictionaryConstant.SHIPPER_TYPE_CK) && shipbillModifyVO.getConsigneeType().equals(DataDictionaryConstant.CONSIGNEE_TYPE_KH)) {
            if (model.getConsigneeUnitId().equals(shipbillModifyVO.getConsigneeUnitId()) || model.getConsigneeId().equals(shipbillModifyVO.getConsigneeId())) {
                LineByCustomerQueryVO lineByCustomerQueryVO = new LineByCustomerQueryVO();
                lineByCustomerQueryVO.setCustomerId(shipbillModifyVO.getConsigneeUnitId());
                lineByCustomerQueryVO.setConsigneeId(shipbillModifyVO.getConsigneeId());
                RestMessage<LineByCustomerQueryDTO> restMessage1 = maindataTmsResource.getLineByCustomerExecute(lineByCustomerQueryVO);
                if (restMessage1.isSuccess()) {
                    if (ToolKits.isNotEmpty(restMessage1.getData())) {
                        model.setLineId(restMessage1.getData().getLineId());
                        model.setLineCode(restMessage1.getData().getLineCode());
                        model.setLineName(restMessage1.getData().getLineName());
                    }
                } else {
                    throw new ParameterException(restMessage1.getMessage());
                }
            }
        }

        // 汇总赋值
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        // 删除原有商品信息
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillModifyVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsShipbillDetailMapper.deleteByCriteria(criteria);

        if (ToolKits.isNotEmpty(shipbillModifyVO.getDetails())) {
            // 设置明细行号
            Integer seqno = 1;
            for (ShipbillDetailModifyVO shipbillDetailModifyVO : shipbillModifyVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailModifyVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailModifyVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailModifyVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailModifyVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailModifyVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(seqno);
                tmsShipbillDetailModel.setShipbillId(model.getShipbillId());
                tmsShipbillDetailModel.setShipbillNo(model.getShipbillNo());
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(model.getCreateperson());
                tmsShipbillDetailModel.setCreatetime(model.getCreatetime());
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);

                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

                // 行号自增长
                seqno++;
            }
        }
        // 运单业务流程匹配
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);
        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_LINE_STRATEGY)) {
            updateShipBillLine(model, "CR");
        }

        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 0未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);

        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);

        // 运单汇总表保存
        tmsShipbillHeaderMapper.update(model);

        // 运单操作日志保存
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
        shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
        shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
        shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_OPERATENAME_XG + " 匹配业务流程：" + flowData.getFlowName());
        shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

        // 保存自动提交判定
        if (model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
            List<String> list = Lists.newArrayList();
            list.add(model.getShipbillId());
            try {
                // 调用提交处理
                autoSubmit(list, user, date);
            } catch (Exception e) {
                throw new PrologException("运单保存自动提交处理失败", e);
            }
        }
    }

    /**
     * 运单复制保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String copyShipbillData(ShipbillCopyVO shipbillCopyVO) throws Exception {
        ToolKits.isParamNull(shipbillCopyVO, "运单复制保存请求不为空！");
        ToolKits.isParamNull(shipbillCopyVO.getCargoOwnerId(), "货主ID不为空");
        ToolKits.isParamNull(shipbillCopyVO.getCargoOwnerCode(), "货主编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getCargoOwnerName(), "货主名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillCopyVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillCopyVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillCopyVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillCopyVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillCopyVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillCopyVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillCopyVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillCopyVO.getDepartmentName(), "所属部门名称不为空");

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

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

        // 获取运单汇总ID
        RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("生成运单汇总ID失败");
        }
        String id = restMessage.getData();

        TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillCopyVO, model);

        // 发货方为仓库，收货方为 客户，能匹配上 线路，则自动 将匹配的线路 填入
        /*
         * if (shipbillCopyVO.getShipperType().equals(DataDictionaryConstant.
         * SHIPPER_TYPE_CK) &&
         * shipbillCopyVO.getConsigneeType().equals(DataDictionaryConstant.
         * CONSIGNEE_TYPE_KH)) { LineByCustomerQueryVO lineByCustomerQueryVO = new
         * LineByCustomerQueryVO();
         * lineByCustomerQueryVO.setCustomerId(shipbillCopyVO.getConsigneeUnitId());
         * lineByCustomerQueryVO.setConsigneeId(shipbillCopyVO.getConsigneeId());
         * RestMessage<LineByCustomerQueryDTO> restMessage1 =
         * maindataTmsResource.getLineByCustomerExecute(lineByCustomerQueryVO); if
         * (restMessage1.isSuccess()) { if (ToolKits.isNotEmpty(restMessage1.getData()))
         * { model.setLineId(restMessage1.getData().getLineId());
         * model.setLineCode(restMessage1.getData().getLineCode());
         * model.setLineName(restMessage1.getData().getLineName()); } } else { throw new
         * ParameterException(restMessage1.getMessage()); } }
         */

        // 汇总赋值
        model.setShipbillId(id);
        model.setShipbillNo(id);
        model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        model.setSource(DataDictionaryConstant.SOURCE_ADD);
        model.setEnterpriseId(user.getEnterpriseId());
        model.setOrderDate(ToolKits.isEmpty(model.getOrderDate()) ? date : model.getOrderDate());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setCreateperson(user.getNickname());
        model.setCreatetime(date);
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);
        model.setReturnOrderFlag(ToolKits.isEmpty(shipbillCopyVO.getReturnOrderFlag()) ? StatusConstant.WHETHER_NO : shipbillCopyVO.getReturnOrderFlag());

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());
        List<TmsShipbillDetailModel> detailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillCopyVO.getDetails())) {
            // 设置明细行号
            Integer seqno = 1;
            for (ShipbillDetailCopyVO shipbillDetailCopyVO : shipbillCopyVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailCopyVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailCopyVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailCopyVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailCopyVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailCopyVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(seqno);
                tmsShipbillDetailModel.setShipbillId(id);
                tmsShipbillDetailModel.setShipbillNo(id);
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(user.getNickname());
                tmsShipbillDetailModel.setCreatetime(date);
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);
                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

                // 行号自增长
                seqno++;
                detailModels.add(tmsShipbillDetailModel);
            }
        }
        // 运单业务流程匹配
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);

        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());
        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
        model.setPickUpOrder(1);
        model.setShippingOrder(2);
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_LINE_STRATEGY)) {
            updateShipBillLine(model, "CR");
        }
        // 运单匹配业务规则
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(model, detailModels, user);
        }
        model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
        model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
        model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());
        // 运单汇总表保存
        model.setStagingLocations(detailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
        model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
        tmsShipbillHeaderMapper.save(model);

        // 运单节点保存
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        shipbillNodeTrackingSaveVO.setShipbillId(id);
        shipbillNodeTrackingSaveVO.setShipbillNo(id);
        shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_SC);
        shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

        // 运单操作日志保存
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
        shipbillOperateLogSaveVO.setShipbillId(id);
        shipbillOperateLogSaveVO.setShipbillNo(id);
        shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_CSH + " 匹配业务流程：" + flowData.getFlowName());
        shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

        // 初期化运单装车记录
        saveTransportLog(id, date, DataDictionaryConstant.ACTION_SAVE, model.getEstimatedPickupStartTime());

        // 保存自动提交判定
        if (model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
            List<String> list = Lists.newArrayList();
            list.add(model.getShipbillId());
            try {
                // 调用提交处理
                autoSubmit(list, user, date);
            } catch (Exception e) {
                throw new PrologException("运单保存自动提交处理失败", e);
            }
        }

        return id;
    }

    /**
     * 运单复制保存提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String copySubmitShipbillData(ShipbillCopySubmitVO shipbillCopySubmitVO) throws Exception {
        ToolKits.isParamNull(shipbillCopySubmitVO, "运单复制提交请求不为空！");
        ToolKits.isParamNull(shipbillCopySubmitVO.getCargoOwnerId(), "货主ID不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getCargoOwnerCode(), "货主编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getCargoOwnerName(), "货主名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillCopySubmitVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillCopySubmitVO.getDepartmentName(), "所属部门名称不为空");

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

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

        // 获取运单汇总ID
        RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("生成运单汇总ID失败");
        }
        String id = restMessage.getData();

        TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillCopySubmitVO, model);

        // 发货方为仓库，收货方为 客户，能匹配上 线路，则自动 将匹配的线路 填入
        /*
         * if (shipbillCopySubmitVO.getShipperType().equals(DataDictionaryConstant.
         * SHIPPER_TYPE_CK) &&
         * shipbillCopySubmitVO.getConsigneeType().equals(DataDictionaryConstant.
         * CONSIGNEE_TYPE_KH)) { LineByCustomerQueryVO lineByCustomerQueryVO = new
         * LineByCustomerQueryVO();
         * lineByCustomerQueryVO.setCustomerId(shipbillCopySubmitVO.getConsigneeUnitId()
         * );
         * lineByCustomerQueryVO.setConsigneeId(shipbillCopySubmitVO.getConsigneeId());
         * RestMessage<LineByCustomerQueryDTO> restMessage1 =
         * maindataTmsResource.getLineByCustomerExecute(lineByCustomerQueryVO); if
         * (restMessage1.isSuccess()) { if (ToolKits.isNotEmpty(restMessage1.getData()))
         * { model.setLineId(restMessage1.getData().getLineId());
         * model.setLineCode(restMessage1.getData().getLineCode());
         * model.setLineName(restMessage1.getData().getLineName()); } } else { throw new
         * ParameterException(restMessage1.getMessage()); } }
         */

        // 汇总赋值
        model.setShipbillId(id);
        model.setShipbillNo(id);
        model.setSource(DataDictionaryConstant.SOURCE_ADD);
        model.setEnterpriseId(user.getEnterpriseId());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setOrderDate(ToolKits.isEmpty(model.getOrderDate()) ? date : model.getOrderDate());
        model.setCreateperson(user.getNickname());
        model.setCreatetime(date);

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);
        model.setReturnOrderFlag(ToolKits.isEmpty(shipbillCopySubmitVO.getReturnOrderFlag()) ? StatusConstant.WHETHER_NO : shipbillCopySubmitVO.getReturnOrderFlag());

        // 运单明细对象集合
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillCopySubmitVO.getDetails())) {
            for (ShipbillDetailCopySubmitVO shipbillDetailCopySubmitVO : shipbillCopySubmitVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailCopySubmitVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailCopySubmitVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailCopySubmitVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailCopySubmitVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailCopySubmitVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(Integer.parseInt(tmsShipbillDetailId));
                tmsShipbillDetailModel.setShipbillId(id);
                tmsShipbillDetailModel.setShipbillNo(id);
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(user.getNickname());
                tmsShipbillDetailModel.setCreatetime(date);
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);
                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                // 运单明细保存
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

                tmsShipbillDetailModels.add(tmsShipbillDetailModel);
            }
        }
        model.setPickUpOrder(1);
        model.setShippingOrder(2);
        // 运单匹配业务流程
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);
        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());

        // 根据业务规则,修改运单
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(model, tmsShipbillDetailModels, user);
        }
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_LINE_STRATEGY)) {
            updateShipBillLine(model, "CRS");
        }
        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);

        Boolean data = false;
        // 封装判断所需数据
        ApprovalOpenVO approvalOpenVO = new ApprovalOpenVO();
        approvalOpenVO.setApprovalFlowType(DataDictionaryConstant.APPROVAL_FLOW_TYPE_SHIPBILL);
        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());
        }
        data = restMessage1.getData();

        // 声明节点实体
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        // 声明日志实体
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();

        // 初期化运单装车记录
        saveTransportLog(id, date, DataDictionaryConstant.ACTION_COMMIT, shipbillCopySubmitVO.getEstimatedPickupStartTime());

        if (data) {
            // 修改主表状态为待审核
            model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_DSH + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
            model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
            model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());

            // 封装运单汇总临时表
            TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = new TmsShipbillHeaderTempModel();
            BeanUtils.copyProperties(model, tmsShipbillHeaderTempModel);

            // 封装运单明细临时表
            tmsShipbillDetailModels.forEach(o -> {
                TmsShipbillDetailTempModel tmsShipbillDetailTempModel = new TmsShipbillDetailTempModel();
                BeanUtils.copyProperties(o, tmsShipbillDetailTempModel);

                // 运单明细临时表保存
                tmsShipbillDetailTempMapper.save(tmsShipbillDetailTempModel);
            });
            // 运单汇总表新增
            model.setStagingLocations(tmsShipbillDetailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
            model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
            tmsShipbillHeaderMapper.save(model);

            // 运单汇总临时表保存
            tmsShipbillHeaderTempMapper.save(tmsShipbillHeaderTempModel);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(model.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

        } else {
            model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YTJ + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            model.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
            model.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
            model.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());
            // 运单汇总表新增
            model.setStagingLocations(tmsShipbillDetailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
            model.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
            tmsShipbillHeaderMapper.save(model);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(model.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

            Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
            Restriction r1 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, model.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("commitDt", date);
            tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransLog);

            // 判定提交后是否自动审核
            if (flowData.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                // 调用审核处理
                List<String> ids = Lists.newArrayList();
                ids.add(id);
                pendingReviewService.reviewShipbillData(ids);
            }
        }
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.SELF_SUBMIT;
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            messageTypeEnum = MessageTypeEnum.CARRIER_SUBMIT;
        }
        MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), messageTypeEnum.getCode(), Lists.newArrayList(id)));
        return id;
    }

    /**
     * 运单修改保存提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void modifySubmitShipbillHeaderData(ShipbillModifySubmitVO shipbillModifySubmitVO) throws Exception {
        ToolKits.isParamNull(shipbillModifySubmitVO, "运单复制保存请求不为空！");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipbillId(), "订单ID不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillModifySubmitVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillModifySubmitVO.getDepartmentName(), "所属部门名称不为空");

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

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

        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillModifySubmitVO.getShipbillId(), TmsShipbillHeaderModel.class);
        Assert.isTrue(model.getStatus() != DataDictionaryConstant.SHIPBILL_STATUS_DSH, "运单【" + model.getShipbillNo() + "】在审核中");
        BeanUtils.copyProperties(shipbillModifySubmitVO, model);

        // 根据业务规则,修改运单
        List<ShipbillDetailModifySubmitVO> details = shipbillModifySubmitVO.getDetails();
        List<TmsShipbillDetailModel> shipbillDetailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(details)) {
            details.stream().forEach(detail -> {
                TmsShipbillDetailModel detailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(detail, detailModel);
                shipbillDetailModels.add(detailModel);
            });
        }
        // 发货方为仓库，收货方为 客户，能匹配上 线路，则自动 将匹配的线路 填入
        if (shipbillModifySubmitVO.getShipperType().equals(DataDictionaryConstant.SHIPPER_TYPE_CK) && shipbillModifySubmitVO.getConsigneeType().equals(DataDictionaryConstant.CONSIGNEE_TYPE_KH)) {
            if (model.getConsigneeUnitId().equals(shipbillModifySubmitVO.getConsigneeUnitId()) || model.getConsigneeId().equals(shipbillModifySubmitVO.getConsigneeId())) {
                LineByCustomerQueryVO lineByCustomerQueryVO = new LineByCustomerQueryVO();
                lineByCustomerQueryVO.setCustomerId(shipbillModifySubmitVO.getConsigneeUnitId());
                lineByCustomerQueryVO.setConsigneeId(shipbillModifySubmitVO.getConsigneeId());
                RestMessage<LineByCustomerQueryDTO> restMessage1 = maindataTmsResource.getLineByCustomerExecute(lineByCustomerQueryVO);
                if (restMessage1.isSuccess()) {
                    if (ToolKits.isNotEmpty(restMessage1.getData())) {
                        model.setLineId(restMessage1.getData().getLineId());
                        model.setLineCode(restMessage1.getData().getLineCode());
                        model.setLineName(restMessage1.getData().getLineName());
                    }
                } else {
                    throw new ParameterException(restMessage1.getMessage());
                }
            }
        }

        // 封装判断所需数据
        ApprovalOpenVO approvalOpenVO = new ApprovalOpenVO();
        approvalOpenVO.setApprovalFlowType(DataDictionaryConstant.APPROVAL_FLOW_TYPE_SHIPBILL);
        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());
        }
        Boolean data = restMessage1.getData();

        // 声明节点实体
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        // 声明日志实体
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();

        // 汇总赋值
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(date);

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        // 删除原有商品信息
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillModifySubmitVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsShipbillDetailMapper.deleteByCriteria(criteria);

        // 运单明细对象集合
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillModifySubmitVO.getDetails())) {
            // 设置明细行号
            Integer seqno = 1;
            for (ShipbillDetailModifySubmitVO shipbillDetailModifySubmitVO : shipbillModifySubmitVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailModifySubmitVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailModifySubmitVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailModifySubmitVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailModifySubmitVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailModifySubmitVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailModel.setSeqno(seqno);
                tmsShipbillDetailModel.setShipbillId(model.getShipbillId());
                tmsShipbillDetailModel.setShipbillNo(model.getShipbillNo());
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailModel.setCreateperson(model.getCreateperson());
                tmsShipbillDetailModel.setCreatetime(model.getCreatetime());
                tmsShipbillDetailModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailModel.setUpdatetime(date);
                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                // 运单明细保存
                tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

                tmsShipbillDetailModels.add(tmsShipbillDetailModel);

                // 行号自增长
                seqno++;
            }
        }
        // 运单匹配业务流程
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(model);
        // 订单绑定流程配置
        model.setFlowConfig(flowData.getFlowConfig());

        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(model, shipbillDetailModels, user);
        }
        // 运单匹配线路
        if (StrUtil.isNotBlank(model.getFlowConfig()) && model.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_LINE_STRATEGY)) {
            updateShipBillLine(model, "S");
        }
        // 运输状态 待发货
        model.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        model.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        model.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 扫描状态 初始
        model.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 异常状态 0未异常
        model.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
        // 拆单状态 0承运商未拆单
        model.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        model.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);

        if (data) {
            // 修改主表状态为待审核
            model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_DSH + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_DSH);

            // 运单临时表处理
            TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = tmsShipbillHeaderTempMapper.findById(model.getShipbillId(), TmsShipbillHeaderTempModel.class);
            if (ToolKits.isEmpty(tmsShipbillHeaderTempModel)) {
                // 封装运单汇总临时表
                tmsShipbillHeaderTempModel = new TmsShipbillHeaderTempModel();
                BeanUtils.copyProperties(model, tmsShipbillHeaderTempModel);

                // 封装运单明细临时表
                tmsShipbillDetailModels.forEach(o -> {
                    TmsShipbillDetailTempModel tmsShipbillDetailTempModel = new TmsShipbillDetailTempModel();
                    BeanUtils.copyProperties(o, tmsShipbillDetailTempModel);

                    // 运单明细临时表保存
                    tmsShipbillDetailTempMapper.save(tmsShipbillDetailTempModel);

                });

                // 运单汇总临时表保存
                tmsShipbillHeaderTempMapper.save(tmsShipbillHeaderTempModel);
            } else {
                BeanUtils.copyProperties(model, tmsShipbillHeaderTempModel);

                // 封装运单明细临时表
                tmsShipbillDetailModels.forEach(o -> {
                    TmsShipbillDetailTempModel tmsShipbillDetailTempModel = tmsShipbillDetailTempMapper.findById(o.getId(), TmsShipbillDetailTempModel.class);
                    BeanUtils.copyProperties(o, tmsShipbillDetailTempModel);

                    // 运单明细临时表保存
                    tmsShipbillDetailTempMapper.update(tmsShipbillDetailTempModel);

                });

                // 运单汇总临时表保存
                tmsShipbillHeaderTempMapper.update(tmsShipbillHeaderTempModel);
            }

            // 运单汇总表修改
            tmsShipbillHeaderMapper.update(model);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(model.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
        } else {
            model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            // 节点状态
            shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            // 日志状态
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YTJ + " 匹配业务流程：" + flowData.getFlowName());
            shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);

            // 运单汇总表新增
            tmsShipbillHeaderMapper.update(model);

            // 节点保存
            shipbillNodeTrackingSaveVO.setShipbillId(model.getShipbillId());
            shipbillNodeTrackingSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_TJ);
            shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

            // 日志保存
            shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
            shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

            Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
            Restriction r3 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, model.getShipbillId());
            Restriction r4 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, user.getEnterpriseId());
            criteriaTransLog.setRestriction(Restrictions.and(r3, r4));

            Map<String, Object> mapUpdate = Maps.newHashMap();
            mapUpdate.put("updateperson", user.getNickname());
            mapUpdate.put("updatetime", date);
            mapUpdate.put("commitDt", date);
            tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransLog);

            // 判定提交后是否自动审核
            if (flowData.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                // 调用审核处理
                List<String> ids = Lists.newArrayList();
                ids.add(model.getShipbillId());
                pendingReviewService.reviewShipbillData(ids);
            }
        }
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.SELF_SUBMIT;
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            messageTypeEnum = MessageTypeEnum.CARRIER_SUBMIT;
        }
        MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), messageTypeEnum.getCode(), Lists.newArrayList(shipbillModifySubmitVO.getShipbillId())));
    }

    /**
     * 运单地址解析查询
     */
    @SuppressWarnings("resource")
    @Override
    public Page<ShipbillAddressResolutionPageDTO> pageAddressResolutionData(ShipbillAddressResolutionPageVO shipbillAddressResolutionPageVO) {
        ToolKits.isParamNull(shipbillAddressResolutionPageVO, "运单地址解析查询请求不为空");
        ToolKits.isParamNull(shipbillAddressResolutionPageVO.getPageNum(), "当前页码不为空");
        ToolKits.isParamNull(shipbillAddressResolutionPageVO.getPageSize(), "每页条数不为空");
        ToolKits.isParamNull(shipbillAddressResolutionPageVO.getShipbillIds(), "运单ID集不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();

        // 发货方类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("发货方类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 收货方类型
        RestMessage<List<Map<String, Object>>> restMessage2 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
        if (!restMessage2.isSuccess()) {
            throw new RuntimeException("收货方类型翻译失败!");
        } else {
            data2 = restMessage2.getData();
        }

        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = ToolKits.isEmpty(shipbillAddressResolutionPageVO.getOrderNo()) ? null : Restrictions.like("orderNo",
         "%" + shipbillAddressResolutionPageVO.getOrderNo() + "%");
        Restriction r2 = ToolKits.isEmpty(shipbillAddressResolutionPageVO.getShipbillNo()) ? null : Restrictions.like("shipbillNo",
"%" + shipbillAddressResolutionPageVO.getShipbillNo() + "%");
        Restriction r3 = ToolKits.isEmpty(shipbillAddressResolutionPageVO.getCargoOwnerName()) ? null : Restrictions.like("cargoOwnerName",
 "%" + shipbillAddressResolutionPageVO.getCargoOwnerName() + "%");
        Restriction r4 = ToolKits.isEmpty(shipbillAddressResolutionPageVO.getShipperUnitName()) ? null : Restrictions.like("shipperUnitName",
         "%" + shipbillAddressResolutionPageVO.getShipperUnitName() + "%");
        Restriction r5 = ToolKits.isEmpty(shipbillAddressResolutionPageVO.getConsigneeUnitName()) ? null : Restrictions.like("consigneeUnitName",
                "%" + shipbillAddressResolutionPageVO.getConsigneeUnitName() + "%");
        Restriction r6 = Restrictions.in("shipbillId", shipbillAddressResolutionPageVO.getShipbillIds().toArray());
        Restriction r8 = Restrictions.eq("enterpriseId", user.getEnterpriseId());

        // 权限控制
        Restriction r7 = null;
        Restriction r11 = null;
        Restriction r12 = null;
        Restriction r13 = null;
        Restriction r14 = null;
        Restriction r15 = null;
        Restriction r16 = null;
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 判断是否为部门权限
            r7 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
            } else {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
                // 其它权限
                // 货主
                r12 = Restrictions.in("cargoOwnerId", user.getConsignors().toArray());
                // 客户
                r13 = Restrictions.in("consigneeUnitId", user.getCustomers().toArray());
                // 供应商
                r14 = Restrictions.in("consigneeUnitId", user.getSuppliers().toArray());
                // 仓库
                r15 = Restrictions.in("consigneeUnitId", user.getWarehouses().toArray());

                r16 = Restrictions.or(r13, r14, r15);
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            // 运单状态
            r7 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK});
            // 承运商账号
            r11 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            // 承运商运单状态
            r12 = Restrictions.in("carrierShipbillStatus", new Integer[]{DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK,
             DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED});
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
            r7 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            r11 = Restrictions.eq(TmsShipbillHeaderModel::getCargoOwnerId, Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        } else {
            throw new BizException("当前人员没有操作权限！");
        }

        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6, r7, r8, r11, r12, r16));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));
        PageUtils.startPage(shipbillAddressResolutionPageVO.getPageNum(), shipbillAddressResolutionPageVO.getPageSize());
        List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

        List<ShipbillAddressResolutionPageDTO> shipbillAddressResolutionPageDTOs = Lists.newArrayList();
        for (TmsShipbillHeaderModel tmsShipbillHeaderModel : tmsShipbillHeaderModels) {
            ShipbillAddressResolutionPageDTO shipbillAddressResolutionPageDTO = new ShipbillAddressResolutionPageDTO();
            BeanUtils.copyProperties(tmsShipbillHeaderModel, shipbillAddressResolutionPageDTO);
            shipbillAddressResolutionPageDTO.setShipperTypeName(PublicMethods.change(data1, String.valueOf(shipbillAddressResolutionPageDTO.getShipperType())));
            shipbillAddressResolutionPageDTO.setConsigneeTypeName(PublicMethods.change(data2, String.valueOf(shipbillAddressResolutionPageDTO.getConsigneeType())));

            shipbillAddressResolutionPageDTOs.add(shipbillAddressResolutionPageDTO);
        }

        // 分页重组
        Page<ShipbillAddressResolutionPageDTO> page = PageUtils.getPage(shipbillAddressResolutionPageDTOs);
        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;
    }

    /**
     * 运单地址解析
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addressResolutionData(ShipbillParseAddressVO shipbillParseAddressVO) throws Exception {
        ToolKits.isParamNull(shipbillParseAddressVO, "运单地址解析请求不为空！");
        ToolKits.isParamNull(shipbillParseAddressVO.getShipbillId(), "运单ID不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getShipperId(), "发货方ID不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getShipperLongitude(), "发货方经度不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getShipperLatitude(), "发货方纬度不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getConsigneeId(), "收货方ID不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getConsigneeAddress(), "收货方详细地址不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getConsigneeLongitude(), "收货方经度不为空");
        ToolKits.isParamNull(shipbillParseAddressVO.getConsigneeLatitude(), "收货方纬度不为空");

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

        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillParseAddressVO.getShipbillId(), TmsShipbillHeaderModel.class);

        RestMessage<String> restMessage = new RestMessage<String>();
        // 更新发货方经纬度数据
        if (model.getShipperType() == DataDictionaryConstant.SHIPPER_TYPE_KH) {
            restMessage = maindataTmsResource.parseCustomerConsigneeAddress(shipbillParseAddressVO.getShipperId(), shipbillParseAddressVO.getShipperLongitude(),
             shipbillParseAddressVO.getShipperLatitude(), shipbillParseAddressVO.getShipperAddress());
        } else if (model.getShipperType() == DataDictionaryConstant.SHIPPER_TYPE_CK) {
            restMessage = maindataTmsResource.parseBranchAddress(shipbillParseAddressVO.getShipperId(), shipbillParseAddressVO.getShipperLongitude(),
             shipbillParseAddressVO.getShipperLatitude(), shipbillParseAddressVO.getShipperAddress());
        } else if (model.getShipperType() == DataDictionaryConstant.SHIPPER_TYPE_GYS) {
            restMessage = maindataTmsResource.parseProviderShipperAddress(shipbillParseAddressVO.getShipperId(), shipbillParseAddressVO.getShipperLongitude(),
             shipbillParseAddressVO.getShipperLatitude(), shipbillParseAddressVO.getShipperAddress());
        }

        if (!restMessage.isSuccess()) {
            throw new ParameterException("更新发货方失败");
        }

        // 响应初始化
        restMessage = new RestMessage<String>();
        // 更新收货方经纬度数据
        if (model.getConsigneeType() == DataDictionaryConstant.CONSIGNEE_TYPE_KH) {
            restMessage = maindataTmsResource.parseCustomerConsigneeAddress(shipbillParseAddressVO.getConsigneeId(), shipbillParseAddressVO.getConsigneeLongitude(),
             shipbillParseAddressVO.getConsigneeLatitude(), shipbillParseAddressVO.getConsigneeAddress());
        } else if (model.getShipperType() == DataDictionaryConstant.CONSIGNEE_TYPE_CK) {
            restMessage = maindataTmsResource.parseBranchAddress(shipbillParseAddressVO.getConsigneeId(), shipbillParseAddressVO.getConsigneeLongitude(),
             shipbillParseAddressVO.getConsigneeLatitude(), shipbillParseAddressVO.getConsigneeAddress());
        } else if (model.getShipperType() == DataDictionaryConstant.CONSIGNEE_TYPE_GYS) {
            restMessage = maindataTmsResource.parseProviderShipperAddress(shipbillParseAddressVO.getConsigneeId(), shipbillParseAddressVO.getConsigneeLongitude(),
             shipbillParseAddressVO.getConsigneeLatitude(), shipbillParseAddressVO.getConsigneeAddress());
        }

        if (!restMessage.isSuccess()) {
            throw new ParameterException("更新收货方失败");
        }

        // 修改运单上的经纬度信息
        model.setShipperLatitude(shipbillParseAddressVO.getShipperLatitude());
        model.setShipperLongitude(shipbillParseAddressVO.getShipperLongitude());
        model.setShipperAddress(ToolKits.isEmpty(shipbillParseAddressVO.getShipperAddress()) ? null : shipbillParseAddressVO.getShipperAddress());
        model.setConsigneeLatitude(shipbillParseAddressVO.getConsigneeLatitude());
        model.setConsigneeLatitude(shipbillParseAddressVO.getConsigneeLatitude());
        model.setConsigneeAddress(ToolKits.isEmpty(shipbillParseAddressVO.getConsigneeAddress()) ? null : shipbillParseAddressVO.getConsigneeAddress());
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(DateUtil.date());
        tmsShipbillHeaderMapper.update(model);

        // 运单操作日志保存
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
        shipbillOperateLogSaveVO.setShipbillId(model.getShipbillId());
        shipbillOperateLogSaveVO.setShipbillNo(model.getShipbillNo());
        shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_OPERATENAME_XG);
        shipbillOperateLogSaveVO.setOldStatus(model.getStatus());
        shipbillOperateLogSaveVO.setNewStatus(model.getStatus());
        shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
    }

    /**
     * 运单打印
     *
     * @return
     */
    @Override
    public Map<String, Object> shipbillPrintData(ShipbillPrintVO shipbillPrintVO) {
        ToolKits.isParamNull(shipbillPrintVO, "运单打印请求不为空");
        ToolKits.isParamNull(shipbillPrintVO.getShipbillId(), "运单ID不为空");

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

        // 查询运单信息
        TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillPrintVO.getShipbillId(), TmsShipbillHeaderModel.class);

        ToolKits.isParamNull(tmsShipbillHeaderModel, "运单ID[" + shipbillPrintVO.getShipbillId() + "]信息不存在");

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();

        // 订单类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }

        // 打印头部数据
        ShipbillPrintHeadDTO shipbillPSPrintHeadDTO = new ShipbillPrintHeadDTO();
        shipbillPSPrintHeadDTO.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
        shipbillPSPrintHeadDTO.setCreatetime(tmsShipbillHeaderModel.getCreatetime());
        shipbillPSPrintHeadDTO.setOrderType(PublicMethods.change(data1, String.valueOf(tmsShipbillHeaderModel.getOrderType())));
        shipbillPSPrintHeadDTO.setShipperName(tmsShipbillHeaderModel.getShipperName());
        shipbillPSPrintHeadDTO.setShipperContact(tmsShipbillHeaderModel.getShipperContact());
        shipbillPSPrintHeadDTO.setShipperPhoneNumber(tmsShipbillHeaderModel.getShipperPhoneNumber());
        shipbillPSPrintHeadDTO.setShipperLandlineNumber(tmsShipbillHeaderModel.getShipperLandlineNumber());
        shipbillPSPrintHeadDTO.setShipperProvinceName(tmsShipbillHeaderModel.getShipperProvinceName());
        shipbillPSPrintHeadDTO.setShipperCityName(tmsShipbillHeaderModel.getShipperCityName());
        shipbillPSPrintHeadDTO.setShipperDistrictName(tmsShipbillHeaderModel.getShipperDistrictName());
        shipbillPSPrintHeadDTO.setShipperAddress(tmsShipbillHeaderModel.getShipperAddress());
        shipbillPSPrintHeadDTO.setConsigneeName(tmsShipbillHeaderModel.getConsigneeName());
        shipbillPSPrintHeadDTO.setConsigneeContact(tmsShipbillHeaderModel.getConsigneeContact());
        shipbillPSPrintHeadDTO.setConsigneePhoneNumber(tmsShipbillHeaderModel.getConsigneePhoneNumber());
        shipbillPSPrintHeadDTO.setConsigneeLandlineNumber(tmsShipbillHeaderModel.getConsigneeLandlineNumber());
        shipbillPSPrintHeadDTO.setConsigneeProvinceName(tmsShipbillHeaderModel.getConsigneeProvinceName());
        shipbillPSPrintHeadDTO.setConsigneeCityName(tmsShipbillHeaderModel.getConsigneeCityName());
        shipbillPSPrintHeadDTO.setConsigneeDistrictName(tmsShipbillHeaderModel.getConsigneeDistrictName());
        shipbillPSPrintHeadDTO.setConsigneeAddress(tmsShipbillHeaderModel.getConsigneeAddress());

        // 获取商品信息
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillPrintVO.getShipbillId());
        criteria.setRestriction(r1);
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);

        List<ShipbillPrintTableDTO> shipbillPSPrintTableDTOs = new ArrayList<ShipbillPrintTableDTO>();

        if (ToolKits.isNotEmpty(tmsShipbillDetailModels)) {
            for (TmsShipbillDetailModel item : tmsShipbillDetailModels) {
                ShipbillPrintTableDTO dto = new ShipbillPrintTableDTO();
                dto.setItemCode(item.getItemCode());
                dto.setItemName(item.getItemName());
                dto.setPcs(item.getPcs());
                dto.setWeight(item.getWeight());
                dto.setVolume(item.getVolume());
                shipbillPSPrintTableDTOs.add(dto);
            }
        }

        // TODO print

        return null;
    }

    /**
     * 导出所有数据
     *
     * @param shipbillExportAllVO
     * @return
     */
    @Override
    public List<ExportShipbillDTO> exportAllShipbillData(ShipbillExportAllVO shipbillExportAllVO) {
        ToolKits.isParamNull(shipbillExportAllVO, "运单导出请求不为空！");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 数据字典翻译数据集合
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT, // 签到时间点单位
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, // 配送方式
                DataDictionaryConstant.TRANSPORT_TYPE, // 运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, // 温度要求
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.ORDER_TYPE, // 订单类型
                DataDictionaryConstant.SHIPBILL_STATUS, // 运单状态
                DataDictionaryConstant.CARRIER_SHIPBILL_STATUS, // 承运商运单状态
                DataDictionaryConstant.ORDER_BUSINESS_TYPE // 订单业务类型
        });

        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = ToolKits.isEmpty(shipbillExportAllVO.getShipbillNo()) ? null : Restrictions.like("shipbillNo", "%" + shipbillExportAllVO.getShipbillNo() + "%");
        Restriction r2 = ToolKits.isEmpty(shipbillExportAllVO.getCargoOwnerName()) ? null : Restrictions.like("cargoOwnerName", "%" + shipbillExportAllVO.getCargoOwnerName() +
 "%");
        Restriction r3 = ToolKits.isEmpty(shipbillExportAllVO.getOrderNo()) ? null : Restrictions.like("orderNo", "%" + shipbillExportAllVO.getOrderNo() + "%");
        Restriction r4 = ToolKits.isEmpty(shipbillExportAllVO.getOrderStartDate()) ? null : Restrictions.ge("orderDate", shipbillExportAllVO.getOrderStartDate());
        Restriction r5 = ToolKits.isEmpty(shipbillExportAllVO.getOrderEndDate()) ? null : Restrictions.le("orderDate", shipbillExportAllVO.getOrderEndDate());
        Restriction r6 = ToolKits.isEmpty(shipbillExportAllVO.getOrderBusinessType()) ? null : Restrictions.eq("orderBusinessType", shipbillExportAllVO.getOrderBusinessType());
        Restriction r7 = ToolKits.isEmpty(shipbillExportAllVO.getCreateStartTime()) ? null : Restrictions.ge("createtime", shipbillExportAllVO.getCreateStartTime());
        Restriction r8 = ToolKits.isEmpty(shipbillExportAllVO.getCreateEndTime()) ? null : Restrictions.le("createtime", shipbillExportAllVO.getCreateEndTime());
        Restriction r10 = Restrictions.eq("enterpriseId", user.getEnterpriseId());

        // 权限控制
        Restriction r9 = null;
        Restriction r11 = null;
        Restriction r12 = null;
        Restriction r13 = null;
        Restriction r14 = null;
        Restriction r15 = null;
        Restriction r16 = null;
        Restriction r30 = null;
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 拆单状态 0未拆单
            Restriction r31 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            // 承运商拆单类型 1未拆单
            Restriction r32 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
            Restriction r33 = Restrictions.and(r31, r32);
            // 承运商拆单类型 2拆分主单
            Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
            // 承运商拆单类型 2中转主单
            Restriction r35 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
            r30 = Restrictions.or(r33, r34, r35);

            // 判断是否为部门权限
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
            } else {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
                // 其它权限
                // 货主
                r12 = Restrictions.in("cargoOwnerId", user.getConsignors().toArray());
                // 客户
                r13 = Restrictions.in("consigneeUnitId", user.getCustomers().toArray());
                // 供应商
                r14 = Restrictions.in("consigneeUnitId", user.getSuppliers().toArray());
                // 仓库
                r15 = Restrictions.in("consigneeUnitId", user.getWarehouses().toArray());

                Restriction r23 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getWarehouses().stream().toArray(Long[]::new));
                Restriction r24 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getSuppliers().stream().toArray(Long[]::new));
                Restriction r25 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getCustomers().stream().toArray(Long[]::new));

                r16 = Restrictions.or(r13, r14, r15, r23, r24, r25);
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            r30 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
            // 运单状态
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK});
            // 承运商账号
            r11 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            // 承运商运单状态
            r12 = Restrictions.in("carrierShipbillStatus", new Integer[]{DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK,
             DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED});
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
            r7 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            r11 = Restrictions.eq(TmsShipbillHeaderModel::getCargoOwnerId, Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        } else {
            throw new BizException("当前人员没有操作权限！");
        }

        Restriction r17 = null;
        if (ToolKits.isNotEmpty(shipbillExportAllVO.getShipperLocation()) && shipbillExportAllVO.getShipperLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("shipperLongitude");
            Restriction r19 = Restrictions.isnull("shipperLatitude");
            r17 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillExportAllVO.getShipperLocation()) && shipbillExportAllVO.getShipperLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("shipperLongitude");
            Restriction r19 = Restrictions.isNotNull("shipperLatitude");
            r17 = Restrictions.and(r18, r19);
        }
        Restriction r20 = null;
        if (ToolKits.isNotEmpty(shipbillExportAllVO.getConsigneeLocation()) && shipbillExportAllVO.getConsigneeLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("consigneeLongitude");
            Restriction r19 = Restrictions.isnull("consigneeLatitude");
            r20 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillExportAllVO.getConsigneeLocation()) && shipbillExportAllVO.getConsigneeLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("consigneeLongitude");
            Restriction r19 = Restrictions.isNotNull("consigneeLatitude");
            r20 = Restrictions.and(r18, r19);
        }

        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r16, r17, r20, r30));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));

        List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

        List<ExportShipbillDTO> list = Lists.newArrayList();
        for (TmsShipbillHeaderModel model : tmsShipbillHeaderModels) {
            ExportShipbillDTO dto = new ExportShipbillDTO();
            BeanUtils.copyProperties(model, dto);
            // 收货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude())) {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_WDW);
            }
            // 发货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getShipperLongitude()) && ToolKits.isNotEmpty(model.getShipperLatitude())) {
                dto.setShipperPositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setShipperPositioning(StatusConstant.POSITIONING_WDW);
            }

            // 类型翻译
            dto.setOrderTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(model.getOrderType())));
            dto.setOrderBusinessTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(model.getOrderBusinessType())));
            dto.setDeliveryMethodTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(model.getDeliveryMethodType())));
            dto.setTransportTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(model.getTransportType())));
            dto.setTemperatureRequirementName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(model.getTemperatureRequirement())));
            dto.setShipperTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(model.getShipperType())));
            dto.setConsigneeTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(model.getConsigneeType())));

            list.add(dto);
        }

        return list;
    }

    /**
     * 导出当前页数据
     *
     * @param shipbillExportPageVO
     * @return
     */
    @Override
    public List<ExportShipbillDTO> exportPageShipbillData(ShipbillExportPageVO shipbillExportPageVO) {
        ToolKits.isParamNull(shipbillExportPageVO, "运单导出请求不为空！");
        ToolKits.isParamNull(shipbillExportPageVO.getPageNum(), "当前页码不为空");
        ToolKits.isParamNull(shipbillExportPageVO.getPageSize(), "每页条数不为空");

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

        // 数据字典翻译数据集合
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT, // 签到时间点单位
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, // 配送方式
                DataDictionaryConstant.TRANSPORT_TYPE, // 运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, // 温度要求
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.ORDER_TYPE, // 订单类型
                DataDictionaryConstant.SHIPBILL_STATUS, // 运单状态
                DataDictionaryConstant.CARRIER_SHIPBILL_STATUS, // 承运商运单状态
                DataDictionaryConstant.ORDER_BUSINESS_TYPE // 订单业务类型
        });

        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = ToolKits.isEmpty(shipbillExportPageVO.getShipbillNo()) ? null : Restrictions.like("shipbillNo", shipbillExportPageVO.getShipbillNo());
        Restriction r2 = ToolKits.isEmpty(shipbillExportPageVO.getCargoOwnerName()) ? null : Restrictions.like("cargoOwnerName", shipbillExportPageVO.getCargoOwnerName());
        Restriction r3 = ToolKits.isEmpty(shipbillExportPageVO.getOrderNo()) ? null : Restrictions.like("orderNo", shipbillExportPageVO.getOrderNo());
        Restriction r4 = ToolKits.isEmpty(shipbillExportPageVO.getOrderStartDate()) ? null : Restrictions.ge("orderDate", shipbillExportPageVO.getOrderStartDate());
        Restriction r5 = ToolKits.isEmpty(shipbillExportPageVO.getOrderEndDate()) ? null : Restrictions.le("orderDate", shipbillExportPageVO.getOrderEndDate());
        Restriction r6 = ToolKits.isEmpty(shipbillExportPageVO.getOrderBusinessType()) ? null : Restrictions.eq("orderBusinessType", shipbillExportPageVO.getOrderBusinessType());
        Restriction r7 = ToolKits.isEmpty(shipbillExportPageVO.getCreateStartTime()) ? null : Restrictions.ge("createtime", shipbillExportPageVO.getCreateStartTime());
        Restriction r8 = ToolKits.isEmpty(shipbillExportPageVO.getCreateEndTime()) ? null : Restrictions.le("createtime", shipbillExportPageVO.getCreateEndTime());
        Restriction r10 = Restrictions.eq("enterpriseId", user.getEnterpriseId());

        // 权限控制
        Restriction r9 = null;
        Restriction r11 = null;
        Restriction r12 = null;
        Restriction r13 = null;
        Restriction r14 = null;
        Restriction r15 = null;
        Restriction r16 = null;
        Restriction r30 = null;
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 拆单状态 0未拆单
            Restriction r31 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            // 承运商拆单类型 1未拆单
            Restriction r32 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
            Restriction r33 = Restrictions.and(r31, r32);
            // 承运商拆单类型 2拆分主单
            Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
            // 承运商拆单类型 2中转主单
            Restriction r35 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
            r30 = Restrictions.or(r33, r34, r35);
            // 判断是否为部门权限
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
            } else {
                r11 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
                // 货主
                r12 = Restrictions.in("cargoOwnerId", user.getConsignors().toArray());
                // 客户
                r13 = Restrictions.in("consigneeUnitId", user.getCustomers().toArray());
                // 供应商
                r14 = Restrictions.in("consigneeUnitId", user.getSuppliers().toArray());
                // 仓库
                r15 = Restrictions.in("consigneeUnitId", user.getWarehouses().toArray());
                Restriction r23 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getWarehouses().stream().toArray(Long[]::new));
                Restriction r24 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getSuppliers().stream().toArray(Long[]::new));
                Restriction r25 = Restrictions.in(TmsShipbillHeaderModel::getShipperUnitId, user.getCustomers().stream().toArray(Long[]::new));

                r16 = Restrictions.or(r13, r14, r15, r23, r24, r25);
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            r30 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
            // 运单状态
            r9 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK});
            // 承运商账号
            r11 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            // 承运商运单状态
            r12 = Restrictions.in("carrierShipbillStatus", new Integer[]{DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK,
             DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED});
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_HZ)) {
            r7 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
             DataDictionaryConstant.SHIPBILL_STATUS_DSH});
            r11 = Restrictions.eq(TmsShipbillHeaderModel::getCargoOwnerId, Long.valueOf(user.getLoginUserCompanyInfo().getId()));
        } else {
            throw new BizException("当前人员没有操作权限！");
        }

        Restriction r17 = null;
        if (ToolKits.isNotEmpty(shipbillExportPageVO.getShipperLocation()) && shipbillExportPageVO.getShipperLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("shipperLongitude");
            Restriction r19 = Restrictions.isnull("shipperLatitude");
            r17 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillExportPageVO.getShipperLocation()) && shipbillExportPageVO.getShipperLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("shipperLongitude");
            Restriction r19 = Restrictions.isNotNull("shipperLatitude");
            r17 = Restrictions.and(r18, r19);
        }
        Restriction r20 = null;
        if (ToolKits.isNotEmpty(shipbillExportPageVO.getConsigneeLocation()) && shipbillExportPageVO.getConsigneeLocation().intValue() == 0) {
            Restriction r18 = Restrictions.isnull("consigneeLongitude");
            Restriction r19 = Restrictions.isnull("consigneeLatitude");
            r20 = Restrictions.or(r18, r19);
        } else if (ToolKits.isNotEmpty(shipbillExportPageVO.getConsigneeLocation()) && shipbillExportPageVO.getConsigneeLocation().intValue() == 1) {
            Restriction r18 = Restrictions.isNotNull("consigneeLongitude");
            Restriction r19 = Restrictions.isNotNull("consigneeLatitude");
            r20 = Restrictions.and(r18, r19);
        }

        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r16, r17, r20, r30));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));

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

        List<ExportShipbillDTO> list = Lists.newArrayList();
        for (TmsShipbillHeaderModel model : tmsShipbillHeaderModels) {
            ExportShipbillDTO dto = new ExportShipbillDTO();
            BeanUtils.copyProperties(model, dto);
            // 收货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude())) {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_WDW);
            }
            // 发货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getShipperLongitude()) && ToolKits.isNotEmpty(model.getShipperLatitude())) {
                dto.setShipperPositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setShipperPositioning(StatusConstant.POSITIONING_WDW);
            }

            // 类型翻译
            dto.setOrderTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(model.getOrderType())));
            dto.setOrderBusinessTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(model.getOrderBusinessType())));
            dto.setDeliveryMethodTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(model.getDeliveryMethodType())));
            dto.setTransportTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(model.getTransportType())));
            dto.setTemperatureRequirementName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(model.getTemperatureRequirement())));
            dto.setShipperTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(model.getShipperType())));
            dto.setConsigneeTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(model.getConsigneeType())));

            list.add(dto);
        }

        return list;
    }

    /**
     * 导出选中数据
     *
     * @param ids
     * @return
     */
    @Override
    public List<ExportShipbillDTO> exportChooseShipbillData(List<String> ids) {
        ToolKits.isParamNull(ids, "运单导出请求不为空！");

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

        // 数据字典翻译数据集合
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.PICK_UP_SIGN_TIME, // 发货方签到时间点
                DataDictionaryConstant.DELIVERY_SIGN_TIME, // 收货方签到时间点
                DataDictionaryConstant.SIGN_TIME_UNIT, // 签到时间点单位
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, // 配送方式
                DataDictionaryConstant.TRANSPORT_TYPE, // 运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, // 温度要求
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.ORDER_TYPE, // 订单类型
                DataDictionaryConstant.SHIPBILL_STATUS, // 运单状态
                DataDictionaryConstant.CARRIER_SHIPBILL_STATUS, // 承运商运单状态
                DataDictionaryConstant.ORDER_BUSINESS_TYPE // 订单业务类型
        });

        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = Restrictions.in("shipbillNo", ids.toArray());
        Restriction r2 = Restrictions.in("status", new Integer[]{DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_YTH,
         DataDictionaryConstant.SHIPBILL_STATUS_DSH});
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));

        List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

        List<ExportShipbillDTO> list = Lists.newArrayList();
        for (TmsShipbillHeaderModel model : tmsShipbillHeaderModels) {
            ExportShipbillDTO dto = new ExportShipbillDTO();
            BeanUtils.copyProperties(model, dto);
            // 收货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude())) {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setConsigneePositioning(StatusConstant.POSITIONING_WDW);
            }
            // 发货方位置(经纬度判断)
            if (ToolKits.isNotEmpty(model.getShipperLongitude()) && ToolKits.isNotEmpty(model.getShipperLatitude())) {
                dto.setShipperPositioning(StatusConstant.POSITIONING_YDW);
            } else {
                dto.setShipperPositioning(StatusConstant.POSITIONING_WDW);
            }

            // 类型翻译
            dto.setOrderTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(model.getOrderType())));
            dto.setOrderBusinessTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(model.getOrderBusinessType())));
            dto.setDeliveryMethodTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(model.getDeliveryMethodType())));
            dto.setTransportTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(model.getTransportType())));
            dto.setTemperatureRequirementName(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(model.getTemperatureRequirement())));
            dto.setShipperTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(model.getShipperType())));
            dto.setConsigneeTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(model.getConsigneeType())));

            list.add(dto);
        }

        return list;
    }

    /**
     * 运单导入
     */
    @Override
    public String importShipbillData(MultipartFile file, String templateId) {
        // 人员权限
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        // 获取导入批次号
        RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.IMPORT_BATCHNO, "L");
        if (!restMessage.isSuccess()) {
            throw new ParameterException("获取导入批次号调用失败 :" + restMessage.getMessage());
        }
        String importBatchNumber = restMessage.getData();
        ToolKits.isParamNull(importBatchNumber, "导入批次号生成失败");
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(DataDictionaryConstant.SHIPBILL_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);
        try {
            EasyExcelListener readListener = new EasyExcelListener();
            try {
                EasyExcelFactory.read(file.getInputStream(), readListener).sheet().doReadSync();
            } catch (Exception e) {
                log.error("【运单导入】excel解析失败", e);
                throw new ParameterException("excel解析失败:" + e.getMessage());
            }
            if (CollectionUtil.isEmpty(readListener.getHeadList()) || CollectionUtil.isEmpty(readListener.getDataList())) {
                throw new BizException("导入数据为空,请重新导入");
            }
            List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = getTemplateById(templateId);
            log.info("【运单导入{}】运单导入配置={}", importBatchNumber, JSON.toJSONString(standardTemplateDetailsListDTOs));
            Map<String, StandardTemplateDetailsListDTO> detailsListDTOMap = standardTemplateDetailsListDTOs.stream().collect(Collectors.toMap(t1 -> t1.getStdColNo(), t2 -> t2,
(t1, t2) -> t2));
            Map<String, Integer> headMap = MapUtil.inverse(readListener.getHeadList().get(0));
            List<ShipbillImportVO> importVOList = readListener.getDataList().parallelStream().map(data -> {
                log.info("【运单导入{}】解析数据={}", importBatchNumber, JSON.toJSONString(data));
                Map<String, String> excelData = Maps.newHashMap();
                detailsListDTOMap.forEach((key, value) -> {
                    String dataValue = StrUtil.EMPTY;
                    if (StrUtil.isBlank(value.getCustColName())) {
                        dataValue = value.getDefaultName();
                    } else if (headMap.containsKey(value.getCustColName())) {
                        dataValue = data.get(headMap.get(value.getCustColName()));
                    }
                    excelData.put(key, dataValue);
                });
                ShipbillImportVO shipbillImportVO = BeanUtil.mapToBean(excelData, ShipbillImportVO.class, true);
                log.info("【运单导入{}】转换数据={}", importBatchNumber, JSON.toJSONString(shipbillImportVO));
                return shipbillImportVO;
            }).collect(Collectors.toList());

            // 按序号分组 相同序号的行为同一运单
            Map<String, List<ShipbillImportVO>> shipbillImportMap = importVOList.stream().collect(Collectors.groupingBy(ShipbillImportVO::getSerialNumber));

            // ============准备校验的基础资料
            // 部门
            RestMessage<List<Organization>> departMents = userTmsResource.search(null, null, null, String.valueOf(user.getEnterpriseId()));
            if (!departMents.isSuccess()) {
                throw new BizException("部门查询失败：" + departMents.getMessage());
            }
            List<Organization> departmentData = departMents.getData();

            // 数据字典
            List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{DataDictionaryConstant.ORDER_TYPE, DataDictionaryConstant.ORDER_BUSINESS_TYPE,
             DataDictionaryConstant.DELIVERY_METHOD_TYPE, DataDictionaryConstant.TRANSPORT_TYPE, DataDictionaryConstant.TEMPERATURE_REQUIREMENT,
              DataDictionaryConstant.SHIPPER_TYPE, DataDictionaryConstant.WHETHER, DataDictionaryConstant.PICK_UP_SIGN_TIME, DataDictionaryConstant.SIGN_TIME_UNIT,
               DataDictionaryConstant.CONSIGNEE_TYPE, DataDictionaryConstant.DELIVERY_SIGN_TIME, DataDictionaryConstant.PACK_TYPE, DataDictionaryConstant.CARGO_THERMOSPHERE});

            // 行政编码
            RestMessage<List<LmsTmsZoneMinDTO>> zoneModel = maindataTmsResource.getAllZoneMin();
            if (!zoneModel.isSuccess() || ObjectUtil.isNull(zoneModel.getData())) {
                throw new BizException("行政编码获取失败 " + zoneModel.getMessage());
            }
            List<LmsTmsZoneMinDTO> zoneModelList = zoneModel.getData();

            // 货主
            CargoOwnerPageVO cargoOwnerPageVO = new CargoOwnerPageVO();
            cargoOwnerPageVO.setPageNum(1);
            cargoOwnerPageVO.setPageSize(Integer.MAX_VALUE);
            RestMessage<Page<CargoOwnerPageDTO>> cargoOwner = maindataTmsResource.pageCargoOwnerExecute(cargoOwnerPageVO);
            if (!cargoOwner.isSuccess() || ObjectUtil.isNull(cargoOwner.getData())) {
                throw new BizException("货主获取失败 " + cargoOwner.getMessage());
            }
            List<CargoOwnerPageDTO> cargoOwnerDTOList = cargoOwner.getData().getList();

            // 商品
            ItemPagingQueryVO itemPagingQueryVO = new ItemPagingQueryVO();
            itemPagingQueryVO.setPageNum(1);
            itemPagingQueryVO.setPageSize(Integer.MAX_VALUE);
            RestMessage<Page<ItemPagingQueryDTO>> itemExecute = maindataTmsResource.pageItemExecute(itemPagingQueryVO);
            if (!itemExecute.isSuccess() || ObjectUtil.isNull(itemExecute.getData())) {
                throw new BizException("商品获取失败 " + itemExecute.getMessage());
            }
            List<ItemPagingQueryDTO> itemPagingQueryDTOList = itemExecute.getData().getList();

            // 仓库
            TmsBaseBranchQueryVO tmsBaseBranchQueryVO = new TmsBaseBranchQueryVO();
            tmsBaseBranchQueryVO.setPageNum(1);
            tmsBaseBranchQueryVO.setPageSize(Integer.MAX_VALUE);
            RestMessage<Page<TmsBaseBranchDTO>> branch = maindataTmsResource.queryBranch(tmsBaseBranchQueryVO);
            if (!branch.isSuccess() || ObjectUtil.isNull(branch.getData())) {
                throw new BizException("仓库获取失败 " + branch.getMessage());
            }
            List<TmsBaseBranchDTO> branchDTOList = branch.getData().getList();
            String userkey = HystrixVarUtil.getUserKey();
            log.info("【运单导入{}】userkey={}", importBatchNumber, userkey);
            ThreadUtil.execute(() -> importProcess(shipbillImportMap, importBatchNumber, user, departmentData, dicData, zoneModelList, cargoOwnerDTOList, itemPagingQueryDTOList,
             branchDTOList, userkey));
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_ING);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(0);
            RestMessage<String> restMessage1 = maindataTmsResource.addImportLogExecute(logAddVO);
            if (!restMessage1.isSuccess()) {
                throw new ParameterException(restMessage1.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【运单导入】导入失败", e);
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(0);
            logAddVO.setFailReason(e.getMessage());
            RestMessage<String> restMessage1 = maindataTmsResource.addImportLogExecute(logAddVO);
            if (!restMessage1.isSuccess()) {
                throw new ParameterException(restMessage1.getMessage());
            }
            throw new ParameterException(e.getMessage());
        }
        return importBatchNumber;
    }

    /**
     * 运单审核信息查询
     *
     * @param shipbillApprovalInfoVO
     * @return
     */
    @Override
    public ShipbillApprovalInfoDTO getApprovalInfoData(ShipbillApprovalInfoVO shipbillApprovalInfoVO) {
        ToolKits.isParamNull(shipbillApprovalInfoVO, "审批请求不为空");
        ToolKits.isParamNull(shipbillApprovalInfoVO.getShipbillId(), "运单ID不为空");

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

        // 数据字典翻译数据集合
        List<Map<String, Object>> data1 = Lists.newArrayList();
        List<Map<String, Object>> data2 = Lists.newArrayList();
        List<Map<String, Object>> data3 = Lists.newArrayList();
        List<Map<String, Object>> data4 = Lists.newArrayList();
        List<Map<String, Object>> data5 = Lists.newArrayList();
        List<Map<String, Object>> data6 = Lists.newArrayList();
        List<Map<String, Object>> data7 = Lists.newArrayList();
        List<Map<String, Object>> data8 = Lists.newArrayList();
        List<Map<String, Object>> data9 = Lists.newArrayList();

        // 订单类型
        RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data1 = restMessage1.getData();
        }
        // 订单业务类型
        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();
        }
        // 配送方式
        RestMessage<List<Map<String, Object>>> restMessage3 = maindataTmsResource.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
        if (!restMessage3.isSuccess()) {
            throw new RuntimeException("配送方式翻译失败!");
        } else {
            data3 = restMessage3.getData();
        }
        // 运输类型(运输模式)
        RestMessage<List<Map<String, Object>>> restMessage4 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
        if (!restMessage4.isSuccess()) {
            throw new RuntimeException("运输类型(运输模式)翻译失败!");
        } else {
            data4 = restMessage4.getData();
        }
        // 温度要求
        RestMessage<List<Map<String, Object>>> restMessage5 = maindataTmsResource.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);
        if (!restMessage5.isSuccess()) {
            throw new RuntimeException("温度要求翻译失败!");
        } else {
            data5 = restMessage5.getData();
        }
        // 发货方类型
        RestMessage<List<Map<String, Object>>> restMessage6 = maindataTmsResource.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
        if (!restMessage6.isSuccess()) {
            throw new RuntimeException("发货方类型翻译失败!");
        } else {
            data6 = restMessage6.getData();
        }
        // 收货方类型
        RestMessage<List<Map<String, Object>>> restMessage7 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
        if (!restMessage7.isSuccess()) {
            throw new RuntimeException("收货方类型翻译失败!");
        } else {
            data7 = restMessage7.getData();
        }
        // 包装类型
        RestMessage<List<Map<String, Object>>> restMessage8 = maindataTmsResource.getDropDownById(DataDictionaryConstant.PACK_TYPE, null, null, null);
        if (!restMessage8.isSuccess()) {
            throw new RuntimeException("订单类型翻译失败!");
        } else {
            data8 = restMessage8.getData();
        }
        // 货物温层
        RestMessage<List<Map<String, Object>>> restMessage9 = maindataTmsResource.getDropDownById(DataDictionaryConstant.CARGO_THERMOSPHERE, null, null, null);
        if (!restMessage9.isSuccess()) {
            throw new RuntimeException("货物温层翻译失败!");
        } else {
            data9 = restMessage9.getData();
        }

        // 查询运单汇总信息
        TmsShipbillHeaderModel model = tmsShipbillHeaderMapper.findById(shipbillApprovalInfoVO.getShipbillId(), TmsShipbillHeaderModel.class);

        ToolKits.isParamNull(model, "运单ID[" + shipbillApprovalInfoVO.getShipbillId() + "]有误,查询运单为空");

        ShipbillApprovalInfoDTO dto = new ShipbillApprovalInfoDTO();
        BeanUtils.copyProperties(model, dto);

        // 类型翻译
        dto.setOrderTypeName(PublicMethods.change(data1, String.valueOf(dto.getOrderType())));
        dto.setOrderBusinessTypeName(PublicMethods.change(data2, String.valueOf(dto.getOrderBusinessType())));
        dto.setDeliveryMethodTypeName(PublicMethods.change(data3, String.valueOf(dto.getDeliveryMethodType())));
        dto.setTransportTypeName(PublicMethods.change(data4, String.valueOf(dto.getTransportType())));
        dto.setTemperatureRequirementName(PublicMethods.change(data5, String.valueOf(dto.getTemperatureRequirement())));
        dto.setShipperTypeName(PublicMethods.change(data6, String.valueOf(dto.getShipperType())));
        dto.setConsigneeTypeName(PublicMethods.change(data7, String.valueOf(dto.getConsigneeType())));

        // 运单明细数据集
        List<ShipbillDetailApprovalDTO> shipbillDetailApprovalDTOS = Lists.newArrayList();

        // 查询运单明细
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillApprovalInfoVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().asc(new String[]{"seqno"}));
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(tmsShipbillDetailModels)) {
            for (TmsShipbillDetailModel tmsShipbillDetailModel : tmsShipbillDetailModels) {
                ShipbillDetailApprovalDTO detailDTO = new ShipbillDetailApprovalDTO();
                BeanUtils.copyProperties(tmsShipbillDetailModel, detailDTO);

                // 数据字典翻译
                detailDTO.setPackTypeName(PublicMethods.change(data8, String.valueOf(detailDTO.getPackType())));
                detailDTO.setCargoThermosphereName(PublicMethods.change(data9, String.valueOf(detailDTO.getCargoThermosphere())));

                shipbillDetailApprovalDTOS.add(detailDTO);
            }
            dto.setShipbillDetailApprovalDTOList(shipbillDetailApprovalDTOS);
        }

        RestMessage<List<ApprovalLogDTO>> resourceBusLog = maindataTmsResource.getBusLog(shipbillApprovalInfoVO.getApprovalBusinessId());
        if (!resourceBusLog.isSuccess()) {
            throw new PrologException("调用审批日志服务失败!");
        }
        dto.setShipbillApprovalLogDTOList(resourceBusLog.getData());

        RestMessage<List<ApprovalNodeSelDTO>> resourceBusDetail = maindataTmsResource.getBusDetail(shipbillApprovalInfoVO.getApprovalBusinessId());
        if (!resourceBusLog.isSuccess()) {
            throw new PrologException("调用审批节点服务失败!");
        }
        dto.setShipbillApprovalNodeDTOList(resourceBusDetail.getData());

        return dto;
    }

    /**
     * 运单审批作废
     *
     * @param shipbillApprovalInvalidVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipbillApprovalInvalidData(ShipbillApprovalInvalidVO shipbillApprovalInvalidVO) {
        ToolKits.isParamNull(shipbillApprovalInvalidVO, "运单审批撤回作废请求不为空");
        ToolKits.isParamNull(shipbillApprovalInvalidVO.getShipbillId(), "运单ID不为空");
        ToolKits.isParamNull(shipbillApprovalInvalidVO.getApprovalBusinessId(), "审批业务ID不为空");

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

        TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillApprovalInvalidVO.getShipbillId(), TmsShipbillHeaderModel.class);
        ToolKits.isParamNull(tmsShipbillHeaderModel, "运单ID[" + shipbillApprovalInvalidVO.getShipbillId() + "]有误,查询为空!");

        // 审核业务作废
        RestMessage<Object> restMessage = maindataTmsResource.approvalInvalidExecute(shipbillApprovalInvalidVO.getApprovalBusinessId());
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("调用审核作废失败");
        }

        // 运单状态回退
        tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

        // 删除临时表数据
        tmsShipbillHeaderTempMapper.deleteById(shipbillApprovalInvalidVO.getShipbillId(), TmsShipbillHeaderTempModel.class);

    }

    /**
     * 运单审批撤回
     *
     * @param shipbillApprovalRetractVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipbillApprovalRetractData(ShipbillApprovalRetractVO shipbillApprovalRetractVO) {
        ToolKits.isParamNull(shipbillApprovalRetractVO, "运单审批撤回请求不为空");
        ToolKits.isParamNull(shipbillApprovalRetractVO.getShipbillId(), "运单ID不为空");
        ToolKits.isParamNull(shipbillApprovalRetractVO.getApprovalBusinessId(), "审批业务ID不为空");

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

        TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillApprovalRetractVO.getShipbillId(), TmsShipbillHeaderModel.class);
        ToolKits.isParamNull(tmsShipbillHeaderModel, "运单ID[" + shipbillApprovalRetractVO.getShipbillId() + "]有误,查询为空!");

        // 审核业务撤回
        RestMessage<Object> restMessage = maindataTmsResource.approvalRetractExecute(shipbillApprovalRetractVO.getApprovalBusinessId());
        if (!restMessage.isSuccess()) {
            throw new RuntimeException("调用审核撤回失败");
        }

    }

    /**
     * 运单审批提交
     *
     * @param shipbillApprovalSubmitVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipbillApprovalSubmitData(ShipbillApprovalSubmitVO shipbillApprovalSubmitVO) {
        ToolKits.isParamNull(shipbillApprovalSubmitVO, "运单修改保存请求不为空！");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipbillId(), "订单ID不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillApprovalSubmitVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillApprovalSubmitVO.getDepartmentName(), "所属部门名称不为空");

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

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

        // 查询临时表数据
        TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = tmsShipbillHeaderTempMapper.findById(shipbillApprovalSubmitVO.getShipbillId(), TmsShipbillHeaderTempModel.class);
        ToolKits.isParamNull(tmsShipbillHeaderTempModel, "运单ID[" + shipbillApprovalSubmitVO.getShipbillId() + "]有误,查询临时表为空!");

        // 汇总赋值
        tmsShipbillHeaderTempModel.setUpdateperson(user.getNickname());
        tmsShipbillHeaderTempModel.setUpdatetime(date);

        // 实际件数、体积、总量默认
        tmsShipbillHeaderTempModel.setActualTotalPcs(tmsShipbillHeaderTempModel.getTotalPcs());
        tmsShipbillHeaderTempModel.setActualTotalVolume(tmsShipbillHeaderTempModel.getTotalVolume());
        tmsShipbillHeaderTempModel.setActualTotalWeight(tmsShipbillHeaderTempModel.getTotalWeight());

        // 删除原有商品信息
        Criteria criteria = Criteria.forClass(TmsShipbillDetailTempModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipbillApprovalSubmitVO.getShipbillId());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsShipbillDetailTempMapper.deleteByCriteria(criteria);

        // 运单明细对象集合
        if (ToolKits.isNotEmpty(shipbillApprovalSubmitVO.getDetails())) {
            // 设置明细行号
            Integer seqno = 1;
            for (ShipbillDetailApprovalSubmitVO shipbillDetailApprovalSubmitVO : shipbillApprovalSubmitVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailApprovalSubmitVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailApprovalSubmitVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailApprovalSubmitVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailApprovalSubmitVO.getPcs(), "商品件数不为空");

                // 获取运单明细ID
                RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                if (!restMessage2.isSuccess()) {
                    throw new RuntimeException("生成运单明细ID失败");
                }
                String tmsShipbillDetailId = restMessage2.getData();

                TmsShipbillDetailTempModel tmsShipbillDetailTempModel = new TmsShipbillDetailTempModel();
                BeanUtils.copyProperties(shipbillDetailApprovalSubmitVO, tmsShipbillDetailTempModel);

                // 明细赋值
                tmsShipbillDetailTempModel.setId(tmsShipbillDetailId);
                tmsShipbillDetailTempModel.setSeqno(seqno);
                tmsShipbillDetailTempModel.setShipbillId(tmsShipbillHeaderTempModel.getShipbillId());
                tmsShipbillDetailTempModel.setShipbillNo(tmsShipbillHeaderTempModel.getShipbillNo());
                tmsShipbillDetailTempModel.setCargoOwnerId(tmsShipbillHeaderTempModel.getCargoOwnerId());
                tmsShipbillDetailTempModel.setCargoOwnerCode(tmsShipbillHeaderTempModel.getCargoOwnerCode());
                tmsShipbillDetailTempModel.setCargoOwnerName(tmsShipbillHeaderTempModel.getCargoOwnerName());
                tmsShipbillDetailTempModel.setEnterpriseId(user.getEnterpriseId());
                tmsShipbillDetailTempModel.setEnterpriseName(user.getEnterpriseName());
                tmsShipbillDetailTempModel.setCreateperson(tmsShipbillHeaderTempModel.getCreateperson());
                tmsShipbillDetailTempModel.setCreatetime(tmsShipbillHeaderTempModel.getCreatetime());
                tmsShipbillDetailTempModel.setUpdateperson(user.getNickname());
                tmsShipbillDetailTempModel.setUpdatetime(date);
                tmsShipbillDetailTempModel.setItemId(Long.valueOf(shipbillDetailApprovalSubmitVO.getItemId()));

                tmsShipbillDetailTempMapper.save(tmsShipbillDetailTempModel);
                // 行号自增长
                seqno++;
            }
        }

        // 查询当前审批节点
        RestMessage<Object> restMessage1 = maindataTmsResource.approvalSubmitExecute(shipbillApprovalSubmitVO.getApprovalBusinessId());
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("调用审批提交失败");
        }

        // 修改临时表数据
        tmsShipbillHeaderTempMapper.update(tmsShipbillHeaderTempModel);
    }

    /**
     * 运单审核
     *
     * @param shipbillApprovalVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipbillApprovalData(ShipbillApprovalVO shipbillApprovalVO) {
        ToolKits.isParamNull(shipbillApprovalVO, "运单审核请求不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getApprovalObjectId(), "运单ID不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getApprovalBusinessId(), "审批业务ID不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getApprovalObjectName(), "审批对象名称不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getApprovalId(), "审批流程ID不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getNextApproverNodeId(), "下一审批节点ID不为空");
        ToolKits.isParamNull(shipbillApprovalVO.getNextApprovalOrder(), "下一节点顺序不为空");

        ToolKits.isParamNull(shipbillApprovalVO.getResult(), "审批结果不为空");

        if (!shipbillApprovalVO.getResult().equals(DataDictionaryConstant.NODE_APPROVAL_RESULT_PASS)) {
            ToolKits.isParamNull(shipbillApprovalVO.getApprovalOpinion(), "驳回意见不为空");
        }

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

        TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillApprovalVO.getApprovalObjectId(), TmsShipbillHeaderModel.class);
        ToolKits.isParamNull(tmsShipbillHeaderModel, "运单ID[" + shipbillApprovalVO.getApprovalObjectId() + "]有误,查询为空!");

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

        // 封装审核所需数据
        ApprovalBusinessNodeVO approvalBusinessNodeVO = new ApprovalBusinessNodeVO();
        approvalBusinessNodeVO.setApprovalObjectName(shipbillApprovalVO.getApprovalObjectName());
        approvalBusinessNodeVO.setApprovalBusinessId(shipbillApprovalVO.getApprovalBusinessId());
        approvalBusinessNodeVO.setApprovalId(shipbillApprovalVO.getApprovalId());
        approvalBusinessNodeVO.setNextApprovalNodeId(shipbillApprovalVO.getNextApproverNodeId());
        approvalBusinessNodeVO.setNextApprovalOrder(shipbillApprovalVO.getNextApprovalOrder());
        approvalBusinessNodeVO.setNextApproverRoleId(shipbillApprovalVO.getNextApproverRoleId());
        approvalBusinessNodeVO.setNextApproverRoleName(shipbillApprovalVO.getNextApproverRoleName());
        approvalBusinessNodeVO.setNextApproverUserId(shipbillApprovalVO.getNextApproverUserId());
        approvalBusinessNodeVO.setNextApproverUserName(shipbillApprovalVO.getNextApproverUserName());
        approvalBusinessNodeVO.setApproverPersonId(user.getUserid());
        approvalBusinessNodeVO.setApproverPersonName(user.getNickname());
        approvalBusinessNodeVO.setApprovalOpinion(ToolKits.isEmpty(shipbillApprovalVO.getApprovalOpinion()) ? "" : shipbillApprovalVO.getApprovalOpinion());
        approvalBusinessNodeVO.setApprovalTime(date);
        approvalBusinessNodeVO.setResult(shipbillApprovalVO.getResult());

        approvalBusinessNodeVO.setApproverPersonRoleId(user.getRoles().stream().map(role -> String.valueOf(role)).collect(Collectors.joining(",")));
        approvalBusinessNodeVO.setApproverPersonRoleName("");

        approvalBusinessNodeVO.setNodeApproverType(shipbillApprovalVO.getNodeApproverType());
        approvalBusinessNodeVO.setNodeApprovalType(shipbillApprovalVO.getNodeApprovalType());

        // 流程节点审批
        RestMessage<Boolean> restMessage1 = maindataTmsResource.nodeApprovalExecute(approvalBusinessNodeVO);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("调用审核失败:" + restMessage1.getMessage());
        }
        Boolean isFinish = restMessage1.getData();

        // 判断是否已结束流程
        if (isFinish) {
            // 查询临时表数据
            TmsShipbillHeaderTempModel tmsShipbillHeaderTempModel = tmsShipbillHeaderTempMapper.findById(shipbillApprovalVO.getApprovalObjectId(),
TmsShipbillHeaderTempModel.class);

            Criteria criteria = Criteria.forClass(TmsShipbillDetailTempModel.class);
            Restriction r1 = Restrictions.eq("shipbillId", tmsShipbillHeaderTempModel.getShipbillId());
            criteria.setRestriction(r1);
            List<TmsShipbillDetailTempModel> tmsShipbillDetailTempModels = tmsShipbillDetailTempMapper.findByCriteria(criteria);

            // 判断临时表是否为空
            if (ToolKits.isNotEmpty(tmsShipbillHeaderTempModel)) {
                // 修改正式数据
                BeanUtils.copyProperties(tmsShipbillHeaderTempModel, tmsShipbillHeaderModel);
                tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
                tmsShipbillHeaderModel.setUpdatetime(date);
                tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

                // 删除临时表数据
                tmsShipbillHeaderTempMapper.deleteById(tmsShipbillHeaderTempModel.getShipbillId(), TmsShipbillHeaderTempModel.class);
            } else {
                tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
                tmsShipbillHeaderModel.setUpdatetime(date);
                tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);
            }

            if (ToolKits.isNotEmpty(tmsShipbillDetailTempModels)) {

                for (TmsShipbillDetailTempModel tmsShipbillDetailTempModel : tmsShipbillDetailTempModels) {
                    TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                    BeanUtils.copyProperties(tmsShipbillDetailTempModel, tmsShipbillDetailModel);

                    tmsShipbillDetailMapper.update(tmsShipbillDetailModel);
                }

                // 删除临时表数据
                tmsShipbillDetailTempMapper.deleteByCriteria(criteria);
            }

            Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
            Restriction r3 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
            Restriction r4 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, user.getEnterpriseId());
            criteriaTransLog.setRestriction(Restrictions.and(r3, r4));

            Map<String, Object> mapUpdate = Maps.newHashMap();
            mapUpdate.put("updateperson", user.getNickname());
            mapUpdate.put("updatetime", date);
            mapUpdate.put("commitDt", date);
            tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransLog);

            // 提交后自动审核
            if (tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_COMMIT_REVIEW)) {
                // 调用审核处理
                List<String> ids = Lists.newArrayList();
                ids.add(tmsShipbillHeaderModel.getShipbillId());
                pendingReviewService.reviewShipbillData(ids);
            }
        }
    }

    /**
     * 执行导入过程
     *
     * @param shipbillImportMap
     * @param importBatchNumber
     * @param user
     * @param departmentData
     * @param dicData
     * @param zoneModelList
     * @param cargoOwnerDTOList
     * @param itemPagingQueryDTOList
     * @param branchDTOList
     */
    public void importProcess(Map<String, List<ShipbillImportVO>> shipbillImportMap, String importBatchNumber, UserEntity user, List<Organization> departmentData,
                              List<SysRefdatadModel> dicData, List<LmsTmsZoneMinDTO> zoneModelList, List<CargoOwnerPageDTO> cargoOwnerDTOList, List<ItemPagingQueryDTO> itemPagingQueryDTOList,
                              List<TmsBaseBranchDTO> branchDTOList, String userkey) {
        long totalStart = System.currentTimeMillis();
        // 仓库 客户 供应商缓存
        Map<String, RestMessage<ImportMatchingDataDTO>> matchBranch = Maps.newConcurrentMap();
        Map<String, RestMessage<ImportMatchingDataDTO>> matchCustomer = Maps.newConcurrentMap();
        Map<String, RestMessage<ImportMatchingDataDTO>> matchProvider = Maps.newConcurrentMap();
        List<Future<List<ShipBillExportDTO>>> futureList = Lists.newArrayList();
        // excel成功条数
        AtomicInteger success = new AtomicInteger(0);
        // excel失败条数
        AtomicInteger fail = new AtomicInteger(0);
        // 运单成功条数
        AtomicInteger successShipBill = new AtomicInteger(0);
        // 运单成功条数
        AtomicInteger failShipBill = new AtomicInteger(0);
        for (String obj : shipbillImportMap.keySet()) {
            final List<ShipbillImportVO>[] shipbillList = new List[]{shipbillImportMap.get(obj)};
            Future<List<ShipBillExportDTO>> future = executor.submit(() -> {
                List<ShipBillExportDTO> exportDTOList;
                try {
                    HystrixRequestContext.initializeContext();
                    HystrixVarUtil.setUserKey(userkey);
                    TmsShipbillHeaderModel tmsShipbillHeaderModel = shipbillService.singleImportShipBill(shipbillList[0], user, departmentData, dicData, zoneModelList,
                     cargoOwnerDTOList, itemPagingQueryDTOList, branchDTOList, matchBranch, matchCustomer, matchProvider);
                    exportDTOList = shipbillList[0].stream().map(vo -> {
                        ShipBillExportDTO exportDTO = BeanUtil.copyProperties(vo, ShipBillExportDTO.class);
                        if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getBackReason())) {
                            exportDTO.setImportResult("导入成功，" + tmsShipbillHeaderModel.getBackReason());
                        } else {
                            exportDTO.setImportResult("导入成功，生成运单【" + tmsShipbillHeaderModel.getShipbillId() + "】");
                        }
                        return exportDTO;
                    }).collect(Collectors.toList());
                    success.getAndAdd(shipbillList[0].size());
                    successShipBill.getAndIncrement();
                } catch (Exception e) {
                    log.error("【运单导入{}】单个运单导入失败={}", importBatchNumber, JSON.toJSONString(shipbillList[0]), e);
                    exportDTOList = shipbillList[0].stream().map(vo -> {
                        ShipBillExportDTO exportDTO = BeanUtil.copyProperties(vo, ShipBillExportDTO.class);
                        exportDTO.setImportResult("导入失败，" + e.getMessage());
                        return exportDTO;
                    }).collect(Collectors.toList());
                    fail.getAndAdd(shipbillList[0].size());
                    failShipBill.getAndIncrement();
                }
                return exportDTOList;
            });
            futureList.add(future);
        }
        List<ShipBillExportDTO> resultExcel = futureList.parallelStream().flatMap(future -> {
            try {
                return future.get().stream();
            } catch (InterruptedException | ExecutionException e) {
                log.error("运单结果获取失败", e);
            }
            return new ArrayList<ShipBillExportDTO>().stream();
        }).collect(Collectors.toList());
        log.info("【运单导入{}】总条数{}，成功条数:{}，失败条数{}，运单总条数{}，成功运单条数:{}，失败运单条数{}", importBatchNumber, (success.get() + fail.get()), success.get(), fail.get(),
         shipbillImportMap.keySet().size(), successShipBill.get(), failShipBill.get());
        // 导入结果异步上传
        ThreadUtil.execute(() -> {
            String fileName = "导入结果" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN) + "_批次" + importBatchNumber + ".xlsx";
            File file = FileUtil.file(FileUtil.getTmpDirPath() + File.separator + fileName);
            log.info("【运单导入{}】本地文件路径={}", importBatchNumber, file.getPath());
            log.info("【运单导入{}】开始生成文件", importBatchNumber);
            try {
                EasyExcel.write(file, ShipBillExportDTO.class).sheet("导入结果").doWrite(resultExcel);
                log.info("【运单导入{}】生成文件成功", importBatchNumber);
            } catch (Exception e) {
                log.info("【运单导入{}】生成文件失败", importBatchNumber);
                log.error("【运单导入{}】生成文件失败", importBatchNumber, e);
            }
            log.info("【运单导入{}】开始上传文件", importBatchNumber);
            UploadFileDTO uploadFileDTO = null;
            try {
                uploadFileDTO = uploadFile(file, importBatchNumber);
                log.info("【运单导入{}】上传文件成功", importBatchNumber);
            } catch (Exception e) {
                log.info("【运单导入{}】上传文件失败", importBatchNumber);
                log.error("【运单导入{}】上传文件失败", importBatchNumber, e);
            }
            if (ObjectUtil.isNotNull(uploadFileDTO)) {
                ImportLogUpdateVO updateVO = new ImportLogUpdateVO();
                updateVO.setFailReason(uploadFileDTO.getPath());
                updateVO.setImportBatchNumber(importBatchNumber);
                updateVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
                updateVO.setSuccessNum(success.get());
                updateVO.setFailNum(fail.get());
                maindataTmsResource.updateImportLogData(updateVO);
            }
        });
        ImportLogUpdateVO updateVO = new ImportLogUpdateVO();
        updateVO.setImportBatchNumber(importBatchNumber);
        updateVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
        updateVO.setSuccessNum(success.get());
        updateVO.setFailNum(fail.get());
        updateVO.setFailReason("导入结果生成中");
        maindataTmsResource.updateImportLogData(updateVO);
        log.info("【运单导入耗时{}】总耗时:{}ms", importBatchNumber, System.currentTimeMillis() - totalStart);
    }

    /**
     * 单个运单导入 singleImportShipBill
     *
     * @param shipbillList
     * @param user
     * @param departmentData
     * @param dicData
     * @param zoneModelList
     * @param cargoOwnerDTOList
     * @param itemPagingQueryDTOList
     * @param branchDTOList
     * @param matchBranch
     * @param matchCustomer
     * @param matchProvider
     * @return TmsShipbillHeaderModel
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TmsShipbillHeaderModel singleImportShipBill(List<ShipbillImportVO> shipbillList, UserEntity user, List<Organization> departmentData, List<SysRefdatadModel> dicData,
     List<LmsTmsZoneMinDTO> zoneModelList, List<CargoOwnerPageDTO> cargoOwnerDTOList, List<ItemPagingQueryDTO> itemPagingQueryDTOList, List<TmsBaseBranchDTO> branchDTOList,
      Map<String, RestMessage<ImportMatchingDataDTO>> matchBranch, Map<String, RestMessage<ImportMatchingDataDTO>> matchCustomer,
       Map<String, RestMessage<ImportMatchingDataDTO>> matchProvider) {
        long singleStart = System.currentTimeMillis();
        Date date = new Date();
        ShipbillImportVO shipbillImportVO = shipbillList.get(0);

        // 订单号已存在直接返回
        if (StrUtil.isNotBlank(shipbillImportVO.getOrderNo())) {
            Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
            Restriction r1 = Restrictions.eq(TmsShipbillHeaderModel::getOrderNo, shipbillImportVO.getOrderNo());
            Restriction r2 = Restrictions.eq(TmsShipbillHeaderModel::getEnterpriseId, user.getEnterpriseId());
            Restriction r3 = Restrictions.ne(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_ZF);
            criteria.setRestriction(Restrictions.and(r1, r2, r3));
            List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByCriteria(criteria);
            if (CollectionUtil.isNotEmpty(tmsShipbillHeaderModelList)) {
                TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderModelList.get(0);
                tmsShipbillHeaderModel.setBackReason("订单号【" + shipbillImportVO.getOrderNo() + "】已存在运单【" + tmsShipbillHeaderModel.getShipbillId() + "】");
                return tmsShipbillHeaderModel;
            }
        }

        ToolKits.isParamNull(shipbillImportVO.getSerialNumber(), "序号不为空");
        ToolKits.isParamNull(shipbillImportVO.getCargoOwnerName(), "序号【" + shipbillImportVO.getSerialNumber() + "】货主名称不为空");
        ToolKits.isParamNull(shipbillImportVO.getOrderType(), "序号【" + shipbillImportVO.getSerialNumber() + "】订单类型不为空");
        ToolKits.isParamNull(shipbillImportVO.getOrderBusinessType(), "序号【" + shipbillImportVO.getSerialNumber() + "】订单业务类型不为空");
        ToolKits.isParamNull(shipbillImportVO.getDeliveryMethodType(), "序号【" + shipbillImportVO.getSerialNumber() + "】配送方式不为空");
        ToolKits.isParamNull(shipbillImportVO.getTransportType(), "序号【" + shipbillImportVO.getSerialNumber() + "】运输模式不为空");
        ToolKits.isParamNull(shipbillImportVO.getTemperatureRequirement(), "序号【" + shipbillImportVO.getSerialNumber() + "】温度要求不为空");
        ToolKits.isParamNull(shipbillImportVO.getDepartmentName(), "序号【" + shipbillImportVO.getSerialNumber() + "】所属部门不为空");
        ToolKits.isParamNull(shipbillImportVO.getShipperType(), "序号【" + shipbillImportVO.getSerialNumber() + "】发货方类型不为空");
        ToolKits.isParamNull(shipbillImportVO.getShipperUnitName(), "序号【" + shipbillImportVO.getSerialNumber() + "】发货方单位不为空");
        ToolKits.isParamNull(shipbillImportVO.getConsigneeType(), "序号【" + shipbillImportVO.getSerialNumber() + "】收货方类型不为空");
        ToolKits.isParamNull(shipbillImportVO.getConsigneeUnitName(), "序号【" + shipbillImportVO.getSerialNumber() + "】收货方单位不为空");

        List<Organization> filterOrganization =
         departmentData.stream().filter(organization -> organization.getName().equals(shipbillImportVO.getDepartmentName())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(filterOrganization)) {
            throw new BizException("部门【" + shipbillImportVO.getDepartmentName() + "】不存在!");
        }
        if (!user.getDepts().contains(filterOrganization.get(0).getId())) {
            throw new BizException("部门【" + shipbillImportVO.getDepartmentName() + "】不存在，请先维护部门!");
        }

        // 运单对象
        TmsShipbillHeaderModel tmsShipbillHeaderModel = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillImportVO, tmsShipbillHeaderModel);
        tmsShipbillHeaderModel.setPickUpOrder(1);
        tmsShipbillHeaderModel.setShippingOrder(2);
        // 获取运单汇总ID
        RestMessage<String> restMessage1 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
        if (!restMessage1.isSuccess()) {
            throw new ParameterException("生成运单汇总ID失败:" + restMessage1.getMessage());
        }
        String shipbillId = restMessage1.getData();

        // 初始化装车运输记录表
        saveTransportLog(shipbillId, date, DataDictionaryConstant.ACTION_SAVE, shipbillImportVO.getEstimatedPickupStartTime(), user);
        // 汇总赋值
        tmsShipbillHeaderModel.setShipbillId(shipbillId);
        tmsShipbillHeaderModel.setShipbillNo(shipbillId);
        tmsShipbillHeaderModel.setDepartmentId(filterOrganization.get(0).getId());
        tmsShipbillHeaderModel.setDepartmentCode(filterOrganization.get(0).getCode());
        tmsShipbillHeaderModel.setDepartmentName(filterOrganization.get(0).getName());

        // 订单类型数据字典
        tmsShipbillHeaderModel.setOrderType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.ORDER_TYPE, shipbillImportVO.getOrderType())));
        // 订单业务类型数据字典
        tmsShipbillHeaderModel.setOrderBusinessType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE,
         shipbillImportVO.getOrderBusinessType())));
        // 配送方式数据字典
        tmsShipbillHeaderModel.setDeliveryMethodType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE,
         shipbillImportVO.getDeliveryMethodType())));
        // 运输模式数据字典
        tmsShipbillHeaderModel.setTransportType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.TRANSPORT_TYPE, shipbillImportVO.getTransportType())));
        // 温度要求数据字典
        tmsShipbillHeaderModel.setTemperatureRequirement(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT,
         shipbillImportVO.getTemperatureRequirement())));
        // 发货方类型数据字典
        tmsShipbillHeaderModel.setShipperType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.SHIPPER_TYPE, shipbillImportVO.getShipperType())));
        if (StrUtil.isNotBlank(shipbillImportVO.getShipperPickUpSign())) {
            // 发货方提货签到数据字典
            tmsShipbillHeaderModel.setShipperPickUpSign(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER, shipbillImportVO.getShipperPickUpSign())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getShipperAutoPickUpSign())) {
            // 发货方自动提货签到数据字典
            tmsShipbillHeaderModel.setShipperAutoPickUpSign(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
             shipbillImportVO.getShipperAutoPickUpSign())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getShipperSignTime())) {
            // 提货可签到时间点数据字典
            tmsShipbillHeaderModel.setShipperSignTime(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.PICK_UP_SIGN_TIME,
             shipbillImportVO.getShipperSignTime())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getShipperSignTimeUnit())) {
            // 提货可签到时间点单位数据字典
            tmsShipbillHeaderModel.setShipperSignTimeUnit(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.SIGN_TIME_UNIT,
shipbillImportVO.getShipperSignTimeUnit())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getShipperPickUpPicture())) {
            // 发货方提货图片数据字典
            tmsShipbillHeaderModel.setShipperPickUpPicture(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
             shipbillImportVO.getShipperPickUpPicture())));
        }
        // 收货方类型数据字典
        tmsShipbillHeaderModel.setConsigneeType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, shipbillImportVO.getConsigneeType())));
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeDeliverySign())) {
            // 收货方送达签到数据字典
            tmsShipbillHeaderModel.setConsigneeDeliverySign(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
             shipbillImportVO.getConsigneeDeliverySign())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeAutoDeliverySign())) {
            // 收货方自动送达签到数据字典
            tmsShipbillHeaderModel.setConsigneeAutoDeliverySign(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
shipbillImportVO.getConsigneeAutoDeliverySign())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeSignTime())) {
            // 送达可签到时间点数据字典
            tmsShipbillHeaderModel.setConsigneeSignTime(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.DELIVERY_SIGN_TIME,
             shipbillImportVO.getConsigneeSignTime())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeSignTimeUnit())) {
            // 送达可签到时间点单位数据字典
            tmsShipbillHeaderModel.setConsigneeSignTimeUnit(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.SIGN_TIME_UNIT,
             shipbillImportVO.getConsigneeSignTimeUnit())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeDeliveryPicture())) {
            // 收货方送货图片数据字典
            tmsShipbillHeaderModel.setConsigneeDeliveryPicture(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
shipbillImportVO.getConsigneeDeliveryPicture())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getConsigneeReturnOrderPicture())) {
            // 收货方回单图片数据字典
            tmsShipbillHeaderModel.setConsigneeReturnOrderPicture(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER,
shipbillImportVO.getConsigneeReturnOrderPicture())));
        }
        if (StrUtil.isNotBlank(shipbillImportVO.getReturnOrderFlag())) {
            // 收货方是否要求回单数据字典
            tmsShipbillHeaderModel.setReturnOrderFlag(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.WHETHER, shipbillImportVO.getReturnOrderFlag())));
        }

        // 货主校验
        List<CargoOwnerPageDTO> filterCargoOwnerDTOList =
         cargoOwnerDTOList.stream().filter(cargoOwnerDTO -> cargoOwnerDTO.getCargoOwnerName().equals(shipbillImportVO.getCargoOwnerName())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(filterCargoOwnerDTOList)) {
            throw new BizException("货主【" + shipbillImportVO.getCargoOwnerName() + "】不存在");
        } else {
            tmsShipbillHeaderModel.setCargoOwnerId(filterCargoOwnerDTOList.get(0).getCargoOwnerId());
            tmsShipbillHeaderModel.setCargoOwnerCode(filterCargoOwnerDTOList.get(0).getCargoOwnerCode());
        }

        // 发货方省市区处理
        String zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getShipperProvinceName(), Integer.valueOf(2));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setShipperProvince(null);
            tmsShipbillHeaderModel.setShipperProvinceName(null);
        } else {
            tmsShipbillHeaderModel.setShipperProvince(zoneCode);
            tmsShipbillHeaderModel.setShipperProvinceName(shipbillImportVO.getShipperProvinceName());
        }
        zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getShipperCityName(), Integer.valueOf(3));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setShipperCity(null);
            tmsShipbillHeaderModel.setShipperCityName(null);
        } else {
            tmsShipbillHeaderModel.setShipperCity(zoneCode);
            tmsShipbillHeaderModel.setShipperCityName(shipbillImportVO.getShipperCityName());
        }
        zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getShipperDistrictName(), Integer.valueOf(4));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setShipperDistrict(null);
            tmsShipbillHeaderModel.setShipperDistrictName(null);
        } else {
            tmsShipbillHeaderModel.setShipperDistrict(zoneCode);
            tmsShipbillHeaderModel.setShipperDistrictName(shipbillImportVO.getShipperDistrictName());
        }

        // 收货方省市区处理
        zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getConsigneeProvinceName(), Integer.valueOf(2));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setConsigneeProvince(null);
            tmsShipbillHeaderModel.setConsigneeProvinceName(null);
        } else {
            tmsShipbillHeaderModel.setConsigneeProvince(zoneCode);
            tmsShipbillHeaderModel.setConsigneeProvinceName(shipbillImportVO.getConsigneeProvinceName());
        }
        zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getConsigneeCityName(), Integer.valueOf(3));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setConsigneeCity(null);
            tmsShipbillHeaderModel.setConsigneeCityName(null);
        } else {
            tmsShipbillHeaderModel.setConsigneeCity(zoneCode);
            tmsShipbillHeaderModel.setConsigneeCityName(shipbillImportVO.getConsigneeCityName());
        }
        zoneCode = getZoneCodeByZoneData(zoneModelList, shipbillImportVO.getConsigneeDistrictName(), Integer.valueOf(4));
        if (ToolKits.isEmpty(zoneCode)) {
            tmsShipbillHeaderModel.setConsigneeDistrict(null);
            tmsShipbillHeaderModel.setConsigneeDistrictName(null);
        } else {
            tmsShipbillHeaderModel.setConsigneeDistrict(zoneCode);
            tmsShipbillHeaderModel.setConsigneeDistrictName(shipbillImportVO.getConsigneeDistrictName());
        }

        // 发货方信息匹配
        RestMessage<ImportMatchingDataDTO> restMessageShipperUnit;
        ImportMatchingDataVO importMatchingDataVO;
        if (tmsShipbillHeaderModel.getShipperType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_CK.intValue()) {
            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getShipperUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getShipperUnitName());
            String key = shipbillImportVO.getShipperUnitCode() + "~" + shipbillImportVO.getShipperUnitName();
            if (matchBranch.containsKey(key)) {
                restMessageShipperUnit = matchBranch.get(key);
            } else {
                restMessageShipperUnit = matchBranchLocal(branchDTOList, importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 1);
                matchBranch.put(key, restMessageShipperUnit);
            }
        } else if (tmsShipbillHeaderModel.getShipperType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_KH.intValue()) {
            ToolKits.isParamNull(shipbillImportVO.getShipperName(), "发货方名称不为空");
            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getShipperUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getShipperUnitName());
            importMatchingDataVO.setCode(shipbillImportVO.getShipperCode());
            importMatchingDataVO.setName(shipbillImportVO.getShipperName());
            importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
            importMatchingDataVO.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
            importMatchingDataVO.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
            String key =
             shipbillImportVO.getShipperUnitCode() + "~" + shipbillImportVO.getShipperUnitName() + "~" + shipbillImportVO.getShipperCode() + "~" + shipbillImportVO.getShipperName();
            if (matchCustomer.containsKey(key)) {
                restMessageShipperUnit = matchCustomer.get(key);
            } else {
                // importMatchingDataVO 发货方赋值
                transformation(importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 1);
                restMessageShipperUnit = maindataTmsResource.importMatchingCustomerDataExecute(importMatchingDataVO);
                Assert.isTrue(restMessageShipperUnit.isSuccess(), "客户发货方匹配失败：" + restMessageShipperUnit.getMessage());
                matchCustomer.put(key, restMessageShipperUnit);
            }
        } else {
            ToolKits.isParamNull(shipbillImportVO.getShipperName(), "发货方名称不为空");
            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getShipperUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getShipperUnitName());
            importMatchingDataVO.setCode(shipbillImportVO.getShipperCode());
            importMatchingDataVO.setName(shipbillImportVO.getShipperName());
            importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
            importMatchingDataVO.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
            importMatchingDataVO.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
            String key =
             shipbillImportVO.getShipperUnitCode() + "~" + shipbillImportVO.getShipperUnitName() + "~" + shipbillImportVO.getShipperCode() + "~" + shipbillImportVO.getShipperName();
            if (matchProvider.containsKey(key)) {
                restMessageShipperUnit = matchProvider.get(key);
            } else {
                // importMatchingDataVO 发货方赋值
                transformation(importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 1);
                restMessageShipperUnit = maindataTmsResource.importMatchingProviderDataExecute(importMatchingDataVO);
                Assert.isTrue(restMessageShipperUnit.isSuccess(), "供应商发货方匹配失败：" + restMessageShipperUnit.getMessage());
                matchProvider.put(key, restMessageShipperUnit);
            }
        }

        Assert.isTrue(ToolKits.isNotEmpty(restMessageShipperUnit.getData()), "发货方【" + shipbillImportVO.getShipperUnitName() + "】未维护");
        tmsShipbillHeaderModel.setShipperUnitId(restMessageShipperUnit.getData().getShipperUnitId());
        tmsShipbillHeaderModel.setShipperUnitCode(restMessageShipperUnit.getData().getShipperUnitCode());
        tmsShipbillHeaderModel.setShipperUnitName(restMessageShipperUnit.getData().getShipperUnitName());
        tmsShipbillHeaderModel.setShipperId(restMessageShipperUnit.getData().getShipperId());
        tmsShipbillHeaderModel.setShipperCode(restMessageShipperUnit.getData().getShipperCode());
        tmsShipbillHeaderModel.setShipperName(restMessageShipperUnit.getData().getShipperName());
        tmsShipbillHeaderModel.setShipperContact(ToolKits.isEmpty(shipbillImportVO.getShipperContact()) ? restMessageShipperUnit.getData().getShipperContact() :
         shipbillImportVO.getShipperContact());
        tmsShipbillHeaderModel.setShipperPhoneNumber(ToolKits.isEmpty(shipbillImportVO.getShipperPhoneNumber()) ? restMessageShipperUnit.getData().getShipperPhoneNumber() :
shipbillImportVO.getShipperPhoneNumber());
        tmsShipbillHeaderModel.setShipperLandlineNumber(ToolKits.isEmpty(shipbillImportVO.getShipperLandlineNumber()) ?
         restMessageShipperUnit.getData().getShipperLandlineNumber() : shipbillImportVO.getShipperLandlineNumber());
        tmsShipbillHeaderModel.setShipperEmail(ToolKits.isEmpty(shipbillImportVO.getShipperEmail()) ? restMessageShipperUnit.getData().getShipperEmail() :
         shipbillImportVO.getShipperEmail());
        tmsShipbillHeaderModel.setShipperRelatedPhoneNumber(restMessageShipperUnit.getData().getShipperRelatedPhoneNumber());
        tmsShipbillHeaderModel.setShipperStationId(restMessageShipperUnit.getData().getStationId());
        tmsShipbillHeaderModel.setShipperStationCode(restMessageShipperUnit.getData().getStationCode());
        tmsShipbillHeaderModel.setShipperStationName(restMessageShipperUnit.getData().getStationName());
        tmsShipbillHeaderModel.setShipperStationAreas(restMessageShipperUnit.getData().getStationAreas());
        tmsShipbillHeaderModel.setShipperDeliveryOrder(restMessageShipperUnit.getData().getStationDeliveryOrder());

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperProvince())) {
            tmsShipbillHeaderModel.setShipperProvince(restMessageShipperUnit.getData().getShipperProvince());
            tmsShipbillHeaderModel.setShipperProvinceName(restMessageShipperUnit.getData().getShipperProvinceName());
        }

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperCity())) {
            tmsShipbillHeaderModel.setShipperCity(restMessageShipperUnit.getData().getShipperCity());
            tmsShipbillHeaderModel.setShipperCityName(restMessageShipperUnit.getData().getShipperCityName());
        }

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperDistrict())) {
            tmsShipbillHeaderModel.setShipperDistrict(restMessageShipperUnit.getData().getShipperDistrict());
            tmsShipbillHeaderModel.setShipperDistrictName(restMessageShipperUnit.getData().getShipperDistrictName());
        }

        tmsShipbillHeaderModel.setShipperAddress(ToolKits.isEmpty(shipbillImportVO.getShipperAddress()) ? restMessageShipperUnit.getData().getShipperAddress() :
         shipbillImportVO.getShipperAddress());
        tmsShipbillHeaderModel.setShipperLongitude(restMessageShipperUnit.getData().getShipperLongitude());
        tmsShipbillHeaderModel.setShipperLatitude(restMessageShipperUnit.getData().getShipperLatitude());
        tmsShipbillHeaderModel.setShipperMemo(ToolKits.isEmpty(shipbillImportVO.getShipperMemo()) ? restMessageShipperUnit.getData().getShipperMemo() :
         shipbillImportVO.getShipperMemo());

        tmsShipbillHeaderModel.setShipperPickUpSign(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperPickUpSign()) ? restMessageShipperUnit.getData().getShipperPickUpSign() :
         tmsShipbillHeaderModel.getShipperPickUpSign());
        tmsShipbillHeaderModel.setShipperAutoPickUpSign(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperAutoPickUpSign()) ?
         restMessageShipperUnit.getData().getShipperAutoPickUpSign() : tmsShipbillHeaderModel.getShipperAutoPickUpSign());
        tmsShipbillHeaderModel.setShipperPickUpPicture(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperPickUpPicture()) ?
         restMessageShipperUnit.getData().getShipperPickUpPicture() : tmsShipbillHeaderModel.getShipperPickUpPicture());
        tmsShipbillHeaderModel.setShipperPickUpRail(ToolKits.isEmpty(shipbillImportVO.getShipperPickUpRail()) ? restMessageShipperUnit.getData().getShipperPickUpRail() :
         shipbillImportVO.getShipperPickUpRail());

        tmsShipbillHeaderModel.setShipperSignTime(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperSignTime()) ? restMessageShipperUnit.getData().getShipperSignTime() :
         tmsShipbillHeaderModel.getShipperSignTime());
        tmsShipbillHeaderModel.setShipperSignTimeUnit(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperSignTimeUnit()) ?
         restMessageShipperUnit.getData().getShipperSignTimeUnit() : tmsShipbillHeaderModel.getShipperSignTimeUnit());
        tmsShipbillHeaderModel.setShipperSignTimeDura(ToolKits.isEmpty(shipbillImportVO.getShipperSignTimeDura()) ? restMessageShipperUnit.getData().getShipperSignTimeDura() :
         shipbillImportVO.getShipperSignTimeDura());

        // 收货方信息匹配
        RestMessage<ImportMatchingDataDTO> restMessageConsigneeUnit;
        if (tmsShipbillHeaderModel.getConsigneeType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_CK.intValue()) {
            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getConsigneeUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getConsigneeUnitName());
            String key = shipbillImportVO.getConsigneeUnitCode() + "~" + shipbillImportVO.getConsigneeUnitName();
            if (matchBranch.containsKey(key)) {
                restMessageConsigneeUnit = matchBranch.get(key);
            } else {
                restMessageConsigneeUnit = matchBranchLocal(branchDTOList, importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 2);
                matchBranch.put(key, restMessageConsigneeUnit);
            }
        } else if (tmsShipbillHeaderModel.getConsigneeType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_KH.intValue()) {
            ToolKits.isParamNull(shipbillImportVO.getConsigneeName(), "收货方名称不为空");
            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getConsigneeUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getConsigneeUnitName());
            importMatchingDataVO.setCode(shipbillImportVO.getConsigneeCode());
            importMatchingDataVO.setName(shipbillImportVO.getConsigneeName());
            importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
            importMatchingDataVO.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
            importMatchingDataVO.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
            String key =
             shipbillImportVO.getConsigneeUnitCode() + "~" + shipbillImportVO.getConsigneeUnitName() + "~" + shipbillImportVO.getConsigneeCode() + "~" + shipbillImportVO.getConsigneeName();
            if (matchCustomer.containsKey(key)) {
                restMessageConsigneeUnit = matchCustomer.get(key);
            } else {
                // importMatchingDataVO 发货方赋值
                transformation(importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 2);
                restMessageConsigneeUnit = maindataTmsResource.importMatchingCustomerDataExecute(importMatchingDataVO);
                Assert.isTrue(restMessageConsigneeUnit.isSuccess(), "客户收货方匹配失败：" + restMessageConsigneeUnit.getMessage());
                matchCustomer.put(key, restMessageConsigneeUnit);
            }
        } else {
            ToolKits.isParamNull(shipbillImportVO.getConsigneeName(), "收货方名称不为空");

            // 请求对象
            importMatchingDataVO = new ImportMatchingDataVO();
            importMatchingDataVO.setUser(user);
            importMatchingDataVO.setUnitCode(shipbillImportVO.getConsigneeUnitCode());
            importMatchingDataVO.setUnitName(shipbillImportVO.getConsigneeUnitName());
            importMatchingDataVO.setCode(shipbillImportVO.getConsigneeCode());
            importMatchingDataVO.setName(shipbillImportVO.getConsigneeName());
            importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
            importMatchingDataVO.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
            importMatchingDataVO.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
            String key =
             shipbillImportVO.getConsigneeUnitCode() + "~" + shipbillImportVO.getConsigneeUnitName() + "~" + shipbillImportVO.getConsigneeCode() + "~" + shipbillImportVO.getConsigneeName();
            if (matchProvider.containsKey(key)) {
                restMessageConsigneeUnit = matchProvider.get(key);
            } else {
                // importMatchingDataVO 发货方赋值
                transformation(importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, 2);
                restMessageConsigneeUnit = maindataTmsResource.importMatchingProviderDataExecute(importMatchingDataVO);
                Assert.isTrue(restMessageConsigneeUnit.isSuccess(), "供应商收货方匹配失败：" + restMessageConsigneeUnit.getMessage());
                matchProvider.put(key, restMessageConsigneeUnit);
            }
        }

        Assert.isTrue(ToolKits.isNotEmpty(restMessageConsigneeUnit.getData()), "收货方【" + shipbillImportVO.getConsigneeUnitName() + "】未维护");
        tmsShipbillHeaderModel.setConsigneeUnitId(restMessageConsigneeUnit.getData().getConsigneeUnitId());
        tmsShipbillHeaderModel.setConsigneeUnitCode(restMessageConsigneeUnit.getData().getConsigneeUnitCode());
        tmsShipbillHeaderModel.setConsigneeUnitName(restMessageConsigneeUnit.getData().getConsigneeUnitName());
        tmsShipbillHeaderModel.setConsigneeId(restMessageConsigneeUnit.getData().getConsigneeId());
        tmsShipbillHeaderModel.setConsigneeCode(restMessageConsigneeUnit.getData().getConsigneeCode());
        tmsShipbillHeaderModel.setConsigneeName(restMessageConsigneeUnit.getData().getConsigneeName());
        tmsShipbillHeaderModel.setConsigneeContact(ToolKits.isEmpty(shipbillImportVO.getConsigneeContact()) ? restMessageConsigneeUnit.getData().getConsigneeContact() :
         shipbillImportVO.getConsigneeContact());
        tmsShipbillHeaderModel.setConsigneePhoneNumber(ToolKits.isEmpty(shipbillImportVO.getConsigneePhoneNumber()) ?
         restMessageConsigneeUnit.getData().getConsigneePhoneNumber() : shipbillImportVO.getConsigneePhoneNumber());
        tmsShipbillHeaderModel.setConsigneeLandlineNumber(ToolKits.isEmpty(shipbillImportVO.getConsigneeLandlineNumber()) ?
         restMessageConsigneeUnit.getData().getConsigneeLandlineNumber() : shipbillImportVO.getConsigneeLandlineNumber());
        tmsShipbillHeaderModel.setConsigneeEmail(ToolKits.isEmpty(shipbillImportVO.getConsigneeEmail()) ? restMessageConsigneeUnit.getData().getConsigneeEmail() :
         shipbillImportVO.getConsigneeEmail());
        tmsShipbillHeaderModel.setConsigneeRelatedPhoneNumber(restMessageConsigneeUnit.getData().getConsigneeRelatedPhoneNumber());
        tmsShipbillHeaderModel.setConsigneeStationId(restMessageConsigneeUnit.getData().getStationId());
        tmsShipbillHeaderModel.setConsigneeStationCode(restMessageConsigneeUnit.getData().getStationCode());
        tmsShipbillHeaderModel.setConsigneeStationName(restMessageConsigneeUnit.getData().getStationName());
        tmsShipbillHeaderModel.setConsigneeStationAreas(restMessageConsigneeUnit.getData().getStationAreas());
        tmsShipbillHeaderModel.setConsigneeDeliveryOrder(restMessageConsigneeUnit.getData().getStationDeliveryOrder());

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeProvince())) {
            tmsShipbillHeaderModel.setConsigneeProvince(restMessageConsigneeUnit.getData().getConsigneeProvince());
            tmsShipbillHeaderModel.setConsigneeProvinceName(restMessageConsigneeUnit.getData().getConsigneeProvinceName());
        }

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeCity())) {
            tmsShipbillHeaderModel.setConsigneeCity(restMessageConsigneeUnit.getData().getConsigneeCity());
            tmsShipbillHeaderModel.setConsigneeCityName(restMessageConsigneeUnit.getData().getConsigneeCityName());
        }

        if (ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeDistrict())) {
            tmsShipbillHeaderModel.setConsigneeDistrict(restMessageConsigneeUnit.getData().getConsigneeDistrict());
            tmsShipbillHeaderModel.setConsigneeDistrictName(restMessageConsigneeUnit.getData().getConsigneeDistrictName());
        }

        tmsShipbillHeaderModel.setConsigneeAddress(ToolKits.isEmpty(shipbillImportVO.getConsigneeAddress()) ? restMessageConsigneeUnit.getData().getConsigneeAddress() :
         shipbillImportVO.getConsigneeAddress());
        tmsShipbillHeaderModel.setConsigneeLongitude(restMessageConsigneeUnit.getData().getConsigneeLongitude());
        tmsShipbillHeaderModel.setConsigneeLatitude(restMessageConsigneeUnit.getData().getConsigneeLatitude());
        tmsShipbillHeaderModel.setConsigneeMemo(ToolKits.isEmpty(shipbillImportVO.getConsigneeMemo()) ? restMessageConsigneeUnit.getData().getConsigneeMemo() :
shipbillImportVO.getConsigneeMemo());

        tmsShipbillHeaderModel.setConsigneeDeliverySign(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeDeliverySign()) ?
         restMessageConsigneeUnit.getData().getConsigneeDeliverySign() : tmsShipbillHeaderModel.getConsigneeDeliverySign());
        tmsShipbillHeaderModel.setConsigneeAutoDeliverySign(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeAutoDeliverySign()) ?
         restMessageConsigneeUnit.getData().getConsigneeAutoDeliverySign() : tmsShipbillHeaderModel.getConsigneeAutoDeliverySign());
        tmsShipbillHeaderModel.setConsigneeDeliveryPicture(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeDeliveryPicture()) ?
         restMessageConsigneeUnit.getData().getConsigneeDeliveryPicture() : tmsShipbillHeaderModel.getConsigneeDeliveryPicture());
        tmsShipbillHeaderModel.setConsigneeDeliveryRail(ToolKits.isEmpty(shipbillImportVO.getConsigneeDeliveryRail()) ?
         restMessageConsigneeUnit.getData().getConsigneeDeliveryRail() : shipbillImportVO.getConsigneeDeliveryRail());
        tmsShipbillHeaderModel.setReturnOrderFlag(ToolKits.isEmpty(tmsShipbillHeaderModel.getReturnOrderFlag()) ? restMessageConsigneeUnit.getData().getReturnOrderFlag() :
         tmsShipbillHeaderModel.getReturnOrderFlag());
        tmsShipbillHeaderModel.setReturnOrderDeadline(ToolKits.isEmpty(shipbillImportVO.getReturnOrderDeadline()) ? restMessageConsigneeUnit.getData().getReturnOrderDeadline() :
         shipbillImportVO.getReturnOrderDeadline());
        tmsShipbillHeaderModel.setConsigneeReturnOrderPicture(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeReturnOrderPicture()) ?
         restMessageConsigneeUnit.getData().getConsigneeReturnOrderPicture() : tmsShipbillHeaderModel.getConsigneeReturnOrderPicture());

        tmsShipbillHeaderModel.setConsigneeSignTime(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeSignTime()) ? restMessageConsigneeUnit.getData().getConsigneeSignTime() :
         tmsShipbillHeaderModel.getConsigneeSignTime());
        tmsShipbillHeaderModel.setConsigneeSignTimeUnit(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeSignTimeUnit()) ?
         restMessageConsigneeUnit.getData().getConsigneeSignTimeUnit() : tmsShipbillHeaderModel.getConsigneeSignTimeUnit());
        tmsShipbillHeaderModel.setConsigneeSignTimeDura(ToolKits.isEmpty(shipbillImportVO.getConsigneeSignTimeDura()) ?
         restMessageConsigneeUnit.getData().getConsigneeSignTimeDura() : shipbillImportVO.getConsigneeSignTimeDura());

        tmsShipbillHeaderModel.setOrderId(shipbillImportVO.getOrderNo());
        tmsShipbillHeaderModel.setOrderDate(ObjectUtil.isNull(shipbillImportVO.getOrderDate()) ? DateUtil.date() : shipbillImportVO.getOrderDate());
        tmsShipbillHeaderModel.setWmsOrderId(shipbillImportVO.getWmsOrderNo());
        tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        tmsShipbillHeaderModel.setSource(DataDictionaryConstant.SOURCE_EXCEL);
        tmsShipbillHeaderModel.setActualTotalPcs(tmsShipbillHeaderModel.getTotalPcs());
        tmsShipbillHeaderModel.setActualTotalVolume(tmsShipbillHeaderModel.getTotalVolume());
        tmsShipbillHeaderModel.setActualTotalWeight(tmsShipbillHeaderModel.getTotalWeight());

        tmsShipbillHeaderModel.setEnterpriseId(user.getEnterpriseId());
        tmsShipbillHeaderModel.setEnterpriseName(user.getEnterpriseName());
        tmsShipbillHeaderModel.setCreateperson(user.getNickname());
        tmsShipbillHeaderModel.setCreatetime(date);
        tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
        tmsShipbillHeaderModel.setUpdatetime(date);

        // 运单业务流程匹配
        ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(tmsShipbillHeaderModel, user);
        // 订单绑定流程配置
        tmsShipbillHeaderModel.setFlowConfig(flowData.getFlowConfig());

        // 运输状态 待发货
        tmsShipbillHeaderModel.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        // 拆单状态 0未拆单
        tmsShipbillHeaderModel.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1未拆单
        tmsShipbillHeaderModel.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
        // 异常状态 0未异常
        tmsShipbillHeaderModel.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
        // 扫描状态 初始
        tmsShipbillHeaderModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
        // 拆单状态 0承运商未拆单
        tmsShipbillHeaderModel.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
        // 拆单类型 1承运商未拆单
        tmsShipbillHeaderModel.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);

        // 运单匹配线路
        if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_LINE_STRATEGY)) {
            updateShipBillLine(tmsShipbillHeaderModel, "CR");
        }
        tmsShipbillHeaderModel.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
        tmsShipbillHeaderModel.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
        tmsShipbillHeaderModel.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());

        List<TmsShipbillDetailModel> detailModels = Lists.newArrayList();
        int seqNo = 1;
        BigDecimal totalPcs = BigDecimal.ZERO;
        BigDecimal totalWeight = BigDecimal.ZERO;
        BigDecimal totalVolume = BigDecimal.ZERO;
        for (ShipbillImportVO shipbillDetailImportVO : shipbillList) {
            ToolKits.isParamNull(shipbillDetailImportVO.getItemCode(), "序号【" + shipbillDetailImportVO.getSerialNumber() + "】商品编码不为空");
            ToolKits.isParamNull(shipbillDetailImportVO.getItemName(), "序号【" + shipbillDetailImportVO.getSerialNumber() + "】商品名称不为空");
            ToolKits.isParamNull(shipbillDetailImportVO.getPcs(), "序号【" + shipbillDetailImportVO.getSerialNumber() + "】商品件数不为空");

            // 判断商品资料
            List<ItemPagingQueryDTO> filterItemList =
             itemPagingQueryDTOList.stream().filter(dto -> dto.getCargoOwnerId().equals(tmsShipbillHeaderModel.getCargoOwnerId()) && dto.getItemCode().equals(shipbillDetailImportVO.getItemCode()) && dto.getItemName().equals(shipbillDetailImportVO.getItemName())).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(filterItemList)) {
                throw new BizException("序号【" + shipbillDetailImportVO.getSerialNumber() + "】商品【" + shipbillDetailImportVO.getItemCode() + "】【" + shipbillDetailImportVO.getItemName() + "】不存在，货主【" + tmsShipbillHeaderModel.getCargoOwnerName() + "】");
            }
            ItemPagingQueryDTO itemPagingQueryDTO = filterItemList.get(0);

            // 判断仓资料
            TmsBaseBranchDTO tmsBaseBranchDTO = null;
            if (ToolKits.isNotEmpty(shipbillDetailImportVO.getBranchName())) {
                List<TmsBaseBranchDTO> filterBranchList =
                 branchDTOList.stream().filter(branchDTO -> branchDTO.getName().equals(shipbillDetailImportVO.getBranchName())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(filterBranchList)) {
                    tmsBaseBranchDTO = filterBranchList.get(0);
                }
            }
            // 运单明细对象
            TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
            BeanUtils.copyProperties(shipbillDetailImportVO, tmsShipbillDetailModel);
            if (StrUtil.isNotBlank(shipbillDetailImportVO.getPackType())) {
                // 商品包装类型数据字典
                tmsShipbillDetailModel.setPackType(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.PACK_TYPE, shipbillDetailImportVO.getPackType())));
            }
            if (StrUtil.isNotBlank(shipbillDetailImportVO.getCargoThermosphere())) {
                // 商品货物温层数据字典
                tmsShipbillDetailModel.setCargoThermosphere(Integer.valueOf(checkAndReturnDicCode(dicData, DataDictionaryConstant.CARGO_THERMOSPHERE,
                 shipbillDetailImportVO.getCargoThermosphere())));
            }
            // 获取运单明细ID
            RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
            if (!restMessage2.isSuccess()) {
                throw new ParameterException("生成运单明细ID失败:" + restMessage2.getMessage());
            }
            String shipbillDetailId = restMessage2.getData();
            tmsShipbillDetailModel.setId(shipbillDetailId);
            tmsShipbillDetailModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
            tmsShipbillDetailModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
            tmsShipbillDetailModel.setBranchId(ToolKits.isEmpty(tmsBaseBranchDTO) ? null : tmsBaseBranchDTO.getId());
            tmsShipbillDetailModel.setBranchCode(ToolKits.isEmpty(tmsBaseBranchDTO) ? null : tmsBaseBranchDTO.getCode());
            tmsShipbillDetailModel.setBranchName(ToolKits.isEmpty(tmsBaseBranchDTO) ? null : tmsBaseBranchDTO.getName());
            tmsShipbillDetailModel.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
            tmsShipbillDetailModel.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
            tmsShipbillDetailModel.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
            tmsShipbillDetailModel.setSeqno(seqNo);
            tmsShipbillDetailModel.setItemId(itemPagingQueryDTO.getItemId());
            tmsShipbillDetailModel.setItemCode(shipbillDetailImportVO.getItemCode());
            tmsShipbillDetailModel.setItemName(shipbillDetailImportVO.getItemName());
            tmsShipbillDetailModel.setItemCategoryId(itemPagingQueryDTO.getItemCategoryId());
            tmsShipbillDetailModel.setItemCategoryCode(itemPagingQueryDTO.getItemCategoryCode());
            tmsShipbillDetailModel.setItemCategoryName(itemPagingQueryDTO.getItemCategoryName());
            tmsShipbillDetailModel.setMemo(itemPagingQueryDTO.getMemo());
            tmsShipbillDetailModel.setEnterpriseId(user.getEnterpriseId());
            tmsShipbillDetailModel.setEnterpriseName(user.getEnterpriseName());
            tmsShipbillDetailModel.setCreateperson(user.getNickname());
            tmsShipbillDetailModel.setCreatetime(date);
            tmsShipbillDetailModel.setUpdateperson(user.getNickname());
            tmsShipbillDetailModel.setUpdatetime(date);
            tmsShipbillDetailModel.setTemperatureCtlLowerLimit(ToolKits.isEmpty(shipbillDetailImportVO.getTemperatureCtlLowerLimit()) ?
             itemPagingQueryDTO.getTemperatureCtlLowerLimit() : shipbillDetailImportVO.getTemperatureCtlLowerLimit());
            tmsShipbillDetailModel.setTemperatureCtlUpperLimit(ToolKits.isEmpty(shipbillDetailImportVO.getTemperatureCtlUpperLimit()) ?
             itemPagingQueryDTO.getTemperatureCtlUpperLimit() : shipbillDetailImportVO.getTemperatureCtlUpperLimit());
            tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
            tmsShipbillDetailModel.setClosingPcs(BigDecimal.ZERO);
            tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.ZERO);
            tmsShipbillDetailModel.setSignInPcs(BigDecimal.ZERO);
            tmsShipbillDetailModel.setPickUpPcs(BigDecimal.ZERO);
            tmsShipbillDetailModel.setPlanDeliveryPcs(BigDecimal.ZERO);
            tmsShipbillDetailModel.setUnitVolume(itemPagingQueryDTO.getVolume());
            tmsShipbillDetailModel.setUnitWeight(itemPagingQueryDTO.getWeight());
            tmsShipbillDetailModel.setPackType(ToolKits.isEmpty(tmsShipbillDetailModel.getPackType()) ? itemPagingQueryDTO.getPackType() : tmsShipbillDetailModel.getPackType());
            tmsShipbillDetailModel.setCargoThermosphere(ToolKits.isEmpty(tmsShipbillDetailModel.getCargoThermosphere()) ? itemPagingQueryDTO.getCargoThermosphere() :
             tmsShipbillDetailModel.getCargoThermosphere());
            tmsShipbillDetailModel.setWeight(ToolKits.isEmpty(shipbillDetailImportVO.getWeight()) ? itemPagingQueryDTO.getWeight().multiply(tmsShipbillDetailModel.getPcs()) :
             shipbillDetailImportVO.getWeight());
            tmsShipbillDetailModel.setVolume(ToolKits.isEmpty(shipbillDetailImportVO.getVolume()) ? itemPagingQueryDTO.getVolume().multiply(tmsShipbillDetailModel.getPcs()) :
shipbillDetailImportVO.getVolume());
            tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
            tmsShipbillDetailMapper.save(tmsShipbillDetailModel);

            detailModels.add(tmsShipbillDetailModel);
            seqNo++;
            if (ToolKits.isNotEmpty(tmsShipbillDetailModel.getPcs())) {
                totalPcs = totalPcs.add(tmsShipbillDetailModel.getPcs());
            }
            if (ToolKits.isNotEmpty(tmsShipbillDetailModel.getWeight())) {
                totalWeight = totalWeight.add(tmsShipbillDetailModel.getWeight());
            }
            if (ToolKits.isNotEmpty(tmsShipbillDetailModel.getVolume())) {
                totalVolume = totalVolume.add(tmsShipbillDetailModel.getVolume());
            }
        }
        tmsShipbillHeaderModel.setTotalPcs(totalPcs);
        tmsShipbillHeaderModel.setTotalWeight(totalWeight);
        tmsShipbillHeaderModel.setTotalVolume(totalVolume);
        tmsShipbillHeaderModel.setActualTotalPcs(totalPcs);
        tmsShipbillHeaderModel.setActualTotalWeight(totalWeight);
        tmsShipbillHeaderModel.setActualTotalVolume(totalVolume);
        tmsShipbillHeaderModel.setTotalDeliveryPcs(BigDecimal.ZERO);
        tmsShipbillHeaderModel.setTotalDeliveryWeight(BigDecimal.ZERO);
        tmsShipbillHeaderModel.setTotalDeliveryVolume(BigDecimal.ZERO);
        tmsShipbillHeaderModel.setOrderDate(ToolKits.isEmpty(shipbillImportVO.getOrderDate()) ? date : shipbillImportVO.getOrderDate());

        // 匹配运单业务规则策略 提升效率 产品说暂时屏蔽
        if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_BUSINESS_STRATEGY)) {
            updateShipbillHeaderByBusinessRule(tmsShipbillHeaderModel, detailModels, user);
        }
        tmsShipbillHeaderModel.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
        tmsShipbillHeaderMapper.save(tmsShipbillHeaderModel);

        // 运单节点保存
        ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
        shipbillNodeTrackingSaveVO.setShipbillId(shipbillId);
        shipbillNodeTrackingSaveVO.setShipbillNo(shipbillId);
        shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_SC);
        shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO, user);

        // 运单操作日志保存
        ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
        shipbillOperateLogSaveVO.setShipbillId(shipbillId);
        shipbillOperateLogSaveVO.setShipbillNo(shipbillId);
        shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_CSH + " 匹配业务流程：" + flowData.getFlowName());
        shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
        shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO, user);
        if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
            try {
                // 调用提交处理
                autoSubmit(Lists.newArrayList(tmsShipbillHeaderModel.getShipbillId()), user, date);
            } catch (Exception e) {
                throw new PrologException("运单导入自动提交处理失败", e);
            }
        }
        log.info("【运单导入耗时】单个运单:{}ms", System.currentTimeMillis() - singleStart);
        List<SendMessageDTO> sendMessageDTOList = MessageUtil.getMessage();
        if (CollectionUtil.isNotEmpty(sendMessageDTOList)) {
            try {
                mainDataProxy.sendMessageList(sendMessageDTOList, user);
            } catch (Exception e) {
                log.warn("订单导入发送消息异常警告", e);
            }
        }
        MessageUtil.remove();
        return tmsShipbillHeaderModel;
    }

    /**
     * 运单导入时 收发货方请求VO处理
     */
    public void transformation(ImportMatchingDataVO importMatchingDataVO, ShipbillImportVO shipbillImportVO, TmsShipbillHeaderModel tmsShipbillHeaderModel, Integer type) {
        // type=1发货方处理 type=2收货方处理
        if (type == 1) {
            importMatchingDataVO.setShipperUnitId(null);
            importMatchingDataVO.setShipperUnitCode(shipbillImportVO.getShipperUnitCode());
            importMatchingDataVO.setShipperUnitName(shipbillImportVO.getShipperUnitName());
            importMatchingDataVO.setShipperId(null);
            importMatchingDataVO.setShipperCode(shipbillImportVO.getShipperCode());
            importMatchingDataVO.setShipperName(shipbillImportVO.getShipperName());
            importMatchingDataVO.setShipperContact(shipbillImportVO.getShipperContact());
            importMatchingDataVO.setShipperPhoneNumber(shipbillImportVO.getShipperPhoneNumber());
            importMatchingDataVO.setShipperLandlineNumber(shipbillImportVO.getShipperLandlineNumber());
            importMatchingDataVO.setShipperEmail(shipbillImportVO.getShipperEmail());
            importMatchingDataVO.setShipperRelatedPhoneNumber(null);
            importMatchingDataVO.setShipperProvince(tmsShipbillHeaderModel.getShipperProvince());
            importMatchingDataVO.setShipperProvinceName(shipbillImportVO.getShipperProvinceName());
            importMatchingDataVO.setShipperCity(tmsShipbillHeaderModel.getShipperCity());
            importMatchingDataVO.setShipperCityName(shipbillImportVO.getShipperCityName());
            importMatchingDataVO.setShipperDistrict(tmsShipbillHeaderModel.getShipperDistrict());
            importMatchingDataVO.setShipperDistrictName(shipbillImportVO.getShipperDistrictName());
            importMatchingDataVO.setShipperAddress(shipbillImportVO.getShipperAddress());
            importMatchingDataVO.setShipperLongitude(null);
            importMatchingDataVO.setShipperLatitude(null);
            importMatchingDataVO.setShipperMemo(shipbillImportVO.getShipperMemo());
            importMatchingDataVO.setShipperPickUpSign(tmsShipbillHeaderModel.getShipperPickUpSign());
            importMatchingDataVO.setShipperAutoPickUpSign(tmsShipbillHeaderModel.getShipperAutoPickUpSign());
            importMatchingDataVO.setShipperPickUpPicture(tmsShipbillHeaderModel.getShipperPickUpPicture());
            importMatchingDataVO.setShipperPickUpRail(tmsShipbillHeaderModel.getShipperPickUpRail());
            importMatchingDataVO.setShipperSignTime(tmsShipbillHeaderModel.getShipperSignTime());
            importMatchingDataVO.setShipperSignTimeDura(tmsShipbillHeaderModel.getShipperSignTimeDura());
            importMatchingDataVO.setShipperSignTimeUnit(tmsShipbillHeaderModel.getShipperSignTimeUnit());
            importMatchingDataVO.setDepartmentId(tmsShipbillHeaderModel.getDepartmentId());
            importMatchingDataVO.setDepartmentCode(tmsShipbillHeaderModel.getDepartmentCode());
            importMatchingDataVO.setDepartmentName(tmsShipbillHeaderModel.getDepartmentName());
        } else {
            importMatchingDataVO.setConsigneeUnitId(null);
            importMatchingDataVO.setConsigneeUnitCode(shipbillImportVO.getConsigneeUnitCode());
            importMatchingDataVO.setConsigneeUnitName(shipbillImportVO.getConsigneeUnitName());
            importMatchingDataVO.setConsigneeId(null);
            importMatchingDataVO.setConsigneeCode(shipbillImportVO.getConsigneeCode());
            importMatchingDataVO.setConsigneeName(shipbillImportVO.getConsigneeName());
            importMatchingDataVO.setConsigneeContact(shipbillImportVO.getConsigneeContact());
            importMatchingDataVO.setConsigneePhoneNumber(shipbillImportVO.getConsigneePhoneNumber());
            importMatchingDataVO.setConsigneeLandlineNumber(shipbillImportVO.getConsigneeLandlineNumber());
            importMatchingDataVO.setConsigneeEmail(shipbillImportVO.getConsigneeEmail());
            importMatchingDataVO.setConsigneeRelatedPhoneNumber(null);
            importMatchingDataVO.setConsigneeProvince(tmsShipbillHeaderModel.getConsigneeProvince());
            importMatchingDataVO.setConsigneeProvinceName(shipbillImportVO.getConsigneeProvinceName());
            importMatchingDataVO.setConsigneeCity(tmsShipbillHeaderModel.getConsigneeCity());
            importMatchingDataVO.setConsigneeCityName(shipbillImportVO.getConsigneeCityName());
            importMatchingDataVO.setConsigneeDistrict(tmsShipbillHeaderModel.getConsigneeDistrict());
            importMatchingDataVO.setConsigneeDistrictName(shipbillImportVO.getConsigneeDistrictName());
            importMatchingDataVO.setConsigneeAddress(shipbillImportVO.getConsigneeAddress());
            importMatchingDataVO.setConsigneeLongitude(null);
            importMatchingDataVO.setConsigneeLatitude(null);
            importMatchingDataVO.setConsigneeMemo(shipbillImportVO.getConsigneeMemo());
            importMatchingDataVO.setConsigneeDeliverySign(tmsShipbillHeaderModel.getConsigneeDeliverySign());
            importMatchingDataVO.setConsigneeAutoDeliverySign(tmsShipbillHeaderModel.getConsigneeAutoDeliverySign());
            importMatchingDataVO.setConsigneeSignTime(tmsShipbillHeaderModel.getConsigneeSignTime());
            importMatchingDataVO.setConsigneeSignTimeDura(tmsShipbillHeaderModel.getConsigneeSignTimeDura());
            importMatchingDataVO.setConsigneeSignTimeUnit(tmsShipbillHeaderModel.getConsigneeSignTimeUnit());
            importMatchingDataVO.setConsigneeDeliveryPicture(tmsShipbillHeaderModel.getConsigneeDeliveryPicture());
            importMatchingDataVO.setConsigneeDeliveryRail(tmsShipbillHeaderModel.getConsigneeDeliveryRail());
            importMatchingDataVO.setReturnOrderFlag(tmsShipbillHeaderModel.getReturnOrderFlag());
            importMatchingDataVO.setReturnOrderDeadline(tmsShipbillHeaderModel.getReturnOrderDeadline());
            importMatchingDataVO.setConsigneeReturnOrderPicture(tmsShipbillHeaderModel.getConsigneeReturnOrderPicture());
            importMatchingDataVO.setDepartmentId(tmsShipbillHeaderModel.getDepartmentId());
            importMatchingDataVO.setDepartmentCode(tmsShipbillHeaderModel.getDepartmentCode());
            importMatchingDataVO.setDepartmentName(tmsShipbillHeaderModel.getDepartmentName());
        }
    }

    /**
     * 接单
     *
     * @param ids
     * @return
     */
    @Override
    public void receiveShipbillData(List<String> ids) {
        ToolKits.isParamNull(ids, "运单接单请求不为空");
        Assert.isTrue(ids.size() > 0, "运单接单请求不为空");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        Assert.isTrue(user.getUserType().equals(BussinessConstant.USER_TYPE_CYS), "当前人员没有操作权限");
        // 当前时间
        Date date = DateUtil.date();
        List<String> commitObjs = Lists.newArrayList();
        for (String id : ids) {
            ToolKits.isParamNull(id, "运单ID不为空");
            // 更新
            TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);

            if (!tmsShipbillHeaderModel.getCarrierShipbillStatus().equals(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE)) {
                throw new PrologException("运单【" + id + "】不能接单!");
            }

            // 运单状态更新
            tmsShipbillHeaderModel.setCarrierShipbillStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED);
            tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
            tmsShipbillHeaderModel.setUpdatetime(date);
            tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

            // 承运商运单操作日志保存
            ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
            shipbillOperateLogSaveVO.setShipbillId(id);
            shipbillOperateLogSaveVO.setShipbillNo(id);
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.CARRIER_SHIPBILL_NODE_STATUSNAME_RECEIVED);
            shipbillOperateLogSaveVO.setOldStatus(tmsShipbillHeaderModel.getCarrierShipbillStatus());
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED);
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

            if (tmsShipbillHeaderModel.getCarrierFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_RECEIVE_COMMIT)) {
                commitObjs.add(id);
            }
            MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.CARRIER_RECEIVE.getCode(), Lists.newArrayList(id)));
        }
        if (ToolKits.isNotEmpty(commitObjs)) {
            try {
                // 调用提交处理
                autoSubmit(commitObjs, user, date);
            } catch (Exception e) {
                throw new PrologException("运单保存自动提交处理失败", e);
            }
        }
    }

    /**
     * 运单拒绝
     *
     * @param ids
     * @return
     */
    @Override
    public void rejectShipbillData(List<String> ids) {
        ToolKits.isParamNull(ids, "运单拒绝请求不为空");
        Assert.isTrue(ids.size() > 0, "运单拒绝请求不为空");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        Assert.isTrue(user.getUserType().equals(BussinessConstant.USER_TYPE_CYS), "当前人员没有操作权限");
        // 当前时间
        Date date = DateUtil.date();
        for (String id : ids) {
            // 更新
            TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(id, TmsShipbillHeaderModel.class);
            if (!tmsShipbillHeaderModel.getCarrierShipbillStatus().equals(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE) && !tmsShipbillHeaderModel.getCarrierShipbillStatus().equals(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK)) {
                throw new PrologException("运单【" + id + "】不能拒绝!");
            }
            // 运单状态更新
            tmsShipbillHeaderModel.setCarrierShipbillStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_REJECTED);
            tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
            tmsShipbillHeaderModel.setUpdatetime(date);
            tmsShipbillHeaderModel.setCarrierId(null);
            tmsShipbillHeaderModel.setCarrierCode(null);
            tmsShipbillHeaderModel.setCarrierName(null);
            tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

            // 承运商运单操作日志保存
            ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
            shipbillOperateLogSaveVO.setShipbillId(id);
            shipbillOperateLogSaveVO.setShipbillNo(id);
            shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.CARRIER_SHIPBILL_NODE_STATUSNAME_REFUSE);
            shipbillOperateLogSaveVO.setOldStatus(tmsShipbillHeaderModel.getCarrierShipbillStatus());
            shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_REJECTED);
            shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
            MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.CARRIER_REJECT.getCode(), Lists.newArrayList(id)));
        }

        // 运单调用撤销调度
        dispatchService.undoDispatchData(ids, "Reject");
    }

    /**
     * 运单匹配业务流程
     *
     * @param model
     * @return
     */
    public ShipbillFitBusinessFlowDTO shipbillMatchBusinessFlow(TmsShipbillHeaderModel model, UserEntity user) {
        // 新增后自动提交判定
        BusinessFlowShipbillVO matchFlowVO = new BusinessFlowShipbillVO();
        // 流程类型
        matchFlowVO.setFlowType(2);
        // 配送方式
        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());
        matchFlowVO.setUser(user);
        matchFlowVO.setCarriersType(model.getCarriersType());
        RestMessage<ShipbillFitBusinessFlowDTO> matchRs = maindataTmsResource.shipbillMatchFlowQuery(matchFlowVO);
        if (!matchRs.isSuccess()) {
            throw new PrologException("运单【" + model.getShipbillNo() + "】调用maindata服务运单匹配业务流程失败");
        }
        if (ToolKits.isEmpty(matchRs.getData()) || ToolKits.isEmpty(matchRs.getData().getFlowConfig())) {
            throw new PrologException("运单【" + model.getShipbillNo() + "】没有匹配到业务流程，请重新生成运单");
        }
        return matchRs.getData();
    }

    public ShipbillFitBusinessFlowDTO shipbillMatchBusinessFlow(TmsShipbillHeaderModel model) {
        return shipbillMatchBusinessFlow(model, null);
    }

    /**
     * 运单匹配线路
     *
     * @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();
    }

    /**
     * 生成运输记录表
     */
    public void saveTransportLog(String shipbillId, Date date, String act, Date pickUpStartDt) {
        saveTransportLog(shipbillId, date, act, pickUpStartDt, null);
    }

    public void saveTransportLog(String shipbillId, Date date, String act, Date pickUpStartDt, UserEntity user) {
        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();
        if (ObjectUtil.isNull(user)) {
            user = PlgFxUsrUtils.getUserEntity();
        }
        logModel.setId(id);
        logModel.setShipbillId(shipbillId);
        logModel.setShipbillNo(shipbillId);

        logModel.setOrderDt(date);
        if (DataDictionaryConstant.ACTION_COMMIT.equals(act)) {
            logModel.setCommitDt(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);
    }

    /**
     * 运单资料接口数据处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<IntfErrorLogDTO> saveShipbillInterfaceData(List<IntfShipbillHeaderVO> intfShipbillHeaderVOs) {
        ToolKits.isParamNull(intfShipbillHeaderVOs, "运单资料接口请求不为空");

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

        // 响应集合
        List<IntfErrorLogDTO> intfErrorLogDTOs = Lists.newArrayList();

        // 当前日期
        Date date = DateUtil.date();

        for (IntfShipbillHeaderVO intfShipbillHeaderVO : intfShipbillHeaderVOs) {
            // 响应对象
            IntfErrorLogDTO intfErrorLogDTO = new IntfErrorLogDTO();

            try {
                // 判断订单是否已存在
                Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
                Restriction r1 = Restrictions.eq(TmsShipbillHeaderModel::getOrderId, intfShipbillHeaderVO.getOrderId());
                Restriction r2 = Restrictions.eq(TmsShipbillHeaderModel::getEnterpriseId, intfShipbillHeaderVO.getEnterpriseId());
                Restriction r3 = Restrictions.ne(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_ZF);
                criteria.setRestriction(Restrictions.and(r1, r2, r3));
                List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);
                // 存在直接跳过当前循环按成功处理
                if (tmsShipbillHeaderModels.size() > 0) {
                    // 成功信息
                    intfErrorLogDTO.setErrorInfo(null);
                    intfErrorLogDTO.setDataId(intfShipbillHeaderVO.getShipbillId());
                    intfErrorLogDTO.setStatus(true);

                    intfErrorLogDTOs.add(intfErrorLogDTO);

                    continue;
                }

                // 货主校验
                CargoOwnerByEncodingNameVO cargoOwnerByEncodingNameVO = new CargoOwnerByEncodingNameVO();
                cargoOwnerByEncodingNameVO.setCargoOwnerCode(intfShipbillHeaderVO.getCargoOwnerCode());
                cargoOwnerByEncodingNameVO.setCargoOwnerName(intfShipbillHeaderVO.getCargoOwnerName());
                RestMessage<CargoOwnerByEncodingNameDTO> cargoOwnerRestMessage = maindataTmsResource.getCargoOwnerByEncodingNameExecute(cargoOwnerByEncodingNameVO);
                Assert.isTrue(cargoOwnerRestMessage.isSuccess(), cargoOwnerRestMessage.getMessage());

				// 承运商校验
				CarriersByEncodingNameVO carriersByEncodingNameVO = new CarriersByEncodingNameVO();
				carriersByEncodingNameVO.setCode(intfShipbillHeaderVO.getCarriersCode());
				carriersByEncodingNameVO.setName(intfShipbillHeaderVO.getCarriersName());
				RestMessage<CarriersByEncodingNameDTO> carriersRestMessage = maindataTmsResource.getCarriersByEncodingNameExecute(carriersByEncodingNameVO);
				Assert.isTrue(carriersRestMessage.isSuccess(), carriersRestMessage.getMessage());
				CarriersByEncodingNameDTO carriersByEncodingNameDTO = carriersRestMessage.getData();

				// 仓库校验
				BranchByEncodingNameVO branchByEncodingNameVO = new BranchByEncodingNameVO();
				branchByEncodingNameVO.setCode(intfShipbillHeaderVO.getBranchCode());
				branchByEncodingNameVO.setName(intfShipbillHeaderVO.getBranchName());
				RestMessage<BranchByEncodingNameDTO> branchRestMessage = maindataTmsResource.getBranchByEncodingNameExecute(branchByEncodingNameVO);
				Assert.isTrue(branchRestMessage.isSuccess(), branchRestMessage.getMessage());

                // 运单对象
                TmsShipbillHeaderModel tmsShipbillHeaderModel = new TmsShipbillHeaderModel();
                BeanUtils.copyProperties(intfShipbillHeaderVO, tmsShipbillHeaderModel);

                // 获取运单汇总ID
                RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_HEADER_ID, "L");
                Assert.isTrue(restMessage.isSuccess(), "生成运单汇总ID失败:" + restMessage.getMessage());

				tmsShipbillHeaderModel.setShipbillId(restMessage.getData());
				tmsShipbillHeaderModel.setShipbillNo(restMessage.getData());
				tmsShipbillHeaderModel.setCargoOwnerId(cargoOwnerRestMessage.getData().getCargoOwnerId());
				tmsShipbillHeaderModel.setBranchId(branchRestMessage.getData().getId());
				tmsShipbillHeaderModel.setCarriersType(carriersByEncodingNameDTO.getCarriersType());
				tmsShipbillHeaderModel.setCarriersId(carriersByEncodingNameDTO.getId());

				// 发货方信息匹配
				RestMessage<ImportMatchingDataDTO> restMessage3 = null;
				ImportMatchingDataVO importMatchingDataVO = new ImportMatchingDataVO();
				if (tmsShipbillHeaderModel.getShipperType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_CK.intValue()) {
					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getShipperUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getShipperUnitName());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage3 = maindataTmsResource.importMatchingBranchDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage3.isSuccess(), "仓库发货方匹配失败：" + restMessage3.getMessage());
                } else if (tmsShipbillHeaderModel.getShipperType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_KH.intValue()) {
                    ToolKits.isParamNull(intfShipbillHeaderVO.getShipperCode(), "发货方编码不为空");
                    ToolKits.isParamNull(intfShipbillHeaderVO.getShipperName(), "发货方名称不为空");

					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getShipperUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getShipperUnitName());
					importMatchingDataVO.setCode(intfShipbillHeaderVO.getShipperCode());
					importMatchingDataVO.setName(intfShipbillHeaderVO.getShipperName());
					importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage3 = maindataTmsResource.importMatchingCustomerDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage3.isSuccess(), "客户发货方匹配失败：" + restMessage3.getMessage());
                } else {
                    ToolKits.isParamNull(intfShipbillHeaderVO.getShipperCode(), "发货方编码不为空");
                    ToolKits.isParamNull(intfShipbillHeaderVO.getShipperName(), "发货方名称不为空");

					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getShipperUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getShipperUnitName());
					importMatchingDataVO.setCode(intfShipbillHeaderVO.getShipperCode());
					importMatchingDataVO.setName(intfShipbillHeaderVO.getShipperName());
					importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage3 = maindataTmsResource.importMatchingProviderDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage3.isSuccess(), "供应商发货方匹配失败：" + restMessage3.getMessage());
                }

                Assert.isTrue(ToolKits.isNotEmpty(restMessage3.getData()), "发货方【" + intfShipbillHeaderVO.getShipperUnitName() + "】未维护");
                tmsShipbillHeaderModel.setShipperUnitId(restMessage3.getData().getShipperUnitId());
                tmsShipbillHeaderModel.setShipperUnitCode(restMessage3.getData().getShipperUnitCode());
                tmsShipbillHeaderModel.setShipperUnitName(restMessage3.getData().getShipperUnitName());
                tmsShipbillHeaderModel.setShipperId(restMessage3.getData().getShipperId());
                tmsShipbillHeaderModel.setShipperCode(restMessage3.getData().getShipperCode());
                tmsShipbillHeaderModel.setShipperName(restMessage3.getData().getShipperName());
                tmsShipbillHeaderModel.setShipperContact(restMessage3.getData().getShipperContact());
                tmsShipbillHeaderModel.setShipperPhoneNumber(restMessage3.getData().getShipperPhoneNumber());
                tmsShipbillHeaderModel.setShipperLandlineNumber(restMessage3.getData().getShipperLandlineNumber());
                tmsShipbillHeaderModel.setShipperEmail(restMessage3.getData().getShipperEmail());
                tmsShipbillHeaderModel.setShipperRelatedPhoneNumber(restMessage3.getData().getShipperRelatedPhoneNumber());
                tmsShipbillHeaderModel.setShipperProvince(restMessage3.getData().getShipperProvince());
                tmsShipbillHeaderModel.setShipperProvinceName(restMessage3.getData().getShipperProvinceName());
                tmsShipbillHeaderModel.setShipperCity(restMessage3.getData().getShipperCity());
                tmsShipbillHeaderModel.setShipperCityName(restMessage3.getData().getShipperCityName());
                tmsShipbillHeaderModel.setShipperDistrict(restMessage3.getData().getShipperDistrict());
                tmsShipbillHeaderModel.setShipperDistrictName(restMessage3.getData().getShipperDistrictName());
                tmsShipbillHeaderModel.setShipperAddress(restMessage3.getData().getShipperAddress());
                tmsShipbillHeaderModel.setShipperLongitude(restMessage3.getData().getShipperLongitude());
                tmsShipbillHeaderModel.setShipperLatitude(restMessage3.getData().getShipperLatitude());
                tmsShipbillHeaderModel.setShipperMemo(restMessage3.getData().getShipperMemo());
                tmsShipbillHeaderModel.setShipperPickUpSign(restMessage3.getData().getShipperPickUpSign());
                tmsShipbillHeaderModel.setShipperAutoPickUpSign(restMessage3.getData().getShipperAutoPickUpSign());
                tmsShipbillHeaderModel.setShipperPickUpPicture(restMessage3.getData().getShipperPickUpPicture());
                tmsShipbillHeaderModel.setShipperPickUpRail(restMessage3.getData().getShipperPickUpRail());

				// 收货方信息匹配
				RestMessage<ImportMatchingDataDTO> restMessage4 = null;
				if (tmsShipbillHeaderModel.getConsigneeType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_CK.intValue()) {
					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getConsigneeUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getConsigneeUnitName());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage4 = maindataTmsResource.importMatchingBranchDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage4.isSuccess(), "仓库收货方匹配失败：" + restMessage4.getMessage());
                } else if (tmsShipbillHeaderModel.getConsigneeType().intValue() == DataDictionaryConstant.SHIPPER_TYPE_KH.intValue()) {
                    ToolKits.isParamNull(intfShipbillHeaderVO.getConsigneeCode(), "收货方编码不为空");
                    ToolKits.isParamNull(intfShipbillHeaderVO.getConsigneeName(), "收货方名称不为空");

					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getConsigneeUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getConsigneeUnitName());
					importMatchingDataVO.setCode(intfShipbillHeaderVO.getConsigneeCode());
					importMatchingDataVO.setName(intfShipbillHeaderVO.getConsigneeName());
					importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage4 = maindataTmsResource.importMatchingCustomerDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage4.isSuccess(), "客户收货方匹配失败：" + restMessage4.getMessage());
                } else {
                    ToolKits.isParamNull(intfShipbillHeaderVO.getConsigneeCode(), "收货方编码不为空");
                    ToolKits.isParamNull(intfShipbillHeaderVO.getConsigneeName(), "收货方名称不为空");

					// 请求对象
					importMatchingDataVO = new ImportMatchingDataVO();
					importMatchingDataVO.setUnitCode(intfShipbillHeaderVO.getConsigneeUnitCode());
					importMatchingDataVO.setUnitName(intfShipbillHeaderVO.getConsigneeUnitName());
					importMatchingDataVO.setCode(intfShipbillHeaderVO.getConsigneeCode());
					importMatchingDataVO.setName(intfShipbillHeaderVO.getConsigneeName());
					importMatchingDataVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
					importMatchingDataVO.setUser(user);
					importMatchingDataVO.setNoSave(false);

                    restMessage4 = maindataTmsResource.importMatchingProviderDataExecute(importMatchingDataVO);
                    Assert.isTrue(restMessage4.isSuccess(), "供应商收货方匹配失败：" + restMessage4.getMessage());
                }

				Assert.isTrue(ToolKits.isNotEmpty(restMessage4.getData()), "收货方【" + intfShipbillHeaderVO.getConsigneeUnitName() + "】未维护");
				tmsShipbillHeaderModel.setConsigneeUnitId(restMessage4.getData().getConsigneeUnitId());
				tmsShipbillHeaderModel.setConsigneeUnitCode(restMessage4.getData().getConsigneeUnitCode());
				tmsShipbillHeaderModel.setConsigneeUnitName(restMessage4.getData().getConsigneeUnitName());
				tmsShipbillHeaderModel.setConsigneeId(restMessage4.getData().getConsigneeId());
				tmsShipbillHeaderModel.setConsigneeCode(restMessage4.getData().getConsigneeCode());
				tmsShipbillHeaderModel.setConsigneeName(restMessage4.getData().getConsigneeName());
				tmsShipbillHeaderModel.setConsigneeContact(restMessage4.getData().getConsigneeContact());
				tmsShipbillHeaderModel.setConsigneePhoneNumber(restMessage4.getData().getConsigneePhoneNumber());
				tmsShipbillHeaderModel.setConsigneeLandlineNumber(restMessage4.getData().getConsigneeLandlineNumber());
				tmsShipbillHeaderModel.setConsigneeEmail(restMessage4.getData().getConsigneeEmail());
				tmsShipbillHeaderModel.setConsigneeRelatedPhoneNumber(restMessage4.getData().getConsigneeRelatedPhoneNumber());
				tmsShipbillHeaderModel.setConsigneeProvince(restMessage4.getData().getConsigneeProvince());
				tmsShipbillHeaderModel.setConsigneeProvinceName(restMessage4.getData().getConsigneeProvinceName());
				tmsShipbillHeaderModel.setConsigneeCity(restMessage4.getData().getConsigneeCity());
				tmsShipbillHeaderModel.setConsigneeCityName(restMessage4.getData().getConsigneeCityName());
				tmsShipbillHeaderModel.setConsigneeDistrict(restMessage4.getData().getConsigneeDistrict());
				tmsShipbillHeaderModel.setConsigneeDistrictName(restMessage4.getData().getConsigneeDistrictName());
				tmsShipbillHeaderModel.setConsigneeAddress(ToolKits.isNotEmpty(intfShipbillHeaderVO.getConsigneeAddress()) ? intfShipbillHeaderVO.getConsigneeAddress() : restMessage4.getData().getConsigneeAddress());
				tmsShipbillHeaderModel.setConsigneeLongitude(restMessage4.getData().getConsigneeLongitude());
				tmsShipbillHeaderModel.setConsigneeLatitude(restMessage4.getData().getConsigneeLatitude());
				tmsShipbillHeaderModel.setConsigneeMemo(restMessage4.getData().getConsigneeMemo());
				tmsShipbillHeaderModel.setConsigneeDeliverySign(restMessage4.getData().getConsigneeDeliverySign());
				tmsShipbillHeaderModel.setConsigneeAutoDeliverySign(restMessage4.getData().getConsigneeAutoDeliverySign());
				tmsShipbillHeaderModel.setConsigneeDeliveryPicture(restMessage4.getData().getConsigneeDeliveryPicture());
				tmsShipbillHeaderModel.setConsigneeDeliveryRail(restMessage4.getData().getConsigneeDeliveryRail());
				tmsShipbillHeaderModel.setReturnOrderFlag(restMessage4.getData().getReturnOrderFlag());
				tmsShipbillHeaderModel.setReturnOrderDeadline(restMessage4.getData().getReturnOrderDeadline());
				tmsShipbillHeaderModel.setConsigneeReturnOrderPicture(restMessage4.getData().getConsigneeReturnOrderPicture());

                tmsShipbillHeaderModel.setTemperatureRequirement(ToolKits.isEmpty(intfShipbillHeaderVO.getTemperatureRequirement()) ?
                 DataDictionaryConstant.TEMPERATURE_REQUIREMENT_CW : intfShipbillHeaderVO.getTemperatureRequirement());
                tmsShipbillHeaderModel.setActualTotalPcs(tmsShipbillHeaderModel.getTotalPcs());
                tmsShipbillHeaderModel.setActualTotalVolume(tmsShipbillHeaderModel.getTotalVolume());
                tmsShipbillHeaderModel.setActualTotalWeight(tmsShipbillHeaderModel.getTotalWeight());
                tmsShipbillHeaderModel.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
                tmsShipbillHeaderModel.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS_NO);
                tmsShipbillHeaderModel.setSplitOrderStatus(DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
                tmsShipbillHeaderModel.setSplitOrderType(DataDictionaryConstant.SPLIT_ORDER_TYPE_UN);
                tmsShipbillHeaderModel.setCarrierSplitOrderStatus(DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
                tmsShipbillHeaderModel.setCarrierSplitOrderType(DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
                tmsShipbillHeaderModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                tmsShipbillHeaderModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                tmsShipbillHeaderModel.setSource(DataDictionaryConstant.SOURCE_INTERFACE);
                tmsShipbillHeaderModel.setOrderDate(date);
				// 包裹整件数
				tmsShipbillHeaderModel.setPackageWholePiece(BigDecimal.ZERO);
				// 包裹拼箱数
				tmsShipbillHeaderModel.setPackageLclPiece(BigDecimal.ZERO);
				// 包裹总体积
				tmsShipbillHeaderModel.setPackageTotalVolume(BigDecimal.ZERO);
				// 包裹总重量
				tmsShipbillHeaderModel.setPackageTotalWeight(BigDecimal.ZERO);
                tmsShipbillHeaderModel.setCreatetime(date);
                tmsShipbillHeaderModel.setUpdatetime(date);
                tmsShipbillHeaderModel.setCreateperson(intfShipbillHeaderVO.getCreateperson());
                tmsShipbillHeaderModel.setUpdateperson(intfShipbillHeaderVO.getUpdateperson());

                // 运单明细资料处理
                List<TmsShipbillDetailModel> detailModels = Lists.newArrayList();
                List<IntfShipbillDetailVO> intfShipbillDetailVOs = intfShipbillHeaderVO.getDetails();
                for (IntfShipbillDetailVO intfShipbillDetailVO : intfShipbillDetailVOs) {
                    // 判断商品资料
                    ItemByEncodingNameVO itemByEncodingNameVO = new ItemByEncodingNameVO();
                    itemByEncodingNameVO.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
                    itemByEncodingNameVO.setCode(intfShipbillDetailVO.getItemCode());
                    RestMessage<ItemByEncodingNameDTO> itemMessage = maindataTmsResource.getItemByEncodingNameExecute(itemByEncodingNameVO);
                    Assert.isTrue(itemMessage.isSuccess(), itemMessage.getMessage());
                    ItemByEncodingNameDTO itemByEncodingNameDTO = itemMessage.getData();

                    // 获取运单明细ID
                    RestMessage<String> restMessage2 = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_DETAIL_ID, "L");
                    Assert.isTrue(restMessage2.isSuccess(), "生成运单明细ID失败:" + restMessage2.getMessage());

					TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
					tmsShipbillDetailModel.setId(restMessage2.getData());
					tmsShipbillDetailModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
					tmsShipbillDetailModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
					tmsShipbillDetailModel.setBranchId(tmsShipbillHeaderModel.getBranchId());
					tmsShipbillDetailModel.setBranchCode(tmsShipbillHeaderModel.getBranchCode());
					tmsShipbillDetailModel.setBranchName(tmsShipbillHeaderModel.getBranchName());
					tmsShipbillDetailModel.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
					tmsShipbillDetailModel.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
					tmsShipbillDetailModel.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
					tmsShipbillDetailModel.setSeqno(intfShipbillDetailVO.getSeqno());
					tmsShipbillDetailModel.setOriginalSeqno(intfShipbillDetailVO.getOriginalSeqno());
					tmsShipbillDetailModel.setItemId(itemByEncodingNameDTO.getItemId());
					tmsShipbillDetailModel.setItemCode(itemByEncodingNameDTO.getItemCode());
					tmsShipbillDetailModel.setItemName(itemByEncodingNameDTO.getItemName());
					tmsShipbillDetailModel.setItemCategoryId(itemByEncodingNameDTO.getItemCategoryId());
					tmsShipbillDetailModel.setItemCategoryCode(itemByEncodingNameDTO.getItemCategoryCode());
					tmsShipbillDetailModel.setItemCategoryName(itemByEncodingNameDTO.getItemCategoryName());
					tmsShipbillDetailModel.setPackType(itemByEncodingNameDTO.getPackType());
					tmsShipbillDetailModel.setCargoThermosphere(itemByEncodingNameDTO.getCargoThermosphere());
					tmsShipbillDetailModel.setPcs(intfShipbillDetailVO.getPcs());
					if (intfShipbillDetailVO.getVolume().compareTo(BigDecimal.ZERO) == 0) {
						tmsShipbillDetailModel.setVolume(ToolKits.isEmpty(itemByEncodingNameDTO.getVolume()) ? BigDecimal.ZERO : itemByEncodingNameDTO.getVolume().multiply(intfShipbillDetailVO.getPcs()));
					} else {
						tmsShipbillDetailModel.setVolume(intfShipbillDetailVO.getVolume());
					}
					if (intfShipbillDetailVO.getWeight().compareTo(BigDecimal.ZERO) == 0) {
						tmsShipbillDetailModel.setWeight(ToolKits.isEmpty(itemByEncodingNameDTO.getWeight()) ? BigDecimal.ZERO : itemByEncodingNameDTO.getWeight().multiply(intfShipbillDetailVO.getPcs()));
					} else {
						tmsShipbillDetailModel.setWeight(intfShipbillDetailVO.getWeight());
					}

					tmsShipbillDetailModel.setMemo(itemByEncodingNameDTO.getMemo());
					tmsShipbillDetailModel.setInventoryPcs(intfShipbillDetailVO.getInventoryPcs());
					tmsShipbillDetailModel.setStagingLocation(intfShipbillDetailVO.getStagingLocation());
					tmsShipbillDetailModel.setEnterpriseId(tmsShipbillHeaderModel.getEnterpriseId());
					tmsShipbillDetailModel.setEnterpriseName(tmsShipbillHeaderModel.getEnterpriseName());
					tmsShipbillDetailModel.setExtStr1(intfShipbillDetailVO.getExtStr1());
					tmsShipbillDetailModel.setExtStr2(intfShipbillDetailVO.getExtStr2());
					tmsShipbillDetailModel.setExtStr3(intfShipbillDetailVO.getExtStr3());
					tmsShipbillDetailModel.setExtStr4(intfShipbillDetailVO.getExtStr4());
					tmsShipbillDetailModel.setExtStr5(intfShipbillDetailVO.getExtStr5());
					tmsShipbillDetailModel.setExtNum1(intfShipbillDetailVO.getExtNum1());
					tmsShipbillDetailModel.setExtNum2(intfShipbillDetailVO.getExtNum2());
					tmsShipbillDetailModel.setExtNum3(intfShipbillDetailVO.getExtNum3());
					tmsShipbillDetailModel.setExtNum4(intfShipbillDetailVO.getExtNum4());
					tmsShipbillDetailModel.setExtNum5(intfShipbillDetailVO.getExtNum5());
					tmsShipbillDetailModel.setExtDate1(intfShipbillDetailVO.getExtDate1());
					tmsShipbillDetailModel.setExtDate2(intfShipbillDetailVO.getExtDate2());
					tmsShipbillDetailModel.setExtDate3(intfShipbillDetailVO.getExtDate3());
					tmsShipbillDetailModel.setExtDate4(intfShipbillDetailVO.getExtDate4());
					tmsShipbillDetailModel.setExtDate5(intfShipbillDetailVO.getExtDate5());
					tmsShipbillDetailModel.setCreatetime(date);
					tmsShipbillDetailModel.setCreateperson(intfShipbillDetailVO.getCreateperson());
					tmsShipbillDetailModel.setUpdatetime(date);
					tmsShipbillDetailModel.setUpdateperson(intfShipbillDetailVO.getUpdateperson());

                    tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                    tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                    tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                    tmsShipbillDetailModel.setUnitVolume(itemByEncodingNameDTO.getVolume());
                    tmsShipbillDetailModel.setUnitWeight(itemByEncodingNameDTO.getWeight());
                    tmsShipbillDetailModel.setScanStatus(DataDictionaryConstant.SCAN_STATUS_INIT);
                    // 保存
                    tmsShipbillDetailMapper.save(tmsShipbillDetailModel);
                    detailModels.add(tmsShipbillDetailModel);
                }

                // 运单业务流程匹配
                ShipbillFitBusinessFlowDTO flowData = shipbillMatchBusinessFlow(tmsShipbillHeaderModel);
                // 订单绑定流程配置
                tmsShipbillHeaderModel.setFlowConfig(flowData.getFlowConfig());

                tmsShipbillHeaderModel.setPickUpOrder(1);
                tmsShipbillHeaderModel.setShippingOrder(2);
                // 运单匹配线路
                if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_LINE_STRATEGY)) {
                    updateShipBillLine(tmsShipbillHeaderModel, "CR");
                }
                tmsShipbillHeaderModel.setShipbillType(ShipBillTypeEnum.NORMAL.getCode());
                tmsShipbillHeaderModel.setSignInStatus(SignInStatusEnum.NOT_SIGN.getCode());
                tmsShipbillHeaderModel.setDriverReceiveStatus(DriverReceiveStatusEnum.N.getCode());

                // 匹配业务规则
                if (StrUtil.isNotBlank(tmsShipbillHeaderModel.getFlowConfig()) && tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_BUSINESS_STRATEGY)) {
                    updateShipbillHeaderByBusinessRule(tmsShipbillHeaderModel, detailModels, user);
                }
                // 汇总保存
                tmsShipbillHeaderModel.setStagingLocations(detailModels.stream().filter(detail -> ToolKits.isNotEmpty(detail.getStagingLocation())).map(TmsShipbillDetailModel::getStagingLocation).distinct().collect(Collectors.joining(",")));
                tmsShipbillHeaderModel.setIntelligentLock(IntelligentLockEnum.UN_LOCK.getCode());
                tmsShipbillHeaderMapper.save(tmsShipbillHeaderModel);

                // 运单节点保存
                ShipbillNodeTrackingSaveVO shipbillNodeTrackingSaveVO = new ShipbillNodeTrackingSaveVO();
                shipbillNodeTrackingSaveVO.setShipbillId(restMessage.getData());
                shipbillNodeTrackingSaveVO.setShipbillNo(restMessage.getData());
                shipbillNodeTrackingSaveVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                shipbillNodeTrackingSaveVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_NODE_STATUSNAME_SC);
                shipbillNodeTrackingService.addShipbillNodeTrackingData(shipbillNodeTrackingSaveVO);

                // 运单操作日志保存
                ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
                shipbillOperateLogSaveVO.setShipbillId(restMessage.getData());
                shipbillOperateLogSaveVO.setShipbillNo(restMessage.getData());
                shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_CSH + " 匹配业务流程：" + flowData.getFlowName());
                shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_CSH);
                shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);

                // 初期化订单运输记录表
                saveTransportLog(restMessage.getData(), date, DataDictionaryConstant.ACTION_SAVE, tmsShipbillHeaderModel.getEstimatedPickupStartTime());

//                // 保存自动提交判定
//                if (tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
//                    List<String> list = Lists.newArrayList();
//                    list.add(tmsShipbillHeaderModel.getShipbillId());
//                    try {
//                        // 调用提交处理
//                        autoSubmit(list, user, date);
//                    } catch (Exception e) {
//                        throw new PrologException("运单保存自动提交处理失败", e);
//                    }
//                }

                // 成功信息
                intfErrorLogDTO.setErrorInfo(null);
                intfErrorLogDTO.setDataId(intfShipbillHeaderVO.getShipbillId());
                intfErrorLogDTO.setStatus(true);

                intfErrorLogDTOs.add(intfErrorLogDTO);
            } catch (Exception e) {
                e.printStackTrace();

                log.info("运单资料接口处理失败:{}", e);

                // 错误信息
                intfErrorLogDTO.setErrorInfo(e.getMessage());
                intfErrorLogDTO.setDataId(intfShipbillHeaderVO.getShipbillId());
                intfErrorLogDTO.setStatus(false);

                intfErrorLogDTOs.add(intfErrorLogDTO);
            }
        }

        // 修改接口数据状态
        return intfErrorLogDTOs;
    }

    /**
     * 运单包裹资料接口转TMS
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<IntfErrorLogDTO> saveShipbillInterfacePackageData(List<IntfShipbillPackageVO> intfShipbillPackageVOs) {
        ToolKits.isParamNull(intfShipbillPackageVOs, "运单包裹资料接口请求不为空");

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

        // 响应集合
        List<IntfErrorLogDTO> intfErrorLogDTOs = Lists.newArrayList();

        // 当前日期
        Date date = DateUtil.date();

        for (IntfShipbillPackageVO intfShipbillPackageVO : intfShipbillPackageVOs) {
            // 响应对象
            IntfErrorLogDTO intfErrorLogDTO = new IntfErrorLogDTO();

            try {
                // 校验运单
                Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
                Restriction r1 = Restrictions.eq(TmsShipbillHeaderModel::getOrderId, intfShipbillPackageVO.getOrderId());
                Restriction r2 = Restrictions.eq(TmsShipbillHeaderModel::getEnterpriseId, intfShipbillPackageVO.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2));
                List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);
                Assert.isTrue(ToolKits.isNotEmpty(tmsShipbillHeaderModels), "订单【" + intfShipbillPackageVO.getOrderNo() + "】不存在");
                Assert.isTrue(tmsShipbillHeaderModels.size() == 1, "订单【" + intfShipbillPackageVO.getOrderNo() + "】关联重复");

                // 运单对象
                TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderModels.get(0);
				Assert.isTrue(tmsShipbillHeaderModel.getStatus().intValue() != DataDictionaryConstant.SHIPBILL_STATUS_ZF.intValue(), "订单【" + intfShipbillPackageVO.getOrderNo() + "】已取消");

                List<IntfShipbillPackageHeaderVO> intfShipbillPackageHeaderVOs = intfShipbillPackageVO.getHeaders();
                for (IntfShipbillPackageHeaderVO intfShipbillPackageHeaderVO : intfShipbillPackageHeaderVOs) {
                	// 校验运单包裹是否存在
                    Criteria criteria1 = Criteria.forClass(TmsShipbillPackageModel.class);
                    Restriction r11 = Restrictions.eq(TmsShipbillPackageModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
                    Restriction r12 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, intfShipbillPackageVO.getEnterpriseId());
                    Restriction r13 = Restrictions.eq(TmsShipbillPackageModel::getPackageCode, intfShipbillPackageHeaderVO.getPackageCode());
                    criteria1.setRestriction(Restrictions.and(r11, r12,r13));
                    List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteria1);
					Assert.isTrue(tmsShipbillPackageModels.size() <= 0, "订单【" + intfShipbillPackageVO.getOrderNo() + "】的包裹【" + intfShipbillPackageHeaderVO.getPackageCode() + "】已存在");
                	
                    // 获取运单包裹ID
                    RestMessage<String> restMessage = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_PACKAGE_ID, "L");
                    Assert.isTrue(restMessage.isSuccess(), "生成运单包裹ID失败:" + restMessage.getMessage());

                    // 运单包裹对象
                    TmsShipbillPackageModel tmsShipbillPackageModel = new TmsShipbillPackageModel();
                    BeanUtils.copyProperties(intfShipbillPackageHeaderVO, tmsShipbillPackageModel);
                    tmsShipbillPackageModel.setId(restMessage.getData());
                    tmsShipbillPackageModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
                    tmsShipbillPackageModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
                    tmsShipbillPackageModel.setBranchId(tmsShipbillHeaderModel.getBranchId());
                    tmsShipbillPackageModel.setBranchCode(tmsShipbillHeaderModel.getBranchCode());
                    tmsShipbillPackageModel.setBranchName(tmsShipbillHeaderModel.getBranchName());
                    tmsShipbillPackageModel.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
                    tmsShipbillPackageModel.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
                    tmsShipbillPackageModel.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
                    tmsShipbillPackageModel.setPackageId(restMessage.getData());
                    tmsShipbillPackageModel.setStatus(DataDictionaryConstant.PACKAGE_STATUS_INI);
                    tmsShipbillPackageModel.setCreatetime(date);
                    tmsShipbillPackageModel.setUpdatetime(date);
					tmsShipbillPackageModel.setExpressNumber(tmsShipbillPackageModel.getPackageCode());
                    tmsShipbillPackageMapper.save(tmsShipbillPackageModel);

                    // 运单包裹明细处理
                    List<IntfShipbillPkgDetailVO> details = intfShipbillPackageHeaderVO.getDetails();
                    for (IntfShipbillPkgDetailVO intfShipbillPkgDetailVO : details) {
                        // 判断商品资料
                        ItemByEncodingNameVO itemByEncodingNameVO = new ItemByEncodingNameVO();
                        itemByEncodingNameVO.setCargoOwnerId(tmsShipbillPackageModel.getCargoOwnerId());
                        itemByEncodingNameVO.setCode(intfShipbillPkgDetailVO.getItemCode());
                        itemByEncodingNameVO.setName(intfShipbillPkgDetailVO.getItemName());
                        RestMessage<ItemByEncodingNameDTO> itemMessage = maindataTmsResource.getItemByEncodingNameExecute(itemByEncodingNameVO);
                        Assert.isTrue(itemMessage.isSuccess(), itemMessage.getMessage());
                        ItemByEncodingNameDTO itemByEncodingNameDTO = itemMessage.getData();

                        // 运单包裹明细对象
                        TmsShipbillPkgDetailModel tmsShipbillPkgDetailModel = new TmsShipbillPkgDetailModel();
                        BeanUtils.copyProperties(intfShipbillPkgDetailVO, tmsShipbillPkgDetailModel);
                        tmsShipbillPkgDetailModel.setId(ToolKits.getUUID());
                        tmsShipbillPkgDetailModel.setShipbillId(tmsShipbillHeaderModel.getShipbillId());
                        tmsShipbillPkgDetailModel.setShipbillNo(tmsShipbillHeaderModel.getShipbillNo());
                        tmsShipbillPkgDetailModel.setBranchId(tmsShipbillHeaderModel.getBranchId());
                        tmsShipbillPkgDetailModel.setBranchCode(tmsShipbillHeaderModel.getBranchCode());
                        tmsShipbillPkgDetailModel.setBranchName(tmsShipbillHeaderModel.getBranchName());
                        tmsShipbillPkgDetailModel.setCargoOwnerId(tmsShipbillHeaderModel.getCargoOwnerId());
                        tmsShipbillPkgDetailModel.setCargoOwnerCode(tmsShipbillHeaderModel.getCargoOwnerCode());
                        tmsShipbillPkgDetailModel.setCargoOwnerName(tmsShipbillHeaderModel.getCargoOwnerName());
                        tmsShipbillPkgDetailModel.setPackageId(tmsShipbillPackageModel.getPackageId());
                        tmsShipbillPkgDetailModel.setPackageCode(tmsShipbillPackageModel.getPackageCode());
                        tmsShipbillPkgDetailModel.setPackageType(tmsShipbillPackageModel.getPackageType());
                        tmsShipbillPkgDetailModel.setItemId(itemByEncodingNameDTO.getItemId());
                        tmsShipbillPkgDetailModel.setItemCode(intfShipbillPkgDetailVO.getItemCode());
                        tmsShipbillPkgDetailModel.setItemName(intfShipbillPkgDetailVO.getItemName());
                        tmsShipbillPkgDetailModel.setItemCategoryId(itemByEncodingNameDTO.getItemCategoryId());
                        tmsShipbillPkgDetailModel.setItemCategoryCode(itemByEncodingNameDTO.getItemCategoryCode());
                        tmsShipbillPkgDetailModel.setItemCategoryName(itemByEncodingNameDTO.getItemCategoryName());
                        tmsShipbillPkgDetailModel.setPackType(itemByEncodingNameDTO.getPackType());
                        tmsShipbillPkgDetailModel.setCargoThermosphere(itemByEncodingNameDTO.getCargoThermosphere());
                        tmsShipbillPkgDetailModel.setEnterpriseId(tmsShipbillPackageModel.getEnterpriseId());
                        tmsShipbillPkgDetailModel.setEnterpriseName(tmsShipbillPackageModel.getEnterpriseName());
                        tmsShipbillPkgDetailModel.setCreatetime(tmsShipbillPackageModel.getCreatetime());
                        tmsShipbillPkgDetailModel.setCreateperson(tmsShipbillPackageModel.getCreateperson());
                        tmsShipbillPkgDetailModel.setUpdatetime(tmsShipbillPackageModel.getUpdatetime());
                        tmsShipbillPkgDetailModel.setUpdateperson(tmsShipbillPackageModel.getUpdateperson());

                        tmsShipbillPkgDetailModel.setVolume(tmsShipbillPkgDetailModel.getVolume().compareTo(BigDecimal.ZERO) != 0 ? tmsShipbillPkgDetailModel.getVolume() : itemByEncodingNameDTO.getVolume().multiply(tmsShipbillPkgDetailModel.getPcs()));
                        tmsShipbillPkgDetailModel.setWeight(tmsShipbillPkgDetailModel.getWeight().compareTo(BigDecimal.ZERO) != 0 ? tmsShipbillPkgDetailModel.getWeight() : itemByEncodingNameDTO.getWeight().multiply(tmsShipbillPkgDetailModel.getPcs()));

                        tmsShipbillPackageDetailMapper.save(tmsShipbillPkgDetailModel);
                    }

					// 快递单号处理
					if (ToolKits.isEmpty(tmsShipbillHeaderModel.getExpressNumber())) {
						tmsShipbillHeaderModel.setExpressNumber(tmsShipbillPackageModel.getExpressNumber());
					} else {
						if (!tmsShipbillHeaderModel.getExpressNumber().contains(tmsShipbillPackageModel.getExpressNumber())) {
							tmsShipbillHeaderModel.setExpressNumber(tmsShipbillHeaderModel.getExpressNumber() + "," + tmsShipbillPackageModel.getExpressNumber());
						}
					}

					// 暂存位处理
					if (ToolKits.isEmpty(tmsShipbillHeaderModel.getStagingLocations())) {
						tmsShipbillHeaderModel.setStagingLocations(tmsShipbillPackageModel.getStorageCache());
					} else {
						if (!tmsShipbillHeaderModel.getStagingLocations().contains(tmsShipbillPackageModel.getStorageCache())) {
							tmsShipbillHeaderModel.setStagingLocations(tmsShipbillHeaderModel.getStagingLocations() + "," + tmsShipbillPackageModel.getStorageCache());
						}
					}
                }

                // 包裹整件数
				tmsShipbillHeaderModel.setPackageWholePiece(tmsShipbillHeaderModel.getPackageWholePiece().add(intfShipbillPackageHeaderVOs.stream().map(IntfShipbillPackageHeaderVO::getWholePiece).reduce(BigDecimal.ZERO, BigDecimal::add)));
                // 包裹拼箱数
				tmsShipbillHeaderModel.setPackageLclPiece(tmsShipbillHeaderModel.getPackageLclPiece().add(intfShipbillPackageHeaderVOs.stream().map(IntfShipbillPackageHeaderVO::getLclPiece).reduce(BigDecimal.ZERO, BigDecimal::add)));
                // 包裹总体积
				tmsShipbillHeaderModel.setPackageTotalVolume(tmsShipbillHeaderModel.getPackageTotalVolume().add(intfShipbillPackageHeaderVOs.stream().map(IntfShipbillPackageHeaderVO::getVolume).reduce(BigDecimal.ZERO, BigDecimal::add)));
                // 包裹总重量
				tmsShipbillHeaderModel.setPackageTotalWeight(tmsShipbillHeaderModel.getPackageTotalWeight().add(intfShipbillPackageHeaderVOs.stream().map(IntfShipbillPackageHeaderVO::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add)));
				tmsShipbillHeaderModel.setUpdateperson(user.getNickname());
				tmsShipbillHeaderModel.setUpdatetime(date);
				tmsShipbillHeaderMapper.update(tmsShipbillHeaderModel);

				// 判断是否存在最后一个包裹
				List<IntfShipbillPackageHeaderVO> list = intfShipbillPackageHeaderVOs.stream().filter(s -> s.getLastPackage().equals(DataDictionaryConstant.LAST_PACKAGE_YES)).collect(Collectors.toList());
				if (list.size() > 0) {
					Assert.isTrue(list.size() == 1, "订单【" + intfShipbillPackageVO.getOrderNo() + "】存在多个最后包裹");

					// 保存自动提交判定
					if (tmsShipbillHeaderModel.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_ADD_COMMIT)) {
						List<String> shipbillIds = Lists.newArrayList();
						shipbillIds.add(tmsShipbillHeaderModel.getShipbillId());
						try {
							// 调用提交处理
							autoSubmit(shipbillIds, user, date);
						} catch (Exception e) {
							throw new PrologException("运单保存自动提交处理失败", e);
						}
					}
				}

                // 成功信息
                intfErrorLogDTO.setErrorInfo(null);
                intfErrorLogDTO.setDataId(intfShipbillPackageVO.getOrderId());
                intfErrorLogDTO.setStatus(true);

                intfErrorLogDTOs.add(intfErrorLogDTO);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("运单包裹资料接口处理失败:{}", e);

                // 错误信息
                intfErrorLogDTO.setErrorInfo(e.getMessage());
                intfErrorLogDTO.setDataId(intfShipbillPackageVO.getOrderId());
                intfErrorLogDTO.setStatus(false);

                intfErrorLogDTOs.add(intfErrorLogDTO);
            }
        }

        return intfErrorLogDTOs;
    }

    /**
     * 运单匹配业务规则
     *
     * @param model
     * @return
     */
    public StrategyBusinessMatchingDTO shipbillMatchBusinessRule(TmsShipbillHeaderModel model, List<TmsShipbillDetailModel> detailModels) {
        return shipbillMatchBusinessRule(model, detailModels, null);
    }

    public StrategyBusinessMatchingDTO shipbillMatchBusinessRule(TmsShipbillHeaderModel model, List<TmsShipbillDetailModel> detailModels, UserEntity user) {
        // 新增后自动提交判定
        StrategyBusinessMatchingVO matchBusinessVO = new StrategyBusinessMatchingVO();
        matchBusinessVO.setUser(user);
        // 配送方式
        matchBusinessVO.setDeliveryMethodType(model.getDeliveryMethodType());
        // 发货方类型
        matchBusinessVO.setShipperType(model.getShipperType());
        // 发货方单位ID
        matchBusinessVO.setShipperUnitId(model.getShipperUnitId());
        // 收货方类型
        matchBusinessVO.setConsigneeType(model.getConsigneeType());
        // 收货方单位ID
        matchBusinessVO.setConsigneeUnitId(model.getConsigneeUnitId());
        // 订单类型
        matchBusinessVO.setOrderType(model.getOrderType());
        // 订单业务类型
        matchBusinessVO.setOrderBusinessType(model.getOrderBusinessType());
        // 运输模式
        matchBusinessVO.setTransportType(model.getTransportType());
        // 温度要求
        matchBusinessVO.setTemperatureRequirement(model.getTemperatureRequirement());
        // 货主ID
        matchBusinessVO.setCargoOwnerId(model.getCargoOwnerId());
        // 部门
        matchBusinessVO.setDepartmentId(model.getDepartmentId());

        matchBusinessVO.setTotalWeight(model.getTotalWeight());
        matchBusinessVO.setTotalPcs(model.getTotalPcs());

        matchBusinessVO.setShipperProvince(model.getShipperProvince());
        matchBusinessVO.setShipperCity(model.getShipperCity());
        matchBusinessVO.setShipperDistrict(model.getShipperDistrict());

        matchBusinessVO.setConsigneeProvince(model.getConsigneeProvince());
        matchBusinessVO.setConsigneeCity(model.getConsigneeCity());
        matchBusinessVO.setConsigneeDistrict(model.getConsigneeDistrict());

        if (ToolKits.isNotEmpty(detailModels)) {
            List<StrategyBusinessItemVO> businessItemVOS = Lists.newArrayList();
            for (TmsShipbillDetailModel detailModel : detailModels) {
                StrategyBusinessItemVO businessItemVO = new StrategyBusinessItemVO();
                businessItemVO.setItemId(detailModel.getItemId());
                businessItemVO.setItemCategoryId(detailModel.getItemCategoryId());
                businessItemVO.setPcs(detailModel.getPcs());
                businessItemVO.setWeight(detailModel.getWeight());

                businessItemVOS.add(businessItemVO);
            }
            matchBusinessVO.setBusinessItemVOS(businessItemVOS);
        }
        log.info("运单匹配业务规则入参:" + JSON.toJSONString(matchBusinessVO));
        RestMessage<List<StrategyBusinessMatchingDTO>> matchRs = maindataTmsResource.matchingBusinessExecute(matchBusinessVO);
        if (!matchRs.isSuccess()) {
            throw new PrologException("运单【" + model.getShipbillNo() + "】调用maindata服务运单匹配业务规则失败");
        }
        List<StrategyBusinessMatchingDTO> strategyBusinessMatchingDTOS = matchRs.getData();
        log.info("运单匹配到的业务规则:" + JSON.toJSONString(strategyBusinessMatchingDTOS));
        if (ToolKits.isEmpty(strategyBusinessMatchingDTOS)) {
            return null;
        }
        if (strategyBusinessMatchingDTOS.size() > 1) {
            throw new PrologException("运单【" + model.getShipbillNo() + "】匹配到多个业务规则策略");
        }
        return strategyBusinessMatchingDTOS.get(0);
    }

    @Override
    public void addLog(ShipbillOperateLogSaveNewVO shipbillHeaderVOs) {
        shipbillOperateLogService.addShipbillOperateLogNewData(shipbillHeaderVOs);
    }

    /**
     * 通过运单ID查询运单号、装车单号等信息
     *
     * @param
     */
    @Override
    public ShipbillAndLoadingbillInfoDTO getInfoByShipbillid(String shipbillId) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        ShipbillAndLoadingbillInfoDTO dto = new ShipbillAndLoadingbillInfoDTO();

        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("shipbillId", shipbillId);
        queryMap.put("enterpriseId", user.getEnterpriseId());

        List<TmsLoadingBillDetailModel> tmsLoadingBillDetails = tmsLoadingBillDetailMapper.findByMap(queryMap, TmsLoadingBillDetailModel.class);
        if (ToolKits.isNotEmpty(tmsLoadingBillDetails) && tmsLoadingBillDetails.size() > 0) {
            TmsLoadingBillDetailModel tmsLoadingBillDetail = tmsLoadingBillDetails.get(0);
            TmsLoadingBillHeaderModel tmsLoadingBillHeader = tmsLoadingBillHeaderMapper.findById(tmsLoadingBillDetail.getLoadingBillId(), TmsLoadingBillHeaderModel.class);

            dto.setLoadingbillId(tmsLoadingBillHeader.getLoadingBillId());
            dto.setLoadingbillNo(tmsLoadingBillHeader.getLoadingBillNo());
            dto.setVehicleId(tmsLoadingBillHeader.getVehicleId());
            dto.setVehicleCode(tmsLoadingBillHeader.getVehicleCode());
            dto.setVehiclePlateNumber(tmsLoadingBillHeader.getVehiclePlateNumber());
            dto.setDriverCode(tmsLoadingBillHeader.getDriverCode());
            dto.setDriverName(tmsLoadingBillHeader.getDriverName());
            dto.setDriverPhoneNumber(tmsLoadingBillHeader.getDriverPhoneNumber());
            dto.setStatus(tmsLoadingBillDetail.getStatus());
        }

        return dto;
    }

    /**
     * 取得原单下，已调度的运单商品占用量
     *
     * @param origShipbillId
     * @return
     */
    Integer getOirgShipbillDetailDispatchedPcs(String origShipbillId, Long itemId, Integer deliveryMethodType, String selfShipbillId) {
        Integer cnt = 0;
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = Restrictions.eq(TmsShipbillHeaderModel::getOriginalShipbillId, origShipbillId);

        Restriction r2 = null;
        Restriction r3 = null;
        Restriction r4 = null;
        if (deliveryMethodType.equals(DataDictionaryConstant.DELIVERY_METHOD_TYPE_SEND)) {
            r2 = Restrictions.gt(TmsShipbillHeaderModel::getCarrierShipbillStatus, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_AUDITED);
            r3 = Restrictions.eq(TmsShipbillHeaderModel::getCarrierSplitOrderStatus, DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
            r4 = Restrictions.eq(TmsShipbillHeaderModel::getTransportStatus, DataDictionaryConstant.TRANSPORT_STATUS_PENDING_SHIP);
        } else {
            r2 = Restrictions.gt(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
            r3 = Restrictions.eq(TmsShipbillHeaderModel::getSplitOrderStatus, DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            r4 = Restrictions.le(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_HD_ZT);
        }
        Integer[] noStatus = {DataDictionaryConstant.SHIPBILL_STATUS_WZ, DataDictionaryConstant.SHIPBILL_STATUS_RS, DataDictionaryConstant.SHIPBILL_STATUS_WS};
        Restriction r5 = Restrictions.notIn(TmsShipbillHeaderModel::getStatus, noStatus);
        Restriction r6 = Restrictions.ne(TmsShipbillHeaderModel::getShipbillId, selfShipbillId);

        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6));
        List<TmsShipbillHeaderModel> shipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

        for (TmsShipbillHeaderModel headerModel : shipbillHeaderModels) {
            Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
            r1 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, headerModel.getShipbillId());
            r2 = Restrictions.eq(TmsShipbillDetailModel::getItemId, itemId);
            r3 = Restrictions.isNotNull(TmsShipbillDetailModel::getPcs);

            criteriaDetail.setRestriction(Restrictions.and(r1, r2, r3));
            List<TmsShipbillDetailModel> shipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);
            if (ToolKits.isNotEmpty(shipbillDetailModels)) {
                Long sumCnt = shipbillDetailModels.stream().mapToInt(s -> s.getPcs().intValue()).summaryStatistics().getSum();
                if (ToolKits.isNotEmpty(sumCnt)) {
                    cnt = cnt.intValue() + sumCnt.intValue();
                }
            }
        }
        return cnt;
    }

    @Override
    public List<ShipAndLoadingBillDTO> getAllShipBillById(String shipBillId) {
        List<TmsShipbillHeaderModel> tmsShipBillHeaderModelList = Lists.newArrayList();
        TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipBillId, TmsShipbillHeaderModel.class);
        tmsShipBillHeaderModelList.add(tmsShipbillHeaderModel);
        String fatherShipBillId = tmsShipbillHeaderModel.getFatherShipbillId();
        while (StrUtil.isNotBlank(fatherShipBillId)) {
            TmsShipbillHeaderModel fatherModel = tmsShipbillHeaderMapper.findById(fatherShipBillId, TmsShipbillHeaderModel.class);
            if (ObjectUtil.isNull(fatherModel)) {
                break;
            }
            tmsShipBillHeaderModelList.add(fatherModel);
            fatherShipBillId = fatherModel.getFatherShipbillId();
        }
        List<String> shipBillIdList = tmsShipBillHeaderModelList.stream().map(TmsShipbillHeaderModel::getShipbillId).collect(Collectors.toList());
        Criteria criteria = Criteria.forClass(TmsLoadingBillDetailModel.class);
        Restriction r1 = Restrictions.in("shipbillId", shipBillIdList.toArray());
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModelList = tmsLoadingBillDetailMapper.findByCriteria(criteria);
        Map<String, String> shipLoadingBillIdMap = tmsLoadingBillDetailModelList.stream().sorted(Comparator.comparing(TmsLoadingBillDetailModel::getCreatetime)).collect(Collectors.toMap(t1 -> t1.getShipbillId(), t2 -> t2.getLoadingBillId(), (t1, t2) -> t2));
        criteria = Criteria.forClass(TmsLoadingBillHeaderModel.class);
        r1 = Restrictions.in("loadingBillId", shipLoadingBillIdMap.values().toArray());
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsLoadingBillHeaderModel> tmsLoadingBillHeaderModelList = tmsLoadingBillHeaderMapper.findByCriteria(criteria);
        Map<String, TmsLoadingBillHeaderModel> loadingBillMap = tmsLoadingBillHeaderModelList.stream().collect(Collectors.toMap(t1 -> t1.getLoadingBillId(), t2 -> t2, (t1, t2) -> t2));
        return tmsShipBillHeaderModelList.stream().map(tmsShipbillHeaderModel1 -> {
            ShipAndLoadingBillDTO dto = new ShipAndLoadingBillDTO();
            dto.setShipBillId(tmsShipbillHeaderModel1.getShipbillId());
            dto.setShipBillNo(tmsShipbillHeaderModel1.getShipbillNo());
            dto.setStatus(tmsShipbillHeaderModel1.getStatus());
            dto.setRealShipBillId(shipBillId);
            if (StrUtil.isNotBlank(shipLoadingBillIdMap.get(tmsShipbillHeaderModel1.getShipbillId()))) {
                TmsLoadingBillHeaderModel tmsLoadingBillHeaderModel = loadingBillMap.get(shipLoadingBillIdMap.get(tmsShipbillHeaderModel1.getShipbillId()));
                if (ObjectUtil.isNotNull(tmsLoadingBillHeaderModel)) {
                    dto.setLoadingBillId(tmsLoadingBillHeaderModel.getLoadingBillId());
                    dto.setLoadingBillNo(tmsLoadingBillHeaderModel.getLoadingBillNo());
                    dto.setVehicleId(tmsLoadingBillHeaderModel.getVehicleId());
                    dto.setVehicleCode(tmsLoadingBillHeaderModel.getVehicleCode());
                    dto.setVehiclePlateNumber(tmsLoadingBillHeaderModel.getVehiclePlateNumber());
                    dto.setDriverId(tmsLoadingBillHeaderModel.getDriverId());
                    dto.setDriverCode(tmsLoadingBillHeaderModel.getDriverCode());
                    dto.setDriverName(tmsLoadingBillHeaderModel.getDriverName());
                    dto.setDriverPhoneNumber(tmsLoadingBillHeaderModel.getDriverPhoneNumber());
                }
            }
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 运单匹配业务规则
     *
     * @param shipbillHeaderSubmitVO
     */
    @Override
    public ShipbillBusinessRuleDTO matchShipbillBusinessRule(ShipbillHeaderSaveVO shipbillHeaderSubmitVO) {
        ToolKits.isParamNull(shipbillHeaderSubmitVO, "运单匹配业务规则请求不为空！");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerId(), "货主ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerCode(), "货主编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getCargoOwnerName(), "货主名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getOrderType(), "订单类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getOrderBusinessType(), "订单业务类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDeliveryMethodType(), "配送方式不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getTransportType(), "运输模式不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getTemperatureRequirement(), "温度要求不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperType(), "发货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitId(), "发货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitCode(), "发货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperUnitName(), "发货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperProvince(), "发货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperProvinceName(), "发货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperCity(), "发货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperCityName(), "发货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperDistrict(), "发货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperDistrictName(), "发货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getShipperAddress(), "发货方详细地址不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeType(), "收货方类型不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitId(), "收货方单位ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitCode(), "收货方单位编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeUnitName(), "收货方单位名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeProvince(), "收货方省编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeProvinceName(), "收货方省名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeCity(), "收货方市编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeCityName(), "收货方市名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeDistrict(), "收货方区/县编码不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeDistrictName(), "收货方区/县名称不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getConsigneeAddress(), "收货方详细地址不为空");

        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentId(), "所属部门ID不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentCode(), "所属部门编号不为空");
        ToolKits.isParamNull(shipbillHeaderSubmitVO.getDepartmentName(), "所属部门名称不为空");

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

        TmsShipbillHeaderModel model = new TmsShipbillHeaderModel();
        BeanUtils.copyProperties(shipbillHeaderSubmitVO, model);

        // 汇总赋值
        model.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_YTJ);
        model.setSource(DataDictionaryConstant.SOURCE_ADD);
        model.setEnterpriseId(user.getEnterpriseId());
        model.setEnterpriseName(user.getEnterpriseName());
        model.setCreateperson(user.getNickname());

        // 实际件数、体积、总量默认
        model.setActualTotalPcs(model.getTotalPcs());
        model.setActualTotalVolume(model.getTotalVolume());
        model.setActualTotalWeight(model.getTotalWeight());

        model.setUpdateperson(user.getNickname());

        // 运单明细对象集合
        List<TmsShipbillDetailModel> tmsShipbillDetailModels = Lists.newArrayList();
        if (ToolKits.isNotEmpty(shipbillHeaderSubmitVO.getDetails())) {
            for (ShipbillDetailSaveVO shipbillDetailSaveVO : shipbillHeaderSubmitVO.getDetails()) {
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemId(), "商品ID不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemCode(), "商品编码不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getItemName(), "商品名称不为空");
                ToolKits.isParamNull(shipbillDetailSaveVO.getPcs(), "商品件数不为空");
                TmsShipbillDetailModel tmsShipbillDetailModel = new TmsShipbillDetailModel();
                BeanUtils.copyProperties(shipbillDetailSaveVO, tmsShipbillDetailModel);

                // 明细赋值
                tmsShipbillDetailModel.setCargoOwnerId(model.getCargoOwnerId());
                tmsShipbillDetailModel.setCargoOwnerCode(model.getCargoOwnerCode());
                tmsShipbillDetailModel.setCargoOwnerName(model.getCargoOwnerName());
                tmsShipbillDetailModel.setOrigPcs(tmsShipbillDetailModel.getPcs());
                tmsShipbillDetailModel.setClosingPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModel.setDeliveryPcs(BigDecimal.valueOf(0));
                tmsShipbillDetailModels.add(tmsShipbillDetailModel);
            }
        }

        // 匹配业务规则
        ShipbillBusinessRuleDTO ruleDTO = new ShipbillBusinessRuleDTO();
        StrategyBusinessMatchingDTO businessData = shipbillMatchBusinessRule(model, tmsShipbillDetailModels);
        if (ToolKits.isNotEmpty(businessData) && businessData.getDeliveryMethodSelect().intValue() == 1) {
            List<Map<String, Object>> data3 = Lists.newArrayList();
            RestMessage<List<Map<String, Object>>> restMessage3 = maindataTmsResource.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
            if (!restMessage3.isSuccess()) {
                throw new RuntimeException("配送方式翻译失败!");
            } else {
                data3 = restMessage3.getData();
            }
            ruleDTO.setDeliveryMethodTypeName(PublicMethods.change(data3, String.valueOf(businessData.getDeliveryMethodType())));
            ruleDTO.setDeliveryMethodType(businessData.getDeliveryMethodType());
        }
        return ruleDTO;
    }

    @Override
    public ShipBillTemperatureDTO getShipBillTemperature(String shipBillId) {
        ShipBillTemperatureDTO dto = new ShipBillTemperatureDTO();
        dto.setShipbillId(shipBillId);
        dto.setShipbillNo(shipBillId);
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
        Restriction r1 = Restrictions.eq("shipbillId", shipBillId);
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<TmsShipbillDetailModel> tmsShipbillDetailModelList = tmsShipbillDetailMapper.findByCriteria(criteria);
        if (CollectionUtil.isNotEmpty(tmsShipbillDetailModelList)) {
            Map<Long, ItemCheckDTO> itemCheckDTOMap = mainDataProxy.getItemByIdList(tmsShipbillDetailModelList.stream().map(TmsShipbillDetailModel::getItemId).collect(Collectors.toList()));
            BigDecimal temperatureCtlUpperLimit = itemCheckDTOMap.values().stream().sorted(Comparator.comparing(ItemCheckDTO::getTemperatureCtlUpperLimit).reversed()).map(ItemCheckDTO::getTemperatureCtlUpperLimit).findFirst().orElse(BigDecimal.ZERO);
            BigDecimal temperatureCtlLowerLimit = itemCheckDTOMap.values().stream().sorted(Comparator.comparing(ItemCheckDTO::getTemperatureCtlLowerLimit)).map(ItemCheckDTO::getTemperatureCtlLowerLimit).findFirst().orElse(BigDecimal.ZERO);
            dto.setTemperatureCtlUpperLimit(temperatureCtlUpperLimit);
            dto.setTemperatureCtlLowerLimit(temperatureCtlLowerLimit);
        } else {
            dto.setTemperatureCtlUpperLimit(BigDecimal.ZERO);
            dto.setTemperatureCtlLowerLimit(BigDecimal.ZERO);
        }

        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = Lists.newArrayList();
        Criteria crt = Criteria.forClass(TmsVehicleGpsModel.class);
        TmsVehicleGpsModel tmsVehicleGpsModel = new TmsVehicleGpsModel();
        crt.restrictionBuilder().eq(tmsVehicleGpsModel::getShipbillId, shipBillId).build();
        crt.orderAscBy(tmsVehicleGpsModel::getUpdatetime, tmsVehicleGpsModel::getCreatetime);
        List<TmsVehicleGpsModel> tmsVehicleGpsModelList = tmsVehicleGpsMapper.findByCriteria(crt);
        if (CollectionUtil.isNotEmpty(tmsVehicleGpsModelList)) {
            tmsVehicleGpsDTOList = tmsVehicleGpsModelList.stream().map(model -> BeanUtil.toBean(model, TmsVehicleGpsDTO.class)).collect(Collectors.toList());
        }
        dto.setDtoList(tmsVehicleGpsDTOList);
        return dto;
    }

    public String getZoneCode(String zoneName, Integer zlevel) {
        String zoneCode = null;
        List<LmsTmsZoneDTO> zoneList = Lists.newArrayList();
        if (ToolKits.isNotEmpty(zoneName)) {
            LmsTmsZoneQueryVO lmstmszonevo = new LmsTmsZoneQueryVO();
            lmstmszonevo.setZname(zoneName);
            lmstmszonevo.setZlevel(zlevel);
            RestMessage<List<LmsTmsZoneDTO>> zoneModelRestMessage = maindataTmsResource.getLmsTmsZoneByNameExecute(lmstmszonevo);
            if (zoneModelRestMessage.isSuccess() && ToolKits.isNotEmpty(zoneModelRestMessage.getData())) {
                zoneList = zoneModelRestMessage.getData();
            } else {
                throw new ParameterException("行政编码获取失败 " + zoneModelRestMessage.getMessage());
            }
        }
        if (ToolKits.isNotEmpty(zoneList) && ToolKits.isNotEmpty(zoneList.get(0).getZoneid())) {
            zoneCode = zoneList.get(0).getZoneid();
        }
        return zoneCode;
    }

    /**
     * 校验和获取字典code
     *
     * @param dicData
     * @param dicName
     * @param dicValue
     * @return
     */
    private String checkAndReturnDicCode(List<SysRefdatadModel> dicData, String dicName, String dicValue) {
        String code = ConvertorUtil.getCode(dicData, dicName, dicValue);
        if (StrUtil.isBlank(code)) {
            throw new ParameterException("数据字典【" + dicName + "】转换失败：" + dicValue);
        }
        return code;
    }

    /**
     * 获取行政区域id
     *
     * @param zoneModelList
     * @param zoneName
     * @param zlevel
     * @return
     */
    private String getZoneCodeByZoneData(List<LmsTmsZoneMinDTO> zoneModelList, String zoneName, Integer zlevel) {
        return zoneModelList.stream().filter(zone -> zone.getZname().equals(zoneName) && zone.getZlevel().equals(zlevel)).findFirst().orElseGet(() -> {
            LmsTmsZoneMinDTO lmsTmsZoneMinDTO = new LmsTmsZoneMinDTO();
            return lmsTmsZoneMinDTO;
        }).getZoneid();
    }

    /**
     * 仓库匹配
     *
     * @param branchDTOList
     * @param importMatchingDataVO
     * @param shipbillImportVO
     * @param tmsShipbillHeaderModel
     * @return
     */
    private RestMessage<ImportMatchingDataDTO> matchBranchLocal(List<TmsBaseBranchDTO> branchDTOList, ImportMatchingDataVO importMatchingDataVO, ShipbillImportVO shipbillImportVO, TmsShipbillHeaderModel tmsShipbillHeaderModel, Integer type) {
        RestMessage<ImportMatchingDataDTO> restMessageShipperUnit = new RestMessage<>();
        List<TmsBaseBranchDTO> filterBranchDTOList = branchDTOList.stream().filter(tmsBaseBranchDTO -> tmsBaseBranchDTO.getName().equals(shipbillImportVO.getShipperUnitCode()) && tmsBaseBranchDTO.getCode().equals(shipbillImportVO.getShipperUnitName())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(filterBranchDTOList)) {
            // importMatchingDataVO 发货方赋值
            transformation(importMatchingDataVO, shipbillImportVO, tmsShipbillHeaderModel, type);
            restMessageShipperUnit = maindataTmsResource.importMatchingBranchDataExecute(importMatchingDataVO);
            Assert.isTrue(restMessageShipperUnit.isSuccess(), "仓库发货方匹配失败：" + restMessageShipperUnit.getMessage());
        } else {
            ImportMatchingDataDTO importMatchingDataDTO = new ImportMatchingDataDTO();
            importMatchingDataDTO.setShipperUnitId(filterBranchDTOList.get(0).getId());
            importMatchingDataDTO.setShipperUnitCode(filterBranchDTOList.get(0).getCode());
            importMatchingDataDTO.setShipperUnitName(filterBranchDTOList.get(0).getName());
            importMatchingDataDTO.setShipperId(filterBranchDTOList.get(0).getId());
            importMatchingDataDTO.setShipperCode(filterBranchDTOList.get(0).getCode());
            importMatchingDataDTO.setShipperName(filterBranchDTOList.get(0).getName());
            importMatchingDataDTO.setShipperContact(filterBranchDTOList.get(0).getContact());
            importMatchingDataDTO.setShipperPhoneNumber(filterBranchDTOList.get(0).getPhoneNumber());
            importMatchingDataDTO.setShipperLandlineNumber(filterBranchDTOList.get(0).getLandlineNumber());
            importMatchingDataDTO.setShipperEmail(filterBranchDTOList.get(0).getEmail());
            importMatchingDataDTO.setShipperRelatedPhoneNumber(null);
            importMatchingDataDTO.setShipperProvince(filterBranchDTOList.get(0).getProvince());
            importMatchingDataDTO.setShipperProvinceName(filterBranchDTOList.get(0).getProvinceName());
            importMatchingDataDTO.setShipperCity(filterBranchDTOList.get(0).getCity());
            importMatchingDataDTO.setShipperCityName(filterBranchDTOList.get(0).getCityName());
            importMatchingDataDTO.setShipperDistrict(filterBranchDTOList.get(0).getDistrict());
            importMatchingDataDTO.setShipperDistrictName(filterBranchDTOList.get(0).getDistrictName());
            importMatchingDataDTO.setShipperAddress(filterBranchDTOList.get(0).getAddress());
            importMatchingDataDTO.setShipperLongitude(filterBranchDTOList.get(0).getLongitude());
            importMatchingDataDTO.setShipperLatitude(filterBranchDTOList.get(0).getLatitude());
            importMatchingDataDTO.setShipperMemo(filterBranchDTOList.get(0).getMemo());
            importMatchingDataDTO.setShipperAutoPickUpSign(filterBranchDTOList.get(0).getAutoPickUpSign());
            importMatchingDataDTO.setShipperPickUpRail(filterBranchDTOList.get(0).getDefaultPickUpRail());
            importMatchingDataDTO.setConsigneeUnitId(filterBranchDTOList.get(0).getId());
            importMatchingDataDTO.setConsigneeUnitCode(filterBranchDTOList.get(0).getCode());
            importMatchingDataDTO.setConsigneeUnitName(filterBranchDTOList.get(0).getName());
            importMatchingDataDTO.setConsigneeId(filterBranchDTOList.get(0).getId());
            importMatchingDataDTO.setConsigneeCode(filterBranchDTOList.get(0).getCode());
            importMatchingDataDTO.setConsigneeName(filterBranchDTOList.get(0).getName());
            importMatchingDataDTO.setConsigneeContact(filterBranchDTOList.get(0).getContact());
            importMatchingDataDTO.setConsigneePhoneNumber(filterBranchDTOList.get(0).getPhoneNumber());
            importMatchingDataDTO.setConsigneeLandlineNumber(filterBranchDTOList.get(0).getLandlineNumber());
            importMatchingDataDTO.setConsigneeEmail(filterBranchDTOList.get(0).getEmail());
            importMatchingDataDTO.setConsigneeRelatedPhoneNumber(null);
            importMatchingDataDTO.setConsigneeProvince(filterBranchDTOList.get(0).getProvince());
            importMatchingDataDTO.setConsigneeProvinceName(filterBranchDTOList.get(0).getProvinceName());
            importMatchingDataDTO.setConsigneeCity(filterBranchDTOList.get(0).getCity());
            importMatchingDataDTO.setConsigneeCityName(filterBranchDTOList.get(0).getCityName());
            importMatchingDataDTO.setConsigneeDistrict(filterBranchDTOList.get(0).getDistrict());
            importMatchingDataDTO.setConsigneeDistrictName(filterBranchDTOList.get(0).getDistrictName());
            importMatchingDataDTO.setConsigneeAddress(filterBranchDTOList.get(0).getAddress());
            importMatchingDataDTO.setConsigneeLongitude(filterBranchDTOList.get(0).getLongitude());
            importMatchingDataDTO.setConsigneeLatitude(filterBranchDTOList.get(0).getLatitude());
            importMatchingDataDTO.setConsigneeMemo(filterBranchDTOList.get(0).getMemo());
            importMatchingDataDTO.setConsigneeAutoDeliverySign(filterBranchDTOList.get(0).getAutoDeliverySign());
            importMatchingDataDTO.setConsigneeDeliveryRail(filterBranchDTOList.get(0).getDefaultDeliveryRail());
            importMatchingDataDTO.setReturnOrderFlag(StatusConstant.WHETHER_NO);
            importMatchingDataDTO.setReturnOrderDeadline(null);
            importMatchingDataDTO.setConsigneeReturnOrderPicture(filterBranchDTOList.get(0).getReturnOrderPicture());
            importMatchingDataDTO.setShipperSignTime(filterBranchDTOList.get(0).getPickUpSignTime());
            importMatchingDataDTO.setShipperSignTimeDura(filterBranchDTOList.get(0).getPickUpSignTimeDura());
            importMatchingDataDTO.setShipperSignTimeUnit(filterBranchDTOList.get(0).getPickUpSignTimeUnit());
            importMatchingDataDTO.setConsigneeSignTime(filterBranchDTOList.get(0).getDeliverySignTime());
            importMatchingDataDTO.setConsigneeSignTimeDura(filterBranchDTOList.get(0).getDeliverySignTimeDura());
            importMatchingDataDTO.setConsigneeSignTimeUnit(filterBranchDTOList.get(0).getDeliverySignTimeUnit());
            if (StrUtil.isNotBlank(filterBranchDTOList.get(0).getPickUpSign())) {
                importMatchingDataDTO.setShipperPickUpSign(Integer.valueOf(filterBranchDTOList.get(0).getPickUpSign()));
            }
            if (StrUtil.isNotBlank(filterBranchDTOList.get(0).getPickUpPicture())) {
                importMatchingDataDTO.setShipperPickUpPicture(Integer.valueOf(filterBranchDTOList.get(0).getPickUpPicture()));
            }
            if (StrUtil.isNotBlank(filterBranchDTOList.get(0).getDeliverySign())) {
                importMatchingDataDTO.setConsigneeDeliverySign(Integer.valueOf(filterBranchDTOList.get(0).getDeliverySign()));
            }
            if (StrUtil.isNotBlank(filterBranchDTOList.get(0).getDeliveryPicture())) {
                importMatchingDataDTO.setConsigneeDeliveryPicture(Integer.valueOf(filterBranchDTOList.get(0).getDeliveryPicture()));
            }
            restMessageShipperUnit.setData(importMatchingDataDTO);
        }
        return restMessageShipperUnit;
    }

    /**
     * 文件上传文件服务器
     *
     * @param file
     * @return
     */
    private UploadFileDTO uploadFile(File file, String importBatchNumber) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
        FileSystemResource resource = new FileSystemResource(file);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        param.add("directory", "/tmp/tms/shipbill/import");
        param.add("storageType", "0");
        param.add("isFileName", "1");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, httpHeaders);
        ResponseEntity<String> result = restTemplate.postForEntity("http://service-filemanagement/file/upload-file", httpEntity, String.class);
        if (HttpStatus.OK.value() == result.getStatusCode().value()) {
            if (StrUtil.isNotBlank(result.getBody())) {
                log.info("【运单导入{}】文件上传服务返回={}", importBatchNumber, result.getBody());
                RestMessage<UploadFileDTO> restMessage = JSON.parseObject(result.getBody(), new TypeReference<RestMessage<UploadFileDTO>>() {
                });
                if (restMessage.isSuccess()) {
                    log.info("【运单导入{}】服务器文件路径={}", importBatchNumber, restMessage.getData().getPath());
                    FileUtil.del(file);
                    return restMessage.getData();
                }
            }
        }
        return null;
    }

    /**
     * 运单修改定位
     *
     * @param shipbillLocationVOS
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyShipbillHeaderLocationData(List<ShipbillLocationVO> shipbillLocationVOS) {
        ToolKits.isParamNull(shipbillLocationVOS, "运单修改定位请求不为空！");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        for (ShipbillLocationVO locationVO : shipbillLocationVOS) {
            log.info("修改运单定位信息={}", JSON.toJSON(locationVO));
            TmsShipbillHeaderModel headerModel = tmsShipbillHeaderMapper.findById(locationVO.getShipbillId(), TmsShipbillHeaderModel.class);
            if (ToolKits.isNotEmpty(locationVO.getShipperLatitude())) {
                headerModel.setShipperLatitude(locationVO.getShipperLatitude());
            }
            if (ToolKits.isNotEmpty(locationVO.getShipperLongitude())) {
                headerModel.setShipperLongitude(locationVO.getShipperLongitude());
            }
            if (ToolKits.isNotEmpty(locationVO.getShipperAddress()) && ToolKits.isEmpty(headerModel.getShipperAddress())) {
                headerModel.setShipperAddress(locationVO.getShipperAddress());
            }

            if (ToolKits.isNotEmpty(locationVO.getConsigneeLatitude())) {
                headerModel.setConsigneeLatitude(locationVO.getConsigneeLatitude());
            }
            if (ToolKits.isNotEmpty(locationVO.getConsigneeLongitude())) {
                headerModel.setConsigneeLongitude(locationVO.getConsigneeLongitude());
            }
            if (ToolKits.isNotEmpty(locationVO.getConsigneeAddress()) && ToolKits.isEmpty(headerModel.getConsigneeAddress())) {
                headerModel.setConsigneeAddress(locationVO.getConsigneeAddress());
            }
            headerModel.setUpdatetime(DateUtils.nowDate());
            headerModel.setUpdateperson(user.getNickname());
            tmsShipbillHeaderMapper.update(headerModel);
        }
    }

    /**
     * 业务规则匹配-是否显示温度
     *
     * @param shipBillIdList
     * @return
     */
    @Override
    public StrategyBusinessTemperatureDTO showTemperature(List<String> shipBillIdList) {
        shipBillIdList = shipBillIdList.stream().flatMap(s -> Arrays.stream(s.split(","))).collect(Collectors.toList());
        List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class, shipBillIdList.toArray(), null);
        List<StrategyBusinessMatchingDTO> dtoList = Lists.newArrayList();
        tmsShipbillHeaderModelList.forEach(tmsShipbillHeaderModel -> {
            Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
            Restriction r1 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, tmsShipbillHeaderModel.getShipbillId());
            criteria.setRestriction(Restrictions.and(r1));
            List<TmsShipbillDetailModel> tmsShipbillDetailModelList = tmsShipbillDetailMapper.findByCriteria(criteria);
            StrategyBusinessMatchingDTO businessData = shipbillMatchBusinessRule(tmsShipbillHeaderModel, tmsShipbillDetailModelList, PlgFxUsrUtils.getUserEntity());
            if (ObjectUtil.isNotNull(businessData)) {
                dtoList.add(businessData);
            }
        });
        StrategyBusinessTemperatureDTO dto = new StrategyBusinessTemperatureDTO();
        dto.setShowDepartureTemperature(Boolean.FALSE);
        dto.setShowDeliveryTemperature(Boolean.FALSE);
        dto.setDtoList(dtoList);
        if (CollectionUtil.isNotEmpty(dtoList)) {
            if (dtoList.stream().anyMatch(strategyBusinessMatchingDTO -> DataDictionaryConstant.TEMPERATURE_SELECT_YES.equals(strategyBusinessMatchingDTO.getDepartureTemperatureSelect()) && DataDictionaryConstant.TEMPERATURE_ENABLE_YES.equals(strategyBusinessMatchingDTO.getDepartureTemperatureEnable()))) {
                dto.setShowDepartureTemperature(Boolean.TRUE);
            }
            if (dtoList.stream().anyMatch(strategyBusinessMatchingDTO -> DataDictionaryConstant.TEMPERATURE_SELECT_YES.equals(strategyBusinessMatchingDTO.getDeliveryTemperatureSelect()) && DataDictionaryConstant.TEMPERATURE_ENABLE_YES.equals(strategyBusinessMatchingDTO.getDeliveryTemperatureEnable()))) {
                dto.setShowDeliveryTemperature(Boolean.TRUE);
            }
        }
        return dto;
    }

    // 根据业务规则,修改运单
    void updateShipbillHeaderByBusinessRule(TmsShipbillHeaderModel headerModel, List<TmsShipbillDetailModel> detailModels, UserEntity user) {
        StrategyBusinessMatchingDTO businessData = shipbillMatchBusinessRule(headerModel, detailModels, user);
        if (ToolKits.isNotEmpty(businessData)) {
            if (ToolKits.isNotEmpty(businessData.getDeliveryMethodSelect()) && businessData.getDeliveryMethodSelect().intValue() == 1) {
                headerModel.setDeliveryMethodType(businessData.getDeliveryMethodType());
            }
            if (ToolKits.isNotEmpty(businessData.getRtnOrderPicSelect()) && businessData.getRtnOrderPicSelect().intValue() == 1) {
                headerModel.setConsigneeReturnOrderPicture(businessData.getRtnOrderPicEnable());
            }
            if (ToolKits.isNotEmpty(businessData.getRtnOrderPaperSelect()) && businessData.getRtnOrderPaperSelect().intValue() == 1) {
                headerModel.setReturnOrderFlag(businessData.getRtnOrderPaperEnable());
            }
            if (ToolKits.isNotEmpty(businessData.getRtnOrderDeadlineSelect()) && businessData.getRtnOrderDeadlineSelect().intValue() == 1) {
                headerModel.setReturnOrderDeadline(businessData.getRtnOrderDeadline());
            }
            if (ToolKits.isNotEmpty(businessData.getDeliveryDirectionSelect()) && businessData.getDeliveryDirectionSelect().intValue() == 1) {
                headerModel.setLineDirection(businessData.getDeliveryDirection());
            }
            if (ToolKits.isNotEmpty(businessData.getRecordTagSelect()) && businessData.getRecordTagSelect().intValue() == 1) {
                headerModel.setRecordTagWord(businessData.getRecordTagWord());
            }
            if (ToolKits.isNotEmpty(businessData.getColorTagSelect()) && businessData.getColorTagSelect().intValue() == 1) {
                headerModel.setColorTagBgdColor(businessData.getColorTagBgdColor());
                headerModel.setColorTagFontColor(businessData.getColorTagFontColor());
            }
        }
    }

    /**
     * 线路匹配规则策略修改
     *
     * @param headerModel
     * @param operateType
     */
    public void updateShipBillLine(TmsShipbillHeaderModel headerModel, String operateType) {
        ShipbillMatchLineDTO lineData = shipbillMatchLine(headerModel);
        if (ToolKits.isNotEmpty(lineData) && ToolKits.isNotEmpty(lineData.getLineId())) {
            // 订单绑定线路
            headerModel.setLineId(lineData.getLineId());
            headerModel.setLineCode(lineData.getLineCode());
            headerModel.setLineName(lineData.getLineName());
            headerModel.setLineDirection(lineData.getLineDirection());
            headerModel.setShippingOrder(lineData.getShippingOrder());
            headerModel.setPickUpOrder(lineData.getPickUpOrder());
            headerModel.setShipperDeliveryOrder(NumberUtil.toBigDecimal(lineData.getPickUpOrder()));
            headerModel.setConsigneeDeliveryOrder(NumberUtil.toBigDecimal(lineData.getShippingOrder()));
            DataUtils.setEstimatedTime(headerModel, lineData, operateType);
        } else {
            headerModel.setLineDirection(DataDictionaryConstant.LINE_DIRECTION_F);
        }
    }

    /**
     * getTemplateById
     *
     * @param templateId
     * @return
     */
    private List<StandardTemplateDetailsListDTO> getTemplateById(String templateId) {
        // 标准模板查询
        RestMessage<List<StandardTemplateDetailsListDTO>> temprestMessage = maindataTmsResource.templateDetail(templateId);
        if (!temprestMessage.isSuccess()) {
            throw new ParameterException("标准模板详情查询失败:" + temprestMessage.getMessage());
        }
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = temprestMessage.getData();
        ToolKits.isParamNull(standardTemplateDetailsListDTOs, "运单标准模板未配置");
        return standardTemplateDetailsListDTOs;
    }

    public List<ShipbillTrackingDTO> getShipBillTracking(ShipbillTrackVO vo) {
        ToolKits.isParamNull(vo, "获取运单轨迹数据请求不为空！");
        ToolKits.isParamNull(vo.getExpressNumber(), "快递单号不为空！");

        List<ShipbillTrackingDTO> trackingDTOS = Lists.newArrayList();

        Criteria criteriaShipbillRouteData = Criteria.forClass(ShipbillRouteDataModel.class);
        Restriction r1 = Restrictions.eq(ShipbillRouteDataModel::getExpressNumber, vo.getExpressNumber());
        criteriaShipbillRouteData.setRestriction(Restrictions.and(r1));
        criteriaShipbillRouteData.setOrder(Order.newInstance().asc(new String[]{"routeTime"}));
        List<ShipbillRouteDataModel> routeDataModels = shipbillRouteDataMapper.findByCriteria(criteriaShipbillRouteData);
        if (ToolKits.isEmpty(routeDataModels)) {
            return trackingDTOS;
        }
        Criteria criteriaShipbillHeader = Criteria.forClass(TmsShipbillHeaderModel.class);
        r1 = Restrictions.like(TmsShipbillHeaderModel::getExpressNumber, "%" + vo.getExpressNumber() + "%");
        criteriaShipbillHeader.setRestriction(Restrictions.and(r1));
        List<TmsShipbillHeaderModel> shipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteriaShipbillHeader);
        boolean isDelivery = Boolean.FALSE;
        if (ToolKits.isNotEmpty(shipbillHeaderModels) && NumberUtil.isGreater(BigDecimal.valueOf(shipbillHeaderModels.get(0).getStatus()), BigDecimal.valueOf(DataDictionaryConstant.SHIPBILL_STATUS_SD))) {
            isDelivery = Boolean.TRUE;
        }
        int cnt = 0;
        for (ShipbillRouteDataModel dataModel : routeDataModels) {
            if (!isDelivery && routeDataModels.size() > 1 && cnt == routeDataModels.size() - 1) {
                break;
            }
            ShipbillTrackingDTO trackingDTO = BeanUtil.copyProperties(dataModel, ShipbillTrackingDTO.class);
            trackingDTOS.add(trackingDTO);
            cnt++;
        }
        return trackingDTOS;
    }
}
