package com.sckw.transport.service;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.res.ContractCommonInfoResDto;
import com.sckw.core.common.enums.StringConstant;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.OrderGenerateSeqNoUtils;
import com.sckw.core.utils.StringUtils;
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.utils.DateUtil;
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.FindEntCooperateResVo;
import com.sckw.manage.api.model.dto.res.LineFreightAddressRes;
import com.sckw.mongo.enums.BusinessTypeEnum;
import com.sckw.mongo.model.SckwLogisticsOrder;
import com.sckw.order.api.dubbo.RemoteTradeOrderAmountService;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.*;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.product.api.model.KwpGoods;
import com.sckw.redis.config.RedisLockUtil;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.SckwBusSum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.transport.common.config.MessageUrlConfig;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.*;
import com.sckw.transport.model.param.AddLogisticsOrderParam;
import jakarta.annotation.Resource;
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.util.ObjectUtils;

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

/**
 * @author lfdc
 * @description 物流订单Service-v4.2
 * @date 2024-03-04 11:06:07
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class KwtLogisticsOrderConsignmentService {

    @Resource
    private StreamBridge streamBridge;

    @Autowired
    RedisLockUtil redisLockUtil;

    @Autowired
    public KwtTransportCommonService transportCommonService;

    @Autowired
    KwtWaybillOrderService waybillOrderService;

    @Autowired
    KwtLogisticsOrderGoodsService logisticsOrderGoodsService;

    @Autowired
    MessageUrlConfig messageUrlConfig;

    @Autowired
    public KwtCommonService commonService;

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

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

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

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 80000)
    RemoteTradeOrderAmountService tradeOrderAmountService;

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

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

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

    @Autowired
    public KwtLogisticsOrderLineFreightRateMapper logisticsOrderLineFreightRateMapper;

    @Autowired
    public KwtLogisticsOrderContractMapper logisticsOrderContractMapper;

    @Autowired
    public KwtLogisticsOrderAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderAmountMapper logisticsOrderAmountMapper;

    @Autowired
    public KwtLogisticsOrderTrackMapper logisticsOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper logisticsOrderGoodsMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper logisticsOrderUnitMapper;

    @Autowired
    public KwtLogisticsOrderMapper logisticsOrderMapper;

    @Autowired
    public KwtWaybillOrderMapper waybillOrderMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper goodsMapper;

    /**
     * 采购订单/销售订单-物流托运-v4.2
     *
     * @param dto
     */
    @Transactional
    public void logisticsConsignmentSave(LogisticsConsignmentDto dto) {
        commonService.getRedisGenerateOrderNo();
        Long count = logisticsOrderMapper.selectCount(new LambdaQueryWrapper<KwtLogisticsOrder>().eq(KwtLogisticsOrder::getTOrderId, dto.getTOrderId()));
        String lOrderNo = OrderGenerateSeqNoUtils.getSeqNo(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER, "1", "0", String.valueOf(count + 1));
        OrderDetailRes tradeOrder = tradeOrderInfoService.getOrderDetailById(Long.parseLong(dto.getTOrderId()));
        if (tradeOrder == null) {
            log.error("订单id查找失败:{}", dto.getTOrderId());
            throw new BusinessException("贸易订单数据不存在");
        }
        KwtLogisticsOrder order = new KwtLogisticsOrder();
        if (!dto.getIsFullDose()) {
            //BigDecimal amount = tradeOrder.getAmount().subtract(tradeOrder.getEntrustAmount());
            BigDecimal amount = dto.getCarryingCapacity();
            if (dto.getCarryingCapacity() == null || amount.doubleValue() <= 0) {
                log.error("可分配量分配错误:{}", dto.getTOrderId());
                throw new BusinessException("可分配量分配必须填写大于0");
            }
            //可运量校验
            if (!logisticsOrderGoodsService.chenkLogisticsAmount(dto, tradeOrder)) {
                log.error("可分配量分配错误:{}", dto.getTOrderId());
                throw new BusinessException("可分配量分配错误");
            }
            order.setAmount(dto.getCarryingCapacity());

        } else {
            order.setAmount(dto.getCarryingCapacity());
            order.setSubcontractAmount(NumberConstant.ZERO_TWO);
        }
        //地址分配量校验
        if (!checkCarryingCapacity(dto)) {
            log.error("地址分配量与总委派量不一致");
            throw new BusinessException("地址分配量与总委派量不一致");
        }

        /**验证结算方式*/
        checkBillingMode(dto);

        Long orderId = new IdWorker(NumberConstant.ONE).nextId();
        order.setId(new IdWorker(NumberConstant.ONE).nextId());
        //List<ContractDto> contractInfo = dto.getContractInfo();
        long contractId = dto.getContractId();
        List<Long> contractList = new ArrayList<>();
        contractList.add(contractId);
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = contractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new BusinessException("物流托运-并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(contractId) == null) {
            throw new BusinessException("物流托运-并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(contractId);
        /**状态判断
         * 是否是已签约合同
         * */
        // 0 已签约 1待签约
        Integer status = infoResDto.getStatus();
        Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        if (NumberConstant.ONE == status) {
            orderStatus = LogisticsOrderEnum.TO_BE_PLANNED.getCode();
        } else if (NumberConstant.ZERO == status) {
            orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        } else {
            log.info("物流托运创建订单异常");
            throw new BusinessException("物流托运创建订单异常");
        }
        logisticsOrderGoodsService.insertLogisticsGoods(dto, lOrderNo, orderId);
        saveLogisticsOrder(dto, lOrderNo, order, tradeOrder, orderId, orderStatus);
        saveLogisticsOrderContract(dto, orderId);
        saveLogisticsOrderUnit(dto, orderId);
        saveLogisticsOrderAddressAndAmount(dto, orderId);
        saveLogisticsOrderTrack(dto, orderId, orderStatus);
        /**v4.2版本新增*/
        if (dto.getBillingMode().equals("4")) {
            saveLogisticsOrderLineFreight(dto, orderId);
        }
        saveSendMongoDB(lOrderNo, orderId, dto, tradeOrder, orderStatus);

        /**将生成的分配量->贸易订单*/
        List<GoodsLoadingParam> goodsLoading = logisticsOrderGoodsService.goodsLoadingParams(order, false);
        HttpResult httpResult = tradeOrderInfoService.createOrCancelLogisticsOrderV1(LoginUserHolder.getUserId(), LoginUserHolder.getUserName(), order.getTOrderId(), goodsLoading);
        if (httpResult.getCode() != HttpStatus.SUCCESS_CODE) {
            log.info("{}生成物流托运失败!,返回信息:{}", tradeOrder.getTOrderNo(), JSONObject.toJSONString(httpResult));
            throw new BusinessException("{" + tradeOrder.getTOrderNo() + "}生成物流托运失败!" + httpResult.getMsg());
        }
        long tOrderId = Long.parseLong(dto.getTOrderId());
        List<AddressInfoDto> addressInfo = dto.getAddressInfo();
        addressInfo.forEach(addressInfoDto -> {
            UpdateAddressEntrustAmountParam param = new UpdateAddressEntrustAmountParam();
            param.setTOrderId(tOrderId);
            param.setTAddressId(Long.parseLong(addressInfoDto.getAddressId()));
            param.setEntrustAmount(addressInfoDto.getAmount());
            param.setUpdateBy(LoginUserHolder.getUserId());
            param.setUpdateByName(LoginUserHolder.getUserName());
            HttpResult result = tradeOrderAmountService.updateAddressEntrustAmount(param);
            if (result.getCode() != HttpStatus.SUCCESS_CODE) {
                log.info("{}生成物流托运失败!,返回信息:{}", tradeOrder.getTOrderNo(), JSONObject.toJSONString(httpResult));
                throw new BusinessException("{" + tradeOrder.getTOrderNo() + "}生成物流托运失败!" + httpResult.getMsg());
            }
        });
        pushConsoleMessage(dto, lOrderNo);
    }

    /**
     * @param dto 参数
     * @desc 校验地址分配量与总委托量是否一致
     * @author zk
     * @date 2024/4/2
     **/
    private boolean checkCarryingCapacity(LogisticsConsignmentDto dto) {
        //地址信息
        List<AddressInfoDto> addressInfo = dto.getAddressInfo();
        //装货地址-委派量
        BigDecimal loadAmount = addressInfo.stream().map(s -> s.getAddressType() == AddressTypeEnum.SHIPMENT.getCode()
                ? s.getAmount() : BigDecimal.ZERO).reduce(BigDecimal.ZERO, BigDecimal::add);
        //卸货地址-委派量
        BigDecimal unloadAmount = addressInfo.stream().map(s -> s.getAddressType() == AddressTypeEnum.TAKE.getCode()
                ? s.getAmount() : BigDecimal.ZERO).reduce(BigDecimal.ZERO, BigDecimal::add);
        //总委派量
        BigDecimal carryingCapacity = dto.getCarryingCapacity();
        return loadAmount.doubleValue() == carryingCapacity.doubleValue() && unloadAmount.doubleValue() == carryingCapacity.doubleValue();
    }

    private boolean checkBillingMode(LogisticsConsignmentDto dto) {
        if ("4".equals(dto.getBillingMode())) {
            if (dto.getLineFreightList().size() < 1 || CollectionUtils.isEmpty(dto.getLineFreightList())) {
                throw new BusinessException("计费方式为里程计算时,线路不能为空");
            }
        }
        return true;
    }

    private void saveLogisticsOrderLineFreight(LogisticsConsignmentDto dto, Long orderId) {
        List<LineFreightDto> lineFreightList = dto.getLineFreightList();
        Map<Long, BigDecimal> lineFreightMap = lineFreightList.stream().collect(Collectors.toMap(LineFreightDto::getLineFreightId, LineFreightDto::getAmount));
        List<Long> lineFreightId = lineFreightList.stream().map(t -> t.getLineFreightId()).distinct().collect(Collectors.toList());
        Map<Long, LineFreightAddressRes> resMap = manageService.findLineFreightAddress(lineFreightId);
        if (resMap != null) {
            lineFreightId.stream().forEach(id -> {
                if (resMap.get(id) != null) {
                    LineFreightAddressRes res = resMap.get(id);
                    KwtLogisticsOrderLineFreightRate lineFreightRate = new KwtLogisticsOrderLineFreightRate();
                    lineFreightRate.setLineFreightRateId(res.getId());
                    lineFreightRate.setLOrderId(orderId);
                    lineFreightRate.setName(res.getName());
                    lineFreightRate.setLoadName(res.getLoadName());
                    lineFreightRate.setLoadCityCode(res.getLoadCityCode());
                    lineFreightRate.setLoadCityName(res.getLoadCityName());
                    lineFreightRate.setLoadDetailAddress(res.getLoadDetailAddress());
                    lineFreightRate.setLoadLat(res.getLoadLat());
                    lineFreightRate.setLoadLng(res.getLoadLng());
                    lineFreightRate.setUnloadName(res.getUnloadName());
                    lineFreightRate.setUnloadCityCode(res.getUnloadCityCode());
                    lineFreightRate.setUnloadCityName(res.getUnloadCityName());
                    lineFreightRate.setUnloadDetailAddress(res.getUnloadDetailAddress());
                    lineFreightRate.setUnloadLat(res.getUnloadLat());
                    lineFreightRate.setUnloadLng(res.getUnloadLng());
                    lineFreightRate.setTransportMileage(res.getTransportMileage());
                    lineFreightRate.setTransportPrice(res.getTransportPrice());
                    BigDecimal defultBigDecimal = new BigDecimal("0.00");
                    lineFreightRate.setSettlementAmount(defultBigDecimal);
                    lineFreightRate.setTransportAmount(lineFreightMap.get(id));
                    lineFreightRate.setId(new IdWorker(NumberConstant.FOUR).nextId());
                    lineFreightRate.setRemark(res.getRemark());
                    lineFreightRate.setStatus(res.getStatus());
                    lineFreightRate.setCreateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setCreateTime(new Date());
                    lineFreightRate.setUpdateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setUpdateTime(new Date());
                    lineFreightRate.setDelFlag(0);
                    logisticsOrderLineFreightRateMapper.insert(lineFreightRate);
                }
            });
        }

    }

    private void saveSendMongoDB(String lOrderNo, Long orderId, LogisticsConsignmentDto bo, OrderDetailRes tradeOrder, Integer orderStatus) {
        SckwLogisticsOrder logisticsOrder = new SckwLogisticsOrder();
        logisticsOrder.setStatus(String.valueOf(orderStatus));
        logisticsOrder.setLOrderId(orderId);
        logisticsOrder.setLOrderNo(lOrderNo);
        logisticsOrder.setLOrderPid(null);
        logisticsOrder.setTOrderId(tradeOrder.getId());
        logisticsOrder.setTOrderNo("D" + com.sckw.transport.utils.StringUtils.getWaybillNoUtil());
        logisticsOrder.setSettlementCycle(Long.parseLong(bo.getSettlementCycle()));
        logisticsOrder.setPrice(bo.getPrice());
        logisticsOrder.setPriceType(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()) == null ?
                null : Long.parseLong(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()).getValue()));

        if (!bo.getIsFullDose()) {
            if (ArrayUtil.isEmpty(bo.getCarryingCapacity())) {
                throw new RuntimeException("不是全量分配时,分配量不能为空!");
            }
            logisticsOrder.setAmount(bo.getCarryingCapacity());
            logisticsOrder.setUnit(bo.getCarryingCapacityUnit());
            logisticsOrder.setCarryingCapacity(bo.getCarryingCapacity());
        } else {
            logisticsOrder.setAmount(NumberConstant.ZERO_TWO);
            logisticsOrder.setSubcontractAmount(NumberConstant.ZERO_TWO);
            logisticsOrder.setCarryingCapacity(NumberConstant.ZERO_TWO);
        }
        logisticsOrder.setLoss(bo.getLoss() == null ? null : bo.getLoss());
        logisticsOrder.setLossUnit(bo.getLossUnit());
        logisticsOrder.setGoodsPrice(bo.getGoodsPrice() == null ? null : bo.getGoodsPrice());
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        logisticsOrder.setSubcontractAmount(decimal);
        logisticsOrder.setEntrustAmount(decimal);
        logisticsOrder.setUnloadAmount(decimal);
        logisticsOrder.setLoadAmount(decimal);
        logisticsOrder.setIgnoreAmount(decimal);
        logisticsOrder.setDeficitPrice(decimal);
        logisticsOrder.setPayment(Long.parseLong(bo.getPayment()));
        logisticsOrder.setTaxRate(bo.getTaxRate() == null ? null : bo.getTaxRate());
        logisticsOrder.setRemark(bo.getRemark());
        logisticsOrder.setEntId(LoginUserHolder.getEntId());
        logisticsOrder.setFirmName(remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId()).getFirmName());
        logisticsOrder.setGoodsId(bo.getGoodsId());
        KwpGoods goods = goodsInfoService.getGoodsById(bo.getGoodsId());
        logisticsOrder.setGoodsType(goods == null ? null : goods.getGoodsType());
        logisticsOrder.setGoodsSpec(goods == null ? null : goods.getSpec());
        //List<ContractDto> contractInfo = bo.getContractInfo();
        //contractInfo.forEach(contract -> {
            Long contractId = bo.getContractId();
            Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = contractService.queryContractBaseInfo(Collections.singletonList(contractId));
            if (longContractCommonInfoResDtoMap != null && (longContractCommonInfoResDtoMap.get(contractId) != null)) {
                String contractCode = longContractCommonInfoResDtoMap.get(contractId).getContractCode();
                String contactName = longContractCommonInfoResDtoMap.get(contractId).getContactName();
                Integer signingWay = longContractCommonInfoResDtoMap.get(contractId).getSigningWay();
                logisticsOrder.setContractId(String.valueOf(contractId));
                logisticsOrder.setContractNo(contractCode);
                logisticsOrder.setContractName(contactName);
                logisticsOrder.setContractSigningWay(String.valueOf(signingWay));
            }
        //});
        logisticsOrder.setCheckEntId(Long.parseLong(bo.getCheckCompanyId()));
        logisticsOrder.setCheckFirmName(bo.getCheckCompany());
        logisticsOrder.setCheckContacts(bo.getCheckContacts());
        logisticsOrder.setCheckPhone(bo.getCheckContactPhone());
        logisticsOrder.setCarrierEntId(Long.parseLong(bo.getConsignCompanyId()));
        logisticsOrder.setCarrierFirmName(bo.getConsignCompany());
        logisticsOrder.setCarrierContacts(bo.getConsignContacts());
        OrderDetailRes orderDetailRes = tradeOrderInfoService.getOrderDetailById(Long.valueOf(bo.getTOrderId()));
        // 收货单位+发货单位
        if (orderDetailRes != null) {
            List<UnitInfoDetailRes> unitInfo = orderDetailRes.getUnitInfo();
            if (CollectionUtils.isNotEmpty(unitInfo)) {
                for (UnitInfoDetailRes unitInfoDetailRes : unitInfo) {
                    if (String.valueOf(NumberConstant.ONE).equals(unitInfoDetailRes.getUnitType())) {
                        logisticsOrder.setShipmentsUnitEntId(String.valueOf(unitInfoDetailRes.getEntId()));
                        logisticsOrder.setShipmentsUnit(unitInfoDetailRes.getFirmName());
                    } else if (String.valueOf(NumberConstant.TWO).equals(unitInfoDetailRes.getUnitType())) {
                        logisticsOrder.setReceiveGoodsUnitEntId(String.valueOf(unitInfoDetailRes.getEntId()));
                        logisticsOrder.setReceiveGoodsUnit(unitInfoDetailRes.getFirmName());
                    }
                }
            }
        }
        List<AddressInfoDetail> addressInfo = tradeOrder.getAddressInfo();
        for (AddressInfoDetail detail : addressInfo) {
            if (String.valueOf(NumberConstant.ONE).equals(detail.getAddressType())) {
                logisticsOrder.setLoadType(Long.parseLong(detail.getType()));
                logisticsOrder.setLoadCityCode(detail.getCityCode());
                logisticsOrder.setLoadCityName(detail.getCityName());
                logisticsOrder.setLoadDetailAddress(detail.getDetailAddress());
                logisticsOrder.setLoadLat(detail.getLat());
                logisticsOrder.setLoadPhone(detail.getPhone());
                logisticsOrder.setLoadLng(detail.getLng());
                logisticsOrder.setLoadContacts(detail.getContacts());
            }
            if (String.valueOf(NumberConstant.TWO).equals(detail.getAddressType())) {
                logisticsOrder.setUnloadType(Long.parseLong(detail.getType()));
                logisticsOrder.setUnloadPhone(detail.getPhone());
                logisticsOrder.setUnloadCityCode(detail.getCityCode());
                logisticsOrder.setUnloadCityName(detail.getCityName());
                logisticsOrder.setUnloadDetailAddress(detail.getDetailAddress());
                logisticsOrder.setUnloadLat(detail.getLat());
                logisticsOrder.setUnloadLng(detail.getLng());
                logisticsOrder.setUnloadContacts(detail.getContacts());
            }
        }
        //TODO 生成时并无时间
