package com.sckw.transport.service.Import;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.res.ContractLogisticsOrderResDto;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.common.enums.enums.FileEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.model.file.FileInfo;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.easyexcel.ExcelImportListener;
import com.sckw.excel.utils.DateUtil;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.excel.utils.ValidUtil;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.manage.api.RemoteManageService;
import com.sckw.manage.api.model.dto.res.EntAddressResDto;
import com.sckw.manage.api.model.dto.res.FindCooperateByEntReqVo;
import com.sckw.manage.api.model.dto.res.FindCooperateByEntResVo;
import com.sckw.manage.api.model.dto.res.FindEntCooperateResVo;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.payment.api.dubbo.PaymentDubboService;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.redis.config.RedisLockUtil;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.KwsEnterpriseResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.transport.common.config.MessageUrlConfig;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.ExeclDTO.LogisticsOrderExcelImportDTO;
import com.sckw.transport.service.KwtCommonService;
import com.sckw.transport.service.KwtLogisticsOrderGoodsService;
import com.sckw.transport.service.KwtTransportCommonService;
import com.sckw.transport.service.KwtWaybillOrderService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author lfdc
 * @description 承运订单导入service
 * @date 2023-12-17 16:12:50
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KwtAcceptCarriageOrderImportService {
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    RemoteSystemService remoteSystemService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    TradeOrderInfoService tradeOrderInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    GoodsInfoService goodsInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    RemoteFleetService fleetService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteContractService remoteContractService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    RemoteManageService remoteManageService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    PaymentDubboService paymentDubboService;

    @Autowired
    KwtTransportCommonService transportCommonService;

    @Autowired
    private MessageUrlConfig messageUrlConfig;

    @Autowired
    public KwtCommonService commonService;

    @Autowired
    public KwtWaybillOrderService waybillOrderService;

    @Autowired
    public KwtLogisticsOrderGoodsService logisticsOrderGoodsService;

    @Resource
    private StreamBridge streamBridge;

    @Autowired
    private KwtLogisticsOrderMapper logisticsOrderMapper;

    @Autowired
    private KwtLogisticsOrderTrackMapper logisticsOrderTrackMapper;

    @Autowired
    private KwtWaybillOrderMapper waybillOrderMapper;

    @Autowired
    private KwtWaybillOrderTicketMapper waybillOrderTicketMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper kwtLogisticsOrderGoodsMapper;

    @Autowired
    public KwtLogisticsOrderContractMapper kwtLogisticsOrderContractMapper;

    @Autowired
    private KwtLogisticsOrderCirculateMapper logisticsOrderCirculateMapper;

    @Autowired
    private KwtLogisticsOrderAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper logisticsOrderUnitMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper goodsMapper;

    @Autowired
    public KwtLogisticsOrderImportMapper logisticsOrderImportMapper;


    private final RedisLockUtil redisLockUtil;

    /**
     * 承运订单导入
     *
     * @param file
     * @return
     */
    @Transactional
    public HttpResult externalImportExcel(MultipartFile file) {

        /**文件存储至oss*/
        saveImportExcel(file);

        /**文件必填写校验*/
        HttpResult result = this.checkImportExcel(file);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return result;
        }
        /**文件填写数据校验*/
        List<LogisticsOrderExcelImportDTO> driverExcels = (List) result.getData();
        List<Map<String, Object>> messageList = new ArrayList<>();
        checkDataFormat(driverExcels, messageList);

        /**数据存储*/
        saveExternalImportExcel(driverExcels);

        /**导入数据推送至消息列表*/
        pushMessage(messageList, driverExcels.size());
        return HttpResult.ok("导入文件成功");
    }

    private void saveImportExcel(MultipartFile file) {
        FileInfo fileInfo = FileUtils.getFileDataList(file);
        fileInfo.setType(FileEnum.FILE_STORE_TYPE_OSS.getFileType());
        FileInfo returnFileInfo = FileUtils.uploadFileInfo(file, fileInfo, FileEnum.FILE_STORE_TYPE_OSS);
        Date date = new Date();
        KwtLogisticsOrderImport anImport = new KwtLogisticsOrderImport();
        anImport.setEntId(LoginUserHolder.getEntId());
        anImport.setUrl(returnFileInfo.getFilePath());
        anImport.setId(new IdWorker(NumberConstant.ONE).nextId());
        anImport.setRemark(JSON.toJSONString(returnFileInfo));
        anImport.setStatus(0);
        anImport.setCreateBy(LoginUserHolder.getUserId());
        anImport.setCreateTime(date);
        anImport.setUpdateBy(LoginUserHolder.getUserId());
        anImport.setUpdateTime(date);
        anImport.setDelFlag(0);
        logisticsOrderImportMapper.insert(anImport);
    }

    private void pushMessage(List<Map<String, Object>> messageList, Integer number) {
        for (Map<String, Object> objectMap : messageList) {
            //托运
            String consignId = objectMap.get("consignId").toString();
            String consignName = objectMap.get("consignName").toString();
            String consignContactsId = objectMap.get("consignContactsId").toString();
            String consignContacts = objectMap.get("consignContacts").toString();
            String consignPhone = objectMap.get("consignPhone").toString();
            //承运
            String acceptId = objectMap.get("acceptId").toString();
            String acceptName = objectMap.get("acceptName").toString();
            String acceptContactsId = objectMap.get("acceptContactsId").toString();
            String acceptContacts = objectMap.get("acceptContacts").toString();
            String acceptPhone = objectMap.get("acceptPhone").toString();
            /**发送信息至消息列表*/

            //托运单位
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(Long.parseLong(consignId));
            KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
            consignUnit.setUnitType(NumberConstant.ONE);
            consignUnit.setEntId(Long.parseLong(consignId));
            consignUnit.setTopEntId(entCacheResDto == null ? null : entCacheResDto.getId());
            consignUnit.setFirmName(consignName);
            consignUnit.setContactsId(Long.parseLong(consignContactsId));

            //承运单位
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(Long.parseLong(acceptId));
            KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
            carriageUnit.setUnitType(NumberConstant.TWO);
            carriageUnit.setEntId(Long.parseLong(acceptId));
            carriageUnit.setTopEntId(entCacheResDto1 == null ? null : entCacheResDto1.getId());
            carriageUnit.setFirmName(acceptName);
            carriageUnit.setContactsId(Long.parseLong(acceptContactsId));
            commonService.importExcelToMessage(consignUnit, carriageUnit, String.valueOf(number), LoginUserHolder.getUserId(), LoginUserHolder.getEntId()
                    , messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl()
                    , messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl()
                    , MessageEnum.ACCEPT_CARRIAGE_IMPORT_EXCEL, MessageEnum.CONSIGN_IMPORT_EXCEL
                    , "1"
            );
        }
    }

    /**
     * 数据存储
     *
     * @param driverExcels 导入文件数据
     */
    private void saveExternalImportExcel(List<LogisticsOrderExcelImportDTO> driverExcels) {

        //商品分类
        Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.INDUSTRY_TYPE.getType());
        Map<String, SysDictResDto> goodsModel = dictResDtoMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        //计费方式
        Map<String, SysDictResDto> chargingTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.CHARGING_TYPE.getType());
        Map<String, SysDictResDto> chargingType = chargingTypeMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        //运价方式/扣亏货值
        Map<String, SysDictResDto> priceTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.PRICE_TYPE.getType());
        Map<String, SysDictResDto> priceTypeEnum = priceTypeMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        //结算周期
        Map<String, SysDictResDto> settlementCycleMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        Map<String, SysDictResDto> settlementCycleEnum = settlementCycleMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        //支付方式
        Map<String, SysDictResDto> tradeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
        Map<String, SysDictResDto> tradeEnum = tradeMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        //计量单位
        Map<String, SysDictResDto> unitTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.UNIT_TYPE.getType());
        Map<String, SysDictResDto> unitTypeEnum = unitTypeMap.values().stream().collect(Collectors.toMap(SysDictResDto::getLabel, v -> v));

        int number = 0;
        for (LogisticsOrderExcelImportDTO excelImport : driverExcels) {
            number = number + 1;
            commonService.getRedisGenerateOrderNo();
            /**生成订单编号*/
            String lOrderNo = OrderGenerateSeqNoUtils.getSeqNo(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER, "2", "0", "0");
            HttpResult httpResult = ValidUtil.serviceValid(excelImport);
            if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
                throw new RuntimeException(httpResult.getMsg());
            }
            String consignCompany = excelImport.getConsignCompany().trim();
            KwsEnterpriseResDto consignEnterprise = remoteSystemService.findEnterpriseByName(consignCompany);
            String acceptCarriageCompany = excelImport.getAcceptCarriageCompany().trim();
            KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);
            List<FindEntCooperateResVo> entCooperate = remoteManageService.findEntCooperate(acceptCarriageEnterprise.getId(), consignEnterprise.getId(), CooperateTypeEnum.CONSIGN.getCode());
            if (entCooperate == null) {
                throw new RuntimeException("第" + number + "行,该托运企业与我方并无合作关系!");
            }
            /**保存新建数据*/
            Long lOrderId = new IdWorker(NumberConstant.ONE).nextId();
            /**根据合同计算当前单据状态*/
            /**判断生成物流订单应生成哪一种单据状态*/
            String contractNo = excelImport.getContract().trim();
            ContractLogisticsOrderResDto commonInfoResDto = remoteContractService.getContractByContractNo(contractNo, acceptCarriageEnterprise.getId(), consignEnterprise.getId());
            /**状态判断
             * 是否是已签约合同
             * */
            // 0 已签约 1待签约
            Integer status = commonInfoResDto.getStatus();
            Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
            if (NumberConstant.ONE == status) {
                orderStatus = LogisticsOrderEnum.TO_BE_PLANNED.getCode();
            } else if (NumberConstant.ZERO == status) {
                orderStatus = LogisticsOrderEnum.WAIT_DELIVERY.getCode();
            } else {
                log.info("导入订单异常,合同状态:{}", status);
                throw new BusinessException("导入订单异常");
            }
            saveLogisticsOrder(excelImport, lOrderId, orderStatus, lOrderNo, chargingType, priceTypeEnum, settlementCycleEnum, tradeEnum, unitTypeEnum);
            saveLogisticsOrderAddress(excelImport, lOrderId);
            saveLogisticsOrderGoods(excelImport, lOrderId, lOrderNo);
            saveLogisticsOrderContract(excelImport, lOrderId, commonInfoResDto);
            saveLogisticsOrderTrack(lOrderId, orderStatus);
            saveLogisticsOrderUnit(excelImport, lOrderId);
            //目前物流订单未使用MongoDB
