package com.sckw.transport.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.res.ContractCommonInfoResDto;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.core.common.enums.StringConstant;
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.enums.*;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.DateUtil;
import com.sckw.excel.utils.ValidUtil;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.fleet.api.model.vo.RTruckVo;
import com.sckw.manage.api.RemoteManageService;
import com.sckw.manage.api.model.dto.res.FindEntCooperateResVo;
import com.sckw.mongo.enums.BusinessTypeEnum;
import com.sckw.mongo.model.SckwLogisticsOrder;
import com.sckw.mongo.model.SckwWaybillOrder;
import com.sckw.mongo.model.TableTops;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.CompleteLogisticsOrderParam;
import com.sckw.order.api.model.CreateOrCancelLogisticsOrderParam;
import com.sckw.order.api.model.OrderDetailRes;
import com.sckw.order.api.model.UnitInfoDetailRes;
import com.sckw.payment.api.dubbo.PaymentDubboService;
import com.sckw.payment.api.model.dto.SettlementMoney;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.product.api.model.KwpGoods;
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.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.transport.common.config.MessageUrlConfig;
import com.sckw.transport.common.enums.OrderTypeEnum;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.*;
import com.sckw.transport.model.param.AcceptCarriageOrderQuery;
import com.sckw.transport.model.param.DriverParam;
import com.sckw.transport.model.param.LogisticsOrderStatisticsParam;
import com.sckw.transport.model.vo.*;
import com.sckw.transport.model.vo.execlVo.AcceptCarriageOrderExcelVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.sckw.excel.utils.DateUtil.DEF_DATE_FORMAT;

/**
 * @author lfdc
 * @description 承运订单service
 * @date 2023-06-26 16:06:11
 */
@Slf4j
@Service
public class AcceptCarriageOrderService {

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

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

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

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

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

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

    @Autowired
    TransportCommonService transportCommonService;

    @Autowired
    private MessageUrlConfig messageUrlConfig;

    @Autowired
    public CommonService commonService;

    @Autowired
    public KwtWaybillOrderService waybillOrderService;

    @Resource
    private StreamBridge streamBridge;

    @Autowired
    private KwtLogisticsOrderMapper logisticsOrderMapper;

    @Autowired
    private KwtLogisticsOrderTrackMapper logisticsOrderTrackMapper;

    @Autowired
    private KwtWaybillOrderMapper waybillOrderMapper;

    @Autowired
    private KwtWaybillOrderTicketMapper waybillOrderTicketMapper;

    @Autowired
    private KwtWaybillOrderTrackMapper waybillOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper kwtLogisticsOrderGoodsMapper;

    @Autowired
    public KwtLogisticsOrderContractMapper kwtLogisticsOrderContractMapper;

    @Autowired
    private KwtLogisticsOrderCirculateMapper logisticsOrderCirculateMapper;

    @Autowired
    private KwtLogisticsOrderAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper logisticsOrderUnitMapper;

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 承运订单-分包托运
     *
     * @param bo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult subcontractConsignment(SubcontractConsignmentDTO bo) {
        HttpResult httpResult = ValidUtil.serviceValid(bo);
        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.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, 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(new BigDecimal("0.00")) == 0) {
            throw new BusinessException("分配承运量必须填写大于0.00");
        }
        BigDecimal subtract = logisticsOrder.getAmount().subtract((logisticsOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : logisticsOrder.getEntrustAmount()));
        if (bo.getCarryingCapacity().compareTo(subtract) == 1) {
            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 ? new BigDecimal("0.00") : logisticsOrder.getSubcontractAmount();
        BigDecimal entrustAmount = logisticsOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : logisticsOrder.getEntrustAmount();
        BigDecimal waitDistributionAmount = logisticsOrder.getAmount().subtract(subcontractAmount).subtract(entrustAmount);
        if (waitDistributionAmount.compareTo(new BigDecimal("0.00")) == 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();
        /**分包托运需要判断处于哪一级分包托运
         * 需要记录当前分包数据-分包上游数据
         * */
        /**
         * 判断是否已存在分包【当前分包只允许加上主单一共三级】*/
        Long count = logisticsOrderMapper.selectCount(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .in(KwtLogisticsOrder::getPids, bo.getLOrderId()));
        if (count > NumberConstant.TWO) {
            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 = remoteContractService.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("生成物流托运合同异常");
        }
        //主体信息保存
        insertSubcontractLogisticsGoods(bo, lOrderNo, orderId);
        insertSubcontractLogisticsOrder(bo, lOrderNo, order, orderId, pids, orderStatus, logisticsOrder);
        insertSubcontractLogisticsOrderContract(bo, orderId, infoResDto);
        insertSubcontractLogisticsOrderUnit(bo, orderId);
        insertSubcontractLogisticsOrderAddress(bo, orderId, logisticsOrder);
        insertLogisticsOrderTrack(bo, orderId, orderStatus);
        //修改上级分配量以及可分配量委托量等
        logisticsOrder.setSubcontractAmount(logisticsOrder.getSubcontractAmount().add(bo.getCarryingCapacity()));
//        logisticsOrder.setIgnoreAmount(logisticsOrder.getIgnoreAmount().subtract(bo.getCarryingCapacity()));
        logisticsOrderMapper.updateById(logisticsOrder);

        /**数据发送至消息列表*/
        EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getConsignCompanyId()));
        EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getCheckCompanyId()));

        //托运单位
        KwtLogisticsOrderUnit checkUnit = new KwtLogisticsOrderUnit();

        checkUnit.setUnitType(1);
        checkUnit.setFirmName(bo.getCheckCompany());
        checkUnit.setEntId(Long.parseLong(bo.getCheckCompanyId()));
        checkUnit.setTopEntId(consignentMap == null ? null : consignentMap.getId());
        checkUnit.setContactsId(Long.parseLong(bo.getCheckContactsId()));

        //承运单位
        KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
        carriageUnit.setUnitType(2);
        carriageUnit.setFirmName(bo.getConsignCompany());
        carriageUnit.setEntId(Long.parseLong(bo.getConsignCompanyId()));
        carriageUnit.setContactsId(Long.parseLong(bo.getConsignContactsId()));
        carriageUnit.setFirmName(bo.getConsignCompany());
        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");

        //修改父级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);
        return HttpResult.ok();
    }

    /**
     * 推送数据到MongoDB
     *
     * @param lOrderNo          物流订单编号
     * @param orderId           物流订单id
     * @param bo                页面传输实体
     * @param kwtLogisticsOrder 物流订单数据(上一级)
     */
    private void subcontractSendMongoDB(String lOrderNo, Long orderId, SubcontractConsignmentDTO 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(new BigDecimal("0.00"));
            logisticsOrder.setSubcontractAmount(new BigDecimal("0.00"));
            logisticsOrder.setCarryingCapacity(new BigDecimal("0.00"));
        }
        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.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());
        KwtLogisticsOrderAddress orderLoadAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, kwtLogisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE));
        KwtLogisticsOrderAddress orderUnLoadAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, kwtLogisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO));
        if (!ObjectUtils.isEmpty(orderLoadAddress)) {
            logisticsOrder.setLoadType(orderLoadAddress.getType());
            logisticsOrder.setLoadCityCode(orderLoadAddress.getCityCode());
            logisticsOrder.setLoadCityName(orderLoadAddress.getCityName());
            logisticsOrder.setLoadDetailAddress(orderLoadAddress.getDetailAddress());
            logisticsOrder.setLoadLat(orderLoadAddress.getLat());
            logisticsOrder.setLoadPhone(orderLoadAddress.getPhone());
            logisticsOrder.setLoadLng(orderLoadAddress.getLng());
            logisticsOrder.setLoadContacts(orderLoadAddress.getContacts());
        }
        if (!ObjectUtils.isEmpty(orderUnLoadAddress)) {
            logisticsOrder.setUnloadType(orderUnLoadAddress.getType());
            logisticsOrder.setUnloadPhone(orderUnLoadAddress.getPhone());
            logisticsOrder.setUnloadCityCode(orderUnLoadAddress.getCityCode());
            logisticsOrder.setUnloadCityName(orderUnLoadAddress.getCityName());
            logisticsOrder.setUnloadDetailAddress(orderUnLoadAddress.getDetailAddress());
            logisticsOrder.setUnloadLat(orderUnLoadAddress.getLat());
            logisticsOrder.setUnloadLng(orderUnLoadAddress.getLng());
            logisticsOrder.setUnloadContacts(orderUnLoadAddress.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.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));
    }

    /**
     * 分包托运-承运订单-单据状态
     *
     * @param bo
     * @param orderId
     */
    private void insertLogisticsOrderTrack(SubcontractConsignmentDTO 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);
    }

    /**
     * 分包托运-承运订单-装卸货地址信息
     *
     * @param bo
     * @param orderId
     * @param logisticsOrder
     */
    private void insertSubcontractLogisticsOrderAddress(SubcontractConsignmentDTO bo, Long orderId, KwtLogisticsOrder logisticsOrder) {
        KwtLogisticsOrderAddress loadOrderAddress = new KwtLogisticsOrderAddress();
        KwtLogisticsOrderAddress unloadOrderAddress = new KwtLogisticsOrderAddress();
        KwtLogisticsOrderAddress orderLoadAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, logisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE));
        KwtLogisticsOrderAddress orderUnLoadAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(KwtLogisticsOrderAddress::getLOrderId, logisticsOrder.getId())
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO));
        if (!ObjectUtils.isEmpty(orderLoadAddress)) {
            loadOrderAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
            loadOrderAddress.setAddressType(NumberConstant.ONE);
            loadOrderAddress.setDetailAddress(orderLoadAddress.getDetailAddress());
            loadOrderAddress.setContacts(orderLoadAddress.getContacts());
            loadOrderAddress.setLOrderId(orderId);
            loadOrderAddress.setLat(orderLoadAddress.getLat());
            loadOrderAddress.setFence(orderLoadAddress.getFence());
            loadOrderAddress.setCityName(orderLoadAddress.getCityName());
            loadOrderAddress.setEntryType(NumberConstant.FOUR);
            loadOrderAddress.setCreateTime(new Date());
            loadOrderAddress.setPhone(orderLoadAddress.getPhone());
            loadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
            loadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
            loadOrderAddress.setUpdateTime(new Date());
            loadOrderAddress.setName(orderLoadAddress.getName());
            loadOrderAddress.setType(orderLoadAddress.getType());
            loadOrderAddress.setCityCode(orderLoadAddress.getCityCode());
            loadOrderAddress.setLng(orderLoadAddress.getLng());
            loadOrderAddress.setRemark(orderLoadAddress.getRemark());
            loadOrderAddress.setStatus(orderLoadAddress.getStatus());
            logisticsOrderAddressMapper.insert(loadOrderAddress);
        }
        if (!ObjectUtils.isEmpty(orderUnLoadAddress)) {
            unloadOrderAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
            unloadOrderAddress.setAddressType(NumberConstant.TWO);
            unloadOrderAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
            unloadOrderAddress.setContacts(orderUnLoadAddress.getContacts());
            unloadOrderAddress.setLOrderId(orderId);
            unloadOrderAddress.setLat(orderUnLoadAddress.getLat());
            unloadOrderAddress.setFence(orderUnLoadAddress.getFence());
            unloadOrderAddress.setCityName(orderUnLoadAddress.getCityName());
            unloadOrderAddress.setEntryType(NumberConstant.FOUR);
            unloadOrderAddress.setPhone(orderUnLoadAddress.getPhone());
            unloadOrderAddress.setDetailAddress(orderUnLoadAddress.getDetailAddress());
            unloadOrderAddress.setCreateTime(new Date());
            unloadOrderAddress.setCreateBy(LoginUserHolder.getUserId());
            unloadOrderAddress.setUpdateBy(LoginUserHolder.getUserId());
            unloadOrderAddress.setUpdateTime(new Date());
            unloadOrderAddress.setName(orderUnLoadAddress.getName());
            unloadOrderAddress.setType(orderUnLoadAddress.getType());
            unloadOrderAddress.setCityCode(orderUnLoadAddress.getCityCode());
            unloadOrderAddress.setLng(orderUnLoadAddress.getLng());
            unloadOrderAddress.setRemark(orderUnLoadAddress.getRemark());
            unloadOrderAddress.setStatus(orderUnLoadAddress.getStatus());
            logisticsOrderAddressMapper.insert(unloadOrderAddress);
        }
    }

    /**
     * 分包托运-承运订单-单位信息
     *
     * @param bo
     * @param orderId
     */
    private void insertSubcontractLogisticsOrderUnit(SubcontractConsignmentDTO bo, Long orderId) {
        EntCacheResDto consignentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getConsignCompanyId()));
//        .setContactsId(consignentMap.get(Long.parseLong(bo.getConsignCompanyId())).getContactsId())
        EntCacheResDto checkentMap = remoteSystemService.queryEntTreeById(Long.parseLong(bo.getCheckCompanyId()));