//        logisticsOrder.setLoadTime();
//        logisticsOrder.setunLoadTime();
        logisticsOrder.setCreateBy(LoginUserHolder.getUserId());
        logisticsOrder.setCreateByName(LoginUserHolder.getUserName());
        logisticsOrder.setCreateTime(new Date());
        logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
        logisticsOrder.setUpdateByName(LoginUserHolder.getUserName());
        logisticsOrder.setUpdateTime(new Date());
        logisticsOrder.setGoodsPriceUnit(bo.getGoodsPriceUnit());
        logisticsOrder.setBillingMode(bo.getBillingMode());
        logisticsOrder.setStartTime(bo.getStartTime() == null ? null : bo.getStartTime());
        logisticsOrder.setEndTime(bo.getEndTime() == null ? null : bo.getEndTime());
        //rabbitMq业务汇总数据发送/消费对象
        SckwBusSum busSum = new SckwBusSum();
        //业务汇总类型
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        //操作对象（1新增/2修改）
        busSum.setMethod(1);
        //业务汇总数据对象
        busSum.setObject(logisticsOrder);
        streamBridge.send("sckw-busSum", JSON.toJSONString(busSum));

    }

    private void saveLogisticsOrderTrack(LogisticsConsignmentDto dto, Long orderId, Integer orderStatus) {
        KwtLogisticsOrderTrack entity = new KwtLogisticsOrderTrack();
        entity.setId(new IdWorker(NumberConstant.ONE).nextId());
        entity.setLOrderId(orderId);
        entity.setStatus(LogisticsOrderEnum.PENDING_ORDER.getCode());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setCreateBy(LoginUserHolder.getUserId());
        entity.setUpdateBy(LoginUserHolder.getUserId());
        entity.setRemark(dto.getRemark());
        logisticsOrderTrackMapper.insert(entity);
    }

    private void saveLogisticsOrderAddressAndAmount(LogisticsConsignmentDto dto, Long orderId) {
        //todo 装卸货地址 通过dubbo查询
//        OrderDetailRes orderDetailRes = tradeOrderInfoService.getOrderDetailById(Long.parseLong(dto.getTOrderId()));
//        if (ObjectUtils.isEmpty(orderDetailRes)) {
//            log.info("dubbp 查询数据 error :orderId:{}", dto.getTOrderId());
//            throw new RuntimeException("dubbp 查询销售订单数据查找失败!");
//        }
//        List<AddressInfoDetail> addressInfo = orderDetailRes.getAddressInfo();
//        if (CollectionUtils.isEmpty(addressInfo)) {
//            throw new BusinessException("生成物流托运时,地址信息不存在!");
//        }
        List<AddressInfoDto> addressInfo = dto.getAddressInfo();
        for (AddressInfoDto addressInfoDto : addressInfo) {
            OrderAddressDetailRes detail = tradeOrderInfoService.getOrderDetailByTradeOrderIdAndAddressId(Long.parseLong(dto.getTOrderId()), Long.parseLong(addressInfoDto.getAddressId()));
            if (detail != null) {
                if (String.valueOf(NumberConstant.ONE).equals(detail.getAddressType())) {
                    long addressId = new IdWorker(NumberConstant.ONE).nextId();
                    KwtLogisticsOrderAddress loadOrderAddress = new KwtLogisticsOrderAddress();
                    loadOrderAddress.setId(addressId);
                    loadOrderAddress.setAddressType(NumberConstant.ONE);
                    loadOrderAddress.setDetailAddress(detail.getDetailAddress());
                    loadOrderAddress.setContacts(detail.getContacts());
                    loadOrderAddress.setLOrderId(orderId);
                    loadOrderAddress.setLat(detail.getLat());
                    loadOrderAddress.setFence(detail.getFence());
                    loadOrderAddress.setCityName(detail.getCityName());
                    loadOrderAddress.setEntryType(NumberConstant.FOUR);
                    loadOrderAddress.setCreateTime(new Date());
                    loadOrderAddress.setPhone(detail.getPhone());
                    loadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
                    loadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
                    loadOrderAddress.setUpdateTime(new Date());
                    loadOrderAddress.setName(detail.getName());
                    loadOrderAddress.setType(Long.parseLong(detail.getType()));
                    loadOrderAddress.setCityCode(detail.getCityCode());
                    loadOrderAddress.setLng(detail.getLng());
                    loadOrderAddress.setSort(addressInfoDto.getSort());
                    loadOrderAddress.setTAddressId(Long.parseLong(addressInfoDto.getAddressId()));
                    logisticsOrderAddressMapper.insert(loadOrderAddress);

                    KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                    BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                    orderAmount.setLOrderId(orderId);
                    orderAmount.setLAddressId(addressId);
                    orderAmount.setAmount(addressInfoDto.getAmount());
                    orderAmount.setSubcontractAmount(defaultBigDecimal);
                    orderAmount.setEntrustAmount(defaultBigDecimal);
                    orderAmount.setLoadAmount(defaultBigDecimal);
                    orderAmount.setUnloadAmount(defaultBigDecimal);
                    orderAmount.setIgnoreAmount(defaultBigDecimal);
                    orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                    orderAmount.setStatus(0);
                    orderAmount.setCreateBy(LoginUserHolder.getUserId());
                    orderAmount.setCreateTime(new Date());
                    orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                    orderAmount.setUpdateTime(new Date());
                    orderAmount.setDelFlag(0);
                    logisticsOrderAmountMapper.insert(orderAmount);
                }
                if (String.valueOf(NumberConstant.TWO).equals(detail.getAddressType())) {
                    long addressId = new IdWorker(NumberConstant.TWO).nextId();
                    KwtLogisticsOrderAddress unloadOrderAddress = new KwtLogisticsOrderAddress();
                    unloadOrderAddress.setId(addressId);
                    unloadOrderAddress.setAddressType(NumberConstant.TWO);
                    unloadOrderAddress.setContacts(detail.getContacts());
                    unloadOrderAddress.setLOrderId(orderId);
                    unloadOrderAddress.setLat(detail.getLat());
                    unloadOrderAddress.setFence(detail.getFence());
                    unloadOrderAddress.setCityName(detail.getCityName());
                    unloadOrderAddress.setEntryType(NumberConstant.FOUR);
                    unloadOrderAddress.setPhone(detail.getPhone());
                    unloadOrderAddress.setDetailAddress(detail.getDetailAddress());
                    unloadOrderAddress.setCreateTime(new Date());
                    unloadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
                    unloadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
                    unloadOrderAddress.setUpdateTime(new Date());
                    unloadOrderAddress.setName(detail.getName());
                    unloadOrderAddress.setType(Long.valueOf(detail.getType()));
                    unloadOrderAddress.setCityCode(detail.getCityCode());
                    unloadOrderAddress.setLng(detail.getLng());
                    unloadOrderAddress.setSort(addressInfoDto.getSort());
                    unloadOrderAddress.setTAddressId(Long.parseLong(addressInfoDto.getAddressId()));
                    logisticsOrderAddressMapper.insert(unloadOrderAddress);

                    KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                    BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                    orderAmount.setLOrderId(orderId);
                    orderAmount.setLAddressId(addressId);
                    orderAmount.setAmount(addressInfoDto.getAmount());
                    orderAmount.setSubcontractAmount(defaultBigDecimal);
                    orderAmount.setEntrustAmount(defaultBigDecimal);
                    orderAmount.setLoadAmount(defaultBigDecimal);
                    orderAmount.setUnloadAmount(defaultBigDecimal);
                    orderAmount.setIgnoreAmount(defaultBigDecimal);
                    orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                    orderAmount.setStatus(0);
                    orderAmount.setCreateBy(LoginUserHolder.getUserId());
                    orderAmount.setCreateTime(new Date());
                    orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                    orderAmount.setUpdateTime(new Date());
                    orderAmount.setDelFlag(0);
                    logisticsOrderAmountMapper.insert(orderAmount);
                }
            }
        }

//        if (CollectionUtils.isNotEmpty(addressInfo)) {
//            for (AddressInfoDetail detail : addressInfo) {
//                if (String.valueOf(NumberConstant.ONE).equals(detail.getAddressType())) {
//                    List<AddressInfoDto> orderAddressInfo = dto.getAddressInfo();
//                    for (AddressInfoDto addressInfoDto : orderAddressInfo) {
//                        if (addressInfoDto.getAddressId().equals(detail.getId())) {
//                            KwtLogisticsOrderAddress loadOrderAddress = new KwtLogisticsOrderAddress();
//                            loadOrderAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
//                            loadOrderAddress.setAddressType(NumberConstant.ONE);
//                            loadOrderAddress.setDetailAddress(detail.getDetailAddress());
//                            loadOrderAddress.setContacts(detail.getContacts());
//                            loadOrderAddress.setLOrderId(orderId);
//                            loadOrderAddress.setLat(detail.getLat());
//                            loadOrderAddress.setFence(detail.getFence());
//                            loadOrderAddress.setCityName(detail.getCityName());
//                            loadOrderAddress.setEntryType(NumberConstant.FOUR);
//                            loadOrderAddress.setCreateTime(new Date());
//                            loadOrderAddress.setPhone(detail.getPhone());
//                            loadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
//                            loadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
//                            loadOrderAddress.setUpdateTime(new Date());
//                            loadOrderAddress.setName(detail.getName());
//                            loadOrderAddress.setType(Long.parseLong(detail.getType()));
//                            loadOrderAddress.setCityCode(detail.getCityCode());
//                            loadOrderAddress.setLng(detail.getLng());
//                            loadOrderAddress.setSort(addressInfoDto.getSort());
//                            kwtLogisticsOrderAddressMapper.insert(loadOrderAddress);
//                        }
//                    }
//                }
//                if (String.valueOf(NumberConstant.TWO).equals(detail.getAddressType())) {
//                    List<AddressInfoDto> orderAddressInfo = dto.getAddressInfo();
//                    for (AddressInfoDto addressInfoDto : orderAddressInfo) {
//                        if (addressInfoDto.getAddressId().equals(detail.getId())) {
//                            KwtLogisticsOrderAddress unloadOrderAddress = new KwtLogisticsOrderAddress();
//                            unloadOrderAddress.setId(new IdWorker(NumberConstant.TWO).nextId());
//                            unloadOrderAddress.setAddressType(NumberConstant.TWO);
//                            unloadOrderAddress.setContacts(detail.getContacts());
//                            unloadOrderAddress.setLOrderId(orderId);
//                            unloadOrderAddress.setLat(detail.getLat());
//                            unloadOrderAddress.setFence(detail.getFence());
//                            unloadOrderAddress.setCityName(detail.getCityName());
//                            unloadOrderAddress.setEntryType(NumberConstant.FOUR);
//                            unloadOrderAddress.setPhone(detail.getPhone());
//                            unloadOrderAddress.setDetailAddress(detail.getDetailAddress());
//                            unloadOrderAddress.setCreateTime(new Date());
//                            unloadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
//                            unloadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
//                            unloadOrderAddress.setUpdateTime(new Date());
//                            unloadOrderAddress.setName(detail.getName());
//                            unloadOrderAddress.setType(Long.valueOf(detail.getType()));
//                            unloadOrderAddress.setCityCode(detail.getCityCode());
//                            unloadOrderAddress.setLng(detail.getLng());
//                            unloadOrderAddress.setSort(addressInfoDto.getSort());
//                            kwtLogisticsOrderAddressMapper.insert(unloadOrderAddress);
//                        }
//                    }
//                }
//            }
//        }
    }

    /**
     * 消息推送首页信息
     */
    private void pushConsoleMessage(LogisticsConsignmentDto dto, String lOrderNo) {
        /**消息列表
         * 1 采购 2 销售
         * */
        String pcConsignUrl = "", appConsignUrl = "", pcCarriageUrl = "", appCarriageUrl = "";
        MessageEnum consignMessageEnum = null, carriageMessageEnum = null;
        //托运单位
        KwtLogisticsOrderUnit checkUnit = new KwtLogisticsOrderUnit();
        //承运单位
        KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
        String type = dto.getType();
        if (String.valueOf(NumberConstant.ONE).equals(type)) {
            EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getConsignCompanyId()));
            EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getCheckCompanyId()));
            //发起方
            checkUnit.setUnitType(NumberConstant.ONE);
            checkUnit.setFirmName(dto.getCheckCompany());
            checkUnit.setEntId(Long.parseLong(dto.getConsignCompanyId()));
            checkUnit.setTopEntId(consignentMap == null ? null : consignentMap.getId());
            checkUnit.setContactsId(Long.parseLong(dto.getCheckContactsId()));
            //接收方
            carriageUnit.setUnitType(NumberConstant.TWO);
            carriageUnit.setFirmName(dto.getConsignCompany());
            carriageUnit.setEntId(Long.parseLong(dto.getCheckCompanyId()));
            carriageUnit.setTopEntId(checkentMap == null ? null : checkentMap.getId());
            carriageUnit.setContactsId(Long.parseLong(dto.getConsignContactsId()));
            pcConsignUrl = messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl();
            appConsignUrl = messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl();
            pcCarriageUrl = messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl();
            appCarriageUrl = messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl();
            consignMessageEnum = MessageEnum.NEW_CARRIAGE_ORDER;
            carriageMessageEnum = MessageEnum.INITIATING_LOGISTICS_CONSIGNMENT;
            type = "2";
        } else if (String.valueOf(NumberConstant.TWO).equals(type)) {
            EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getConsignCompanyId()));
            EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getCheckCompanyId()));
            //发起方
            checkUnit.setUnitType(NumberConstant.ONE);
            checkUnit.setFirmName(dto.getCheckCompany());
            checkUnit.setEntId(Long.parseLong(dto.getCheckCompanyId()));
            checkUnit.setTopEntId(consignentMap == null ? null : consignentMap.getId());
            checkUnit.setContactsId(Long.parseLong(dto.getConsignContactsId()));
            //接收方
            carriageUnit.setUnitType(NumberConstant.TWO);
            carriageUnit.setFirmName(dto.getConsignCompany());
            carriageUnit.setEntId(Long.parseLong(dto.getConsignCompanyId()));
            carriageUnit.setTopEntId(checkentMap == null ? null : checkentMap.getId());
            carriageUnit.setContactsId(Long.parseLong(dto.getCheckContactsId()));
            pcConsignUrl = messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl();
            appConsignUrl = messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl();
            pcCarriageUrl = messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl();
            appCarriageUrl = messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl();
            consignMessageEnum = MessageEnum.NEW_CARRIAGE_ORDER;
            carriageMessageEnum = MessageEnum.INITIATING_LOGISTICS_CONSIGNMENT;
            type = "1";
        }
        //发送消息
        commonService.newSendLogisticsOrderToMessage(checkUnit, carriageUnit, lOrderNo, LoginUserHolder.getUserId(),
                LoginUserHolder.getEntId(), pcConsignUrl, appConsignUrl, pcCarriageUrl, appCarriageUrl,
                consignMessageEnum, carriageMessageEnum, type);
    }

    private void saveLogisticsOrderUnit(LogisticsConsignmentDto dto, Long orderId) {
        EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getConsignCompanyId()));
        EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(dto.getCheckCompanyId()));
        if (consignentMap == null || checkentMap == null) {
            throw new BusinessException("企业对应一级企业不存在");
        }
        KwtLogisticsOrderUnit checkUnit = new KwtLogisticsOrderUnit()
                .setLOrderId(orderId)
                .setId(new IdWorker(NumberConstant.ONE).nextId())
                .setUnitType(NumberConstant.ONE)
                .setFirmName(dto.getCheckCompany())
                .setRemark(dto.getRemark())
                .setEntId(Long.parseLong(dto.getCheckCompanyId()))
                .setTopEntId(checkentMap.getId())
                .setContacts(dto.getCheckContacts())
                .setPhone(dto.getCheckContactPhone())
                .setCreateBy(LoginUserHolder.getUserId())
                .setCreateTime(new Date())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateTime(new Date())
                .setContactsId(Long.parseLong(dto.getCheckContactsId()));
        logisticsOrderUnitMapper.insert(checkUnit);

        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit()
                .setLOrderId(orderId)
                .setId(new IdWorker(NumberConstant.ONE).nextId())
                .setUnitType(NumberConstant.TWO)
                .setFirmName(dto.getConsignCompany())
                .setRemark(dto.getRemark())
                .setEntId(Long.parseLong(dto.getConsignCompanyId()))
                .setTopEntId(consignentMap.getId())
                .setContacts(dto.getConsignContacts())
                .setPhone(dto.getConsignContactPhone())
                .setCreateBy(LoginUserHolder.getUserId())
                .setCreateTime(new Date())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateTime(new Date())
                .setContactsId(Long.parseLong(dto.getConsignContactsId()));
        logisticsOrderUnitMapper.insert(consignUnit);
    }

    private void saveLogisticsOrderContract(LogisticsConsignmentDto dto, Long orderId) {
        //List<ContractDto> contractInfo = dto.getContractInfo();
        //contractInfo.forEach(contract -> {
            Long contractId = dto.getContractId();
            Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = contractService.queryContractBaseInfo(Collections.singletonList(contractId));
            if (longContractCommonInfoResDtoMap != null && (longContractCommonInfoResDtoMap.get(contractId) != null)) {
                String contractCode = longContractCommonInfoResDtoMap.get(contractId).getContractCode();
                String contactName = longContractCommonInfoResDtoMap.get(contractId).getContactName();
                Integer signingWay = longContractCommonInfoResDtoMap.get(contractId).getSigningWay();
                KwtLogisticsOrderContract kwtLogisticsOrderContract = new KwtLogisticsOrderContract();
                kwtLogisticsOrderContract.setId(new IdWorker(NumberConstant.ONE).nextId());
                kwtLogisticsOrderContract.setLOrderId(orderId);
                kwtLogisticsOrderContract.setContractId(contractId);
                kwtLogisticsOrderContract.setContractNo(contractCode);
                kwtLogisticsOrderContract.setContractName(contactName);
                kwtLogisticsOrderContract.setSigningWay(String.valueOf(signingWay));
                kwtLogisticsOrderContract.setRemark(dto.getRemark());
                kwtLogisticsOrderContract.setCreateBy(LoginUserHolder.getUserId());
                kwtLogisticsOrderContract.setUpdateBy(LoginUserHolder.getUserId());
                kwtLogisticsOrderContract.setCreateTime(new Date());
                kwtLogisticsOrderContract.setUpdateTime(new Date());
                logisticsOrderContractMapper.insert(kwtLogisticsOrderContract);
            }
        //});
    }

    private void saveLogisticsOrder(LogisticsConsignmentDto bo, String lOrderNo, KwtLogisticsOrder order, OrderDetailRes tradeOrder, Long orderId, Integer orderStatus) {
        order.setId(orderId);
        order.setEntId(LoginUserHolder.getEntId());
        order.setType(String.valueOf(NumberConstant.ONE));
        order.setTOrderId(Long.parseLong(bo.getTOrderId()));
        order.setTOrderNo(bo.getTOrderNo());
        order.setLOrderNo(lOrderNo);
        order.setPid(null);
//        order.setPids(orderId + StringConstant.COMMA);
        order.setPids(String.valueOf(orderId));
        order.setSettlementCycle(Long.parseLong(bo.getSettlementCycle()));
        order.setPrice(bo.getPrice());
        order.setPriceType(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()) == null ?
                null : Long.parseLong(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()).getValue()));