//            saveMongoDb(excelImport, orderStatus, lOrderId, lOrderNo, commonInfoResDto);
//            /**发送信息至消息列表*/
//            //托运单位
//            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(consignEnterprise.getId());
//            KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
//            consignUnit.setUnitType(NumberConstant.ONE);
//            consignUnit.setEntId(consignEnterprise.getId());
//            consignUnit.setTopEntId(entCacheResDto == null ? null : entCacheResDto.getId());
//            consignUnit.setFirmName(excelImport.getConsignCompany());
//            consignUnit.setContactsId(consignEnterprise.getContacts());
//
//            //承运单位
//            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(Long.parseLong(orderDTO.getAcceptCompanyId()));
//            KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
//            carriageUnit.setUnitType(NumberConstant.TWO);
//            carriageUnit.setEntId(Long.parseLong(orderDTO.getAcceptCompanyId()));
//            carriageUnit.setTopEntId(entCacheResDto1 == null ? null : entCacheResDto1.getId());
//            carriageUnit.setFirmName(orderDTO.getAcceptCompany());
//            carriageUnit.setContactsId(Long.parseLong(orderDTO.getAcceptContactsId()));
//            commonService.newSendLogisticsOrderToMessage(consignUnit, carriageUnit, lOrderNo, LoginUserHolder.getUserId(), LoginUserHolder.getEntId()
//                    , messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl()
//                    , messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl()
//                    , MessageEnum.NEW_LOGISTICS_ORDER, MessageEnum.NEW_CARRIAGE_ORDER
//                    , "1"
//            );
        }

    }

    /**
     * 物流订单单位
     *
     * @param excelImport
     * @param lOrderId
     */
    private void saveLogisticsOrderUnit(LogisticsOrderExcelImportDTO excelImport, Long lOrderId) {
        //托运
        String consignCompany = excelImport.getConsignCompany().trim();
        KwsEnterpriseResDto consignEnterprise = remoteSystemService.findEnterpriseByName(consignCompany);
        //承运
        String acceptCarriageCompany = excelImport.getAcceptCarriageCompany().trim();
        KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);

        //托运
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignUnit.setLOrderId(lOrderId);
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(consignEnterprise.getId());
        List<Long> entIds = new ArrayList<>();
        entIds.add(consignEnterprise.getId());
        entIds.add(acceptCarriageEnterprise.getId());
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(entIds);
        EntCacheResDto ent = entMap.get(consignEnterprise.getId());
        if (Objects.isNull(ent)) {
            throw new BusinessException("企业:" + excelImport.getConsignCompany() + "的一级企业信息不存在！");
        }
        FindCooperateByEntReqVo vo = new FindCooperateByEntReqVo();
        vo.setEntId(acceptCarriageEnterprise.getId());
        vo.setTargetEntId(consignEnterprise.getId());
        vo.setCooperateType(3);
        List<FindCooperateByEntResVo> cooperateByEnt = remoteManageService.findCooperateByEnt(vo);
        if (cooperateByEnt.size() > 0 && cooperateByEnt.size() == 1) {
            FindCooperateByEntResVo findCooperateByEntResVo = cooperateByEnt.get(0);
            consignUnit.setContacts(findCooperateByEntResVo.getTargetContacts());
            consignUnit.setPhone(findCooperateByEntResVo.getTargetPhone());
            consignUnit.setContactsId(findCooperateByEntResVo.getTargetContactsId());
        }
        consignUnit.setTopEntId(ent.getId());
        consignUnit.setFirmName(excelImport.getConsignCompany());
        consignUnit.setStatus(NumberConstant.ZERO);
        consignUnit.setCreateBy(LoginUserHolder.getUserId());
        consignUnit.setCreateTime(new Date());
        consignUnit.setUpdateBy(LoginUserHolder.getUserId());
        consignUnit.setUpdateTime(new Date());
        //承运
        KwtLogisticsOrderUnit unit = new KwtLogisticsOrderUnit();
        unit.setId(new IdWorker(NumberConstant.TWO).nextId());
        unit.setLOrderId(lOrderId);
        unit.setUnitType(NumberConstant.TWO);
        unit.setEntId(acceptCarriageEnterprise.getId());
        EntCacheResDto ent1 = entMap.get(acceptCarriageEnterprise.getId());
        if (Objects.isNull(ent1)) {
            throw new BusinessException("企业:" + excelImport.getAcceptCarriageCompany() + "的一级企业信息不存在！");
        }
        if (cooperateByEnt.size() > 0 && cooperateByEnt.size() == 1) {
            FindCooperateByEntResVo findCooperateByEntResVo = cooperateByEnt.get(0);
            unit.setContacts(findCooperateByEntResVo.getContacts());
            unit.setPhone(findCooperateByEntResVo.getPhone());
            unit.setContactsId(findCooperateByEntResVo.getContactsId());
        }
        unit.setTopEntId(ent1.getId());
        unit.setFirmName(acceptCarriageEnterprise.getFirmName());
        unit.setRemark("");
        unit.setStatus(NumberConstant.ZERO);
        unit.setCreateBy(LoginUserHolder.getUserId());
        unit.setCreateTime(new Date());
        unit.setUpdateBy(LoginUserHolder.getUserId());
        unit.setUpdateTime(new Date());
        logisticsOrderUnitMapper.insert(consignUnit);
        logisticsOrderUnitMapper.insert(unit);
    }

    /**
     * 物流订单-状态信息
     *
     * @param lOrderId
     * @param orderStatus
     */
    private void saveLogisticsOrderTrack(Long lOrderId, Integer orderStatus) {
        KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
        track.setId(new IdWorker(NumberConstant.ONE).nextId());
        track.setLOrderId(lOrderId);
        track.setStatus(orderStatus);
        track.setCreateBy(LoginUserHolder.getUserId());
        track.setCreateTime(new Date());
        track.setUpdateBy(LoginUserHolder.getUserId());
        track.setUpdateTime(new Date());
        logisticsOrderTrackMapper.insert(track);
    }

    /**
     * 保存合同信息
     *
     * @param excelImport
     * @param lOrderId
     * @param commonInfoResDto
     */
    private void saveLogisticsOrderContract(LogisticsOrderExcelImportDTO excelImport, Long lOrderId, ContractLogisticsOrderResDto commonInfoResDto) {
        KwtLogisticsOrderContract contract = new KwtLogisticsOrderContract();
        contract.setId(new IdWorker(NumberConstant.ONE).nextId());
        contract.setContractId(commonInfoResDto.getId());
        contract.setLOrderId(lOrderId);
        contract.setContractNo(excelImport.getContract());
        contract.setContractName(commonInfoResDto.getContactName());
        contract.setSigningWay(String.valueOf(commonInfoResDto.getSigningWay()));
        contract.setStatus(NumberConstant.ZERO);
        contract.setCreateBy(LoginUserHolder.getUserId());
        contract.setCreateTime(new Date());
        contract.setUpdateBy(LoginUserHolder.getUserId());
        contract.setUpdateTime(new Date());
        kwtLogisticsOrderContractMapper.insert(contract);
    }

    /**
     * 保存商品信息
     *
     * @param excelImport
     * @param lOrderId
     * @param lOrderNo
     */
    private void saveLogisticsOrderGoods(LogisticsOrderExcelImportDTO excelImport, Long lOrderId, String lOrderNo) {
        String goodsName = excelImport.getGoodsName().trim();
//        KwpGoods kwpGoods = goodsInfoService.getGoodsByGoodsName(goodsName);
        KwtLogisticsOrderGoods goods = new KwtLogisticsOrderGoods();
        goods.setId(new IdWorker(NumberConstant.ONE).nextId());
        goods.setLOrderId(lOrderId);
        goods.setLOrderNo(lOrderNo);
        goods.setGoodsName(goodsName);
//        goods.setGoodsType(kwpGoods.getGoodsType());
        goods.setStatus(NumberConstant.ZERO);
        goods.setCreateBy(LoginUserHolder.getUserId());
        goods.setCreateTime(new Date());
        goods.setUpdateBy(LoginUserHolder.getUserId());
        goods.setUpdateTime(new Date());
        goodsMapper.insert(goods);
    }

    /**
     * 保存地址信息
     *
     * @param excelImport
     * @param lOrderId
     */
    private void saveLogisticsOrderAddress(LogisticsOrderExcelImportDTO excelImport, Long lOrderId) {
        String loadAddressName = excelImport.getLoadAddress();
        String unloadAddressName = excelImport.getUnloadAddress();
        String acceptCarriageCompany = excelImport.getAcceptCarriageCompany().trim();
        KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);
        Long id = acceptCarriageEnterprise.getId();
        List<Long> idsList = new ArrayList<>();
        idsList.add(id);
        Map<Long, EntCacheResDto> entTreeByIds = remoteSystemService.queryEntTreeByIds(Collections.singletonList(id));
        if (entTreeByIds != null && entTreeByIds.get(id) != null) {
            idsList.add(entTreeByIds.get(id).getId());
        }
        idsList = idsList.stream().distinct().collect(Collectors.toList());
        Map<Long, List<EntAddressResDto>> longListMap = remoteManageService.queryEntAddressByEntIdList(idsList);
        List<EntAddressResDto> addressRes = longListMap.get(id);
        if (CollectionUtils.isNotEmpty(addressRes)) {
            Map<String, EntAddressResDto> addressMap = addressRes.stream().collect(Collectors.toMap(EntAddressResDto::getName, v -> v));
            /**装货地址*/
            KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
            loadAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
            loadAddress.setLOrderId(lOrderId);
            loadAddress.setAddressType(NumberConstant.ONE);
            if (addressMap != null && addressMap.get(loadAddressName) != null) {
                EntAddressResDto entAddressResDto = addressMap.get(loadAddressName);
                loadAddress.setName(entAddressResDto.getName());
                loadAddress.setContacts(entAddressResDto.getContacts());
                loadAddress.setPhone(entAddressResDto.getPhone());
                loadAddress.setCityCode(entAddressResDto.getCityCode());
                loadAddress.setCityName(entAddressResDto.getCityName());
                loadAddress.setDetailAddress(entAddressResDto.getDetailAddress());
                loadAddress.setLat(entAddressResDto.getLat());
                loadAddress.setLng(entAddressResDto.getLng());
                loadAddress.setEntryType(NumberConstant.FOUR);
                loadAddress.setStatus(NumberConstant.ZERO);
                loadAddress.setCreateBy(LoginUserHolder.getUserId());
                Date date = new Date();
                loadAddress.setCreateTime(date);
                loadAddress.setUpdateBy(LoginUserHolder.getUserId());
                loadAddress.setUpdateTime(date);
                logisticsOrderAddressMapper.insert(loadAddress);
            }
            /**卸货地址*/
            KwtLogisticsOrderAddress unloadAddress = new KwtLogisticsOrderAddress();
            unloadAddress.setId(new IdWorker(NumberConstant.TWO).nextId());
            unloadAddress.setLOrderId(lOrderId);
            unloadAddress.setAddressType(NumberConstant.TWO);
            if (addressMap != null && addressMap.get(unloadAddressName) != null) {
                EntAddressResDto entAddressResDto = addressMap.get(unloadAddressName);
                unloadAddress.setName(entAddressResDto.getName());
                unloadAddress.setContacts(entAddressResDto.getContacts());
                unloadAddress.setPhone(entAddressResDto.getPhone());
                unloadAddress.setCityCode(entAddressResDto.getCityCode());
                unloadAddress.setCityName(entAddressResDto.getCityName());
                unloadAddress.setDetailAddress(entAddressResDto.getDetailAddress());
                unloadAddress.setLat(entAddressResDto.getLat());
                unloadAddress.setLng(entAddressResDto.getLng());
                unloadAddress.setEntryType(NumberConstant.FOUR);
                unloadAddress.setStatus(NumberConstant.ZERO);
                unloadAddress.setCreateBy(LoginUserHolder.getUserId());
                Date date = new Date();
                unloadAddress.setCreateTime(date);
                unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
                unloadAddress.setUpdateTime(date);
                logisticsOrderAddressMapper.insert(unloadAddress);
            }
            /**按照装卸货地址类型 存储地址*/
//            insertOrderAddress(addressRes,lOrderId,loadAddressName,unloadAddressName);

        }
    }

    /**
     * 按照装卸货地址类型 存储地址
     *
     * @param addressRes
     * @param lOrderId
     * @param loadAddressName
     * @param unloadAddressName
     */
    private void insertOrderAddress(List<EntAddressResDto> addressRes, Long lOrderId, String loadAddressName, String unloadAddressName) {
        Map<Integer, List<EntAddressResDto>> collect = addressRes.stream().collect(Collectors.groupingBy(EntAddressResDto::getDefaultType));
        List<EntAddressResDto> loadAddressRes = collect.get(AddressTypeEnum.SHIPMENT.getCode());
        Map<String, EntAddressResDto> loadAddressMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(loadAddressRes)) {
            loadAddressMap = loadAddressRes.stream().collect(Collectors.toMap(EntAddressResDto::getName, v -> v));
        }
        List<EntAddressResDto> unloadAddressRes = collect.get(AddressTypeEnum.TAKE.getCode());
        Map<String, EntAddressResDto> unloadAddressMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(unloadAddressRes)) {
            unloadAddressMap = unloadAddressRes.stream().collect(Collectors.toMap(EntAddressResDto::getName, v -> v));
        }
        List<EntAddressResDto> allAddressRes = collect.get(AddressTypeEnum.BOTH.getCode());
        Map<String, EntAddressResDto> allAddressResMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(allAddressRes)) {
            allAddressResMap = allAddressRes.stream().collect(Collectors.toMap(EntAddressResDto::getName, v -> v));
        }
        /**装货地址*/
        KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
        loadAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
        loadAddress.setLOrderId(lOrderId);
        loadAddress.setAddressType(NumberConstant.ONE);
        if (loadAddressMap != null || allAddressResMap != null) {
            EntAddressResDto entAddressResDto = loadAddressMap.get(loadAddressName);
            EntAddressResDto entAddressResDto1 = allAddressResMap.get(loadAddressName);
            if (entAddressResDto == null) {
                if (entAddressResDto1.getName().equals(loadAddressName)) {
                    loadAddress.setName(entAddressResDto1.getName());
                    loadAddress.setContacts(entAddressResDto1.getContacts());
                    loadAddress.setPhone(entAddressResDto1.getPhone());
                    loadAddress.setCityCode(entAddressResDto1.getCityCode());
                    loadAddress.setCityName(entAddressResDto1.getCityName());
                    loadAddress.setDetailAddress(entAddressResDto1.getDetailAddress());
                    loadAddress.setLat(entAddressResDto1.getLat());
                    loadAddress.setLng(entAddressResDto1.getLng());
                }
            } else {
                if (entAddressResDto.getName().equals(loadAddressName)) {
                    loadAddress.setName(entAddressResDto.getName());
                    loadAddress.setContacts(entAddressResDto.getContacts());
                    loadAddress.setPhone(entAddressResDto.getPhone());
                    loadAddress.setCityCode(entAddressResDto.getCityCode());
                    loadAddress.setCityName(entAddressResDto.getCityName());
                    loadAddress.setDetailAddress(entAddressResDto.getDetailAddress());
                    loadAddress.setLat(entAddressResDto.getLat());
                    loadAddress.setLng(entAddressResDto.getLng());
                }
            }
            loadAddress.setEntryType(NumberConstant.FOUR);
            loadAddress.setStatus(NumberConstant.ZERO);
            loadAddress.setCreateBy(LoginUserHolder.getUserId());
            Date date = new Date();
            loadAddress.setCreateTime(date);
            loadAddress.setUpdateBy(LoginUserHolder.getUserId());
            loadAddress.setUpdateTime(date);
            logisticsOrderAddressMapper.insert(loadAddress);
        }

        /**卸货地址*/
        KwtLogisticsOrderAddress unloadAddress = new KwtLogisticsOrderAddress();
        unloadAddress.setId(new IdWorker(NumberConstant.TWO).nextId());
        unloadAddress.setLOrderId(lOrderId);
        unloadAddress.setAddressType(NumberConstant.TWO);
        if (unloadAddressMap != null || allAddressResMap != null) {
            EntAddressResDto entAddressResDto = unloadAddressMap.get(unloadAddressName);
            EntAddressResDto entAddressResDto1 = allAddressResMap.get(unloadAddressName);
            if (entAddressResDto == null) {
                if (entAddressResDto1.getName().equals(unloadAddressName)) {
                    unloadAddress.setName(entAddressResDto1.getName());
                    unloadAddress.setContacts(entAddressResDto1.getContacts());
                    unloadAddress.setPhone(entAddressResDto1.getPhone());
                    unloadAddress.setCityCode(entAddressResDto1.getCityCode());
                    unloadAddress.setCityName(entAddressResDto1.getCityName());
                    unloadAddress.setDetailAddress(entAddressResDto1.getDetailAddress());
                    unloadAddress.setLat(entAddressResDto1.getLat());
                    unloadAddress.setLng(entAddressResDto1.getLng());
                }
            } else {
                if (entAddressResDto.getName().equals(unloadAddressName)) {
                    unloadAddress.setName(entAddressResDto.getName());
                    unloadAddress.setContacts(entAddressResDto.getContacts());
                    unloadAddress.setPhone(entAddressResDto.getPhone());
                    unloadAddress.setCityCode(entAddressResDto.getCityCode());
                    unloadAddress.setCityName(entAddressResDto.getCityName());
                    unloadAddress.setDetailAddress(entAddressResDto.getDetailAddress());
                    unloadAddress.setLat(entAddressResDto.getLat());
                    unloadAddress.setLng(entAddressResDto.getLng());
                }
            }
            unloadAddress.setEntryType(NumberConstant.FOUR);
            unloadAddress.setStatus(NumberConstant.ZERO);
            unloadAddress.setCreateBy(LoginUserHolder.getUserId());
            Date date = new Date();
            unloadAddress.setCreateTime(date);
            unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
            unloadAddress.setUpdateTime(date);
            logisticsOrderAddressMapper.insert(unloadAddress);
        }
    }

    /**
     * @param excelImport         导入文件
     * @param lOrderId            订单id
     * @param orderStatus         订单状态
     * @param lOrderNo            订单号
     * @param chargingType        计费方式
     * @param priceTypeEnum       运价方式/扣亏货值
     * @param settlementCycleEnum 结算周期
     * @param tradeEnum           支付方式
     */
    private void saveLogisticsOrder(LogisticsOrderExcelImportDTO excelImport, Long lOrderId, Integer orderStatus,
                                    String lOrderNo
            , Map<String, SysDictResDto> chargingType
            , Map<String, SysDictResDto> priceTypeEnum
            , Map<String, SysDictResDto> settlementCycleEnum
            , Map<String, SysDictResDto> tradeEnum
            , Map<String, SysDictResDto> unitTypeEnum
    ) {
        KwtLogisticsOrder order = new KwtLogisticsOrder();
        order.setId(lOrderId);
        order.setEntId(LoginUserHolder.getEntId());
        order.setType(String.valueOf(NumberConstant.TWO));
        order.setLOrderNo(lOrderNo);
        order.setPids(lOrderId.toString());
        String settlementCycle = excelImport.getSettlementCycle().trim();
        order.setSettlementCycle(settlementCycleEnum.get(settlementCycle) == null ? null : Long.parseLong(settlementCycleEnum.get(settlementCycle).getValue()));
        String billingMode = excelImport.getBillingMode().trim();
        order.setBillingMode(chargingType.get(billingMode) == null ? null : chargingType.get(billingMode).getValue());
        order.setPrice(excelImport.getPrice());
        String priceType = excelImport.getPriceType().trim();
        order.setPriceType(priceTypeEnum.get(priceType) == null ? null : Long.parseLong(priceTypeEnum.get(priceType).getValue()));
        String payment = excelImport.getPayment().trim();
        order.setPayment(tradeEnum.get(payment) == null ? null : Long.parseLong(tradeEnum.get(payment).getValue()));
        order.setAmount(excelImport.getAmount());
        String amountUnit = excelImport.getAmountUnit().trim();
        order.setUnit(unitTypeEnum.get(amountUnit) == null ? null : unitTypeEnum.get(amountUnit).getValue());
        order.setLoss(excelImport.getLoss() == null ? null : excelImport.getLoss());
        //当前合理损耗  文档导入默认使用 千分比 ‰
        order.setLossUnit(String.valueOf(TaxRateTypeEnum.PERCENT.getCode()));
        order.setGoodsPrice(excelImport.getGoodsPrice() == null ? null : excelImport.getGoodsPrice());
        if (excelImport.getGoodsPriceUnit() != null) {
            String goodsPriceUnit = excelImport.getGoodsPriceUnit().trim();
            order.setGoodsPriceUnit(priceTypeEnum.get(goodsPriceUnit) == null ? null : priceTypeEnum.get(goodsPriceUnit).getValue());
        } else {
            order.setGoodsPriceUnit("元/" + excelImport.getAmountUnit().trim());
        }
        order.setStartTime(org.apache.commons.lang3.ObjectUtils.isEmpty(excelImport.getStartTime()) ?
                null : DateUtil.strToTime(excelImport.getStartTime() + " 00:00:00"));
        order.setEndTime(org.apache.commons.lang3.ObjectUtils.isEmpty(excelImport.getEndTime()) ?
                null : DateUtil.strToTime(excelImport.getEndTime() + " 23:59:00"));
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        order.setSubcontractAmount(decimal);
        order.setEntrustAmount(decimal);
        order.setUnloadAmount(decimal);
        order.setLoadAmount(decimal);
        order.setIgnoreAmount(decimal);
        order.setDeficitAmount(decimal);
        order.setDeficitPrice(decimal);
        order.setTaxRate(excelImport.getTaxRate());
        order.setRemark(excelImport.getRemark());
        order.setStatus(orderStatus);
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateTime(new Date());
        order.setBindStatus(String.valueOf(NumberConstant.ZERO));
        order.setTotalUnloadAmount(decimal);
        order.setTotalLoadAmount(decimal);
        logisticsOrderMapper.insert(order);
    }

    /**
     * 文件填写数据校验
     *
     * @param driverExcels 导入文件数据检验
     */
    private void checkDataFormat(List<LogisticsOrderExcelImportDTO> driverExcels, List<Map<String, Object>> messageList) {
        //商品分类
        Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.INDUSTRY_TYPE.getType());
        List<String> goodsModel = dictResDtoMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());

        //计费方式
        Map<String, SysDictResDto> chargingTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.CHARGING_TYPE.getType());
        List<String> chargingType = chargingTypeMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());

        //运价方式/扣亏货值
        Map<String, SysDictResDto> priceTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.PRICE_TYPE.getType());
        List<String> priceTypeEnum = priceTypeMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());

        //结算周期
        Map<String, SysDictResDto> settlementCycleMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        List<String> settlementCycleEnum = settlementCycleMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());

        //支付方式
        Map<String, SysDictResDto> tradeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
        List<String> tradeEnum = tradeMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());

        //计量单位
        Map<String, SysDictResDto> unitTypeMap = remoteSystemService.queryDictMapByType(DictTypeEnum.UNIT_TYPE.getType());
        List<String> unitTypeEnum = unitTypeMap.values().stream().map(SysDictResDto::getLabel).distinct().collect(Collectors.toList());


        int number = 3;
        for (int i = 0; i < driverExcels.size(); i++) {
            number = number + 1;
            LogisticsOrderExcelImportDTO excelImport = driverExcels.get(i);
            String consignCompany = excelImport.getConsignCompany().trim();
            KwsEnterpriseResDto consignEnterprise = remoteSystemService.findEnterpriseByName(consignCompany);
            if (consignEnterprise == null) {
                throw new RuntimeException("第" + number + "行托运企业不存在!");
            }
            String acceptCarriageCompany = excelImport.getAcceptCarriageCompany().trim();
            KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);
            if (acceptCarriageEnterprise == null) {
                throw new RuntimeException("第" + number + "行承运企业不存在!");
            }

            FindCooperateByEntReqVo vo = new FindCooperateByEntReqVo();
            vo.setEntId(acceptCarriageEnterprise.getId());
            vo.setTargetEntId(consignEnterprise.getId());
            vo.setCooperateType(3);
            List<FindCooperateByEntResVo> cooperateByEnt = remoteManageService.findCooperateByEnt(vo);
            if (cooperateByEnt.size() < 1) {
                throw new RuntimeException("第" + number + "行承运企业与托运企业不存在合作关系!");
            }

            String goodsName = excelImport.getGoodsName().trim();
            if (StringUtils.isBlank(goodsName)) {
                throw new RuntimeException("第" + number + "行货物信息必填写");
            }