////.setContactsId(checkentMap.get(Long.parseLong(bo.getCheckCompanyId())).getContactsId())
        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.getConsignCompany())
                .setRemark(bo.getRemark())
                .setTopEntId(consignentMap == null ? null : consignentMap.getId())
                .setEntId(Long.parseLong(bo.getConsignCompanyId()))
                .setContacts(bo.getConsignContacts())
                .setPhone(bo.getConsignContactPhone())
                .setCreateBy(LoginUserHolder.getUserId())
                .setCreateTime(new Date())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateTime(new Date())
                .setContactsId(Long.parseLong(bo.getConsignContactsId()));
        logisticsOrderUnitMapper.insert(consignUnit);
    }

    /**
     * 分包托运-承运订单-合同信息
     *
     * @param bo
     * @param orderId
     */
    private void insertSubcontractLogisticsOrderContract(SubcontractConsignmentDTO 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());
        kwtLogisticsOrderContractMapper.insert(kwtLogisticsOrderContract);
    }

    /**
     * 分包托运-承运订单-主体
     *
     * @param bo             页面填写分包数据
     * @param lOrderNo       当前分包物流订单编号
     * @param order          当前物流订单数据
     * @param orderId        当前订单主键id
     * @param pids           组装的pids
     * @param orderStatus    当前单据状态
     * @param logisticsOrder 父级物流订单
     */
    private void insertSubcontractLogisticsOrder(SubcontractConsignmentDTO 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(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.getShipmentsDateTime() == null ? null : DateUtil.localDateToLocalDateTimeStart(bo.getShipmentsDateTime()));
        order.setEndTime(bo.getReceiveGoodsDateTime() == null ? null : DateUtil.localDateToLocalDateTimeEnd(bo.getReceiveGoodsDateTime()));
        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));
        logisticsOrderMapper.insert(order);
    }

    /**
     * 分包托运-承运订单-商品信息
     *
     * @param bo
     * @param lOrderNo
     * @param orderId
     */
    private void insertSubcontractLogisticsGoods(SubcontractConsignmentDTO bo, String lOrderNo, Long orderId) {
        KwtLogisticsOrderGoods kwtLogisticsOrderGoods = new KwtLogisticsOrderGoods();
        kwtLogisticsOrderGoods.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwtLogisticsOrderGoods.setGoodsId(bo.getGoodsId() == null ? null : Long.parseLong(bo.getGoodsId()));
        kwtLogisticsOrderGoods.setGoodsName(bo.getGoodsName());
//        kwtLogisticsOrderGoods.setSkuId(StringUtils.isBlank(bo.getSkuId()) ? null : Long.parseLong(bo.getSkuId()));
        kwtLogisticsOrderGoods.setLOrderId(orderId);
        kwtLogisticsOrderGoods.setLOrderNo(lOrderNo);
        kwtLogisticsOrderGoods.setUpdateBy(LoginUserHolder.getUserId());
        kwtLogisticsOrderGoods.setUpdateTime(new Date());
        kwtLogisticsOrderGoods.setCreateBy(LoginUserHolder.getUserId());
        kwtLogisticsOrderGoods.setCreateTime(new Date());
        kwtLogisticsOrderGoodsMapper.insert(kwtLogisticsOrderGoods);
    }


    /**
     * 是否接单
     *
     * @param orderDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult orderTaking(OrderTakingDTO orderDTO) {
        log.info("接单操作接收数据:{}", JSONObject.toJSONString(orderDTO));
        HttpResult result = new HttpResult();
        result.setCode(HttpStatus.SUCCESS_CODE);
        HttpResult httpResult = ValidUtil.serviceValid(orderDTO);
        if (!String.valueOf(httpResult.getCode()).equals(String.valueOf(HttpStatus.SUCCESS_CODE))) {
            result.setMsg(httpResult.getMsg());
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return result;
        }
        KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(StringUtils.isNotBlank(orderDTO.getLOrderId()), KwtLogisticsOrder::getId, orderDTO.getLOrderId())
                        .eq(StringUtils.isNotBlank(orderDTO.getLOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDTO.getLOrderNo())
                /*.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/
        );
        if (logisticsOrder == null) {
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            result.setMsg("单据不存在!");
            return result;
        }
        if (!LogisticsOrderEnum.PENDING_ORDER.getStatus().equals(String.valueOf(logisticsOrder.getStatus()))) {
            result.setMsg("该【" + orderDTO.getLOrderNo() + "】单号并不是待接单状态!");
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return result;
        }
        KwtLogisticsOrderContract contract = kwtLogisticsOrderContractMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderContract>()
                .eq(KwtLogisticsOrderContract::getLOrderId, orderDTO.getLOrderId()));
        if (contract == null) {
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            result.setMsg("该订单并未存在合同信息!");
            return result;
        }
        /**
         * 根据合同是否已签约 变更物流订单状态 已签约->待派车  未签约->签约中
         * */
        /**判断生成物流订单应生成哪一种单据状态*/
        List<Long> contractList = new ArrayList<>();
        contractList.add(contract.getContractId());
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = remoteContractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new BusinessException("并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(contract.getContractId()) == null) {
            throw new BusinessException("并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(contract.getContractId());
        /**状态判断
         * 是否是已签约合同
         * */
        // 0 已签约 1待签约
        Integer status = infoResDto.getStatus();
        //todo 2023-08-09 验证必须是合同已签约才能进行接单操作
        if (NumberConstant.ZERO != status) {
            result.setMsg("该订单合同未签约!");
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return result;
        }
        Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        if (NumberConstant.ONE == status) {
            orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        } else if (NumberConstant.ZERO == status) {
            orderStatus = LogisticsOrderEnum.WAIT_DELIVERY.getCode();
        } else {
            log.info("接单 物流订单id:{}," +
                            "物流订单编号:{},合同id:{},合同信息:{}",
                    orderDTO.getLOrderId(), orderDTO.getLOrderNo(),
                    contract.getContractId(), JSONObject.toJSONString(infoResDto));
            throw new RuntimeException("物流订单-接单异常");
        }
        if (orderDTO.getType()) {
            //修改单据状态
            logisticsOrderMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(orderDTO.getLOrderId()), KwtLogisticsOrder::getId, orderDTO.getLOrderId())
                    .eq(StringUtils.isNotBlank(orderDTO.getLOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDTO.getLOrderNo())
                    .set(KwtLogisticsOrder::getStatus, orderStatus)
                    .set(KwtLogisticsOrder::getUpdateTime, new Date())
                    .set(KwtLogisticsOrder::getUpdateBy, LoginUserHolder.getUserId()));
            /**消息列表推送*/
            Long id = logisticsOrder.getId();
            KwtLogisticsOrderUnit consignOrderUnit = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                    .eq(KwtLogisticsOrderUnit::getLOrderId, id)
                    .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.ONE));
            KwtLogisticsOrderUnit carriageOrderUnit = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                    .eq(KwtLogisticsOrderUnit::getLOrderId, id)
                    .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.TWO));
//            commonService.publicLogisticsConsignmentPushMessage(consignOrderUnit, carriageOrderUnit, logisticsOrder.getLOrderNo(),
//                    logisticsOrder.getCreateBy(), logisticsOrder.getEntId(),
//                    MessageEnum.CONSIGN_ACCEPT_LOGISTICS, MessageEnum.CARRIAGE_ACCEPT_LOGISTICS);
            commonService.newSendLogisticsOrderToMessage(consignOrderUnit, carriageOrderUnit, logisticsOrder.getLOrderNo(),
                    logisticsOrder.getCreateBy(), logisticsOrder.getEntId(),
                    messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl(),
                    messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl(),
                    MessageEnum.CONSIGN_ACCEPT_LOGISTICS, MessageEnum.CARRIAGE_ACCEPT_LOGISTICS, "1");
        } else {
            orderStatus = LogisticsOrderEnum.REJECT_ORDER.getCode();
            //todo 改为拒绝接单  数据统计在页面已退回状态中
            logisticsOrderMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(orderDTO.getLOrderId()), KwtLogisticsOrder::getId, orderDTO.getLOrderId())
                    .eq(StringUtils.isNotBlank(orderDTO.getLOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDTO.getLOrderNo())
                    .set(KwtLogisticsOrder::getStatus, orderStatus)
                    .set(KwtLogisticsOrder::getUpdateTime, new Date())
                    .set(KwtLogisticsOrder::getUpdateBy, LoginUserHolder.getUserId()));

            /**数据回退至贸易订单/上级物流订单*/
            if (logisticsOrder.getPid() != null) {
                KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(KwtLogisticsOrder::getId, logisticsOrder.getPid())
                );
                if (kwtLogisticsOrder != null) {
                    kwtLogisticsOrder.setEntrustAmount(kwtLogisticsOrder.getEntrustAmount().subtract(logisticsOrder.getAmount()));
                    kwtLogisticsOrder.setSubcontractAmount(kwtLogisticsOrder.getSubcontractAmount().subtract(logisticsOrder.getAmount()));
                    kwtLogisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
                    kwtLogisticsOrder.setUpdateTime(new Date());
                    logisticsOrderMapper.updateById(kwtLogisticsOrder);
                    /**数据回归mongodb*/
                    SckwLogisticsOrder order = new SckwLogisticsOrder();
                    order.set_id(kwtLogisticsOrder.getId());
                    order.setLOrderId(kwtLogisticsOrder.getId());
                    order.setEntrustAmount(kwtLogisticsOrder.getEntrustAmount());
                    order.setSubcontractAmount(kwtLogisticsOrder.getSubcontractAmount());
                    order.setUpdateBy(LoginUserHolder.getUserId());
                    order.setUpdateTime(new Date());
                    order.setUpdateByName(LoginUserHolder.getUserName());
                    SckwBusSum busSum = new SckwBusSum();
                    busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
                    busSum.setMethod(NumberConstant.TWO);
                    busSum.setObject(order);
                    streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
                }
            } else {
                if (logisticsOrder.getTOrderId() != null) {
                    /**将生成的分配量->贸易订单*/
                    CreateOrCancelLogisticsOrderParam param = new CreateOrCancelLogisticsOrderParam();
                    param.setTOrderId(Long.valueOf(logisticsOrder.getTOrderId()));
                    param.setEntrustAmount(logisticsOrder.getAmount().negate());
                    param.setUpdateBy(LoginUserHolder.getUserId());
                    param.setUpdateByName(LoginUserHolder.getUserName());
                    HttpResult result1 = tradeOrderInfoService.createOrCancelLogisticsOrder(param);
                    if (result1.getCode() != HttpStatus.SUCCESS_CODE) {
                        log.info("{}拒绝接单->贸易订单失败!,返回信息:{}", "id:" + logisticsOrder.getTOrderId() + "orderNo" + logisticsOrder.getTOrderNo(), JSONObject.toJSONString(result1));
                        throw new BusinessException("{" + logisticsOrder.getTOrderNo() + "} 拒绝接单->贸易订单失败!");
                    }
                }
            }

            /**消息列表推送*/
            Long id = logisticsOrder.getId();
            KwtLogisticsOrderUnit consignOrderUnit = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                    .eq(KwtLogisticsOrderUnit::getLOrderId, id)
                    .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.ONE));
            KwtLogisticsOrderUnit carriageOrderUnit = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                    .eq(KwtLogisticsOrderUnit::getLOrderId, id)
                    .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.TWO));
//            commonService.publicLogisticsConsignmentPushMessage(consignOrderUnit, carriageOrderUnit, logisticsOrder.getLOrderNo(),
//                    logisticsOrder.getCreateBy(), logisticsOrder.getEntId(),
//                    MessageEnum.REJECT_ORDER, MessageEnum.CARRIAGE_DISALLOTMENT);
            commonService.newSendLogisticsOrderToMessage(consignOrderUnit, carriageOrderUnit, logisticsOrder.getLOrderNo(),
                    logisticsOrder.getCreateBy(), logisticsOrder.getEntId(),
                    messageUrlConfig.getPc().getConsignLogisticsAddOrderUrl(), messageUrlConfig.getApp().getConsignLogisticsAddOrderUrl(),
                    messageUrlConfig.getPc().getCarriageLogisticsAddOrderUrl(), messageUrlConfig.getApp().getCarriageLogisticsAddOrderUrl(),
                    MessageEnum.REJECT_ORDER, MessageEnum.CARRIAGE_DISALLOTMENT, "1");
        }
        //状态表新增状态数据
        KwtLogisticsOrderTrack track = logisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, orderDTO.getLOrderId()).eq(KwtLogisticsOrderTrack::getStatus, orderStatus));
        if (track == null) {
            KwtLogisticsOrderTrack orderTrack = new KwtLogisticsOrderTrack();
            orderTrack.setId(new IdWorker(NumberConstant.ONE).nextId());
            orderTrack.setLOrderId(Long.parseLong(orderDTO.getLOrderId()));
            orderTrack.setRemark(orderDTO.getRemark());
            orderTrack.setStatus(orderStatus);
            orderTrack.setCreateBy(LoginUserHolder.getUserId());
            orderTrack.setCreateTime(new Date());
            orderTrack.setUpdateBy(LoginUserHolder.getUserId());
            orderTrack.setUpdateTime(new Date());
            logisticsOrderTrackMapper.insert(orderTrack);
        } else {
            track.setRemark(orderDTO.getRemark());
            track.setUpdateTime(new Date());
            track.setUpdateBy(LoginUserHolder.getUserId());
            track.setStatus(orderStatus);
            logisticsOrderTrackMapper.updateById(track);
        }
        //修改mongodb状态
        SckwLogisticsOrder order = new SckwLogisticsOrder();
        order.set_id(logisticsOrder.getId());
        order.setLOrderId(logisticsOrder.getId());
        order.setStatus(String.valueOf(orderStatus));
        order.setUpdateTime(new Date());
        order.setUpdateByName(LoginUserHolder.getUserName());
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(NumberConstant.TWO);
        busSum.setObject(order);
        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
        return result;
    }

    /**
     * 承运订单-获取运单详情
     *
     * @param wOrderId
     * @return
     */
    public HttpResult getWaybillData(String wOrderId) {
        SckwWaybillOrder sckwWaybillOrder = mongoTemplate.findById(Long.parseLong(wOrderId), SckwWaybillOrder.class);
        KwtWaybillOrder waybillOrder = waybillOrderMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrder>()
                .eq(KwtWaybillOrder::getId, wOrderId));
        KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, waybillOrder.getLOrderId()));
        SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), kwtLogisticsOrder.getLossUnit());
        List<KwtWaybillOrderTicket> kwtWaybillOrderTickets = waybillOrderTicketMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                .eq(KwtWaybillOrderTicket::getWOrderId, Long.parseLong(wOrderId))
        );
        WaybillDetailVO vo = new WaybillDetailVO();
        vo.setSendCarWeigh(waybillOrder.getEntrustAmount());
        vo.setLoadAmount(waybillOrder.getLoadAmount());
        vo.setUnloadAmount(waybillOrder.getUnloadAmount());
        for (KwtWaybillOrderTicket waybillOrderTicket : kwtWaybillOrderTickets) {
            if (waybillOrderTicket != null) {
                if (waybillOrderTicket.getType() == 1) {
                    vo.setStowageDateTime(waybillOrderTicket.getOperateTime());
                }
                if (waybillOrderTicket.getType() == 2) {
                    vo.setUnloadDateTime(waybillOrderTicket.getOperateTime());
                }
            }
        }
        vo.setUnit(kwtLogisticsOrder.getUnit());
        if (kwtLogisticsOrder.getUnit() != null) {
            SysDictResDto dictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), kwtLogisticsOrder.getUnit());
            vo.setUnitLabel(dictResDto == null ? null : dictResDto.getLabel());
        }
        vo.setWaybillType(waybillOrder.getType());
        vo.setDeficitAmount(waybillOrder.getDeficitAmount());
        vo.setLoss(kwtLogisticsOrder.getLoss());
        vo.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        vo.setGoodsPrice(sckwWaybillOrder.getGoodsPrice());
        if (kwtLogisticsOrder.getGoodsPriceUnit() != null) {
            SysDictResDto dictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), kwtLogisticsOrder.getGoodsPriceUnit());
            vo.setGoodsPriceLabel(dictResDto == null ? null : dictResDto.getLabel());
        }
        vo.setAppointor(sckwWaybillOrder.getCreateByName());
        vo.setFleetName(sckwWaybillOrder.getCarrierFirmName());
        vo.setTruckNo(waybillOrder.getTruckNo());
        vo.setDriverName(waybillOrder.getDriverName());
        vo.setStartTime(waybillOrder.getStartTime());
        vo.setEndTime(waybillOrder.getEndTime());