//        order.setAmount(tradeOrder.getAmount());
        order.setBillingMode(bo.getBillingMode());
        order.setUnit(bo.getCarryingCapacityUnit());
        order.setLoss(bo.getLoss() == null ? null : bo.getLoss());
//        order.setLossUnit(bo.getLossUnit());
        order.setLossUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()) == null ?
                null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()).getValue());
        order.setGoodsPrice(bo.getGoodsPrice() == null ? null : bo.getGoodsPrice());
        order.setGoodsPriceUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()) == null ?
                null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()).getValue());
        order.setGoodsPriceUnit(bo.getGoodsPriceUnit());
        order.setStartTime(bo.getStartTime() == null ? null : bo.getStartTime());
        order.setEndTime(bo.getEndTime() == null ? null : bo.getEndTime());
        order.setRemark(bo.getRemark());
        order.setPayment(Long.parseLong(bo.getPayment()));
        order.setTaxRate(bo.getTaxRate());
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateTime(new Date());
        order.setStatus(orderStatus);
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        /**补充默认值*/
        order.setEntrustAmount(decimal);
        order.setSubcontractAmount(decimal);
        order.setLoadAmount(decimal);
        order.setUnloadAmount(decimal);
        order.setIgnoreAmount(decimal);
        order.setDeficitPrice(decimal);
        order.setDeficitAmount(decimal);
        order.setTotalUnloadAmount(decimal);
        order.setTotalLoadAmount(decimal);
        order.setBindStatus(String.valueOf(NumberConstant.ZERO));
        order.setTotalTake(NumberConstant.ZERO);
        logisticsOrderMapper.insert(order);
    }

    /**
     * 物流订单-自建订单-v4.2
     *
     * @param addLogisticsOrderParam
     * @return
     */
    @Transactional
    public HttpResult addLogisticsOrder(AddLogisticsOrderParam addOrderDTO) {
        commonService.getRedisGenerateOrderNo();
        /**生成订单编号*/
        String lOrderNo = OrderGenerateSeqNoUtils.getSeqNo(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER, "2", "0", "0");
        HttpResult httpResult = ValidUtil.serviceValid(addOrderDTO);
        if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
            return HttpResult.error(httpResult.getMsg());
        }
        /**验证数据*/
        checkCreateLogisticOrderParam(addOrderDTO);
        /**数据填写验证*/
        checkLogisticsOrder(addOrderDTO);
        String consignCompanyId = addOrderDTO.getConsignCompanyId();
        String acceptCompanyId = addOrderDTO.getAcceptCompanyId();
        List<FindEntCooperateResVo> entCooperate = manageService.findEntCooperate(Long.parseLong(consignCompanyId), Long.parseLong(acceptCompanyId), CooperateTypeEnum.CARRIAGE.getCode());