//            KwpGoods goods = goodsInfoService.getGoodsByGoodsName(goodsName);
//            if (goods == null || goods.getId() == null) {
//                throw new RuntimeException("第" + number + "行货物信息不存在");
//            }
            String goodsModelType = excelImport.getGoodsModel().trim();
            if (!goodsModel.contains(goodsModelType)) {
                throw new RuntimeException("第" + number + "行商品分类信息不存在");
            }
            String contractNo = excelImport.getContract().trim();
            ContractLogisticsOrderResDto commonInfoResDto = remoteContractService.getContractByContractNo(contractNo, acceptCarriageEnterprise.getId(), consignEnterprise.getId());
            if (commonInfoResDto == null || (commonInfoResDto.getId() == null)) {
                throw new RuntimeException("第" + number + "行合同信息不存在");
            }
            if (commonInfoResDto.getConsignEntName() == null) {
                throw new RuntimeException("第" + number + "行合同信息托运企业不存在");
            }
            if (!commonInfoResDto.getConsignEntName().equals(consignCompany)) {
                throw new RuntimeException("第" + number + "行合同信息的托运单位并非该[" + consignCompany + "]托运企业");
            }
            if (commonInfoResDto.getAcceptCarriageEntName() == null) {
                throw new RuntimeException("第" + number + "行合同信息承运企业不存在");
            }
            if (!commonInfoResDto.getAcceptCarriageEntName().equals(acceptCarriageCompany)) {
                throw new RuntimeException("第" + number + "行合同信息的托运单位并非该[" + acceptCarriageCompany + "]承运企业");
            }
            String billingMode = excelImport.getBillingMode().trim();
            if (!chargingType.contains(billingMode)) {
                throw new RuntimeException("第" + number + "行计费方式不存在");
            }
            String priceType = excelImport.getPriceType().trim();
            if (!priceTypeEnum.contains(priceType)) {
                throw new RuntimeException("第" + number + "行运价单位错误");
            }
            String amountUnit = excelImport.getAmountUnit().trim();
            if (!unitTypeEnum.contains(amountUnit)) {
                throw new RuntimeException("第" + number + "行承运量单位错误");
            }
            String goodsPriceUnit = excelImport.getGoodsPriceUnit().trim();
            if (StringUtils.isNotBlank(goodsPriceUnit)) {
                if (!priceTypeEnum.contains(goodsPriceUnit)) {
                    throw new RuntimeException("第" + number + "行扣亏货值单位错误");
                }
            }
            String settlementCycle = excelImport.getSettlementCycle().trim();
            if (!settlementCycleEnum.contains(settlementCycle)) {
                throw new RuntimeException("第" + number + "行结算周期不存在");
            }
            String payment = excelImport.getPayment().trim();
            if (!tradeEnum.contains(payment)) {
                throw new RuntimeException("第" + number + "行支付方式不存在");
            }
            String unloadAddressName = excelImport.getUnloadAddress().trim();
            String loadAddressName = excelImport.getLoadAddress().trim();
            Long id = acceptCarriageEnterprise.getId();
            List<Long> idsList = new ArrayList<>();
            idsList.add(id);
            Map<Long, EntCacheResDto> entTreeByIds = remoteSystemService.queryEntTreeByIds(Collections.singletonList(id));
            if (entTreeByIds != null && entTreeByIds.get(id) != null) {
                idsList.add(entTreeByIds.get(id).getId());
            }
            idsList = idsList.stream().distinct().collect(Collectors.toList());
            Map<Long, List<EntAddressResDto>> longListMap = remoteManageService.queryEntAddressByEntIdList(idsList);
            List<EntAddressResDto> addressRes = longListMap.get(id);
            if (CollectionUtils.isNotEmpty(addressRes)) {
                List<String> addressStr = addressRes.stream().map(EntAddressResDto::getName).collect(Collectors.toList());
                //checkOrderAddress(addressRes,loadAddressName,unloadAddressName,number);
                if (!addressStr.contains(loadAddressName)) {
                    throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该装货地址");
                }
                if (!addressStr.contains(unloadAddressName)) {
                    throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该卸货地址");
                }
            } else {
                throw new RuntimeException("第" + number + "行承运企业系统中并未维护装货地址或卸货地址");
            }
        }
        /**验证承运企业是否与当前登录账号是同一个主体机构*/
        List<Long> ids = new ArrayList<>();
        driverExcels.forEach(importExcel -> {
            String acceptCarriageCompany = importExcel.getAcceptCarriageCompany().trim();
            KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);
            if (acceptCarriageEnterprise != null) {
                Long id = acceptCarriageEnterprise.getId();
                ids.add(id);
            }
        });
        if (ids.size() > 0) {
            Map<Long, EntCacheResDto> longEntCacheResDtoMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(LoginUserHolder.getEntId()));
            if (longEntCacheResDtoMap != null) {
                List<Long> entIds = longEntCacheResDtoMap.values().stream().map(EntCacheResDto::getId).distinct().collect(Collectors.toList());
                Map<Long, EntCacheResDto> map = remoteSystemService.queryEntTreeByIds(Collections.singletonList(LoginUserHolder.getEntId()));
                if (map != null) {
                    Long loginEntId = map.get(LoginUserHolder.getEntId()).getId();
                    if (entIds.size() != 1 || (!entIds.get(0).equals(loginEntId))) {
                        throw new RuntimeException("存在有承运单位与登录账号不属于同单位!");
                    }
                } else {
                    throw new RuntimeException("存在有承运单位与登录账号不属于同单位!");
                }
            } else {
                throw new RuntimeException("存在有承运单位与登录账号不属于同单位!");
            }
        } else {
            throw new RuntimeException("存在有承运单位与登录账号不属于同单位!");
        }

        /**获取需要发送工作台消息数据*/
        driverExcels.forEach(importExcel -> {
            Map<String, String> map = new HashMap<>();
            String consignCompany = importExcel.getConsignCompany().trim();
            KwsEnterpriseResDto consignEnterprise = remoteSystemService.findEnterpriseByName(consignCompany);

            String acceptCarriageCompany = importExcel.getAcceptCarriageCompany().trim();
            KwsEnterpriseResDto acceptCarriageEnterprise = remoteSystemService.findEnterpriseByName(acceptCarriageCompany);
            String key = String.valueOf(acceptCarriageEnterprise.getId()) + String.valueOf(consignEnterprise.getId());
            if (map.get(key) == null) {
                FindCooperateByEntReqVo vo = new FindCooperateByEntReqVo();
                vo.setEntId(acceptCarriageEnterprise.getId());
                vo.setTargetEntId(consignEnterprise.getId());
                vo.setCooperateType(3);
                List<FindCooperateByEntResVo> cooperateByEnt = remoteManageService.findCooperateByEnt(vo);
                if (cooperateByEnt.size() > 0) {
                    FindCooperateByEntResVo findCooperateByEntResVo = cooperateByEnt.get(0);
                    Map<String, Object> objectMap = new HashMap<>();
                    //托运
                    objectMap.put("consignId", consignEnterprise.getId());
                    Map<Long, EntCacheResDto> entCarrierMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(consignEnterprise.getId()));
                    entCarrierMap.get(consignEnterprise.getId());
                    objectMap.put("consignTopId", entCarrierMap == null ? null :
                            (entCarrierMap.get(consignEnterprise.getId())) == null ? consignEnterprise.getId() :
                                    (entCarrierMap.get(consignEnterprise.getId())).getId());
                    objectMap.put("consignName", consignEnterprise.getFirmName());
                    objectMap.put("consignContactsId", findCooperateByEntResVo.getTargetContactsId());
                    objectMap.put("consignContacts", findCooperateByEntResVo.getTargetContacts());
                    objectMap.put("consignPhone", findCooperateByEntResVo.getTargetPhone());

                    //承运
                    objectMap.put("acceptId", acceptCarriageEnterprise.getId());
                    Map<Long, EntCacheResDto> entTreeByIds = remoteSystemService.queryEntTreeByIds(Collections.singletonList(acceptCarriageEnterprise.getId()));
                    objectMap.put("acceptTopId", entTreeByIds == null ? null :
                            (entTreeByIds.get(acceptCarriageEnterprise.getId())) == null ? acceptCarriageEnterprise.getId() :
                                    (entTreeByIds.get(acceptCarriageEnterprise.getId())).getId());
                    objectMap.put("acceptName", acceptCarriageEnterprise.getFirmName());
                    objectMap.put("acceptContactsId", findCooperateByEntResVo.getContactsId());
                    objectMap.put("acceptContacts", findCooperateByEntResVo.getContacts());
                    objectMap.put("acceptPhone", findCooperateByEntResVo.getPhone());
                    messageList.add(objectMap);
                    map.put(key, key);
                }
            }
        });
    }

    /**
     * 验证地址是不是装卸货地址类型
     *
     * @param addressRes
     * @param loadAddressName
     * @param unloadAddressName
     * @param number
     */
    private void checkOrderAddress(List<EntAddressResDto> addressRes, String loadAddressName, String unloadAddressName, int number) {
        Map<Integer, List<EntAddressResDto>> collect = addressRes.stream().collect(Collectors.groupingBy(EntAddressResDto::getDefaultType));
        List<String> loadAddress = new ArrayList<>();
        List<String> unloadAddress = new ArrayList<>();
        List<EntAddressResDto> loadAddressRes = collect.get(AddressTypeEnum.SHIPMENT.getCode());
        if (CollectionUtils.isNotEmpty(loadAddressRes)) {
            List<String> loadAddressStr = loadAddressRes.stream().map(EntAddressResDto::getName).collect(Collectors.toList());
            loadAddress.addAll(loadAddressStr);
        }
        List<EntAddressResDto> unloadAddressRes = collect.get(AddressTypeEnum.TAKE.getCode());
        if (CollectionUtils.isNotEmpty(unloadAddressRes)) {
            List<String> unloadAddressStr = unloadAddressRes.stream().map(EntAddressResDto::getName).collect(Collectors.toList());
            unloadAddress.addAll(unloadAddressStr);
        }
        List<EntAddressResDto> allAddressRes = collect.get(AddressTypeEnum.BOTH.getCode());
        if (CollectionUtils.isNotEmpty(allAddressRes)) {
            List<String> allAddress = allAddressRes.stream().map(EntAddressResDto::getName).collect(Collectors.toList());
            loadAddress.addAll(allAddress);
            unloadAddress.addAll(allAddress);
        }
        if (loadAddress.size() < 1) {
            throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该装货地址");
        }
        if (unloadAddress.size() < 1) {
            throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该卸货地址");
        }
        if (loadAddress.size() > 0) {
            loadAddress = loadAddress.stream().distinct().collect(Collectors.toList());
            if (!loadAddress.contains(loadAddressName)) {
                throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该装货地址");
            }
        }
        if (unloadAddress.size() > 0) {
            unloadAddress = unloadAddress.stream().distinct().collect(Collectors.toList());
            if (!unloadAddress.contains(unloadAddressName)) {
                throw new RuntimeException("第" + number + "行承运企业在系统中并未维护该卸货地址");
            }
        }
    }

    /**
     * @param file 上传文件
     * @desc 文件必填写校验
     **/
    public HttpResult checkImportExcel(MultipartFile file) {
        ExcelReader excelReader = null;
        try {
            /**数据校验**/
            if (ExcelUtil.checkExcel(file)) {
                return HttpResult.error("请上传Excel格式的文件！");
            }
            ExcelImportListener importListener = new ExcelImportListener();
            InputStream inputStream = file.getInputStream();
            excelReader = EasyExcel.read(inputStream, importListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(3).head(LogisticsOrderExcelImportDTO.class).build();
            excelReader.read(readSheet);
            if (importListener.getErrorList().size() > 0) {
                return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "数据格式不正确，请确认！", importListener.getErrorList());
            }
            if (importListener.getDataList().size() == 0) {
                return HttpResult.error("导入数据不能空！");
            }
            return HttpResult.ok(importListener.getDataList());
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.error("订单导入异常！");
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
    }

}