//        if (!ObjectUtils.isEmpty(sckwWaybillOrder)) {
//            vo.setFleetName(sckwWaybillOrder.getCarrierFirmName());
//            vo.setTruckNo(sckwWaybillOrder.getTruckNo());
//            vo.setDriverName(sckwWaybillOrder.getDriverName());
//            vo.setSendCarWeigh(sckwWaybillOrder.getEntrustAmount());
//            vo.setLoadAmount(sckwWaybillOrder.getLoadAmount());
//            vo.setStowageDateTime(sckwWaybillOrder.getLoadTime());
//            vo.setWaybillType(sckwWaybillOrder.getType());
//            vo.setUnloadAmount(sckwWaybillOrder.getUnloadAmount());
//            vo.setUnloadDateTime(sckwWaybillOrder.getUnloadTime());
//            vo.setAppointor(sckwWaybillOrder.getCreateByName());
//            vo.setLoss(sckwWaybillOrder.getLoss());
//            vo.setGoodsPrice(sckwWaybillOrder.getGoodsPrice());
//            vo.setStartTime(sckwWaybillOrder.getStartTime());
//            vo.setEndTime(sckwWaybillOrder.getEndTime());
//        }
        return HttpResult.ok(vo);
    }

    /**
     * 获取承运订单-分包托运列表数据
     *
     * @param lOrderIds 物流订单主键id
     * @param page      当前页
     * @param pageSize  每页条数
     * @return
     */
    public PageRes<SubcontractConsignmentVO> getSubcontractConsignment(String lOrderIds, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<String> stringList = StringUtils.splitStrToList(lOrderIds, String.class);
        if (CollectionUtils.isEmpty(stringList)) {
            PageRes<SubcontractConsignmentVO> objectPageRes = new PageRes<>();
            objectPageRes.setPage(page);
            objectPageRes.setPageSize(pageSize);
            return objectPageRes;
        }
        List<Long> ids = StringUtils.splitStrToList(lOrderIds, Long.class);
        /**运价方式*/
        Map<String, String> priceDictData = getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**车载计算方式*/
        Map<String, String> weightDictData = getDictData(DictTypeEnum.WEIGHT_CAR.getType());
        /**签约方式*/
        Map<String, String> singDictData = getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**计费方式*/
        Map<String, String> chargingDictData = getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**订单来源*/
        Map<String, String> orderSource = getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        List<SubcontractConsignmentVO> allList = new ArrayList<>();
        List<SubcontractConsignmentVO> voList = logisticsOrderMapper.getSubcontractConsignmentList(ids);
        if (CollectionUtils.isEmpty(voList)) {
            PageRes<SubcontractConsignmentVO> objectPageRes = new PageRes<>();
            objectPageRes.setPage(page);
            objectPageRes.setPageSize(pageSize);
            return objectPageRes;
        }
        PageInfo<SubcontractConsignmentVO> pageInfo = new PageInfo<>(voList);
        if (CollectionUtils.isNotEmpty(voList)) {
            for (SubcontractConsignmentVO subcontractConsignmentVO : voList) {
                //关联父级承运单据号
                if (subcontractConsignmentVO.getPid() != null) {
                    KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>().eq(KwtLogisticsOrder::getId, subcontractConsignmentVO.getPid()));
                    if (kwtLogisticsOrder != null) {
                        subcontractConsignmentVO.setCarrierOrderNo(kwtLogisticsOrder.getLOrderNo());
                    }
                }
                subcontractConsignmentVO.setStatusLabel(LogisticsOrderEnum.getDestination(subcontractConsignmentVO.getStatus()));
                if (subcontractConsignmentVO.getPriceType() != null) {
                    subcontractConsignmentVO.setPriceTypeLabel(priceDictData == null ? null : priceDictData.get(subcontractConsignmentVO.getPriceType()));
                }
                if (subcontractConsignmentVO.getLossUnit() != null) {
                    subcontractConsignmentVO.setLossUnitLabel(weightDictData == null ? null : weightDictData.get(subcontractConsignmentVO.getLossUnit()));
                }
                if (subcontractConsignmentVO.getGoodsPriceUnit() != null) {
                    subcontractConsignmentVO.setGoodsPriceUnitLabel(priceDictData == null ? null : priceDictData.get(subcontractConsignmentVO.getGoodsPriceUnit()));
                }
                //分包托运不需要展示签约方式
//                subcontractConsignmentVO.setContractSigningWay(singDictData == null ? null : singDictData.get(subcontractConsignmentVO.getContractSigningWay()));
                if (subcontractConsignmentVO.getBillingMode() != null) {
                    subcontractConsignmentVO.setBillingModeLabel(chargingDictData == null ? null : chargingDictData.get(subcontractConsignmentVO.getBillingMode()));
                }
                if (subcontractConsignmentVO.getSettlementCycle() != null) {
                    subcontractConsignmentVO.setSettlementCycleLabel(settlementDictData == null ? null : settlementDictData.get(subcontractConsignmentVO.getSettlementCycle()));
                }
                if (subcontractConsignmentVO.getCreateBy() != null) {
                    UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(Long.parseLong(subcontractConsignmentVO.getCreateBy()));
                    if (userCacheResDto != null) {
                        subcontractConsignmentVO.setCreateName(userCacheResDto.getName());
                    }
                }
                subcontractConsignmentVO.setLoadAddressDetail(subcontractConsignmentVO.getLoadCityName() + subcontractConsignmentVO.getLoadAddress());
                subcontractConsignmentVO.setUnloadAddressDetail(subcontractConsignmentVO.getUnloadCityName() + subcontractConsignmentVO.getUnloadAddress());
                subcontractConsignmentVO.setOrderSourceLabel(orderSource == null ? null : orderSource.get(subcontractConsignmentVO.getOrderSource()));
                subcontractConsignmentVO.setTaxRateLabel(subcontractConsignmentVO.getTaxRate() + "%");
            }
            allList.addAll(voList);
        }
        return PageRes.build(pageInfo, allList);
//        for (String lOrderId : stringList) {
//            List<SubcontractConsignmentVO> list = logisticsOrderMapper.getSubcontractConsignmentNotPage(lOrderId);
//            //联查数据
//            if (CollectionUtils.isNotEmpty(list)) {
//                for (SubcontractConsignmentVO subcontractConsignmentVO : list) {
//                    //关联父级承运单据号
//                    if (subcontractConsignmentVO.getPid() != null) {
//                        KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>().eq(KwtLogisticsOrder::getId, subcontractConsignmentVO.getPid()));
//                        if (kwtLogisticsOrder != null) {
//                            subcontractConsignmentVO.setCarrierOrderNo(kwtLogisticsOrder.getLOrderNo());
//                        }
//                    }
//                    subcontractConsignmentVO.setStatusLabel(LogisticsOrderEnum.getDestination(subcontractConsignmentVO.getStatus()));
//                    if (subcontractConsignmentVO.getPriceType() != null) {
//                        subcontractConsignmentVO.setPriceTypeLabel(priceDictData == null ? null : priceDictData.get(subcontractConsignmentVO.getPriceType()));
//                    }
//                    if (subcontractConsignmentVO.getLossUnit() != null) {
//                        subcontractConsignmentVO.setLossUnitLabel(weightDictData == null ? null : weightDictData.get(subcontractConsignmentVO.getLossUnit()));
//                    }
//                    if (subcontractConsignmentVO.getGoodsPriceUnit() != null) {
//                        subcontractConsignmentVO.setGoodsPriceUnitLabel(priceDictData == null ? null : priceDictData.get(subcontractConsignmentVO.getGoodsPriceUnit()));
//                    }
//                    //分包托运不需要展示签约方式
////                subcontractConsignmentVO.setContractSigningWay(singDictData == null ? null : singDictData.get(subcontractConsignmentVO.getContractSigningWay()));
//                    if (subcontractConsignmentVO.getBillingMode() != null) {
//                        subcontractConsignmentVO.setBillingModeLabel(chargingDictData == null ? null : chargingDictData.get(subcontractConsignmentVO.getBillingMode()));
//                    }
//                    if (subcontractConsignmentVO.getSettlementCycle() != null) {
//                        subcontractConsignmentVO.setSettlementCycleLabel(settlementDictData == null ? null : settlementDictData.get(subcontractConsignmentVO.getSettlementCycle()));
//                    }
//                    if (subcontractConsignmentVO.getCreateBy() != null) {
//                        UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(Long.parseLong(subcontractConsignmentVO.getCreateBy()));
//                        if (userCacheResDto != null) {
//                            subcontractConsignmentVO.setCreateName(userCacheResDto.getName());
//                        }
//                    }
//                    subcontractConsignmentVO.setLoadAddressDetail(subcontractConsignmentVO.getLoadCityName() + subcontractConsignmentVO.getLoadAddress());
//                    subcontractConsignmentVO.setUnloadAddressDetail(subcontractConsignmentVO.getUnloadCityName() + subcontractConsignmentVO.getUnloadAddress());
//                }
//                allList.addAll(list);
//            }
//        }
//        List<SubcontractConsignmentVO> returnList = allList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
//        PageResult build = PageResult.build(page, pageSize, allList.stream().count(), returnList);
//        return HttpResult.ok(build);
    }


    /**
     * 分包列表下方数据统计
     *
     * @param lOrderId 物流订单id
     * @return
     */
    public HttpResult getSubcontractConsignmentCount(String lOrderId) {
        /**页面数据统计*/
        List<Map> countList = logisticsOrderMapper.countSubcontractConsignmentById(lOrderId);
        return HttpResult.ok(countList);
    }

    public String getDictData(String type, String value) {
        if (ObjectUtils.isEmpty(value)) {
            return null;
        }
        if (remoteSystemService.queryDictByTypeAndValue(type, value) == null) {
            return null;
        } else {
            return remoteSystemService.queryDictByTypeAndValue(type, value).getLabel();
        }
    }

    public Map<String, String> getDictData(String type) {
        Map<String, String> maps = new HashMap<>(NumberConstant.SIXTEEN);
        List<SysDictResDto> list = remoteSystemService.queryDictByType(type);
        if (CollectionUtils.isNotEmpty(list)) {
            maps = list.stream().collect(Collectors.toMap(SysDictResDto::getValue, SysDictResDto::getLabel, (key1, key2) -> key2));
        }
        return maps;
    }

    /**
     * 设置停止接单数据查询
     *
     * @param driverParam
     * @return
     */
    public HttpResult stopDocumentDetail(DriverParam driverParam) {
        HttpResult result = new HttpResult();
        result.setCode(HttpStatus.SUCCESS_CODE);
        HttpResult httpResult = ValidUtil.serviceValid(driverParam);
        if (HttpStatus.SUCCESS_CODE != httpResult.getCode()) {
            result.setMsg(httpResult.getMsg());
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return result;
        }
        /**请求参数校验*/
//        checkParam(driverParam);
        /**1 趟次 2 循环*/
        Map<String, RTruckVo> truck = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (String.valueOf(NumberConstant.ONE).equals(driverParam.getType())) {
            //只展示待接单数据
            List<DriverListVo> list = logisticsOrderMapper.selectDriverListById(driverParam);
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> collect = list.stream().map(DriverListVo::getTruckNo).distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    truck = fleetService.findTruck(collect);
                }
            }
            Map<String, String> dictData = commonService.getDictData(DictTypeEnum.TRUCK_TYPE.getType());
            for (DriverListVo driverListVo : list) {
                driverListVo.setStatusLabel(CarWaybillEnum.getName(driverListVo.getStatus()));
                if (!ObjectUtils.isEmpty(truck)) {
                    if (truck.get(driverListVo.getTruckNo()) != null) {
                        driverListVo.setTransportStatus(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getBusinessStatus());
                    }
                    if (driverListVo.getTransportStatus() != null) {
                        driverListVo.setTransportStatusLabel((driverListVo.getTransportStatus() == 0) ? "空闲" : "任务中");
                    }
                    String truckType = truck.get(driverListVo.getTruckNo()).getTruckType();
                    if (StringUtils.isNotBlank(truckType)) {
//                        driverListVo.setCarType(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getTruckType());
                        driverListVo.setCarType(dictData.get(truckType));
                    }
                }
            }
            result.setData(list);
        } else if (String.valueOf(NumberConstant.TWO).equals(driverParam.getType())) {
            List<DriverListVo> list = logisticsOrderMapper.selectLoopOrderAndDriverListByOrderId(driverParam);
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> collect = list.stream().map(DriverListVo::getTruckNo).distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    truck = fleetService.findTruck(collect);
                }
            }
            Map<String, String> dictData = commonService.getDictData(DictTypeEnum.TRUCK_TYPE.getType());
            for (DriverListVo driverListVo : list) {
                if (!driverListVo.getCirculateId().isEmpty()) {
//                    driverListVo.setStatus(1);
                    driverListVo.setStatusLabel(CarWaybillEnum.PENDING_ORDER.getDestination());
                }
                if (!ObjectUtils.isEmpty(truck)) {
//                    driverListVo.setTransportStatus(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getBusinessStatus());
                    if (truck.get(driverListVo.getTruckNo()) != null) {
                        driverListVo.setTransportStatus(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getBusinessStatus());
                    }
                    if (driverListVo.getTransportStatus() != null) {
                        driverListVo.setTransportStatusLabel((driverListVo.getTransportStatus() == 0) ? "空闲" : "任务中");
                    }
                    String truckType = truck.get(driverListVo.getTruckNo()).getTruckType();
                    if (StringUtils.isNotBlank(truckType)) {
//                        driverListVo.setCarType(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getTruckType());
                        driverListVo.setCarType(dictData.get(truckType));
                    }
                }
            }
            result.setData(list);
        } else {
            result.setMsg("查询类型错误!");
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return result;
        }

        return result;
    }

    private void checkParam(DriverParam driverParam) {
        if (StringUtils.isNotBlank(driverParam.getDriverName())) {
            if (driverParam.getDriverName().trim().length() > NumberConstant.TWENTY_FOUR) {
                throw new RuntimeException("司机姓名位数不正确");
            }
            if (!RegularUtils.matchs(RegularUtils.CHINESE, driverParam.getDriverName())) {
                throw new RuntimeException("司机姓名格式不正确");
            }
        }
        //2023-07-25 去除车牌查询格式校验
//        if (StringUtils.isNotBlank(driverParam.getTruckNo())) {
//            int length = driverParam.getTruckNo().trim().length();
//            if (driverParam.getTruckNo().trim().length() > NumberConstant.EIGHT || driverParam.getTruckNo().trim().length() < NumberConstant.SEVEN) {
//                throw new RuntimeException("车牌号位数不正确");
//            }
//            if (driverParam.getTruckNo().trim().length() == NumberConstant.EIGHT) {
//                if (!RegularUtils.matchs(RegularUtils.TRUCK_NUMBER_SIX, driverParam.getTruckNo())) {
//                    throw new RuntimeException("车牌号格式不正确");
//                }
//            } else if (driverParam.getTruckNo().trim().length() == NumberConstant.SEVEN) {
//                if (!RegularUtils.matchs(RegularUtils.TRUCK_NUMBER_FIVE, driverParam.getTruckNo())) {
//                    throw new RuntimeException("车牌号格式不正确");
//                }
//            }
//
//        }
        if (StringUtils.isNotBlank(driverParam.getDriverPhone())) {
            if (driverParam.getDriverPhone().trim().length() > NumberConstant.ELEVEN) {
                throw new RuntimeException("手机号不正确");
            }
            if (!RegularUtils.matchs(RegularUtils.PHONE_REG, driverParam.getDriverPhone())) {
                throw new RuntimeException("手机号格式不正确");
            }
        }
    }

    /**
     * 设置停止接单-针对于循环单
     *
     * @param stopOrderTakingDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult stopDocumentCommit(StopOrderTakingDTO stopOrderTakingDTO) {
        List<String> stringList = StringUtils.splitStrToList(stopOrderTakingDTO.getIds(), ",", String.class);
        List<Long> circulateIds = logisticsOrderCirculateMapper.selectEntityBylOrderIdAndOrderIds(stopOrderTakingDTO.getLOrderId(), stringList);
        if (CollectionUtils.isEmpty(circulateIds)) {
            return HttpResult.error("循环停止接单,单据不存在!");
        }
        List<JSONObject> list = new ArrayList<>(stringList.size());
        acceptStopDocumentCommit(stopOrderTakingDTO, list, circulateIds);
//        String type = stopOrderTakingDTO.getType();
//        if (String.valueOf(NumberConstant.TWO).equals(type)) {
//            acceptStopDocumentCommit(stopOrderTakingDTO, list, wOrderIds);
//        } else if (String.valueOf(NumberConstant.ONE).equals(type)) {
//            consignStopDocumentCommit(stopOrderTakingDTO, list, wOrderIds);
//        } else {
//            return HttpResult.error("单据类型错误!");
//        }
        return HttpResult.ok(list);
    }

    /**
     * 托运订单-设置停止接单
     *
     * @param stopOrderTakingDTO
     */
    private void consignStopDocumentCommit(StopOrderTakingDTO stopOrderTakingDTO, List<JSONObject> list, List<Long> wOrderIds) {

        if (CollectionUtils.isNotEmpty(wOrderIds)) {
            wOrderIds.forEach(wOrderId -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("wOrderId", wOrderId);
                KwtWaybillOrder waybillOrder = waybillOrderMapper.selectOne(new LambdaUpdateWrapper<KwtWaybillOrder>().eq(KwtWaybillOrder::getId, wOrderId));
                if (waybillOrder == null) {
                    jsonObject.put("status", HttpStatus.GLOBAL_EXCEPTION_CODE);
                    jsonObject.put("message", "单据不存在或者单据异常");
                } else {
                    logisticsOrderCirculateMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrderCirculate>()
                            .set(KwtLogisticsOrderCirculate::getStatus, NumberConstant.ONE)
                            .set(KwtLogisticsOrderCirculate::getUpdateBy, LoginUserHolder.getUserId())
                            .set(KwtLogisticsOrderCirculate::getUpdateTime, new Date())
                            .eq(KwtLogisticsOrderCirculate::getWOrderId, wOrderId)
                    );
                    /**更新MongoDB*/
                    SckwWaybillOrder order = new SckwWaybillOrder();
                    order.setStatus(NumberConstant.ONE);
                    order.setUpdateTime(new Date());
                    order.setUpdateByName(LoginUserHolder.getUserName());
                    order.setUpdateBy(LoginUserHolder.getUserId());
                    SckwBusSum busSum = new SckwBusSum();
                    busSum.setBusSumType(BusinessTypeEnum.WAYBILL_ORDER_TYPE.getName());
                    busSum.setMethod(NumberConstant.TWO);
                    busSum.setObject(order);
                    streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
                    jsonObject.put("status", HttpStatus.SUCCESS_CODE);
                    jsonObject.put("message", "停止接单成功");
                }
                list.add(jsonObject);
            });
        }
    }

    /**
     * 承运订单设置停止接单
     *
     * @param stopOrderTakingDTO
     */
    private void acceptStopDocumentCommit(StopOrderTakingDTO stopOrderTakingDTO, List<JSONObject> list, List<Long> circulateIds) {
        if (CollectionUtils.isNotEmpty(circulateIds)) {
            circulateIds.forEach(circulateId -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("circulateId", circulateId);

                logisticsOrderCirculateMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrderCirculate>()
                        .set(KwtLogisticsOrderCirculate::getStatus, NumberConstant.ONE)
                        .set(KwtLogisticsOrderCirculate::getUpdateBy, LoginUserHolder.getUserId())
                        .set(KwtLogisticsOrderCirculate::getUpdateTime, new Date())
                        .eq(KwtLogisticsOrderCirculate::getId, circulateId)
                );
                /**更新MongoDB*/
                SckwWaybillOrder order = new SckwWaybillOrder();
                order.set_id(circulateId);
                order.setStatus(CarWaybillEnum.REVOKED.getCode());
                order.setUpdateTime(new Date());
                order.setUpdateByName(LoginUserHolder.getUserName());
                order.setUpdateBy(LoginUserHolder.getUserId());
                order.setDelFlag(Global.YES);
                SckwBusSum busSum = new SckwBusSum();
                busSum.setBusSumType(BusinessTypeEnum.WAYBILL_ORDER_TYPE.getName());
                busSum.setMethod(NumberConstant.TWO);
                busSum.setObject(order);
                streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
                jsonObject.put("status", HttpStatus.SUCCESS_CODE);
                jsonObject.put("message", "停止接单成功");

//                KwtWaybillOrder waybillOrder = waybillOrderMapper.selectOne(new LambdaUpdateWrapper<KwtWaybillOrder>().eq(KwtWaybillOrder::getId, wOrderId));
//                if (waybillOrder == null) {
//                    jsonObject.put("status", HttpStatus.GLOBAL_EXCEPTION_CODE);
//                    jsonObject.put("message", "单据不存在或者单据异常");
//                } else {
//                }
                list.add(jsonObject);
            });
        }
    }


    /**
     * 承运订单-取消派车
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult cancelDelivery(List<String> ids, String idString) {
        List<Long> ts = StringUtils.splitStrToList(idString, Long.class);
        HttpResult httpResult = waybillOrderService.cancelSendCar(ts);
        return httpResult;
//        List<JSONObject> list = new ArrayList<>();
//        JSONObject result = new JSONObject(NumberConstant.THREE);
//        for (String id : ids) {
//            result.put("id", id);
//            KwtWaybillOrder waybillOrder = waybillOrderMapper.selectOne(new LambdaUpdateWrapper<KwtWaybillOrder>()
//                    .eq(KwtWaybillOrder::getId, Long.parseLong(id)).eq(KwtWaybillOrder::getType, NumberConstant.ONE));
//            if (waybillOrder == null) {
//                result.put("status", HttpStatus.GLOBAL_EXCEPTION_CODE);
//                result.put("message", "单据不存在");
//                list.add(result);
//                continue;
//            }
//            if (!CarWaybillEnum.PENDING_ORDER.getCode().equals(waybillOrder.getStatus())) {
//                result.put("status", HttpStatus.GLOBAL_EXCEPTION_CODE);
//                result.put("message", "单据不是待接单状态,不可取消!");
//                list.add(result);
//                continue;
//            }
//            /**针对于趟次车，需要将可派单数量溯源回归于物流订单中*/
//            KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
//                    .eq(KwtLogisticsOrder::getId, waybillOrder.getLOrderId()));
//            //已委托量
//            BigDecimal entrustAmount = logisticsOrder.getEntrustAmount().add(waybillOrder.getEntrustAmount());
//            //分包量
//            BigDecimal subcontractAmount = logisticsOrder.getSubcontractAmount().subtract(waybillOrder.getEntrustAmount());
//            logisticsOrderMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrder>()
//                    .set(KwtLogisticsOrder::getSubcontractAmount, subcontractAmount)
//                    .set(KwtLogisticsOrder::getEntrustAmount, entrustAmount)
//                    .set(KwtLogisticsOrder::getUpdateTime, new Date())
//                    .set(KwtLogisticsOrder::getUpdateBy, LoginUserHolder.getUserId())
//                    .eq(KwtLogisticsOrder::getId, logisticsOrder.getId()));
//            waybillOrderMapper.update(null, new LambdaUpdateWrapper<KwtWaybillOrder>()
//                    .eq(KwtWaybillOrder::getType, NumberConstant.ONE)
//                    .eq(KwtWaybillOrder::getId, Long.parseLong(id))
//                    .set(KwtWaybillOrder::getStatus, CarWaybillEnum.REVOKED.getCode())
//                    .set(KwtWaybillOrder::getUpdateBy, LoginUserHolder.getUserId())
//                    .set(KwtWaybillOrder::getUpdateTime, new Date()));
//            /**变更单据状态*/
//            KwtWaybillOrderTrack waybillOrderTrack = waybillOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTrack>()
//                    .eq(KwtWaybillOrderTrack::getWOrderId, id)
//                    .eq(KwtWaybillOrderTrack::getStatus, CarWaybillEnum.REVOKED.getCode())
//            );
//            if (waybillOrderTrack == null) {
//                KwtWaybillOrderTrack orderTrack = new KwtWaybillOrderTrack();
//                orderTrack.setId(new IdWorker(NumberConstant.ONE).nextId());
//                orderTrack.setWOrderId(Long.parseLong(id));
//                orderTrack.setStatus(CarWaybillEnum.REVOKED.getCode());
//                orderTrack.setDelFlag(NumberConstant.ZERO);
//                orderTrack.setCreateBy(LoginUserHolder.getUserId());
//                orderTrack.setCreateTime(new Date());
//                orderTrack.setUpdateBy(LoginUserHolder.getUserId());
//                orderTrack.setUpdateTime(new Date());
//                waybillOrderTrackMapper.insert(orderTrack);
//            } else {
//                waybillOrderTrack.setUpdateTime(new Date());
//                waybillOrderTrack.setUpdateBy(LoginUserHolder.getUserId());
//                waybillOrderTrackMapper.updateById(waybillOrderTrack);
//            }
//
//            /**修改mongodb*/
//            //mongodb更新订单状态
//            SckwWaybillOrder updateParam = new SckwWaybillOrder();
//            updateParam.setWOrderId(Long.parseLong(id)).setStatus(CarWaybillEnum.REVOKED.getCode())
//                    .setUpdateBy(LoginUserHolder.getUserId()).setUpdateByName(LoginUserHolder.getUserName()).setUpdateTime(new Date());
//            SckwBusSum busSum = new SckwBusSum();
//            busSum.setBusSumType(BusinessTypeEnum.WAYBILL_ORDER_TYPE.getName());
//            busSum.setMethod(NumberConstant.TWO);
//            busSum.setObject(updateParam);
//            streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
//            SckwLogisticsOrder order = new SckwLogisticsOrder();
//            order.set_id(logisticsOrder.getId());
//            order.setLOrderId(logisticsOrder.getId());
//            order.setEntrustAmount(entrustAmount);
//            order.setSubcontractAmount(subcontractAmount);
//            order.setUpdateByName(LoginUserHolder.getUserName());
//            order.setUpdateTime(new Date());
//            SckwBusSum orderBusSum = new SckwBusSum();
//            orderBusSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
//            orderBusSum.setMethod(NumberConstant.TWO);
//            orderBusSum.setObject(order);
//            streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
//            result.put("status", HttpStatus.SUCCESS_CODE);
//            result.put("message", "取消成功");
//            list.add(result);
//        }
//        return HttpResult.ok(list);
    }

    /**
     * 承运订单-分包托运-完结订单
     *
     * @param orderFinishDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult commitAcceptCarriageOrderFinish(OrderFinishDTO orderFinishDTO) {
        /** 订单完结 物流运单状态为【待派车】、【运输中】可操作*/
        /**完结拦截 必须车辆运单无正在运输中的单据才能完结 状态有 待接单之后已核弹之前的状态 都不能完结*/
        /**完结订单-对应物流订单下子订单都要进行完结*/
        /**完结订单 不做页面填写数量与数据库数量进行计算验证-直接获取页面填写数据进行保存处理*/
        //物流订单id
        String id = orderFinishDTO.getId();
        KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, id));
        if (logisticsOrder == null) {
            throw new RuntimeException("承运订单-完结订单-物流单据不存在!");
        }