//        if (CollectionUtils.isEmpty(entCooperate)) {
//            return HttpResult.error("该承运企业与我方企业并无合作关系!");
//        }
        /**保存新建数据*/
        Long lOrderId = new IdWorker(NumberConstant.ONE).nextId();
        /**根据合同计算当前单据状态*/
        /**判断生成物流订单应生成哪一种单据状态*/
        List<Long> contractList = new ArrayList<>();
        contractList.add(Long.parseLong(addOrderDTO.getContractId()));
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = contractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new BusinessException("新建订单-并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId())) == null) {
            throw new BusinessException("新建订单-并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId()));
        /**状态判断
         * 是否是已签约合同
         * */
        // 0 已签约 1待签约
        Integer status = infoResDto.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("创建订单异常");
            throw new BusinessException("自建订单异常");
        }
        /**数据保存*/
        saveCreateLogisticsOrder(addOrderDTO, lOrderId, orderStatus, lOrderNo);
        saveCreateLogisticsOrderAddressAndAmount(addOrderDTO, lOrderId);
        saveConsignLogisticsOrderGoods(addOrderDTO, lOrderId, lOrderNo);
        saveCreateLogisticsOrderContract(addOrderDTO, lOrderId, infoResDto);
        saveCreateLogisticsOrderTrack(lOrderId, orderStatus);
        saveCreateLogisticsOrderUnit(addOrderDTO, lOrderId);
        if ("4".equals(addOrderDTO.getBillingMode())) {
            saveCreateLogisticsOrderLineFreight(addOrderDTO, lOrderId);
        }
        /**保存mongodb*/
        saveCreateLogisticsOrderToMongoDb(addOrderDTO, orderStatus, lOrderId, lOrderNo, infoResDto);
        /**消息主体*/
        String type = addOrderDTO.getType();
        if (type.equals("1")) {
            logisticsOrderPush(addOrderDTO, lOrderNo, LoginUserHolder.getUserId(), LoginUserHolder.getEntId());
        } else if (type.equals("2")) {
            //托运单位
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(Long.parseLong(addOrderDTO.getConsignCompanyId()));
            KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
            consignUnit.setUnitType(NumberConstant.ONE);
            consignUnit.setEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
            consignUnit.setTopEntId(entCacheResDto == null ? null : entCacheResDto.getId());
            consignUnit.setFirmName(addOrderDTO.getConsignCompany());
            consignUnit.setContactsId(Long.parseLong(addOrderDTO.getConsignContactsId()));
            //承运单位
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
            KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
            carriageUnit.setUnitType(NumberConstant.TWO);
            carriageUnit.setEntId(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
            carriageUnit.setTopEntId(entCacheResDto1 == null ? null : entCacheResDto1.getId());
            carriageUnit.setFirmName(addOrderDTO.getAcceptCompany());
            carriageUnit.setContactsId(Long.parseLong(addOrderDTO.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"
            );
        }
        return HttpResult.ok(lOrderId);
    }

    private void checkLogisticsOrder(AddLogisticsOrderParam addOrderDTO) {
        /**计费方式验证*/
        if (!DictEnum.CHARGING_TYPE_4.getValue().equals(addOrderDTO.getBillingMode())) {
//            if (Objects.isNull(addOrderDTO.getGoodsId())) {
//                throw new RuntimeException("商品id不能为空");
//            }
            if (addOrderDTO.getPrice() == null || addOrderDTO.getPrice().compareTo(NumberConstant.ZERO_TWO) < 1) {
                throw new RuntimeException("运价填写错误");
            }
        }
    }

    private void saveCreateLogisticsOrderLineFreight(AddLogisticsOrderParam addOrderDTO, Long lOrderId) {
        List<LineFreightDto> lineFreightList = addOrderDTO.getLineFreightList();
        Map<Long, BigDecimal> lineFreightMap = lineFreightList.stream().collect(Collectors.toMap(LineFreightDto::getLineFreightId, LineFreightDto::getAmount));
        List<Long> lineFreightId = lineFreightList.stream().map(t -> t.getLineFreightId()).distinct().collect(Collectors.toList());
        Map<Long, LineFreightAddressRes> resMap = manageService.findLineFreightAddress(lineFreightId);
        if (resMap != null) {
            lineFreightId.stream().forEach(id -> {
                if (resMap.get(id) != null) {
                    LineFreightAddressRes res = resMap.get(id);
                    KwtLogisticsOrderLineFreightRate lineFreightRate = new KwtLogisticsOrderLineFreightRate();
                    lineFreightRate.setLineFreightRateId(res.getId());
                    lineFreightRate.setLOrderId(lOrderId);
                    lineFreightRate.setName(res.getName());
                    lineFreightRate.setLoadName(res.getLoadName());
                    lineFreightRate.setLoadCityCode(res.getLoadCityCode());
                    lineFreightRate.setLoadCityName(res.getLoadCityName());
                    lineFreightRate.setLoadDetailAddress(res.getLoadDetailAddress());
                    lineFreightRate.setLoadLat(res.getLoadLat());
                    lineFreightRate.setLoadLng(res.getLoadLng());
                    lineFreightRate.setUnloadName(res.getUnloadName());
                    lineFreightRate.setUnloadCityCode(res.getUnloadCityCode());
                    lineFreightRate.setUnloadCityName(res.getUnloadCityName());
                    lineFreightRate.setUnloadDetailAddress(res.getUnloadDetailAddress());
                    lineFreightRate.setUnloadLat(res.getUnloadLat());
                    lineFreightRate.setUnloadLng(res.getUnloadLng());
                    lineFreightRate.setTransportMileage(res.getTransportMileage());
                    lineFreightRate.setTransportPrice(res.getTransportPrice());
                    BigDecimal defultBigDecimal = new BigDecimal("0.00");
                    lineFreightRate.setSettlementAmount(defultBigDecimal);
                    lineFreightRate.setTransportAmount(lineFreightMap.get(id));
                    lineFreightRate.setId(new IdWorker(NumberConstant.FOUR).nextId());
                    lineFreightRate.setRemark(res.getRemark());
                    lineFreightRate.setStatus(res.getStatus());
                    lineFreightRate.setCreateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setCreateTime(new Date());
                    lineFreightRate.setUpdateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setUpdateTime(new Date());
                    lineFreightRate.setDelFlag(0);
                    logisticsOrderLineFreightRateMapper.insert(lineFreightRate);
                }
            });
        }
    }

    private void saveCreateLogisticsOrderToMongoDb(AddLogisticsOrderParam orderDTO, Integer orderStatus, Long lOrderId, String lOrderNo, ContractCommonInfoResDto infoResDto) {
        SckwLogisticsOrder order = new SckwLogisticsOrder();
        order.set_id(lOrderId);
        order.setLOrderId(lOrderId);
        order.setLOrderNo(lOrderNo);
        order.setLOrderPid(null);
        order.setLOrderPids(String.valueOf(lOrderId));
        order.setType(NumberConstant.TWO);
        order.setSettlementCycle(orderDTO.getSettlementCycle());
        order.setPrice(orderDTO.getPrice());
        order.setPriceType(order.getPriceType());
        order.setAmount(orderDTO.getAmount());
        order.setUnit(orderDTO.getAmountUnit());
        order.setLoss(orderDTO.getLoss());
        order.setLossUnit(orderDTO.getLossUnit());
        order.setGoodsPrice(orderDTO.getGoodsPrice() == null ? null : orderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(orderDTO.getGoodsPriceUnit());
        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.setPayment(orderDTO.getPayment());
        order.setTaxRate(orderDTO.getTaxRate());
        order.setRemark(orderDTO.getRemark());
        order.setStatus(String.valueOf(orderStatus));
        order.setEntId(LoginUserHolder.getEntId());
        order.setFirmName(LoginUserHolder.getEntName());
//        order.setGoodsId(Long.parseLong(orderDTO.getGoodsId()));
//        order.setGoodsCode(goods == null ? null : goods.getCode());
        order.setGoodsName(orderDTO.getGoodsName());
//        order.setGoodsType(goods == null ? null : goods.getGoodsType());
////        order.setGoodsIndustry(goods == null ? null : goods.get);
//        order.setGoodsSpec(goods == null ? null : goods.getSpec());
        order.setContractId(orderDTO.getContractId());
        order.setContractNo(infoResDto.getContractCode());
        order.setContractName(infoResDto.getContactName());
        order.setContractSigningWay(String.valueOf(infoResDto.getSigningWay()));
        order.setCheckEntId(Long.parseLong(orderDTO.getConsignCompanyId()));
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(orderDTO.getConsignCompanyId())));
        EntCacheResDto ent = entMap.get(Long.parseLong(orderDTO.getConsignCompanyId()));
        if (Objects.isNull(ent)) {
            throw new BusinessException("企业:" + orderDTO.getConsignCompany() + "的一级企业信息不存在！");
        }
        order.setCheckTopEntId(ent.getId());
        order.setCheckFirmName(orderDTO.getConsignCompany());
        order.setCheckContacts(orderDTO.getConsignContacts());
        order.setCheckPhone(orderDTO.getConsignContactPhone());
        order.setCarrierEntId(Long.parseLong(orderDTO.getAcceptCompanyId()));
        Map<Long, EntCacheResDto> entMap1 = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(orderDTO.getAcceptCompanyId())));
        EntCacheResDto ent1 = entMap1.get(Long.parseLong(orderDTO.getAcceptCompanyId()));
        if (Objects.isNull(ent1)) {
            throw new BusinessException("企业:" + orderDTO.getConsignCompany() + "的一级企业信息不存在！");
        }
        order.setCarrierTopEntId(ent1.getId());
        order.setCarrierFirmName(orderDTO.getAcceptCompany());
        order.setCarrierContacts(orderDTO.getAcceptContacts());
        order.setCarrierPhone(orderDTO.getAcceptContactPhone());
//        order.setLoadType();
//        order.setLoadContacts(orderDTO.getLoadContacts());
//        order.setLoadPhone(orderDTO.getLoadPhone());
//        order.setLoadCityCode(orderDTO.getLoadCityCode());
//        order.setLoadCityName(orderDTO.getLoadCityName());
//        order.setLoadDetailAddress(orderDTO.getLoadDetailAddress());
//        order.setLoadLat(orderDTO.getLoadLat());
//        order.setLoadLng(orderDTO.getLoadLng());
////        order.setUnloadType();
//        order.setUnloadContacts(orderDTO.getUnloadContacts());
//        order.setUnloadPhone(orderDTO.getUnloadPhone());
//        order.setUnloadCityCode(orderDTO.getUnloadCityCode());
//        order.setUnloadCityName(orderDTO.getUnloadCityName());
//        order.setUnloadDetailAddress(orderDTO.getUnloadDetailAddress());
//        order.setUnloadLat(orderDTO.getUnloadLat());
//        order.setUnloadLng(orderDTO.getUnloadLng());
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateByName(LoginUserHolder.getUserName());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateByName(LoginUserHolder.getUserName());
        order.setUpdateTime(new Date());