//        BigDecimal totalLoadAmount = logisticsOrder.getTotalLoadAmount() == null ? new BigDecimal("0.00") : logisticsOrder.getTotalLoadAmount();
//        if (totalLoadAmount.compareTo(orderFinishDTO.getLoadAmount()) < 0) {
//            throw new BusinessException("完结订单,实装量不能大于分配量");
//        }

        //todo 2023-09-01 根据要求去除校验 物流订单手动完结，实装量可大于分配量，实卸量目前暂定不可大于实装量；根据计费方式，当对应实装或实卸大于分配量时自然完结
//        BigDecimal amount = logisticsOrder.getAmount() == null ? new BigDecimal("0.00") : logisticsOrder.getAmount();
//        if (amount.compareTo(orderFinishDTO.getLoadAmount()) < 0) {
//            throw new BusinessException("完结订单,装货量不能大于运输总量");
//        }
//        if (orderFinishDTO.getUnloadAmount().compareTo(orderFinishDTO.getLoadAmount()) > 0) {
//            throw new BusinessException("完结订单,填写卸货量不能大于装货量");
//        }
        /**订单状态验证*/
        if (!LogisticsOrderEnum.WAIT_DELIVERY.getStatus().equals(String.valueOf(logisticsOrder.getStatus()))
                && !LogisticsOrderEnum.IN_TRANSIT.getStatus().equals(String.valueOf(logisticsOrder.getStatus()))) {
            throw new RuntimeException("当前订单并不属于【待派车】,【运输中】状态");
        }
        /**完结拦截*/
//        List<Integer> statusList = new ArrayList<>();
//        statusList.add(CarWaybillEnum.PENDING_VEHICLE.getCode());
//        statusList.add(CarWaybillEnum.EXIT_COMPLETED.getCode());
//        statusList.add(CarWaybillEnum.WAIT_LOADING.getCode());
//        statusList.add(CarWaybillEnum.COMPLETION_LOADING.getCode());
//        statusList.add(CarWaybillEnum.WAIT_UNLOADING.getCode());
//        statusList.add(CarWaybillEnum.COMPLETION_UNLOADING.getCode());
//        statusList.add(CarWaybillEnum.APPROVAL_IN.getCode());
//        statusList.add(CarWaybillEnum.APPROVAL_NO_PASS.getCode());
//        int count = waybillOrderMapper.selectDataByLorderId(id, statusList);
        boolean flag = commonService.judgmentWaybillOrderIsFinish(id);
        if (flag) {
            throw new BusinessException("检测您现在有运单正在执行中,该订单目前不可完结,请先将运单执行完毕");
        }
        BigDecimal ignoreAmount = logisticsOrder.getAmount().subtract(logisticsOrder.getTotalLoadAmount());
        //修改单据本身数据
        updateDataByItself(logisticsOrder, orderFinishDTO, ignoreAmount);
        //获取物流订单下的子单
        /**完结订单-对应物流订单下子订单都要进行完结*/
        List<KwtLogisticsOrder> kwtLogisticsOrders = logisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getDelFlag, NumberConstant.ZERO)
                .apply(id != null, "FIND_IN_SET ('" + id + "', pids)").ne(KwtLogisticsOrder::getId, id));
        /**找到该订单下所有的物流订单**/
        //需要修改的mongodb数据
        List<Map<String, Object>> list = new ArrayList<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(kwtLogisticsOrders)) {
            //修改单据状态
//            List<Long> ids = kwtLogisticsOrders.stream().map(KwtLogisticsOrder::getId).collect(Collectors.toList());
            //修改单据剩余运输量
            kwtLogisticsOrders.forEach(kwtLogisticsOrder -> {
                BigDecimal subtract = kwtLogisticsOrder.getAmount().subtract(kwtLogisticsOrder.getTotalLoadAmount());
                updateLogisticOrderAndTrack(kwtLogisticsOrder.getId(), orderFinishDTO, subtract);
                //新增mongodb要修改的数据
                Map<String, Object> map = new HashMap<>(Global.NUMERICAL_SIXTEEN);
                map.put("id", kwtLogisticsOrder.getId());
                map.put("ignoreAmount", subtract);
                list.add(map);
//                updateMongoDbByLogisticsOrder(kwtLogisticsOrder.getId(), orderFinishDTO, subtract);
            });
        }
        /**是否是一级订单,是->推送至贸易,否,数据推送至物流订单上级*/
        if (logisticsOrder.getPid() == null && logisticsOrder.getType().equals("1")) {
            //数据推送至贸易订单
            CompleteLogisticsOrderParam tradeOrder = new CompleteLogisticsOrderParam();
            //todo 2023-09-07 修改为传递页面传输值  不传递总量
            //获取实际装货量-实际卸货量
//            Map<String, BigDecimal> map = logisticsOrderMapper.countAmountByTradeOrderId(logisticsOrder.getTOrderId());
            //获取是否订单已经全部处理完成
            List<Integer> orderStatusList = new ArrayList<>();
            orderStatusList.add(LogisticsOrderEnum.TO_BE_PLANNED.getCode());
            orderStatusList.add(LogisticsOrderEnum.PENDING_ORDER.getCode());
            orderStatusList.add(LogisticsOrderEnum.WAIT_DELIVERY.getCode());
            orderStatusList.add(LogisticsOrderEnum.IN_TRANSIT.getCode());
            List<KwtLogisticsOrder> logisticsOrders = logisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>()
                    .eq(KwtLogisticsOrder::getTOrderId, logisticsOrder.getTOrderId())
                    .in(KwtLogisticsOrder::getStatus, orderStatusList));
            if (org.springframework.util.CollectionUtils.isEmpty(logisticsOrders)) {
                tradeOrder.setIsAllComplete(true);
            } else {
                tradeOrder.setIsAllComplete(false);
            }
            tradeOrder.setTOrderId(logisticsOrder.getTOrderId());
//            tradeOrder.setActualLoadAmount(map.get("totalLoadAmount"));
//            tradeOrder.setActualUnloadAmount(map.get("totalUnloadAmount"));
            tradeOrder.setActualLoadAmount(orderFinishDTO.getLoadAmount());
            tradeOrder.setActualUnloadAmount(orderFinishDTO.getUnloadAmount());
            tradeOrder.setUpdateBy(LoginUserHolder.getUserId());
            tradeOrder.setUpdateByName(LoginUserHolder.getUserName());
            log.info("承运订单-分包托运-手动完结订单请求参数:{}", JSONObject.toJSONString(tradeOrder));
            HttpResult httpResult = tradeOrderInfoService.completeLogisticsOrder(tradeOrder);
            if (httpResult.getCode() != HttpStatus.SUCCESS_CODE) {
                log.info("承运订单-分包托运-手动完结订单异常,传递信息:{},返回信息:{}", JSONObject.toJSONString(tradeOrder), JSONObject.toJSONString(httpResult));
                throw new BusinessException("单据完结出现错误！" + httpResult.getMsg());
            }
            /**将生成的分配量->贸易订单*/
            CreateOrCancelLogisticsOrderParam param = new CreateOrCancelLogisticsOrderParam();
            param.setTOrderId(Long.valueOf(logisticsOrder.getTOrderId()));
            param.setEntrustAmount(orderFinishDTO.getLoadAmount().subtract(logisticsOrder.getAmount()));
            param.setUpdateBy(LoginUserHolder.getUserId());
            param.setUpdateByName(LoginUserHolder.getUserName());
            HttpResult result1 = tradeOrderInfoService.createOrCancelLogisticsOrder(param);
            if (result1.getCode() != HttpStatus.SUCCESS_CODE) {
                log.info("{}拒绝接单->贸易订单失败!,返回信息:{}", "id:" + logisticsOrder.getTOrderId() + "orderNo" + logisticsOrder.getTOrderNo(), JSONObject.toJSONString(result1));
                throw new BusinessException("{" + logisticsOrder.getTOrderNo() + "} 拒绝接单->贸易订单失败!" + result1.getMsg());
            }
        }

        //修改合同履约量
        commonService.updatePerformed(logisticsOrder, orderFinishDTO.getLoadAmount(), orderFinishDTO.getUnloadAmount());

        //修改mongodb的数据
        updateMongoDbByLogisticsOrder(logisticsOrder.getId(), orderFinishDTO, ignoreAmount);
        if (!CollectionUtils.isEmpty(list) && list.size() > 0) {
            for (Map<String, Object> map : list) {
                updateMongoDbByLogisticsOrder(Long.parseLong(map.get("id").toString()), orderFinishDTO, new BigDecimal(map.get("ignoreAmount").toString()));
            }
        }
//        /**完结订单-对应物流订单下子订单都要进行完结*/
//        List<KwtLogisticsOrder> kwtLogisticsOrders = kwtLogisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>()
//                .in(KwtLogisticsOrder::getPids, Long.parseLong(orderFinishDTO.getId())));
//        if (CollectionUtils.isNotEmpty(kwtLogisticsOrders)) {
//            for (KwtLogisticsOrder kwtLogisticsOrder : kwtLogisticsOrders) {
//                String[] split = kwtLogisticsOrder.getPids().split(StringConstant.COMMA);
//                if (split.length > NumberConstant.ONE) {
//                    for (String s : split) {
//                        if (String.valueOf(kwtLogisticsOrder.getId()).equals(s)) {
//                            //本身订单
//                            //只存在当前订单无分包订单
//                            /**单据完结修改状态以及数据*/
//                            updateDataByItself(logisticsOrder, orderFinishDTO);
//                        } else {
//                            //修改分包后的订单-代表存在分包订单
//                            /**单据完结修改状态以及数据*/
//                            updateDataBySubset(orderFinishDTO, s);
//                        }
//                    }
//                } else {
//                    //只存在当前订单无分包订单
//                    /**单据完结修改状态以及数据*/
//                    updateDataByItself(logisticsOrder, orderFinishDTO);
//                }
//            }
//        }
        transportCommonService.closeHandle(logisticsOrder.getId());
        waybillOrderService.cancelSendCar(logisticsOrder.getId());
        return HttpResult.ok("承运订单-分包托运完结订单成功");
    }

    private void updateLogisticOrderAndTrack(Long lOrderId, OrderFinishDTO orderFinishDTO, BigDecimal ignoreAmount) {
        Integer code = LogisticsOrderEnum.HAVE_FINISHED.getCode();
        logisticsOrderMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrder>()
                .set(KwtLogisticsOrder::getStatus, code)
                .set(KwtLogisticsOrder::getUpdateBy, LoginUserHolder.getUserId())
                .set(KwtLogisticsOrder::getIgnoreAmount, ignoreAmount)
                .set(KwtLogisticsOrder::getUpdateTime, new Date())
                .eq(KwtLogisticsOrder::getId, lOrderId)
        );
        KwtLogisticsOrderTrack track = logisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, lOrderId).eq(KwtLogisticsOrderTrack::getStatus, code)
        );
        if (track != null) {
            logisticsOrderTrackMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrderTrack>()
                    .set(KwtLogisticsOrderTrack::getUpdateBy, LoginUserHolder.getUserId())
                    .set(KwtLogisticsOrderTrack::getUpdateTime, new Date())
                    .set(KwtLogisticsOrderTrack::getRemark, orderFinishDTO.getRemark())
                    .eq(KwtLogisticsOrderTrack::getId, track.getId())
            );
        } else {
            KwtLogisticsOrderTrack orderTrack = new KwtLogisticsOrderTrack();
            orderTrack.setId(new IdWorker(NumberConstant.ONE).nextId());
            orderTrack.setLOrderId(lOrderId);
            orderTrack.setRemark(orderFinishDTO.getRemark());
            orderTrack.setStatus(code);
            orderTrack.setCreateBy(LoginUserHolder.getUserId());
            orderTrack.setCreateTime(new Date());
            orderTrack.setUpdateBy(LoginUserHolder.getUserId());
            orderTrack.setUpdateTime(new Date());
            orderTrack.setDelFlag(NumberConstant.ZERO);
            logisticsOrderTrackMapper.insert(orderTrack);
        }
    }

    /**
     * 根据物流订单修改mongodb数据
     *
     * @param id             物流订单id
     * @param orderFinishDTO
     * @param ignoreAmount   剩余量
     */
    private void updateMongoDbByLogisticsOrder(Long id, OrderFinishDTO orderFinishDTO, BigDecimal ignoreAmount) {
        //更新mongodb
        SckwLogisticsOrder lOrder = new SckwLogisticsOrder();
        lOrder.set_id(id);
        lOrder.setLOrderId(id);
        lOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getStatus());
        lOrder.setUpdateTime(new Date());
        lOrder.setUpdateBy(LoginUserHolder.getUserId());
        lOrder.setUpdateByName(LoginUserHolder.getUserName());
        lOrder.setTotalLoadAmount(orderFinishDTO.getLoadAmount());
        lOrder.setTotalUnloadAmount(orderFinishDTO.getUnloadAmount());
        lOrder.setIgnoreAmount(ignoreAmount);
        //rabbitMq业务汇总数据发送/消费对象
        SckwBusSum busSum = new SckwBusSum();
        //业务汇总类型
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        //操作对象（1新增/2修改/3替换数据）
        busSum.setMethod(2);
        //业务汇总数据对象
        busSum.setObject(lOrder);
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(NumberConstant.TWO);
        streamBridge.send("sckw-busSum", JSON.toJSONString(busSum));
    }

    /**
     * 承运订单-分包托运-完结订单-修改本身数据
     *
     * @param logisticsOrder 本身物流订单数据
     * @param orderFinishDTO 页面传递数据
     */
    private void updateDataByItself(KwtLogisticsOrder logisticsOrder, OrderFinishDTO orderFinishDTO, BigDecimal ignoreAmount) {
        logisticsOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        logisticsOrder.setLoadAmount(orderFinishDTO.getLoadAmount());
        logisticsOrder.setUnloadAmount(orderFinishDTO.getUnloadAmount());
        logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
        logisticsOrder.setUpdateTime(new Date());
        logisticsOrder.setRemark(orderFinishDTO.getRemark());
        logisticsOrder.setTotalLoadAmount(orderFinishDTO.getLoadAmount());
        logisticsOrder.setTotalUnloadAmount(orderFinishDTO.getUnloadAmount());
        logisticsOrder.setIgnoreAmount(ignoreAmount);
        logisticsOrderMapper.updateById(logisticsOrder);
        KwtLogisticsOrderTrack track = logisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, logisticsOrder.getId()).eq(KwtLogisticsOrderTrack::getStatus, LogisticsOrderEnum.HAVE_FINISHED.getCode())
        );
        if (track != null) {
            logisticsOrderTrackMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrderTrack>()
                    .set(KwtLogisticsOrderTrack::getUpdateBy, LoginUserHolder.getUserId())
                    .set(KwtLogisticsOrderTrack::getUpdateTime, new Date())
                    .set(KwtLogisticsOrderTrack::getRemark, orderFinishDTO.getRemark())
                    .eq(KwtLogisticsOrderTrack::getId, track.getId())
            );
        } else {
            KwtLogisticsOrderTrack orderTrack = new KwtLogisticsOrderTrack();
            orderTrack.setId(new IdWorker(NumberConstant.ONE).nextId());
            orderTrack.setLOrderId(logisticsOrder.getId());
            orderTrack.setRemark(orderFinishDTO.getRemark());
            orderTrack.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
            orderTrack.setCreateBy(LoginUserHolder.getUserId());
            orderTrack.setCreateTime(new Date());
            orderTrack.setUpdateBy(LoginUserHolder.getUserId());
            orderTrack.setUpdateTime(new Date());
            orderTrack.setDelFlag(NumberConstant.ZERO);
            logisticsOrderTrackMapper.insert(orderTrack);
        }
//        /**单据完结修改Mongodb*/
//        SckwLogisticsOrder updateParam = new SckwLogisticsOrder();
//        updateParam.setLOrderId(Long.parseLong(orderFinishDTO.getId()))
//                .setStatus(LogisticsOrderEnum.HAVE_FINISHED.getStatus())
//                .setUpdateBy(LoginUserHolder.getUserId())
//                .setUpdateByName(LoginUserHolder.getUserName())
//                .setUpdateTime(new Date())
//                .setLoadAmount(orderFinishDTO.getLoadAmount())
//                .setUnloadAmount(orderFinishDTO.getUnloadAmount())
//        ;
//        SckwBusSum busSum = new SckwBusSum();
//        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
//        busSum.setMethod(2);
//        busSum.setObject(updateParam);
//        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
    }

    /**
     * 承运订单-分包托运-完结订单-修改分包订单
     *
     * @param orderFinishDTO
     * @param orderId        分包物流订单id
     */
    private void updateDataBySubset(OrderFinishDTO orderFinishDTO, String orderId) {
        KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, Long.parseLong(orderId)));
        if (kwtLogisticsOrder != null) {
            kwtLogisticsOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
            kwtLogisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
            kwtLogisticsOrder.setUpdateTime(new Date());
            kwtLogisticsOrder.setRemark(orderFinishDTO.getRemark());
            logisticsOrderMapper.updateById(kwtLogisticsOrder);
            KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
            track.setId(new IdWorker(NumberConstant.ONE).nextId());
            track.setLOrderId(kwtLogisticsOrder.getId());
            track.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
            track.setCreateTime(new Date());
            track.setRemark(orderFinishDTO.getRemark());
            track.setCreateBy(LoginUserHolder.getUserId());
            track.setUpdateBy(LoginUserHolder.getUserId());
            track.setUpdateTime(new Date());
            logisticsOrderTrackMapper.insert(track);
            /**单据完结修改Mongodb*/
            SckwLogisticsOrder updateParam = new SckwLogisticsOrder();
            updateParam.setLOrderId(kwtLogisticsOrder.getId())
                    .setStatus(LogisticsOrderEnum.HAVE_FINISHED.getStatus())
                    .setUpdateBy(LoginUserHolder.getUserId())
                    .setUpdateByName(LoginUserHolder.getUserName())
                    .setUpdateTime(new Date())
            ;
            SckwBusSum busSum = new SckwBusSum();
            busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
            busSum.setMethod(2);
            busSum.setObject(updateParam);
            streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
        }
    }

    /**
     * 承运订单-获取撤销驳回原因
     *
     * @param id     物流订单id
     * @param status 物流订单状态
     * @return
     */
    public HttpResult getCancelReason(String id, Integer status) {
        Map<String, String> map = logisticsOrderMapper.getRejectReason(id, status);
        return HttpResult.ok(map);
//        KwtLogisticsOrderTrack track = logisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
//                .eq(KwtLogisticsOrderTrack::getLOrderId, Long.parseLong(id))
//                /**.eq(KwtLogisticsOrderTrack::getStatus, LogisticsOrderEnum.SEND_BACK.getCode())*/
//                .eq(KwtLogisticsOrderTrack::getStatus,status)
//        );
//        return HttpResult.ok(track == null ? null : track.getRemark());
    }

    /**
     * 承运订单-分包托运-订单详情
     *
     * @param id 物流订单id
     * @return
     */
    public HttpResult subcontractConsignmentOrderDetail(String id) {
        KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(KwtLogisticsOrder::getId, Long.parseLong(id))
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (logisticsOrder == null) {
            log.info("查无单据 物流订单id:{}", id);
            throw new RuntimeException("查无单据");
        }
        KwtLogisticsOrderContract contract = kwtLogisticsOrderContractMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderContract>()
                .eq(StringUtils.isNotBlank(Long.parseLong(id)), KwtLogisticsOrderContract::getLOrderId, Long.parseLong(id)));
        KwtLogisticsOrderUnit unitOne = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(StringUtils.isNotBlank(Long.parseLong(id)), KwtLogisticsOrderUnit::getLOrderId, Long.parseLong(id))
                .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.ONE));
        KwtLogisticsOrderUnit unitTwo = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(StringUtils.isNotBlank(Long.parseLong(id)), KwtLogisticsOrderUnit::getLOrderId, Long.parseLong(id))
                .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.TWO));
        KwtLogisticsOrderAddress loadOrderAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(StringUtils.isNotBlank(Long.parseLong(id)), KwtLogisticsOrderAddress::getLOrderId, Long.parseLong(id))
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE));
        KwtLogisticsOrderAddress unloadOrderAddress = logisticsOrderAddressMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(StringUtils.isNotBlank(Long.parseLong(id)), KwtLogisticsOrderAddress::getLOrderId, Long.parseLong(id))
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO));
        KwtLogisticsOrderGoods orderGoods = kwtLogisticsOrderGoodsMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderGoods>()
                .eq(StringUtils.isNotBlank(logisticsOrder.getId()), KwtLogisticsOrderGoods::getLOrderId, logisticsOrder.getId()));
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setRemark(logisticsOrder.getRemark());
        orderDetailVO.setTaxRate(logisticsOrder.getTaxRate());
        orderDetailVO.setTaxRateLabel(logisticsOrder.getTaxRate() + "%");
        orderDetailVO.setLoadName(loadOrderAddress.getName());
        orderDetailVO.setUnloadName(unloadOrderAddress.getName());
        orderDetailVO.setId(String.valueOf(logisticsOrder.getId()));
        if (contract != null) {
            orderDetailVO.setContractId(contract.getContractId() == null ? null : String.valueOf(contract.getContractId()));
            //todo 接口调用合同服务查询合同信息
            List<Long> list = new ArrayList<>(NumberConstant.SIXTEEN);
            list.add(contract.getContractId());
            Map<Long, ContractCommonInfoResDto> contractBaseInfo = remoteContractService.queryContractBaseInfo(list);
            if (CollectionUtils.isNotEmpty(contractBaseInfo) && !ObjectUtils.isEmpty(contractBaseInfo.get(contract.getContractId()))) {
                orderDetailVO.setContractName(contractBaseInfo.get(contract.getContractId()).getContactName());
                orderDetailVO.setContractNo(contractBaseInfo.get(contract.getContractId()).getContractCode());
            }
        }
        if (unitOne != null) {
            orderDetailVO.setConsignCompanyId(unitOne.getEntId());
            orderDetailVO.setConsignCompany(unitOne.getFirmName());
            orderDetailVO.setConsignContacts(unitOne.getContacts());
            orderDetailVO.setConsignPhone(unitOne.getPhone());
            orderDetailVO.setCollectionCompany(unitOne.getFirmName());
        }
        if (unitTwo != null) {
            orderDetailVO.setCarrierCompanyId(unitTwo.getEntId());
            orderDetailVO.setCarrierCompany(unitTwo.getFirmName());
            orderDetailVO.setCarrierContacts(unitTwo.getContacts());
            orderDetailVO.setCarrierPhone(unitTwo.getPhone());
        }
        orderDetailVO.setGoodsName(orderGoods == null ? null : orderGoods.getGoodsName());
        orderDetailVO.setNumber(logisticsOrder.getAmount() == null ? null : logisticsOrder.getAmount());
        orderDetailVO.setPrice(logisticsOrder.getPrice() == null ? null : logisticsOrder.getPrice());
        orderDetailVO.setLoss(logisticsOrder.getLoss() == null ? null : logisticsOrder.getLoss());
        orderDetailVO.setDeduct(logisticsOrder.getGoodsPrice() == null ? null : logisticsOrder.getGoodsPrice());
        orderDetailVO.setLoadAddress(loadOrderAddress.getName());
        orderDetailVO.setLoadContacts(loadOrderAddress.getContacts());
        orderDetailVO.setLoadPhone(loadOrderAddress.getPhone());
        orderDetailVO.setLoadAddressDetail(loadOrderAddress.getCityName() + loadOrderAddress.getDetailAddress());
        orderDetailVO.setUnloadAddress(unloadOrderAddress.getName());
        orderDetailVO.setUnloadContacts(unloadOrderAddress.getContacts());
        orderDetailVO.setUnloadPhone(unloadOrderAddress.getPhone());
        orderDetailVO.setUnloadAddressDetail(unloadOrderAddress.getCityName() + unloadOrderAddress.getDetailAddress());
        orderDetailVO.setSettlementCycle(logisticsOrder.getSettlementCycle() == null ? null : String.valueOf(logisticsOrder.getSettlementCycle()));
        orderDetailVO.setBillingMode(logisticsOrder.getBillingMode());
        orderDetailVO.setScheduleStartTime(logisticsOrder.getStartTime() == null ? null : logisticsOrder.getStartTime());
        orderDetailVO.setScheduleEndTime(logisticsOrder.getEndTime() == null ? null : logisticsOrder.getEndTime());
        if (logisticsOrder.getBillingMode().equals(String.valueOf(NumberConstant.ONE))) {
            orderDetailVO.setPerformanceAmount(logisticsOrder.getTotalLoadAmount() == null ? null : logisticsOrder.getTotalLoadAmount());
        } else if (logisticsOrder.getBillingMode().equals(String.valueOf(NumberConstant.TWO))) {
            orderDetailVO.setPerformanceAmount(logisticsOrder.getUnloadAmount() == null ? null : logisticsOrder.getUnloadAmount());
        }