//        order.setWOrderNo(lOrderNo);
        order.setCarryingCapacity(orderDTO.getAmount());
        order.setBillingMode(orderDTO.getBillingMode());
        order.setDelFlag(String.valueOf(NumberConstant.ZERO));
        order.setStartTime(orderDTO.getStartTime() == null ? null : DateUtil.localDateToLocalDateTimeStart(orderDTO.getStartTime()));
        order.setEndTime(orderDTO.getEndTime() == null ? null : DateUtil.localDateToLocalDateTimeEnd(orderDTO.getEndTime()));
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(NumberConstant.ONE);
        busSum.setObject(order);
        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));

    }

    private void saveCreateLogisticsOrderUnit(AddLogisticsOrderParam orderDTO, Long lOrderId) {
        //托运
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignUnit.setLOrderId(lOrderId);
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(Long.parseLong(orderDTO.getConsignCompanyId()));
        List<Long> entIds = new ArrayList<>();
        entIds.add(Long.parseLong(orderDTO.getConsignCompanyId()));
        entIds.add(Long.parseLong(orderDTO.getAcceptCompanyId()));
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(entIds);
        EntCacheResDto ent = entMap.get(Long.parseLong(orderDTO.getConsignCompanyId()));
        if (Objects.isNull(ent)) {
            throw new BusinessException("企业:" + orderDTO.getConsignCompany() + "的一级企业信息不存在！");
        }
        consignUnit.setContactsId(Long.parseLong(orderDTO.getConsignContactsId()));
        consignUnit.setTopEntId(ent.getId());
        consignUnit.setFirmName(orderDTO.getConsignCompany());
        consignUnit.setContacts(orderDTO.getConsignContacts());
        consignUnit.setPhone(orderDTO.getConsignContactPhone());
//        consignUnit.setRemark(orderDTO.getRemark());
        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(Long.parseLong(orderDTO.getAcceptCompanyId()));
        EntCacheResDto ent1 = entMap.get(Long.parseLong(orderDTO.getAcceptCompanyId()));
        if (Objects.isNull(ent1)) {
            throw new BusinessException("企业:" + orderDTO.getAcceptCompany() + "的一级企业信息不存在！");
        }
        unit.setContactsId(Long.parseLong(orderDTO.getAcceptContactsId()));
        unit.setTopEntId(ent1.getId());
        unit.setFirmName(orderDTO.getAcceptCompany());
        unit.setContacts(orderDTO.getAcceptContacts());
        unit.setPhone(orderDTO.getAcceptContactPhone());
//        unit.setRemark(orderDTO.getRemark());
        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);

    }

    private void saveCreateLogisticsOrderTrack(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);
    }

    private void saveCreateLogisticsOrderContract(AddLogisticsOrderParam orderDTO, Long lOrderId, ContractCommonInfoResDto infoResDto) {
        KwtLogisticsOrderContract contract = new KwtLogisticsOrderContract();
        contract.setId(new IdWorker(NumberConstant.ONE).nextId());
        contract.setContractId(Long.parseLong(orderDTO.getContractId()));
        contract.setLOrderId(lOrderId);
        contract.setContractNo(orderDTO.getContractNo() == null ? infoResDto.getContractCode() : orderDTO.getContractNo());
        contract.setContractName(orderDTO.getContractName() == null ? infoResDto.getContactName() : orderDTO.getContractName());
        contract.setSigningWay(orderDTO.getSigningWay() == null ? String.valueOf(infoResDto.getSigningWay()) : orderDTO.getSigningWay());
        contract.setStatus(NumberConstant.ZERO);
        contract.setCreateBy(LoginUserHolder.getUserId());
        contract.setCreateTime(new Date());
        contract.setUpdateBy(LoginUserHolder.getUserId());
        contract.setUpdateTime(new Date());
        logisticsOrderContractMapper.insert(contract);
    }

    private void saveCreateLogisticsOrderAddressAndAmount(AddLogisticsOrderParam orderDTO, Long lOrderId) {
        List<AddressInfoDto> addressInfo = orderDTO.getAddressInfo();
        List<String> addressIds = addressInfo.stream().map(AddressInfoDto::getAddressId).collect(Collectors.toList());
        Map<Long, EntAddressResDto> addressDetailMap = manageService.queryAddressListByAddressIdList(addressIds);
        if (addressDetailMap.isEmpty()) {
            log.info("no address :{}", JSONObject.toJSONString(addressIds));
            throw new BusinessException("地址信息异常");
        }
        Map<Integer, List<AddressInfoDto>> addressMap = addressInfo.stream().collect(Collectors.groupingBy(AddressInfoDto::getAddressType));
        List<AddressInfoDto> loadAddressInfoDtos = addressMap.get(1);
        loadAddressInfoDtos.forEach(address -> {
            EntAddressResDto entAddressResDtos = addressDetailMap.get(Long.parseLong(address.getAddressId()));
            if (entAddressResDtos.getId() != null) {
                KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
                long addressId = new IdWorker(NumberConstant.ONE).nextId();
                loadAddress.setId(addressId);
                loadAddress.setLOrderId(lOrderId);
                loadAddress.setAddressType(NumberConstant.ONE);
                loadAddress.setName(entAddressResDtos.getName() == null ? null : entAddressResDtos.getName());
                loadAddress.setContacts(entAddressResDtos.getContacts());
                loadAddress.setPhone(entAddressResDtos.getPhone());
                loadAddress.setCityCode(entAddressResDtos.getCityCode());
                loadAddress.setCityName(entAddressResDtos.getCityName());
                loadAddress.setDetailAddress(entAddressResDtos.getDetailAddress());
                loadAddress.setLat(entAddressResDtos.getLat());
                loadAddress.setLng(entAddressResDtos.getLng());
                loadAddress.setEntryType(NumberConstant.FOUR);
                loadAddress.setStatus(NumberConstant.ZERO);
                loadAddress.setCreateBy(LoginUserHolder.getUserId());
                loadAddress.setSort(address.getSort());
                Date date = new Date();
                loadAddress.setCreateTime(date);
                loadAddress.setUpdateBy(LoginUserHolder.getUserId());
                loadAddress.setUpdateTime(date);
                logisticsOrderAddressMapper.insert(loadAddress);

                KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                orderAmount.setLOrderId(lOrderId);
                orderAmount.setLAddressId(addressId);
                orderAmount.setAmount(address.getAmount());
                orderAmount.setSubcontractAmount(defaultBigDecimal);
                orderAmount.setEntrustAmount(defaultBigDecimal);
                orderAmount.setLoadAmount(defaultBigDecimal);
                orderAmount.setUnloadAmount(defaultBigDecimal);
                orderAmount.setIgnoreAmount(defaultBigDecimal);
                orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                orderAmount.setStatus(0);
                orderAmount.setCreateBy(LoginUserHolder.getUserId());
                orderAmount.setCreateTime(new Date());
                orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                orderAmount.setUpdateTime(new Date());
                orderAmount.setDelFlag(0);
                logisticsOrderAmountMapper.insert(orderAmount);
            }
        });

        List<AddressInfoDto> unloadAddressInfoDtos = addressMap.get(2);
        unloadAddressInfoDtos.forEach(address -> {
            EntAddressResDto entAddressResDtos = addressDetailMap.get(Long.parseLong(address.getAddressId()));
            if (entAddressResDtos.getId() != null) {
                KwtLogisticsOrderAddress unloadAddress = new KwtLogisticsOrderAddress();
                long addressId = new IdWorker(NumberConstant.ONE).nextId();
                unloadAddress.setId(addressId);
                unloadAddress.setLOrderId(lOrderId);
                unloadAddress.setAddressType(NumberConstant.TWO);
                unloadAddress.setName(entAddressResDtos.getName() == null ? null : entAddressResDtos.getName());
                unloadAddress.setContacts(entAddressResDtos.getContacts());
                unloadAddress.setPhone(entAddressResDtos.getPhone());
                unloadAddress.setCityCode(entAddressResDtos.getCityCode());
                unloadAddress.setCityName(entAddressResDtos.getCityName());
                unloadAddress.setDetailAddress(entAddressResDtos.getDetailAddress());
                unloadAddress.setLat(entAddressResDtos.getLat());
                unloadAddress.setLng(entAddressResDtos.getLng());
                unloadAddress.setEntryType(NumberConstant.FOUR);
                unloadAddress.setStatus(NumberConstant.ZERO);
                unloadAddress.setCreateBy(LoginUserHolder.getUserId());
                unloadAddress.setSort(address.getSort());
                Date date = new Date();
                unloadAddress.setCreateTime(date);
                unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
                unloadAddress.setUpdateTime(date);
                logisticsOrderAddressMapper.insert(unloadAddress);

                KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                orderAmount.setLOrderId(lOrderId);
                orderAmount.setLAddressId(addressId);
                orderAmount.setAmount(address.getAmount());
                orderAmount.setSubcontractAmount(defaultBigDecimal);
                orderAmount.setEntrustAmount(defaultBigDecimal);
                orderAmount.setLoadAmount(defaultBigDecimal);
                orderAmount.setUnloadAmount(defaultBigDecimal);
                orderAmount.setIgnoreAmount(defaultBigDecimal);
                orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                orderAmount.setStatus(0);
                orderAmount.setCreateBy(LoginUserHolder.getUserId());
                orderAmount.setCreateTime(new Date());
                orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                orderAmount.setUpdateTime(new Date());
                orderAmount.setDelFlag(0);
                logisticsOrderAmountMapper.insert(orderAmount);
            }
        });
    }

    private void saveCreateLogisticsOrder(AddLogisticsOrderParam orderDTO, Long lOrderId, Integer orderStatus, String lOrderNo) {
        KwtLogisticsOrder order = new KwtLogisticsOrder();
        order.setId(lOrderId);
        order.setEntId(LoginUserHolder.getEntId());
        order.setType(String.valueOf(NumberConstant.TWO));
        order.setLOrderNo(lOrderNo);
        order.setPids(lOrderId.toString());
        order.setSettlementCycle(orderDTO.getSettlementCycle());
        order.setBillingMode(orderDTO.getBillingMode());
        order.setPrice(orderDTO.getPrice());
        order.setPriceType(orderDTO.getPriceType());
        order.setPayment(orderDTO.getPayment());
        order.setAmount(orderDTO.getAmount());
        order.setUnit(orderDTO.getAmountUnit());
        order.setLoss(orderDTO.getLoss() == null ? null : orderDTO.getLoss());
        order.setLossUnit(orderDTO.getLossUnit());
        order.setGoodsPrice(orderDTO.getGoodsPrice() == null ? null : orderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(orderDTO.getGoodsPriceUnit());
        order.setStartTime(org.apache.commons.lang3.ObjectUtils.isEmpty(orderDTO.getStartTime()) ?
                null : DateUtil.localDateToLocalDateTimeStart(orderDTO.getStartTime()));
        order.setEndTime(org.apache.commons.lang3.ObjectUtils.isEmpty(orderDTO.getEndTime()) ?
                null : DateUtil.localDateToLocalDateTimeEnd(orderDTO.getEndTime()));
        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(orderDTO.getTaxRate());
        order.setRemark(orderDTO.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);
        order.setTotalTake(NumberConstant.ZERO);
        logisticsOrderMapper.insert(order);

    }

    /**
     * 物流订单-商品信息
     *
     * @param bo       页面请求数据
     * @param orderId  物流订单表编号
     * @param lOrderNo 物流订单编号
     */
    public void saveConsignLogisticsOrderGoods(AddLogisticsOrderParam bo, Long orderId, String lOrderNo) {
        KwtLogisticsOrderGoods goods = new KwtLogisticsOrderGoods();
        goods.setId(new IdWorker(NumberConstant.ONE).nextId());
//        kwtLogisticsOrderGoods.setGoodsId(bo.getGoodsId());
        goods.setGoodsName(bo.getGoodsName());
        goods.setGoodsType(bo.getGoodsType());
        goods.setSkuId(StringUtils.isBlank(bo.getSkuId()) ? null : bo.getSkuId());
        goods.setLOrderId(orderId);
        goods.setLOrderNo(lOrderNo);
        goods.setUpdateBy(LoginUserHolder.getUserId());
        goods.setUpdateTime(new Date());
        goods.setCreateBy(LoginUserHolder.getUserId());
        goods.setCreateTime(new Date());
        goodsMapper.insert(goods);

//        //辅助单位
//        List<GoodsUnitParam> assistUnit = bo.getAssistUnit();
//        if (CollectionUtils.isNotEmpty(assistUnit)) {
//            assistUnit.forEach(e -> {
//                KwtLogisticsOrderGoodsUnit unit = BeanUtils.copyProperties(e, KwtLogisticsOrderGoodsUnit.class);
//                unit.setGoodsId(kwtLogisticsOrderGoods.getGoodsId());
//                unit.setLOrderId(kwtLogisticsOrderGoods.getLOrderId());
//                unit.setUnit(unit.getFromUnit().equals(bo.getCarryingCapacityUnit()) ? unit.getToUnit() : unit.getFromUnit());
//                goodsUnitMapper.insert(unit);
//            });
//        }
    }


    public void logisticsOrderPush(AddLogisticsOrderParam addOrderDTO, String lOrderNo, Long createBy, Long entId) {
        //发起方
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        consignUnit.setTopEntId(entCacheResDto == null ? null : entCacheResDto.getId());
        consignUnit.setFirmName(addOrderDTO.getAcceptCompany());
        consignUnit.setContactsId(Long.parseLong(addOrderDTO.getConsignContactsId()));

        //接收方
        EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
        KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
        carriageUnit.setUnitType(NumberConstant.TWO);
        carriageUnit.setEntId(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
        carriageUnit.setTopEntId(entCacheResDto1 == null ? null : entCacheResDto1.getId());
        carriageUnit.setFirmName(addOrderDTO.getConsignCompany());
        carriageUnit.setContactsId(Long.parseLong(addOrderDTO.getAcceptContactsId()));

        sendLogisticsOrderToMessage(consignUnit, carriageUnit, lOrderNo, createBy, entId
                , messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl(),
                messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl(),
                MessageEnum.NEW_LOGISTICS_ORDER, MessageEnum.NEW_CARRIAGE_ORDER, "1"
        );

    }

    /**
     * 发起物流托运-[贸易订单物流托运确认/承运订单分包托运确认]
     *
     * @param consignUnit    托运单位
     * @param carriageUnit   承运单位
     * @param orderNo        单据号
     * @param createBy       创建人
     * @param entId          创建数据的企业id
     * @param pcConsignUrl   PC托运地址
     * @param appConsignUrl  app托运地址
     * @param pcCarriageUrl  PC承运地址
     * @param appCarriageUrl app承运地址
     * @param type           1代表给托运创建人发 2代表给承运创建人发
     */
    public void sendLogisticsOrderToMessage(KwtLogisticsOrderUnit consignUnit, KwtLogisticsOrderUnit carriageUnit,
                                            String orderNo, Long createBy, Long entId,
                                            String pcConsignUrl, String appConsignUrl,
                                            String pcCarriageUrl, String appCarriageUrl,
                                            MessageEnum consignMessageEnum,
                                            MessageEnum carriageMessageEnum,
                                            String type) {
        boolean flag = createBy.equals(consignUnit.getContactsId()) || createBy.equals(carriageUnit.getContactsId());
        Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN);
        map.put("orderNo", orderNo);
        if (flag && createBy.equals(consignUnit.getContactsId())) {
            commonService.sendLogisticsConsignMessage(consignUnit, map, pcConsignUrl, appConsignUrl, consignMessageEnum);
            commonService.sendLogisticsCarriageMessage(carriageUnit, map, pcCarriageUrl, appCarriageUrl, carriageMessageEnum);
        } else if (flag && createBy.equals(carriageUnit.getContactsId())) {
            commonService.sendLogisticsCarriageMessage(carriageUnit, map, pcCarriageUrl, appCarriageUrl, carriageMessageEnum);
            commonService.sendLogisticsConsignMessage(consignUnit, map, pcConsignUrl, appConsignUrl, consignMessageEnum);
        } else {
            commonService.sendLogisticsConsignMessage(consignUnit, map, pcConsignUrl, appConsignUrl, consignMessageEnum);
            commonService.sendLogisticsCarriageMessage(carriageUnit, map, pcCarriageUrl, appCarriageUrl, carriageMessageEnum);
            if ("1".equals(type)) {
                map.put("companyName", consignUnit.getFirmName());
                commonService.sendLogisticsCreateByMessage(createBy, entId, map, pcConsignUrl, appConsignUrl, consignMessageEnum);
            } else {
                map.put("companyName", carriageUnit.getFirmName());
                commonService.sendLogisticsCreateByMessage(createBy, entId, map, pcCarriageUrl, appCarriageUrl, carriageMessageEnum);
            }
        }
    }


    /**
     * 校验请求参数
     *
     * @param addLogisticsOrderParam
     */
    private void checkCreateLogisticOrderParam(AddLogisticsOrderParam addLogisticsOrderParam) {

        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getTaxRate())) {
            if (addLogisticsOrderParam.getTaxRate().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("税率填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getLoss())) {
            if (addLogisticsOrderParam.getLoss().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("合理损耗填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getGoodsPrice())) {
            if (addLogisticsOrderParam.getGoodsPrice().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("扣亏货值填写格式错误!");
            }
        }
    }

    /**
     * 物流订单-分包托运
     *
     * @param logisticsOrderSubcontractDto
     * @return
     */
    @Transactional
    public HttpResult logisticsOrderSubcontract(LogisticsOrderSubcontractDto bo) {
        HttpResult httpResult = ValidUtil.serviceValid(bo);
        String key = String.format(RedisConstant.LOGISTICS_ORDER_SUBCONTRACT_KEY, bo.getLOrderId());
        if (redisLockUtil.tryLock(key)) {
            try {
                if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
                    httpResult.setMsg(httpResult.getMsg());
                    httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
                    return httpResult;
                }

                KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectById(bo.getLOrderId());
                if (logisticsOrder == null) {
                    log.error("订单id查找失败:{},订单编号:{}", bo.getLOrderId(), bo.getLOrderNo());
                    throw new BusinessException("单据错误,数据不存在");
                }
                //todo  校验当前登录角色是否具有4P物流角色
                EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId());
                if (entCacheResDto == null) {
                    log.info("承运订单-分包托运 用户id:{}", LoginUserHolder.getUserId());
                    throw new BusinessException("企业信息查询异常");
                }
                if (!entCacheResDto.getEntTypes().contains(String.valueOf(NumberConstant.THREE))) {
                    throw new BusinessException("当前用户企业不具有分包功能权限！");
                }
                if (bo.getCarryingCapacity().compareTo(NumberConstant.ZERO_TWO) == 0) {
                    throw new BusinessException("分配承运量必须填写大于0.00");
                }
                BigDecimal subtract = logisticsOrder.getAmount().subtract((logisticsOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getEntrustAmount()));
                if (bo.getCarryingCapacity().compareTo(subtract) > 0) {
                    throw new BusinessException("分配承运量必须可待分配量");
                }
                KwtLogisticsOrder order = new KwtLogisticsOrder();
                if (!bo.getIsFullDose()) {
                    BigDecimal amount = bo.getAmount();
                    BigDecimal carryingCapacity = bo.getCarryingCapacity();
                    if (amount.compareTo(carryingCapacity) < 0) {
                        log.error("运订单分包托运-可分配量分配错误:{}", bo.getLOrderId());
                        throw new RuntimeException("可分配量分配错误");
                    }
                    if (ArrayUtil.isEmpty(bo.getCarryingCapacity())) {
                        throw new RuntimeException("不是全量分配时,分配量不能为空!");
                    }
                    order.setAmount(bo.getCarryingCapacity());
                    order.setUnit(bo.getCarryingCapacityUnit());
                } else {
                    order.setAmount(new BigDecimal(NumberConstant.ZERO));
                    order.setSubcontractAmount(new BigDecimal(NumberConstant.ZERO));
                    order.setUnit(bo.getCarryingCapacityUnit());
                }
                BigDecimal subcontractAmount = logisticsOrder.getSubcontractAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getSubcontractAmount();
                BigDecimal entrustAmount = logisticsOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getEntrustAmount();
                BigDecimal waitDistributionAmount = logisticsOrder.getAmount().subtract(subcontractAmount).subtract(entrustAmount);
                if (waitDistributionAmount.compareTo(NumberConstant.ZERO_TWO) == 0) {
                    throw new RuntimeException("剩余可分配量为0，不可进行分包操作！");
                }
                int level = logisticsLevel(logisticsOrder);
                long number = logisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>()
                                .eq(KwtLogisticsOrder::getDelFlag, NumberConstant.ZERO)
                                .apply(logisticsOrder.getId() != null, "FIND_IN_SET ('" + bo.getLOrderId() + "', pids)").ne(KwtLogisticsOrder::getId, bo.getLOrderId()))
                        .stream().count();
                String pidOrderNo = logisticsOrder.getLOrderNo();
                String substring = pidOrderNo.substring(0, 11);
                String lOrderNo = substring + logisticsOrder.getType() + String.valueOf(level) + String.valueOf(number + 1);
                Long orderId = new IdWorker(NumberConstant.ONE).nextId();
                //分包托运需要判断处于哪一级分包托运,需要记录当前分包数据-分包上游数据
                //判断是否已存在分包【当前分包只允许加上主单一共四级】
                if (level >= 4) {
                    throw new RuntimeException("分包次数已达上限!");
                }
                String pids = logisticsOrder.getPids();
                if (StringUtils.isNotBlank(pids)) {
                    pids = pids + StringConstant.COMMA + orderId;
                } else {
                    pids = bo.getLOrderId() + StringConstant.COMMA + orderId;
                }
                /**判断生成物流订单应生成哪一种单据状态*/
                List<Long> contractList = new ArrayList<>();
                contractList.add(Long.parseLong(bo.getContractId()));
                Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = contractService.queryContractBaseInfo(contractList);
                if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
                    throw new RuntimeException("并未有对应合同,应先签约合同");
                }
                if (longContractCommonInfoResDtoMap.get(Long.parseLong(bo.getContractId())) == null) {
                    throw new RuntimeException("并未有对应合同,应先签约合同");
                }
                ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(bo.getContractId()));
                /**状态判断
                 * 是否是已签约合同
                 * */
                // 0 已签约 1待签约
                Integer status = infoResDto.getStatus();
                Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
                if (NumberConstant.ONE == status) {
                    orderStatus = LogisticsOrderEnum.TO_BE_PLANNED.getCode();
                } else if (NumberConstant.ZERO == status) {
                    orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
                } else {
                    log.info("分包托运-物流订单id:{}," +
                                    "物流订单编号:{},合同id:{},合同信息:{}",
                            bo.getLOrderId(), bo.getLOrderNo(),
                            bo.getContractId(), JSONObject.toJSONString(infoResDto));
                    throw new RuntimeException("分包托运合同异常");
                }
                //主体信息保存
                logisticsOrderGoodsService.insertSubcontractLogisticsGoods(logisticsOrder, lOrderNo, orderId);
                insertSubcontractLogisticsOrder(bo, lOrderNo, order, orderId, pids, orderStatus, logisticsOrder);
                insertSubcontractLogisticsOrderContract(bo, orderId, infoResDto);
                insertSubcontractLogisticsOrderUnit(bo, orderId);
                insertSubcontractLogisticsOrderAddressAndAmount(bo, orderId, logisticsOrder);
                insertLogisticsOrderTrack(bo, orderId, orderStatus);
                if (bo.getBillingMode().equals("4")) {
                    insertLogisticsOrderLineFreight(bo, orderId);
                }
                //修改上级分配量以及可分配量委托量等
                logisticsOrder.setSubcontractAmount(logisticsOrder.getSubcontractAmount().add(bo.getCarryingCapacity()));
                logisticsOrderMapper.updateById(logisticsOrder);

                List<AddressInfoDto> addressInfo = bo.getAddressInfo();
                addressInfo.forEach(addressInfoDto -> {
                    String addressId = addressInfoDto.getAddressId();
                    KwtLogisticsOrderAmount orderAmount = logisticsOrderAmountMapper.selectById(addressId);
                    if (orderAmount != null) {
                        orderAmount.setSubcontractAmount(orderAmount.getSubcontractAmount().add(addressInfoDto.getAmount()));
                        logisticsOrderAmountMapper.updateById(orderAmount);
                    }
                });


                /**数据发送至消息列表*/
                String type = bo.getType();
                if ("1".equals(type)) {
                    /**托运订单*/
                } else if ("2".equals(type)) {
                    /**承运订单*/
                    EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getAcceptCompanyId()));
                    EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getConsignCompanyId()));
                    //托运单位
                    KwtLogisticsOrderUnit checkUnit = new KwtLogisticsOrderUnit();
                    checkUnit.setUnitType(1);
                    checkUnit.setFirmName(bo.getConsignCompany());
                    checkUnit.setEntId(Long.parseLong(bo.getConsignCompanyId()));
                    checkUnit.setTopEntId(consignentMap == null ? null : consignentMap.getId());
                    checkUnit.setContactsId(Long.parseLong(bo.getConsignContactsId()));
                    //承运单位
                    KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
                    carriageUnit.setUnitType(2);
                    carriageUnit.setFirmName(bo.getAcceptCompany());
                    carriageUnit.setEntId(Long.parseLong(bo.getAcceptCompanyId()));
                    carriageUnit.setContactsId(Long.parseLong(bo.getAcceptContactsId()));
                    carriageUnit.setFirmName(bo.getAcceptCompany());
                    carriageUnit.setTopEntId(checkentMap == null ? null : checkentMap.getId());

//        commonService.initIatingLogisticsConsignment(checkUnit, carriageUnit, logisticsOrder.getLOrderNo(), logisticsOrder.getCreateBy(), logisticsOrder.getEntId());
                    commonService.newSendLogisticsOrderToMessage(carriageUnit, checkUnit, logisticsOrder.getLOrderNo(), logisticsOrder.getCreateBy(), logisticsOrder.getEntId(),
                            messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl(),
                            messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl(),
                            MessageEnum.INITIATING_LOGISTICS_CONSIGNMENT, MessageEnum.NEW_CARRIAGE_ORDER,
                            "1");
                }
                /** 2024-03-26 停止mq->mongodb数据*/
                //修改父级mongodb数据
                //更新mongodb
                SckwLogisticsOrder lOrder = new SckwLogisticsOrder();
                lOrder.set_id(order.getId());
                lOrder.setLOrderId(order.getId());
                lOrder.setEntrustAmount(order.getEntrustAmount());
                lOrder.setStatus(String.valueOf(order.getStatus()));
                lOrder.setUpdateTime(order.getUpdateTime());
                lOrder.setUpdateBy(order.getUpdateBy());
                lOrder.setUpdateByName(LoginUserHolder.getUserName());
                lOrder.setSubcontractAmount(logisticsOrder.getSubcontractAmount().add(bo.getCarryingCapacity()));