//        orderDetailVO.setPerformanceAmount(logisticsOrder.getLoadAmount() == null ? null : logisticsOrder.getLoadAmount());
        if (logisticsOrder.getSettlementCycle() != null) {
            Map<String, SysDictResDto> dtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SETTLEMENT_CYCLE.getType());
            orderDetailVO.setSettlementCycleLabel(dtoMap.isEmpty() ? null :
                    (dtoMap.get(String.valueOf(logisticsOrder.getSettlementCycle())) == null ? null : dtoMap.get(String.valueOf(logisticsOrder.getSettlementCycle())).getLabel()));
        }
        orderDetailVO.setBillingMode(logisticsOrder.getBillingMode());
        if (logisticsOrder.getBillingMode() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.CHARGING_TYPE.getType());
            orderDetailVO.setBillingModeLabel(dictResDtoMap.isEmpty() ? null :
                    (dictResDtoMap.get(logisticsOrder.getBillingMode()) == null ? null : dictResDtoMap.get(logisticsOrder.getBillingMode()).getLabel()));
        }
        if (logisticsOrder.getPayment() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
            if (dictResDtoMap.isEmpty()) {
                orderDetailVO.setPaymentLabel(null);
            } else {
                if (dictResDtoMap.get(logisticsOrder.getPayment().toString()) != null) {
                    orderDetailVO.setPaymentLabel(dictResDtoMap.get(logisticsOrder.getPayment().toString()).getLabel());
                }
            }
        }
        if (orderDetailVO.getSigningWay() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SIGNING_TYPE.getType());
            if (dictResDtoMap.isEmpty()) {
                orderDetailVO.setPaymentLabel(null);
            } else {
                if (dictResDtoMap.get(orderDetailVO.getSigningWay().toString()) != null) {
                    orderDetailVO.setSigningWayLabel(dictResDtoMap.get(orderDetailVO.getSigningWay().toString()).getLabel());
                }
            }
        }
        if (logisticsOrder.getGoodsPriceUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), logisticsOrder.getGoodsPriceUnit());
            orderDetailVO.setDeductLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getLossUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), logisticsOrder.getLossUnit());
            orderDetailVO.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), logisticsOrder.getUnit());
            orderDetailVO.setNumberLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getPriceType() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), String.valueOf(logisticsOrder.getPriceType()));
            orderDetailVO.setPriceLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        return HttpResult.ok(orderDetailVO);
    }

    /**
     * 承运订单-完结订单-数据查询展示
     *
     * @param orderId 物流订单id
     * @return
     */
    public HttpResult acceptCarriageOrderFinishDetail(String orderId) {
//        OrderFinishVO orderFinishVO = kwtLogisticsOrderMapper.selectOrderFinishData(orderId);
        Map<String, Object> map = new HashMap(NumberConstant.SIXTEEN);
        map.put("upperlOrderId", orderId);
        //随意给个值 主要是传递不为null
        map.put("passStatus", 1);
        WaybillCountVo waybillOrderCount = waybillOrderMapper.findWaybillOrderCount(map);
        OrderFinishVO orderFinishVO = new OrderFinishVO();
        orderFinishVO.setLoadAmount(waybillOrderCount == null ? new BigDecimal("0.00") : waybillOrderCount.getLoadAmount());
        orderFinishVO.setUnloadAmount(waybillOrderCount == null ? new BigDecimal("0.00") : waybillOrderCount.getUnloadAmount());
        orderFinishVO.setNumber(waybillOrderCount == null ? NumberConstant.ZERO : waybillOrderCount.getTotalComplete());
        return HttpResult.ok(orderFinishVO);
    }

    /**
     * 承运订单-页面新建订单
     *
     * @param orderDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult addOrder(AddOrderDTO orderDTO) {
        commonService.getRedisGenerateOrderNo();
        /**生成订单编号*/
        String lOrderNo = OrderGenerateSeqNoUtils.getSeqNo(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER, "2", "0", "0");
        HttpResult httpResult = ValidUtil.serviceValid(orderDTO);
        if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
            return HttpResult.error(httpResult.getMsg());
        }
        checkAddOrderParam(orderDTO);
        /**2023-08-16 新增校验承运企业与托运企业是否存在合作关系*/
        String consignCompanyId = orderDTO.getConsignCompanyId();
        String acceptCompanyId = orderDTO.getAcceptCompanyId();
        List<FindEntCooperateResVo> entCooperate = remoteManageService.findEntCooperate(Long.parseLong(acceptCompanyId), Long.parseLong(consignCompanyId), CooperateTypeEnum.CONSIGN.getCode());
        if (entCooperate == null) {
            return HttpResult.error("该托运企业与我方并无合作关系!");
        }
        /**保存新建数据*/
        Long lOrderId = new IdWorker(NumberConstant.ONE).nextId();
        /**根据合同计算当前单据状态*/
        /**判断生成物流订单应生成哪一种单据状态*/
        List<Long> contractList = new ArrayList<>();
        contractList.add(Long.parseLong(orderDTO.getContractId()));
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = remoteContractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new RuntimeException("承运订单新建订单-并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(Long.parseLong(orderDTO.getContractId())) == null) {
            throw new RuntimeException("承运订单新建订单-并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(orderDTO.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("自建订单异常");
        }
        /**2023-08-04 自建订单商品可以不需要关联查询*/
//        /**获取商品信息*/
//        KwpGoods goods = goodsInfoService.getGoodsById(Long.parseLong(orderDTO.getGoodsId()));
//        if (goods == null) {
//            log.info("自建订单获取商品信息失败 商品id:{},商品名称:{}", orderDTO.getGoodsId(), orderDTO.getGoodsName());
//            throw new BusinessException("商品信息获取失败");
//        }
        saveLogisticsOrder(orderDTO, lOrderId, orderStatus, lOrderNo);
        saveLogisticsOrderAddress(orderDTO, lOrderId);
        saveLogisticsOrderGoods(orderDTO, lOrderId, lOrderNo);
        saveLogisticsOrderContract(orderDTO, lOrderId, infoResDto);
        saveLogisticsOrderTrack(lOrderId, orderStatus);
        saveLogisticsOrderUnit(orderDTO, lOrderId);
        saveMongoDb(orderDTO, orderStatus, lOrderId, lOrderNo, infoResDto);
        /**发送信息至消息列表*/
        //托运单位
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(Long.parseLong(orderDTO.getConsignCompanyId()));
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(Long.parseLong(orderDTO.getConsignCompanyId()));
        consignUnit.setTopEntId(entCacheResDto == null ? null : entCacheResDto.getId());
        consignUnit.setFirmName(orderDTO.getConsignCompany());
        consignUnit.setContactsId(Long.parseLong(orderDTO.getConsignContactsId()));

        //承运单位
        EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(Long.parseLong(orderDTO.getAcceptCompanyId()));
        KwtLogisticsOrderUnit carriageUnit = new KwtLogisticsOrderUnit();
        carriageUnit.setUnitType(NumberConstant.TWO);
        carriageUnit.setEntId(Long.parseLong(orderDTO.getAcceptCompanyId()));
        carriageUnit.setTopEntId(entCacheResDto1 == null ? null : entCacheResDto1.getId());
        carriageUnit.setFirmName(orderDTO.getAcceptCompany());
        carriageUnit.setContactsId(Long.parseLong(orderDTO.getAcceptContactsId()));
//        System.out.println("承运订单新建订单-消息列表推送 start");
//        commonService.publicLogisticsConsignmentPushMessage(consignUnit, carriageUnit, lOrderNo, LoginUserHolder.getUserId(), LoginUserHolder.getEntId()
//                , MessageEnum.CARRIAGE_NEW_LOGISTICS, MessageEnum.CARRIAGE_NEW_LOGISTICS_ORDER);

        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"
        );

//        System.out.println("承运订单新建订单-消息列表推送 end ");
        return HttpResult.ok();
    }

    /**
     * 承运订单-页面新增订单-商品信息
     *
     * @param orderDTO 页面参数
     * @param lOrderId 订单id
     * @param lOrderNo 订单编号
     */
    private void saveLogisticsOrderGoods(AddOrderDTO orderDTO, Long lOrderId, String lOrderNo) {
        KwtLogisticsOrderGoods goods = new KwtLogisticsOrderGoods();
        goods.setId(new IdWorker(NumberConstant.ONE).nextId());
        goods.setLOrderId(lOrderId);
        goods.setLOrderNo(lOrderNo);
//        goods.setGoodsId();
        goods.setGoodsName(orderDTO.getGoodsName());
        goods.setGoodsType(orderDTO.getGoodsType());
        goods.setStatus(NumberConstant.ZERO);
        goods.setCreateBy(LoginUserHolder.getUserId());
        goods.setCreateTime(new Date());
        goods.setUpdateBy(LoginUserHolder.getUserId());
        goods.setUpdateTime(new Date());
        kwtLogisticsOrderGoodsMapper.insert(goods);
    }

    /**
     * 校验请求参数
     *
     * @param orderDTO
     */
    private void checkAddOrderParam(AddOrderDTO orderDTO) {
        if (!ObjectUtils.isEmpty(orderDTO.getTaxRate())) {
            if (orderDTO.getTaxRate().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("税率填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(orderDTO.getLoss())) {
            if (orderDTO.getLoss().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("合理损耗填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(orderDTO.getGoodsPrice())) {
            if (orderDTO.getGoodsPrice().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("扣亏货值填写格式错误!");
            }
        }
    }

    /**
     * 承运订单-新建订单-保存mongodb
     *
     * @param orderDTO    页面请求参数
     * @param orderStatus 主体单据状态
     * @param lOrderId    主体订单id
     * @param lOrderNo    主体订单编号
     * @param infoResDto  合同信息
     */
    private void saveMongoDb(AddOrderDTO 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));

    }

    /**
     * 承运订单-页面新增订单-订单对应企业单位
     *
     * @param orderDTO 页面请求参数
     * @param lOrderId 主体id
     */
    private void saveLogisticsOrderUnit(AddOrderDTO 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);

    }

    /**
     * 承运订单-页面新增订单-订单状态
     *
     * @param lOrderId    主体id
     * @param orderStatus 主体单据状态
     */
    private void saveLogisticsOrderTrack(Long lOrderId, Integer orderStatus) {
        KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
        track.setId(new IdWorker(NumberConstant.ONE).nextId());
        track.setLOrderId(lOrderId);
        track.setStatus(orderStatus);
        track.setCreateBy(LoginUserHolder.getUserId());
        track.setCreateTime(new Date());
        track.setUpdateBy(LoginUserHolder.getUserId());
        track.setUpdateTime(new Date());
        logisticsOrderTrackMapper.insert(track);
    }

    /**
     * 承运订单-新建订单-地址信息保存
     *
     * @param orderDTO 页面请求参数
     * @param lOrderId 主体id
     */
    private void saveLogisticsOrderAddress(AddOrderDTO orderDTO, Long lOrderId) {
        KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
        loadAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
        loadAddress.setLOrderId(lOrderId);
        loadAddress.setAddressType(NumberConstant.ONE);
        loadAddress.setName(orderDTO.getLoadName() == null ? null : orderDTO.getLoadName());
//        loadAddress.setType();
        loadAddress.setContacts(orderDTO.getLoadContacts());
        loadAddress.setPhone(orderDTO.getLoadPhone());
        loadAddress.setCityCode(orderDTO.getLoadCityCode());
        loadAddress.setCityName(orderDTO.getLoadCityName());
        loadAddress.setDetailAddress(orderDTO.getLoadDetailAddress());
        loadAddress.setLat(orderDTO.getLoadLat());
        loadAddress.setLng(orderDTO.getLoadLng());
        loadAddress.setEntryType(NumberConstant.FOUR);
        loadAddress.setStatus(NumberConstant.ZERO);
        loadAddress.setCreateBy(LoginUserHolder.getUserId());
        Date date = new Date();
        loadAddress.setCreateTime(date);
        loadAddress.setUpdateBy(LoginUserHolder.getUserId());
        loadAddress.setUpdateTime(date);

        KwtLogisticsOrderAddress unloadAddress = new KwtLogisticsOrderAddress();
        unloadAddress.setId(new IdWorker(NumberConstant.TWO).nextId());
        unloadAddress.setLOrderId(lOrderId);
        unloadAddress.setAddressType(NumberConstant.TWO);
        unloadAddress.setName(orderDTO.getUnloadName() == null ? null : orderDTO.getUnloadName());
//        unloadAddress.setType();
        unloadAddress.setContacts(orderDTO.getUnloadContacts());
        unloadAddress.setPhone(orderDTO.getUnloadPhone());
        unloadAddress.setCityCode(orderDTO.getUnloadCityCode());
        unloadAddress.setCityName(orderDTO.getUnloadCityName());
        unloadAddress.setDetailAddress(orderDTO.getUnloadDetailAddress());
        unloadAddress.setLat(orderDTO.getUnloadLat());
        unloadAddress.setLng(orderDTO.getUnloadLng());
        unloadAddress.setEntryType(NumberConstant.FOUR);
        unloadAddress.setStatus(NumberConstant.ZERO);
        unloadAddress.setCreateBy(LoginUserHolder.getUserId());
        unloadAddress.setCreateTime(date);
        unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
        unloadAddress.setUpdateTime(date);
        logisticsOrderAddressMapper.insert(loadAddress);
        logisticsOrderAddressMapper.insert(unloadAddress);
    }

    /**
     * 承运订单-新建订单-合体主体
     *
     * @param orderDTO 页面请求参数
     * @param lOrderId 主体id
     */
    private void saveLogisticsOrderContract(AddOrderDTO 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());
        kwtLogisticsOrderContractMapper.insert(contract);
    }

    /**
     * 承运订单-页面新增订单-订单主体
     *
     * @param orderDTO    页面请求参数
     * @param lOrderId    主体id
     * @param orderStatus 订单状态
     * @param lOrderNo    主体订单编号
     */
    private void saveLogisticsOrder(AddOrderDTO 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);
        logisticsOrderMapper.insert(order);
    }

    /**
     * 承运订单首页条件查询
     *
     * @param query
     * @param type
     * @return
     */
    public PageRes selectLogisticsOrderList(AcceptCarriageOrderQuery query, String type) {
        Long entId = LoginUserHolder.getEntId();
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<Integer> orderList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.SEVEN).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
//        LoginUserHolder.getIsMain()
        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getIds())) {
            idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        }
        List<AcceptCarriageOrderVO> list = logisticsOrderMapper.selectLogisticsOrderListByAcceptCarriage(query, orderList, type, entId, longList, longList, idsList);
        PageInfo<AcceptCarriageOrderVO> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(pageInfo, list);
        }