//        lOrder.setIgnoreAmount(logisticsOrder.getIgnoreAmount().subtract(bo.getCarryingCapacity()));
                //rabbitMq业务汇总数据发送/消费对象
                SckwBusSum busSum = new SckwBusSum();
                //业务汇总类型
                busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
                //操作对象（1新增/2修改/3替换数据）
                busSum.setMethod(2);
                //业务汇总数据对象
//                busSum.setObject(lOrder);
//                streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
//                //新增当前分包mongodb数据
//                subcontractSendMongoDB(lOrderNo, orderId, bo, logisticsOrder, orderStatus);
            } finally {
                redisLockUtil.unlock(key);
            }
            return HttpResult.ok();
        }
        return HttpResult.error("当前数据正在处理,请勿重复提交");
    }

    private void subcontractSendMongoDB(String lOrderNo, Long orderId, LogisticsOrderSubcontractDto bo, KwtLogisticsOrder kwtLogisticsOrder, Integer orderStatus) {
        SckwLogisticsOrder logisticsOrder = new SckwLogisticsOrder();
        logisticsOrder.setStatus(String.valueOf(orderStatus));
        logisticsOrder.setLOrderId(orderId);
        logisticsOrder.setLOrderNo(lOrderNo);
        logisticsOrder.setLOrderPid(Long.parseLong(bo.getLOrderId()));
        logisticsOrder.setSettlementCycle(bo.getSettlementCycle());
        logisticsOrder.setPrice(bo.getPrice());
        logisticsOrder.setPriceType(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()) == null ?
                null : Long.parseLong(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()).getValue()));
        if (!bo.getIsFullDose()) {
            if (ArrayUtil.isEmpty(bo.getCarryingCapacity())) {
                throw new RuntimeException("不是全量分配时,分配量不能为空!");
            }
            logisticsOrder.setAmount(bo.getCarryingCapacity());
            logisticsOrder.setUnit(bo.getCarryingCapacityUnit());
            logisticsOrder.setCarryingCapacity(bo.getCarryingCapacity());
        } else {
            logisticsOrder.setAmount(NumberConstant.ZERO_TWO);
            logisticsOrder.setSubcontractAmount(NumberConstant.ZERO_TWO);
            logisticsOrder.setCarryingCapacity(NumberConstant.ZERO_TWO);
        }
        logisticsOrder.setLoss(bo.getLoss() == null ? null : bo.getLoss());
        logisticsOrder.setLossUnit(bo.getLossUnit());
        logisticsOrder.setGoodsPrice(bo.getGoodsPrice());
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        logisticsOrder.setSubcontractAmount(decimal);
        logisticsOrder.setEntrustAmount(decimal);
        logisticsOrder.setUnloadAmount(decimal);
        logisticsOrder.setLoadAmount(decimal);
        logisticsOrder.setIgnoreAmount(decimal);
        logisticsOrder.setDeficitPrice(decimal);
        logisticsOrder.setPayment(Long.parseLong(bo.getPayment()));
        logisticsOrder.setTaxRate(bo.getTaxRate() == null ? null : new BigDecimal(bo.getTaxRate()));
        logisticsOrder.setRemark(bo.getRemark());
        logisticsOrder.setEntId(LoginUserHolder.getEntId());
        logisticsOrder.setFirmName(remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId()).getFirmName());
        if (bo.getGoodsId() != null) {
            logisticsOrder.setGoodsId(Long.parseLong(bo.getGoodsId()));
            KwpGoods goods = goodsInfoService.getGoodsById(Long.parseLong(bo.getGoodsId()));
            logisticsOrder.setGoodsType(goods == null ? null : goods.getGoodsType());
            logisticsOrder.setGoodsSpec(goods == null ? null : goods.getSpec());
        }
        logisticsOrder.setGoodsName(bo.getGoodsName());
        logisticsOrder.setContractId(bo.getContractId());
        logisticsOrder.setContractNo(bo.getContractNo());
        logisticsOrder.setContractName(bo.getContractName());
        logisticsOrder.setContractSigningWay(bo.getPayment());
        logisticsOrder.setCheckEntId(Long.parseLong(bo.getConsignCompanyId()));
        logisticsOrder.setCheckFirmName(bo.getConsignCompany());
        logisticsOrder.setCheckContacts(bo.getConsignContacts());
        logisticsOrder.setCheckPhone(bo.getConsignContactPhone());
        logisticsOrder.setCarrierEntId(Long.parseLong(bo.getAcceptContactsId()));
        logisticsOrder.setCarrierFirmName(bo.getAcceptCompany());
        logisticsOrder.setCarrierContacts(bo.getAcceptContacts());
        //TODO 生成时并无时间
//        logisticsOrder.setLoadTime();
//        logisticsOrder.setunLoadTime();
        logisticsOrder.setCreateBy(LoginUserHolder.getUserId());
        logisticsOrder.setCreateByName(LoginUserHolder.getUserName());
        logisticsOrder.setCreateTime(new Date());
        logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
        logisticsOrder.setUpdateByName(LoginUserHolder.getUserName());
        logisticsOrder.setUpdateTime(new Date());
        logisticsOrder.setGoodsPriceUnit(bo.getGoodsPriceUnit());
        logisticsOrder.setContractName(bo.getContractName());
        logisticsOrder.setBillingMode(bo.getBillingMode());
        //rabbitMq业务汇总数据发送/消费对象
        SckwBusSum busSum = new SckwBusSum();
        //业务汇总类型
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        //操作对象（1新增/2修改）
        busSum.setMethod(1);
        //业务汇总数据对象
        busSum.setObject(logisticsOrder);
        streamBridge.send("sckw-busSum", JSON.toJSONString(busSum));

    }

    private void insertLogisticsOrderLineFreight(LogisticsOrderSubcontractDto dto, Long orderId) {
        List<LineFreightDto> lineFreightList = dto.getLineFreightList();
        Map<Long, BigDecimal> lineFreihtMap = lineFreightList.stream().collect(Collectors.toMap(LineFreightDto::getLineFreightId, LineFreightDto::getAmount));
        List<Long> lineFreightId = lineFreightList.stream().map(t -> t.getLineFreightId()).distinct().collect(Collectors.toList());
        Map<Long, LineFreightAddressRes> resMap = manageService.findLineFreightAddress(lineFreightId);
        if (resMap != null) {
            lineFreightId.stream().forEach(id -> {
                if (resMap.get(id) != null) {
                    LineFreightAddressRes res = resMap.get(id);
                    KwtLogisticsOrderLineFreightRate lineFreightRate = new KwtLogisticsOrderLineFreightRate();
                    lineFreightRate.setLOrderId(orderId);
                    lineFreightRate.setName(res.getName());
                    lineFreightRate.setLoadName(res.getLoadName());
                    lineFreightRate.setLoadCityCode(res.getLoadCityCode());
                    lineFreightRate.setLoadCityName(res.getLoadCityName());
                    lineFreightRate.setLoadDetailAddress(res.getLoadDetailAddress());
                    lineFreightRate.setLoadLat(res.getLoadLat());
                    lineFreightRate.setLoadLng(res.getLoadLng());
                    lineFreightRate.setUnloadName(res.getUnloadName());
                    lineFreightRate.setUnloadCityCode(res.getUnloadCityCode());
                    lineFreightRate.setUnloadCityName(res.getUnloadCityName());
                    lineFreightRate.setUnloadDetailAddress(res.getUnloadDetailAddress());
                    lineFreightRate.setUnloadLat(res.getUnloadLat());
                    lineFreightRate.setUnloadLng(res.getUnloadLng());
                    lineFreightRate.setTransportMileage(res.getTransportMileage());
                    lineFreightRate.setTransportPrice(res.getTransportPrice());
                    BigDecimal defultBigDecimal = new BigDecimal("0.00");
                    lineFreightRate.setSettlementAmount(defultBigDecimal);
                    lineFreightRate.setTransportAmount(lineFreihtMap.get(id));
                    lineFreightRate.setId(new IdWorker(NumberConstant.FOUR).nextId());
                    lineFreightRate.setRemark(res.getRemark());
                    lineFreightRate.setStatus(res.getStatus());
                    lineFreightRate.setCreateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setCreateTime(new Date());
                    lineFreightRate.setUpdateBy(LoginUserHolder.getUserId());
                    lineFreightRate.setUpdateTime(new Date());
                    lineFreightRate.setDelFlag(0);
                    logisticsOrderLineFreightRateMapper.insert(lineFreightRate);
                }
            });
        }

    }

    private void insertLogisticsOrderTrack(LogisticsOrderSubcontractDto bo, Long orderId, Integer orderStatus) {
        KwtLogisticsOrderTrack entity = new KwtLogisticsOrderTrack();
        entity.setId(new IdWorker(NumberConstant.ONE).nextId());
        entity.setLOrderId(orderId);
        entity.setStatus(orderStatus);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setCreateBy(LoginUserHolder.getUserId());
        entity.setUpdateBy(LoginUserHolder.getUserId());
        entity.setRemark(bo.getRemark());
        logisticsOrderTrackMapper.insert(entity);
    }

    private void insertSubcontractLogisticsOrderAddressAndAmount(LogisticsOrderSubcontractDto bo, Long orderId, KwtLogisticsOrder logisticsOrder) {
        List<AddressInfoDto> addressInfo = bo.getAddressInfo();
        Map<Integer, List<AddressInfoDto>> addressMap = addressInfo.stream().collect(Collectors.groupingBy(AddressInfoDto::getAddressType));

        /**处理装货*/
        List<AddressInfoDto> loadAddress = addressMap.get(NumberConstant.ONE);
        List<String> loadAddressIds = loadAddress.stream().map(AddressInfoDto::getAddressId).distinct().collect(Collectors.toList());
        List<KwtLogisticsOrderAddress> orderLoadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, logisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE)
                .in(KwtLogisticsOrderAddress::getId, loadAddressIds)
        );
        Map<Long, KwtLogisticsOrderAddress> parentLoadOrderMap = new HashMap<Long, KwtLogisticsOrderAddress>();
        if (!CollectionUtils.isEmpty(orderLoadAddress)) {
            parentLoadOrderMap = orderLoadAddress.stream().collect(Collectors.toMap(KwtLogisticsOrderAddress::getId, Function.identity()));
        }
        if (!CollectionUtils.isEmpty(loadAddress)) {
            int sort = 1;
            for (AddressInfoDto address : loadAddress) {
                if (address.getAmount().compareTo(new BigDecimal("0.00")) == 0) {
                    continue;
                }
                if (parentLoadOrderMap.get(Long.parseLong(address.getAddressId())) != null) {
                    KwtLogisticsOrderAddress loadAddressData = parentLoadOrderMap.get(Long.parseLong(address.getAddressId()));
                    KwtLogisticsOrderAddress loadOrderAddress = new KwtLogisticsOrderAddress();
                    long addressId = new IdWorker(NumberConstant.ONE).nextId();
                    loadOrderAddress.setId(addressId);
                    loadOrderAddress.setAddressType(NumberConstant.ONE);
                    loadOrderAddress.setTAddressId(loadAddressData.getTAddressId() == null ? null : loadAddressData.getTAddressId());
                    loadOrderAddress.setPAddressId(loadAddressData.getId());
                    loadOrderAddress.setDetailAddress(loadAddressData.getDetailAddress());
                    loadOrderAddress.setContacts(loadAddressData.getContacts());
                    loadOrderAddress.setLOrderId(orderId);
                    loadOrderAddress.setSort(sort);
                    loadOrderAddress.setLat(loadAddressData.getLat());
                    loadOrderAddress.setFence(loadAddressData.getFence());
                    loadOrderAddress.setCityName(loadAddressData.getCityName());
                    loadOrderAddress.setEntryType(NumberConstant.FOUR);
                    loadOrderAddress.setCreateTime(new Date());
                    loadOrderAddress.setPhone(loadAddressData.getPhone());
                    loadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
                    loadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
                    loadOrderAddress.setUpdateTime(new Date());
                    loadOrderAddress.setName(loadAddressData.getName());
                    loadOrderAddress.setType(loadAddressData.getType());
                    loadOrderAddress.setCityCode(loadAddressData.getCityCode());
                    loadOrderAddress.setLng(loadAddressData.getLng());
                    loadOrderAddress.setRemark(loadAddressData.getRemark());
                    loadOrderAddress.setStatus(loadAddressData.getStatus());
                    logisticsOrderAddressMapper.insert(loadOrderAddress);

                    KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                    BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                    orderAmount.setLOrderId(orderId);
                    orderAmount.setLAddressId(loadOrderAddress.getId());
                    orderAmount.setAmount(address.getAmount());
                    orderAmount.setSubcontractAmount(defaultBigDecimal);
                    orderAmount.setEntrustAmount(defaultBigDecimal);
                    orderAmount.setLoadAmount(defaultBigDecimal);
                    orderAmount.setUnloadAmount(defaultBigDecimal);
                    orderAmount.setIgnoreAmount(defaultBigDecimal);
                    orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                    orderAmount.setStatus(0);
                    orderAmount.setCreateBy(LoginUserHolder.getUserId());
                    orderAmount.setCreateTime(new Date());
                    orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                    orderAmount.setUpdateTime(new Date());
                    orderAmount.setDelFlag(0);
                    logisticsOrderAmountMapper.insert(orderAmount);
                    sort += 1;
                }
            }

        }
        /**处理卸货*/
        List<AddressInfoDto> unloadAddress = addressMap.get(NumberConstant.TWO);
        List<String> unloadAddressIds = unloadAddress.stream().map(AddressInfoDto::getAddressId).distinct().collect(Collectors.toList());
        List<KwtLogisticsOrderAddress> orderUnLoadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, logisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO)
                .in(KwtLogisticsOrderAddress::getId, unloadAddressIds)
        );
        Map<Long, KwtLogisticsOrderAddress> parentUnloadOrderMap = new HashMap<Long, KwtLogisticsOrderAddress>();
        if (!CollectionUtils.isEmpty(orderUnLoadAddress)) {
            parentUnloadOrderMap = orderUnLoadAddress.stream().collect(Collectors.toMap(KwtLogisticsOrderAddress::getId, Function.identity()));
        }

        if (!ObjectUtils.isEmpty(unloadAddress)) {
            int sort = 1;
            for (AddressInfoDto address : unloadAddress) {
                if (address.getAmount().compareTo(new BigDecimal("0.00")) == 0) {
                    continue;
                }
                if (parentUnloadOrderMap.get(Long.parseLong(address.getAddressId())) != null) {
                    KwtLogisticsOrderAddress loadAddressData = parentUnloadOrderMap.get(Long.parseLong(address.getAddressId()));
                    KwtLogisticsOrderAddress unloadOrderAddress = new KwtLogisticsOrderAddress();
                    long addressId = new IdWorker(NumberConstant.ONE).nextId();
                    unloadOrderAddress.setId(addressId);
                    unloadOrderAddress.setAddressType(NumberConstant.TWO);
                    unloadOrderAddress.setTAddressId(loadAddressData.getTAddressId() == null ? null : loadAddressData.getTAddressId());
                    unloadOrderAddress.setPAddressId(loadAddressData.getId());
                    unloadOrderAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
                    unloadOrderAddress.setContacts(loadAddressData.getContacts());
                    unloadOrderAddress.setLOrderId(orderId);
                    unloadOrderAddress.setLat(loadAddressData.getLat());
                    unloadOrderAddress.setFence(loadAddressData.getFence());
                    unloadOrderAddress.setCityName(loadAddressData.getCityName());
                    unloadOrderAddress.setEntryType(NumberConstant.FOUR);
                    unloadOrderAddress.setPhone(loadAddressData.getPhone());
                    unloadOrderAddress.setDetailAddress(loadAddressData.getDetailAddress());
                    unloadOrderAddress.setCreateTime(new Date());
                    unloadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
                    unloadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
                    unloadOrderAddress.setUpdateTime(new Date());
                    unloadOrderAddress.setName(loadAddressData.getName());
                    unloadOrderAddress.setType(loadAddressData.getType());
                    unloadOrderAddress.setCityCode(loadAddressData.getCityCode());
                    unloadOrderAddress.setLng(loadAddressData.getLng());
                    unloadOrderAddress.setRemark(loadAddressData.getRemark());
                    unloadOrderAddress.setStatus(loadAddressData.getStatus());
                    unloadOrderAddress.setSort(sort);
                    logisticsOrderAddressMapper.insert(unloadOrderAddress);

                    KwtLogisticsOrderAmount orderAmount = new KwtLogisticsOrderAmount();
                    BigDecimal defaultBigDecimal = new BigDecimal("0.00");
                    orderAmount.setLOrderId(orderId);
                    orderAmount.setLAddressId(unloadOrderAddress.getId());
                    orderAmount.setAmount(address.getAmount());
                    orderAmount.setSubcontractAmount(defaultBigDecimal);
                    orderAmount.setEntrustAmount(defaultBigDecimal);
                    orderAmount.setLoadAmount(defaultBigDecimal);
                    orderAmount.setUnloadAmount(defaultBigDecimal);
                    orderAmount.setIgnoreAmount(defaultBigDecimal);
                    orderAmount.setId(new IdWorker(NumberConstant.THREE).nextId());
                    orderAmount.setStatus(0);
                    orderAmount.setCreateBy(LoginUserHolder.getUserId());
                    orderAmount.setCreateTime(new Date());
                    orderAmount.setUpdateBy(LoginUserHolder.getUserId());
                    orderAmount.setUpdateTime(new Date());
                    orderAmount.setDelFlag(0);
                    logisticsOrderAmountMapper.insert(orderAmount);
                    sort += 1;
                }
            }
        }
    }


    private void insertSubcontractLogisticsOrderUnit(LogisticsOrderSubcontractDto bo, Long orderId) {
        EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getAcceptCompanyId()));
        EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getCheckCompanyId()));
        KwtLogisticsOrderUnit checkUnit = new KwtLogisticsOrderUnit()
                .setLOrderId(orderId)
                .setId(new IdWorker(NumberConstant.ONE).nextId())
                .setUnitType(NumberConstant.ONE)
                .setFirmName(bo.getCheckCompany())
                .setRemark(bo.getRemark())
                .setTopEntId(checkentMap == null ? null : checkentMap.getId())
                .setEntId(Long.parseLong(bo.getCheckCompanyId()))
                .setContacts(bo.getCheckContacts())
                .setPhone(bo.getCheckContactPhone())
                .setCreateBy(LoginUserHolder.getUserId())
                .setCreateTime(new Date())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateTime(new Date())
                .setContactsId(Long.parseLong(bo.getCheckContactsId()));
        logisticsOrderUnitMapper.insert(checkUnit);

        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit()
                .setLOrderId(orderId)
                .setId(new IdWorker(NumberConstant.ONE).nextId())
                .setUnitType(NumberConstant.TWO)
                .setFirmName(bo.getAcceptCompany())
                .setRemark(bo.getRemark())
                .setTopEntId(consignentMap == null ? null : consignentMap.getId())
                .setEntId(Long.parseLong(bo.getAcceptCompanyId()))
                .setContacts(bo.getAcceptContacts())
                .setPhone(bo.getAcceptContactPhone())
                .setCreateBy(LoginUserHolder.getUserId())
                .setCreateTime(new Date())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateTime(new Date())
                .setContactsId(Long.parseLong(bo.getAcceptContactsId()));
        logisticsOrderUnitMapper.insert(consignUnit);
    }


    private void insertSubcontractLogisticsOrderContract(LogisticsOrderSubcontractDto bo, Long orderId, ContractCommonInfoResDto infoResDto) {
        KwtLogisticsOrderContract kwtLogisticsOrderContract = new KwtLogisticsOrderContract();
        kwtLogisticsOrderContract.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwtLogisticsOrderContract.setLOrderId(orderId);
        kwtLogisticsOrderContract.setContractId(Long.parseLong(bo.getContractId()));
        kwtLogisticsOrderContract.setContractName(bo.getContractName() == null ? infoResDto.getContactName() : bo.getContractName());
        kwtLogisticsOrderContract.setContractNo(bo.getContractNo() == null ? infoResDto.getContractCode() : bo.getContractNo());
        kwtLogisticsOrderContract.setSigningWay(infoResDto.getSigningWay() != null ? String.valueOf(infoResDto.getSigningWay()) : null);
        kwtLogisticsOrderContract.setRemark(bo.getRemark());
        kwtLogisticsOrderContract.setCreateBy(LoginUserHolder.getUserId());
        kwtLogisticsOrderContract.setUpdateBy(LoginUserHolder.getUserId());
        kwtLogisticsOrderContract.setCreateTime(new Date());
        kwtLogisticsOrderContract.setUpdateTime(new Date());
        logisticsOrderContractMapper.insert(kwtLogisticsOrderContract);
    }

    /**
     * 分包托运-订单-主体
     *
     * @param bo             页面填写分包数据
     * @param lOrderNo       当前分包物流订单编号
     * @param order          当前物流订单数据
     * @param orderId        当前订单主键id
     * @param pids           组装的pids
     * @param orderStatus    当前单据状态
     * @param logisticsOrder 父级物流订单
     */
    private void insertSubcontractLogisticsOrder(LogisticsOrderSubcontractDto bo, String lOrderNo,
                                                 KwtLogisticsOrder order,
                                                 Long orderId, String pids, Integer orderStatus, KwtLogisticsOrder logisticsOrder) {
        order.setId(orderId);
        order.setEntId(LoginUserHolder.getEntId());
        order.setType(logisticsOrder.getType());
        order.setTOrderId(logisticsOrder.getTOrderId());
        order.setTOrderNo(logisticsOrder.getTOrderNo());
        order.setLOrderNo(lOrderNo);
        //分包时,存放分包上级id
        order.setPid(Long.parseLong(bo.getLOrderId()));
        //存放所有的分包的父级id
        order.setPids(pids);
        order.setSettlementCycle(bo.getSettlementCycle());
        order.setPrice(bo.getPrice());
        order.setPriceType(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()) == null ?
                null : Long.parseLong(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()).getValue()));
        order.setAmount(bo.getCarryingCapacity());
        order.setBillingMode(bo.getBillingMode());
        order.setLoss(bo.getLoss());
        order.setLossUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()) == null ?
                null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()).getValue());
        order.setGoodsPrice(bo.getGoodsPrice() == null ? null : bo.getGoodsPrice());
        order.setGoodsPriceUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()) == null ?
                null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()).getValue());
        order.setStartTime(bo.getStartTime() == null ? null : DateUtil.localDateToLocalDateTimeStart(bo.getStartTime()));
        order.setEndTime(bo.getEndTime() == null ? null : DateUtil.localDateToLocalDateTimeEnd(bo.getEndTime()));
        order.setRemark(bo.getRemark());
        order.setPayment(Long.parseLong(bo.getPayment()));
        order.setTaxRate(new BigDecimal(bo.getTaxRate()));
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateTime(new Date());
        order.setStatus(orderStatus);
        /**补充默认值*/
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        order.setEntrustAmount(decimal);
        order.setSubcontractAmount(decimal);
        order.setLoadAmount(decimal);
        order.setUnloadAmount(decimal);
        order.setIgnoreAmount(decimal);
        order.setDeficitPrice(decimal);
        order.setDeficitAmount(decimal);
        order.setTotalUnloadAmount(decimal);
        order.setTotalLoadAmount(decimal);
        order.setBindStatus(String.valueOf(NumberConstant.ZERO));
        order.setTotalTake(NumberConstant.ZERO);
        logisticsOrderMapper.insert(order);
    }

    /**
     * @param logisticsOrder 承运订单
     * @description 当前承运订单所属分包层级
     * @author zk
     * @date 2023/7/24
     **/
    public int logisticsLevel(KwtLogisticsOrder logisticsOrder) {
        String pids = logisticsOrder.getPids();
        String[] idArrays = StringUtils.isBlank(pids) ? new String[0] : pids.split(Global.COMMA);
        return idArrays.length <= 1 ? Global.NUMERICAL_ONE : idArrays.length;
    }

}