//        List<AcceptCarriageOrderVO> detailRes = new ArrayList<>();
        /**计量单位*/
        Map<String, String> unitTypeDictData = getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**运价方式*/
        Map<String, String> priceDictData = getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**计费方式*/
        Map<String, String> chargingDictData = getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
        Map<String, String> signingWay = getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗*/
//        Map<String, String> taxRateTypeDictData = getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        /**订单来源*/
        Map<String, String> orderSource = getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        Map<Long, UserCacheResDto> longUserMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(AcceptCarriageOrderVO::getCreateBy).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                longUserMap = remoteSystemService.queryUserCacheMapByIds(collect);
            }
        }
        for (AcceptCarriageOrderVO vo : list) {
            vo.setAccountsCycleLabel(settlementDictData.get(vo.getAccountsCycle()));
            vo.setAppointor(longUserMap.get(vo.getCreateBy()) == null ? null : longUserMap.get(vo.getCreateBy()).getName());
            vo.setBillingModeLabel(chargingDictData.get(vo.getBillingMode()));
            vo.setSigningLabel(signingWay.get(vo.getSigning()));
            vo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
            vo.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));
            vo.setLoadAddress(vo.getLoadCityName() + vo.getLoadAddress());
            vo.setUnloadAddress(vo.getUnloadCityName() + vo.getUnloadAddress());
            vo.setLoadCityName(vo.getLoadName());
            vo.setUnloadCityName(vo.getUnloadName());
            if (vo.getTOrderId() != null) {
//                try {
//                    OrderDetailRes orderDetailRes = tradeOrderInfoService.getOrderDetailById(Long.valueOf(vo.getTOrderId()));
//                    if (orderDetailRes != null) {
//                        List<UnitInfoDetailRes> unitInfo = orderDetailRes.getUnitInfo();
//                        for (UnitInfoDetailRes detailRes : unitInfo) {
//                            if (String.valueOf(NumberConstant.ONE).equals(detailRes.getUnitType())) {
//                                vo.setShipmentsUnitEntId(String.valueOf(detailRes.getEntId()));
//                                vo.setShipmentsUnit(detailRes.getFirmName());
//                            } else {
//                                vo.setReceiveGoodsUnitEntId(String.valueOf(detailRes.getEntId()));
//                                vo.setReceiveGoodsUnit(detailRes.getFirmName());
//                            }
//                        }
//                    }
//                } catch (NumberFormatException e) {
////                    throw new RuntimeException(e);
//                    log.info("查询失败:{},信息:{}",vo.getTOrderId(),e.getMessage(),e);
//                }
            }
            vo.setWaitDistributionAmount(vo.getCarryingCapacity().subtract(vo.getSubcontractAmount()).subtract(vo.getEntrustAmount()));
            String tOrderId = vo.getTOrderId();
            if (StringUtils.isNotBlank(tOrderId)) {
                try {
                    OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(Long.parseLong(tOrderId));
                    if (orderDetailById != null) {
                        List<UnitInfoDetailRes> unitInfo = orderDetailById.getUnitInfo();
                        if (CollectionUtils.isNotEmpty(unitInfo)) {
                            for (UnitInfoDetailRes detailRes : unitInfo) {
                                if ("1".equals(detailRes.getUnitType())) {
                                    vo.setReceiveGoodsUnit(detailRes.getFirmName());
                                    vo.setReceiveGoodsUnitEntId(detailRes.getEntId() == null ? null : detailRes.getEntId().toString());
                                }
                                if ("2".equals(detailRes.getUnitType())) {
                                    vo.setShipmentsUnit(detailRes.getFirmName());
                                    vo.setShipmentsUnitEntId(detailRes.getEntId() == null ? null : detailRes.getEntId().toString());
                                }
                            }
                        }
                    }
                } catch (BusinessException e) {
//                    throw new RuntimeException(e);
                    log.info("查询失败:{},信息:{}", vo.getTOrderId(), e.getMessage(), e);
                }
            }

        }
        return PageRes.build(pageInfo, list);
    }

    public HttpResult statisticsAcceptCarriage(AcceptCarriageOrderQuery query, String type) {
        Long entId = LoginUserHolder.getEntId();
        List<Integer> orderList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.EIGHT).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
        List<Long> idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        List<TableTops> list = logisticsOrderMapper.countLogisticsOrderListByAcceptCarriageStatus(query, orderList, type, entId, longList, longList, idsList);
        List<TableTops> arrayList = new ArrayList<>();
        arrayList.addAll(list);
        /**补全数据状态不齐的情况*/
        arrayList = commonService.packageReturnStatistics(list, arrayList);
        // 查询结果
        Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN);
        map.put("tableTop", arrayList);
        // 查询结果
        return HttpResult.ok(map);
    }

    /**
     * 企业app-订单主页面-承运订单统计
     *
     * @return
     */
    public HttpResult statisticsCarriage(AcceptCarriageOrderQuery query) {
//        Long entId = LoginUserHolder.getEntId();
//        Long queryEntId = 0L;
//        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(entId));
//        if (entMap == null) {
//            queryEntId = entId;
//        } else {
//            queryEntId = entMap.get(entId).getId();
//        }
        String type = "2";
        HttpResult httpResult = statisticsAcceptCarriage(query, type);
        return httpResult;
    }

    /**
     * @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 - Global.NUMERICAL_ONE);
    }

    public HttpResult getOrderTrackByOrderId(String orderId, String number) {
        List<KwtLogisticsOrderTrack> list = logisticsOrderTrackMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, orderId)
                .eq(KwtLogisticsOrderTrack::getDelFlag, NumberConstant.ZERO).orderByDesc(KwtLogisticsOrderTrack::getCreateTime)
        );
        List<LogisticsOrderTrackVO> vos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(KwtLogisticsOrderTrack::getCreateBy).collect(Collectors.toList());
            Map<Long, UserCacheResDto> longUserCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(collect);
            for (KwtLogisticsOrderTrack track : list) {
                LogisticsOrderTrackVO vo = new LogisticsOrderTrackVO();
                vo.setId(track.getId());
                vo.setLOrderId(track.getLOrderId());
                vo.setRemark(track.getRemark());
                vo.setStatus(track.getStatus());
                vo.setStatusLabel(LogisticsOrderEnum.getName(track.getStatus()));
                vo.setCreateBy(track.getCreateBy());
                if (!longUserCacheResDtoMap.isEmpty()) {
                    if (longUserCacheResDtoMap.get(track.getCreateBy()) != null) {
                        vo.setCreateName(longUserCacheResDtoMap.get(track.getCreateBy()).getName());
                        if (longUserCacheResDtoMap.get(track.getCreateBy()).getRoleInfo() != null && longUserCacheResDtoMap.get(track.getCreateBy()).getRoleInfo().get(0) != null) {
                            vo.setCreateRole(longUserCacheResDtoMap.get(track.getCreateBy()).getRoleInfo().get(0).getName());
                        }
                    }
                }
                vo.setCreateTime(track.getCreateTime());
                vo.setUpdateBy(track.getUpdateBy());
                vo.setUpdateTime(track.getUpdateTime());
                vos.add(vo);
            }
        }
        return HttpResult.ok(vos);
    }

    /**
     * 承运订单-导出
     *
     * @param query 查询条件
     * @param type  类型 1托运 2承运
     * @return
     */
    public List<AcceptCarriageOrderExcelVo> exportAcceptCarriage(AcceptCarriageOrderQuery query, String type) {
        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getIds())) {
            idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        }
        Long entId = LoginUserHolder.getEntId();
//        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<Integer> orderList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.SEVEN).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
        List<AcceptCarriageOrderVO> list = logisticsOrderMapper.selectLogisticsOrderListByAcceptCarriage(query, orderList, type, entId, longList, longList, idsList);
        /**计费方式*/
        Map<String, String> chargingDictData = getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
        Map<String, String> signingWay = getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗单位*/
        Map<String, String> taxRate = getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        /**运价方式*/
        Map<String, String> priceType = getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**订单来源*/
        Map<String, String> orderSource = getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        Map<Long, UserCacheResDto> longUserMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(AcceptCarriageOrderVO::getCreateBy).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                longUserMap = remoteSystemService.queryUserCacheMapByIds(collect);
            }
        }
        List<AcceptCarriageOrderExcelVo> exportList = new ArrayList<>();
        for (AcceptCarriageOrderVO vo : list) {
            AcceptCarriageOrderExcelVo carriageOrderExcelVo = new AcceptCarriageOrderExcelVo();
            BeanUtils.copyProperties(vo, carriageOrderExcelVo);
            carriageOrderExcelVo.setPriceLabel(vo.getPrice() == null ? null : vo.getPrice().toString() + priceType.get(vo.getPriceType()));
            carriageOrderExcelVo.setLossUnitLabel(vo.getLoss() == null ? null : vo.getLoss().toString() + taxRate.get(vo.getLossUnit()));
//            carriageOrderExcelVo.setGoodsPriceLabel(vo.getGoodsPrice() == null ? null : vo.getGoodsPrice().toString() + priceType.get(vo.getGoodsPriceUnit()));
            carriageOrderExcelVo.setAccountsCycleLabel(settlementDictData.get(vo.getAccountsCycle()));
            carriageOrderExcelVo.setAppointor(longUserMap.get(vo.getCreateBy()) == null ? null : longUserMap.get(vo.getCreateBy()).getName());
            carriageOrderExcelVo.setBillingModeLabel(chargingDictData.get(vo.getBillingMode()));
//            carriageOrderExcelVo.setSigningLabel(signingWay.get(vo.getSigning()));
            carriageOrderExcelVo.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));
            carriageOrderExcelVo.setLoadAddress(vo.getLoadCityName() + vo.getLoadAddress());
            carriageOrderExcelVo.setUnloadAddress(vo.getUnloadCityName() + vo.getUnloadAddress());
            carriageOrderExcelVo.setLoadAddress(vo.getLoadName());
            carriageOrderExcelVo.setUnloadAddress(vo.getUnloadName());
            carriageOrderExcelVo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
//            if (vo.getTOrderId() != null) {
//                try {
//                    OrderDetailRes orderDetailRes = tradeOrderInfoService.getOrderDetailById(Long.valueOf(vo.getTOrderId()));
//                    if (orderDetailRes != null) {
//                        List<UnitInfoDetailRes> unitInfo = orderDetailRes.getUnitInfo();
//                        for (UnitInfoDetailRes detailRes : unitInfo) {
//                            if (String.valueOf(NumberConstant.ONE).equals(detailRes.getUnitType())) {
//                                carriageOrderExcelVo.setShipmentsUnit(detailRes.getFirmName());
//                            } else {
//                                carriageOrderExcelVo.setReceiveGoodsUnit(detailRes.getFirmName());
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    log.error("tradeOrderInfoService.getOrderDetailById error id:{}.errorMessage:{}",vo.getTOrderId(),e.getMessage(),e);
//                }
//            }
            BigDecimal subtract = vo.getCarryingCapacity().subtract(vo.getSubcontractAmount()).subtract(vo.getEntrustAmount());
            DecimalFormat df = new DecimalFormat("0.00");
            carriageOrderExcelVo.setWaitDistributionAmount(subtract == null ? null : df.format(subtract));
            String tOrderId = vo.getTOrderId();
            if (StringUtils.isNotBlank(tOrderId)) {
                try {
                    OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(Long.parseLong(tOrderId));
                    if (orderDetailById != null) {
                        List<UnitInfoDetailRes> unitInfo = orderDetailById.getUnitInfo();
                        if (CollectionUtils.isNotEmpty(unitInfo)) {
                            for (UnitInfoDetailRes detailRes : unitInfo) {
                                if ("1".equals(detailRes.getUnitType())) {
                                    carriageOrderExcelVo.setReceiveGoodsUnit(detailRes.getFirmName());
                                }
                                if ("2".equals(detailRes.getUnitType())) {
                                    carriageOrderExcelVo.setShipmentsUnit(detailRes.getFirmName());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("tradeOrderInfoService.getOrderDetailById error id:{}.errorMessage:{}", vo.getTOrderId(), e.getMessage(), e);
                }
            }
//            carriageOrderExcelVo.setSubcontractAmount(Objects.isNull(vo.getSubcontractAmount()) ? null : df.format(vo.getSubcontractAmount()) + priceType.get(vo.getPriceType()));
//            carriageOrderExcelVo.setEntrustAmount(Objects.isNull(vo.getEntrustAmount()) ? null : df.format(vo.getEntrustAmount()) + priceType.get(vo.getPriceType()));
            carriageOrderExcelVo.setLoadAmount(Objects.isNull(vo.getLoadAmount()) ? null : df.format(vo.getLoadAmount()) + priceType.get(vo.getPriceType()));
            carriageOrderExcelVo.setUnloadAmount(Objects.isNull(vo.getUnloadAmount()) ? null : df.format(vo.getUnloadAmount()) + priceType.get(vo.getPriceType()));
            exportList.add(carriageOrderExcelVo);
        }
        return exportList;
    }

    /**
     * 工作台-承运业务统计
     *
     * @param dateType
     * @return
     */
    public HttpResult workbenchStatistics(String dateType) {
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId());
        Long id = entCacheResDto.getId();
        //周
        if (String.valueOf(NumberConstant.ONE).equals(dateType)) {

            //本周时间

            //开始时间
            String weekDateStart = DateUtil.getLastWeekDateStartToString(LocalDate.now(), 6);
            //结束时间
            String weekDateEnd = DateUtil.getLastWeekDateEndToString(0);
            //环比上周
            //开始时间
            String lastWeekDateStart = DateUtil.getLastWeekDateStartToString(LocalDate.now(), 13);
            //结束时间
            String lastWeekDateEnd = DateUtil.getLastWeekDateEndToString(7);
            return computeCompare(id, weekDateStart, weekDateEnd, lastWeekDateStart, lastWeekDateEnd, 2);
        } else if (String.valueOf(NumberConstant.TWO).equals(dateType)) {

            //本月
            //开始时间
            String monthDateStart = DateUtil.getBeforeMonthDateAndDaysStartToString(LocalDateTime.now(), 1, -1);
            //结束时间
            String monthDateEnd = DateUtil.getLastWeekDateEndToString(0);


            //环比上月

            //上个月
            //开始时间
            String lastMonthDateStart = DateUtil.getBeforeMonthDateAndDaysStartToString(LocalDateTime.now(), 2, -1);
            //结束时间
            String lastMonthDateEnd = DateUtil.getBeforeMonthDateAndDaysEndToString(LocalDateTime.now(), 1, 0);
            return computeCompare(id, monthDateStart, monthDateEnd, lastMonthDateStart, lastMonthDateEnd, 3);
        } else if (String.valueOf(NumberConstant.THREE).equals(dateType)) {
            //年
            // 获取当前日期
            String currentDateEnd = DateUtil.format(LocalDate.now()) + " 23:59:59";
            LocalDate currentDate = LocalDate.now();
            // 计算一年前的日期
            LocalDate oneYearAgo = currentDate.minusYears(1);
            LocalDateTime currentDateStart = oneYearAgo.atStartOfDay();

        } else {
            HttpResult.error("统计纬度错误!");
        }
        return null;
    }

    /**
     * 环比计算
     *
     * @param id                企业集团id
     * @param weekDateStart     环比本次开始时间
     * @param weekDateEnd       环比本次结束时间
     * @param lastWeekDateStart 环比上次开始时间
     * @param lastWeekDateEnd   环比上次结束时间
     * @return
     */
    private HttpResult computeCompare(Long id, String weekDateStart, String weekDateEnd, String lastWeekDateStart, String lastWeekDateEnd, Integer dateType) {
        HttpResult httpResult = new HttpResult();
        StatisticsResultVO resultVO = new StatisticsResultVO();
        //获取完结的单据-排除掉不做统计中的数据
        List<Integer> statusList = new ArrayList<>();
        statusList.add(LogisticsOrderEnum.TO_BE_PLANNED.getCode());
        statusList.add(LogisticsOrderEnum.PENDING_ORDER.getCode());
        statusList.add(LogisticsOrderEnum.WAIT_DELIVERY.getCode());
        statusList.add(LogisticsOrderEnum.IN_TRANSIT.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_RECONCILED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getCode());
        //本周
        StatisticsByOrderVO currentWeek = logisticsOrderMapper.selectStatisticsByOrder(statusList, weekDateStart, weekDateEnd, id, OrderTypeEnum.ACCEPT_CARRIAGE_ORDER.getType());

        //上周
        StatisticsByOrderVO lastWeek = logisticsOrderMapper.selectStatisticsByOrder(statusList, lastWeekDateStart, lastWeekDateEnd, id, OrderTypeEnum.ACCEPT_CARRIAGE_ORDER.getType());
        //环比计算
        StatisticsByOrderVO vo = new StatisticsByOrderVO();
        vo.setWaitingAmount(currentWeek.getWaitingAmount());
        vo.setAmount(currentWeek.getAmount());
        vo.setEntrustAmount(currentWeek.getEntrustAmount());
        vo.setSubcontractAmount(currentWeek.getSubcontractAmount());
        vo.setTotalPrice(currentWeek.getTotalPrice());

        vo.setLastWaitingAmount(lastWeek.getWaitingAmount());
        vo.setLastAmount(lastWeek.getAmount());
        vo.setLastEntrustAmount(lastWeek.getEntrustAmount());
        vo.setLastSubcontractAmount(lastWeek.getSubcontractAmount());
        vo.setLastTotalPrice(lastWeek.getTotalPrice());

        /**计算待承运量*/
        computeCompareWaitingAmount(resultVO, currentWeek, lastWeek);

        /**承运量*/
        computeCompareAmount(resultVO, currentWeek, lastWeek);

        /**总金额（费用）*/
        computeCompareTotalPrice(resultVO, currentWeek, lastWeek);

        /**待处理的金额*/
        SettlementMoney settlementMoney = paymentDubboService.countCarrier(id, dateType);
        StatisticsMoneyVO moneyVO = new StatisticsMoneyVO();
        moneyVO.setCurrent(settlementMoney.getCurrent());
        moneyVO.setBefore(settlementMoney.getBefore());
        moneyVO.setChainRatio(settlementMoney.getPercent());
        moneyVO.setFlag(settlementMoney.getFlag());
        resultVO.setMoneyVO(moneyVO);
        httpResult.setData(resultVO);
        return httpResult;
    }

    private void computeCompareTotalPrice(StatisticsResultVO resultVO, StatisticsByOrderVO currentWeek, StatisticsByOrderVO lastWeek) {
        Integer flag = 1;
        BigDecimal chainRatio = new BigDecimal("0.00");
        if (currentWeek.getTotalPrice().compareTo(new BigDecimal("0.00")) == 0
                && lastWeek.getTotalPrice().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = new BigDecimal("0.00");
        } else if (currentWeek.getTotalPrice().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = chainRatio.subtract(new BigDecimal("100.00"));
            flag = 2;
        } else if (lastWeek.getTotalPrice().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = new BigDecimal("100.00").subtract(chainRatio);
        } else {
            chainRatio = (currentWeek.getTotalPrice().subtract(lastWeek.getTotalPrice())).divide(lastWeek.getTotalPrice(), NumberConstant.SIX, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, BigDecimal.ROUND_HALF_UP);
        }
        if (chainRatio.compareTo(new BigDecimal("0.00")) == -1) {
            flag = 2;
        }
        StatisticsTotalPriceVO priceVO = new StatisticsTotalPriceVO();
        priceVO.setTotalPrice(currentWeek.getTotalPrice());
//        priceVO.setChainRatio(chainRatio.abs() + "%");
        priceVO.setChainRatio(chainRatio.abs().toString());
        priceVO.setFlag(flag);
        priceVO.setLastTotalPrice(lastWeek.getTotalPrice());
        resultVO.setTotalPriceVO(priceVO);
    }

    private void computeCompareAmount(StatisticsResultVO resultVO, StatisticsByOrderVO currentWeek, StatisticsByOrderVO lastWeek) {
        Integer amountFlag = 1;
        BigDecimal amountChainRatio = new BigDecimal("0.00");
        if (currentWeek.getAmount().compareTo(new BigDecimal("0.00")) == 0
                && lastWeek.getAmount().compareTo(new BigDecimal("0.00")) == 0) {
            amountChainRatio = new BigDecimal("0.00");
        } else if (currentWeek.getAmount().compareTo(new BigDecimal("0.00")) == 0) {
            amountChainRatio = amountChainRatio.subtract(new BigDecimal("100.00"));
            amountFlag = 2;
        } else if (lastWeek.getAmount().compareTo(new BigDecimal("0.00")) == 0) {
            amountChainRatio = new BigDecimal("100.00").subtract(amountChainRatio);
        } else {
            amountChainRatio = (currentWeek.getAmount().subtract(lastWeek.getAmount())).divide(lastWeek.getAmount(), NumberConstant.SIX, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, BigDecimal.ROUND_HALF_UP);
        }
        if (amountChainRatio.compareTo(new BigDecimal("0.00")) == -1) {
            amountFlag = 2;
        }

        /**承运量*/
        StatisticsAmountVO amountVO = new StatisticsAmountVO();
        amountVO.setAmount(currentWeek.getAmount());
//        amountVO.setChainRatio(amountChainRatio.abs() + "%");
        amountVO.setChainRatio(amountChainRatio.abs().toString());
        amountVO.setFlag(amountFlag);
        amountVO.setLastAmount(lastWeek.getAmount());
        resultVO.setAmountVO(amountVO);
    }

    private void computeCompareWaitingAmount(StatisticsResultVO resultVO, StatisticsByOrderVO currentWeek, StatisticsByOrderVO lastWeek) {
        Integer flag = 1;
        BigDecimal chainRatio = new BigDecimal("0.00");
        if (currentWeek.getWaitingAmount().compareTo(new BigDecimal("0.00")) == 0
                && lastWeek.getWaitingAmount().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = new BigDecimal("0.00");
        } else if (currentWeek.getWaitingAmount().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = chainRatio.subtract(new BigDecimal("100.00"));
            flag = 2;
        } else if (lastWeek.getWaitingAmount().compareTo(new BigDecimal("0.00")) == 0) {
            chainRatio = new BigDecimal("100.00").subtract(chainRatio);
        } else {
            chainRatio = (currentWeek.getWaitingAmount().subtract(lastWeek.getWaitingAmount())).divide(lastWeek.getWaitingAmount(), NumberConstant.SIX, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, BigDecimal.ROUND_HALF_UP);
        }
        if (chainRatio.compareTo(new BigDecimal("0.00")) == -1) {
            flag = 2;
        }
        /**待分配量*/
        StatisticsWaitingAmountVO waitingAmountVO = new StatisticsWaitingAmountVO();
        waitingAmountVO.setWaitingAmount(currentWeek.getWaitingAmount());
//        waitingAmountVO.setChainRatio(chainRatio.abs() + "%");
        waitingAmountVO.setChainRatio(chainRatio.abs().toString());
        waitingAmountVO.setFlag(flag);
        waitingAmountVO.setLastWaitingAmount(lastWeek.getWaitingAmount());
        resultVO.setWaitingAmountVO(waitingAmountVO);
    }

    /**
     * 工作台-物流运输数据统计
     *
     * @return
     */
    public HttpResult workbenchLogisticsOrderStatistics(LogisticsOrderStatisticsParam logisticsOrderStatistics) {
//        List<String> stringList = StringUtils.splitStrToList(logisticsOrderStatistics.getTypes(), String.class);
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId());
        if (entCacheResDto == null) {
            return HttpResult.ok();
        }
        Long id = entCacheResDto.getId();
        //获取完结的单据-排除掉不做统计中的数据
        List<Integer> statusList = new ArrayList<>();
        statusList.add(LogisticsOrderEnum.TO_BE_PLANNED.getCode());
        statusList.add(LogisticsOrderEnum.PENDING_ORDER.getCode());
        statusList.add(LogisticsOrderEnum.WAIT_DELIVERY.getCode());
        statusList.add(LogisticsOrderEnum.IN_TRANSIT.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_RECONCILED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getCode());

        /**1.目前只统计承运单位属性的数据
         * 2.月统计->默认当前往前推12个月
         * 3.日统计->默认当前往前推30天*/
        if (String.valueOf(NumberConstant.THREE).equals(logisticsOrderStatistics.getDateType())) {
            //本月
            //开始时间
            DateTime dateTime = cn.hutool.core.date.DateUtil.truncate(new Date(), DateField.MONTH);
            LocalDateTime localDateTime = dateTime.toLocalDateTime().minusMonths(11);
            String dateStart = cn.hutool.core.date.DateUtil.format(localDateTime, DEF_DATE_FORMAT);
            //结束时间
            String dateEnd = cn.hutool.core.date.DateUtil.format(dateTime, DEF_DATE_FORMAT);

            List<LogisticsOrderStatisticsVO> list = logisticsOrderMapper.workbenchLogisticsOrderStatisticsByMonth(id, statusList,
                    OrderTypeEnum.ACCEPT_CARRIAGE_ORDER.getType(), dateStart, dateEnd, logisticsOrderStatistics.getTypeOne(), logisticsOrderStatistics.getTypeTwo());
            if (logisticsOrderStatistics.getTypeOne().equals("2")) {
                list.forEach(vo -> {
                    vo.setTypeTwo(vo.getTypeTwo().setScale(2, RoundingMode.HALF_UP));
                    vo.setTypeOne(vo.getTypeOne().divide(new BigDecimal("10000")).setScale(2, RoundingMode.HALF_UP));
                });
            }
            if (logisticsOrderStatistics.getTypeTwo().equals("2")) {
                list.forEach(vo -> {
                    vo.setTypeOne(vo.getTypeOne().setScale(2, RoundingMode.HALF_UP));
                    vo.setTypeTwo(vo.getTypeTwo().divide(new BigDecimal("10000")).setScale(2, RoundingMode.HALF_UP));
                });
            }
            return HttpResult.ok(list);
        } else if (String.valueOf(NumberConstant.ONE).equals(logisticsOrderStatistics.getDateType())) {
            //开始时间
            String format = cn.hutool.core.date.DateUtil.format(LocalDateTime.now(), DEF_DATE_FORMAT);
            String dateStart = null;
            try {
                dateStart = DateUtil.getThirtyDaysDate(format, 29);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            //结束时间
            String dateEnd = DateUtil.getLastWeekDateEndToString(0);
            List<LogisticsOrderStatisticsVO> list = logisticsOrderMapper.workbenchLogisticsOrderStatisticsByDays(id, statusList,
                    OrderTypeEnum.ACCEPT_CARRIAGE_ORDER.getType(), dateStart, dateEnd, logisticsOrderStatistics.getTypeOne(), logisticsOrderStatistics.getTypeTwo());
            if (logisticsOrderStatistics.getTypeOne().equals("2")) {
                list.forEach(vo -> {
                    vo.setTypeTwo(vo.getTypeTwo().setScale(2, RoundingMode.HALF_UP));
                    vo.setTypeOne(vo.getTypeOne().divide(new BigDecimal("10000")).setScale(2, RoundingMode.HALF_UP));
                });
            }
            if (logisticsOrderStatistics.getTypeTwo().equals("2")) {
                list.forEach(vo -> {
                    vo.setTypeOne(vo.getTypeOne().setScale(2, RoundingMode.HALF_UP));
                    vo.setTypeTwo(vo.getTypeTwo().divide(new BigDecimal("10000")).setScale(2, RoundingMode.HALF_UP));
                });
            }
            return HttpResult.ok(list);
        }
        return null;
    }
}
