package com.sckw.transport.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
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.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.model.vo.BaseList;
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.TableTops;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.CompleteLogisticsOrderParam;
import com.sckw.order.api.model.GoodsLoadingParam;
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.redis.config.RedisLockUtil;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.stream.model.SckwBusSum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.AreaTreeFrontResDto;
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.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.ConsignOrderQuery;
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.ConsignOrderExcelVo;
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:13
 */
@Slf4j
@Service
public class KwtConsignOrderService {

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

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

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

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

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

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

    @Autowired
    RedisLockUtil redisLockUtil;

    @Autowired
    public KwtCommonService commonService;

    @Autowired
    public MongoTemplate mongoTemplate;

    @Resource
    private StreamBridge streamBridge;

    @Autowired
    public KwtLogisticsOrderMapper kwtLogisticsOrderMapper;

    @Autowired
    public KwtWaybillOrderSubtaskMapper waybillOrderSubtaskMapper;

    @Autowired
    public KwtLogisticsOrderLineFreightRateMapper lineFreightRateMapper;

    @Autowired
    public KwtLogisticsOrderAddressMapper kwtLogisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderContractMapper logisticsOrderContractMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper kwtLogisticsOrderUnitMapper;

    @Autowired
    public KwtLogisticsOrderTrackMapper kwtLogisticsOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper logisticsOrderGoodsMapper;

    @Autowired
    public KwtWaybillOrderMapper kwtWaybillOrderMapper;

    @Autowired
    private KwtLogisticsOrderAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwtWaybillOrderTicketMapper kwtWaybillOrderTicketMapper;

    @Autowired
    public KwtWaybillOrderTrackMapper kwtWaybillOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderCirculateMapper kwtLogisticsOrderCirculateMapper;

    @Autowired
    public KwtTransportCommonService transportCommonService;

    @Autowired
    KwtLogisticsOrderGoodsService logisticsOrderGoodsService;

    @Autowired
    KwtWaybillOrderService waybillOrderService;


    /**
     * 托运订单/承运订单-获取车辆运单
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarWaybillByOrder(OrderDTO orderDto) {
        HttpResult httpResult = new HttpResult();
        if (String.valueOf(NumberConstant.ONE).equals(orderDto.getType())) {
            httpResult = getCarWaybillOrderByConsign(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(orderDto.getType())) {
            httpResult = getCarWaybillOrderByAcceptCarriage(orderDto);
        } else {
            throw new RuntimeException("单据类型错误");
        }
        return httpResult;
    }

    /**
     * 托运订单/承运订单-获取车辆运单-下方数据统计
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarWaybillByOrderCount(OrderDTO orderDto) {
        HttpResult httpResult = new HttpResult();
        if (String.valueOf(NumberConstant.ONE).equals(orderDto.getType())) {
            httpResult = getCarWaybillOrderByConsignCount(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(orderDto.getType())) {
            httpResult = getCarWaybillOrderByAcceptCarriageCount(orderDto);
        } else {
            throw new RuntimeException("单据类型错误");
        }
        return httpResult;
    }

    /**
     * 托运订单-车辆运单列表统计
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByConsignCount(OrderDTO orderDto) {
        KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                /**    .eq(StringUtils.isNotBlank(orderDto.getId()), KwtLogisticsOrder::getId, Long.parseLong(orderDto.getId()))
                 .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())*/
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (ObjectUtils.isEmpty(order)) {
            return HttpResult.ok();
        }
        List<KwtWaybillOrderSubtask> waybillOrderSubtasks = waybillOrderSubtaskMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrderSubtask>()
                        .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrderSubtask::getLOrderId, order.getId()));
        List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                        .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId())*/);
        JSONObject statistics = new JSONObject();
        //合理损耗
        BigDecimal loss = order.getLoss() == null ? NumberConstant.ZERO_TWO : order.getLoss();
        //派车量
        BigDecimal sendCarWeighNumber = NumberConstant.ZERO_TWO;
        //装货量
        BigDecimal loadAmountNumber = NumberConstant.ZERO_TWO;
        //卸货量
        BigDecimal unloadAmountNumber = NumberConstant.ZERO_TWO;
        /**亏吨量/吨->装货量-卸货量
         * 合理损耗值=已委托量*合理损耗
         扣亏量/吨->亏吨量-合理损耗值 扣亏量/吨->亏吨量-合理损耗值(分配量(委托量)*合理损耗)*/
        //亏吨量
        BigDecimal defectiveWeighNumber = NumberConstant.ZERO_TWO;
        //扣亏量/吨
        BigDecimal deductWeighNumber = NumberConstant.ZERO_TWO;
        if (CollectionUtils.isNotEmpty(waybillOrderSubtasks)) {
            for (KwtWaybillOrderSubtask kwtWaybillOrder : waybillOrderSubtasks) {
                //派车量
                BigDecimal sendCarWeigh = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                /**亏吨量/吨->装货量-卸货量
                 * 合理损耗值=装货量*合理损耗
                 扣亏量/吨->亏吨量-合理损耗值
                 罚款值 扣亏量/吨*扣亏货值
                 总运价:
                 按照装货量 运输运价*装货量
                 按照卸货量 卸货量*运输单价-罚款值
                 按照趟次=运输运价
                 */
                //已委托量
                BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                //合理损耗值
                BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                //亏吨量
                BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getDeficitAmount();
                //扣亏量/吨
                BigDecimal deduct = defectiveWeigh.compareTo(NumberConstant.ZERO_TWO) == 0 ? NumberConstant.ZERO_TWO : defectiveWeigh.subtract(multiply);
                sendCarWeighNumber = sendCarWeighNumber.add(sendCarWeigh);
                if (kwtWaybillOrder.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(kwtWaybillOrder.getLoadAmount());
                }
                if (kwtWaybillOrder.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(kwtWaybillOrder.getUnloadAmount());
                }
                defectiveWeighNumber = defectiveWeighNumber.add(defectiveWeigh);
                deductWeighNumber = deductWeighNumber.add(deduct);
            }
        }
        statistics.put("count", waybillOrderSubtasks.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        statistics.put("deductWeighNumber", deductWeighNumber);
        return HttpResult.ok(statistics);
    }

    /**
     * 承运订单-车辆运单列表-下方统计
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByAcceptCarriageCount(OrderDTO orderDto) {
        KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                /** .eq(StringUtils.isNotBlank(orderDto.getId()), KwtLogisticsOrder::getId, Long.parseLong(orderDto.getId()))
                 .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())*/
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (ObjectUtils.isEmpty(order)) {
            return HttpResult.ok();
        }
        List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                        .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId())*/);
        JSONObject statistics = new JSONObject();
        //合理损耗
        BigDecimal loss = order.getLoss();
        //派车量
        BigDecimal sendCarWeighNumber = new BigDecimal(NumberConstant.ZERO);
        //装货量
        BigDecimal loadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        //卸货量
        BigDecimal unloadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        /**亏吨量/吨->装货量-卸货量
         扣亏量/吨->亏吨量-合理损耗 (扣亏量/吨->亏吨量-合理损耗值(分配量(委托量)*合理损耗))*/
        //亏吨量
        BigDecimal defectiveWeighNumber = new BigDecimal(NumberConstant.ZERO);
        //扣亏量/吨
        BigDecimal deductWeighNumber = new BigDecimal(NumberConstant.ZERO);
        if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
            for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                //派车量
                BigDecimal sendCarWeigh = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                /**亏吨量/吨->装货量-卸货量
                 * 合理损耗值=装货量*合理损耗
                 扣亏量/吨->亏吨量-合理损耗值
                 */
                //已委托量
                BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                //合理损耗值
                BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                //亏吨量
                BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getDeficitAmount();
                //扣亏量/吨
                BigDecimal deduct = defectiveWeigh.compareTo(NumberConstant.ZERO_TWO) == 0 ? NumberConstant.ZERO_TWO : defectiveWeigh.subtract(multiply);
                sendCarWeighNumber = sendCarWeighNumber.add(sendCarWeigh);
                if (kwtWaybillOrder.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(kwtWaybillOrder.getLoadAmount());
                }
                if (kwtWaybillOrder.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(kwtWaybillOrder.getUnloadAmount());
                }
                defectiveWeighNumber = defectiveWeighNumber.add(defectiveWeigh);
                deductWeighNumber = deductWeighNumber.add(deduct);
            }
        }
        statistics.put("count", kwtWaybillOrders.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        statistics.put("deductWeighNumber", deductWeighNumber);
        return HttpResult.ok(statistics);
    }

    /**
     * 通过订单id+类型 查询承运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByAcceptCarriage(OrderDTO orderDto) {
        List<String> list = StringUtils.splitStrToList(orderDto.getIds(), String.class);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        List<CarWaybillVO> returnList = new ArrayList<>();
        list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        /**计量单位*/
        Map<String, String> unitDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        for (String id : list) {
            KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(id), KwtLogisticsOrder::getId, Long.parseLong(id))
            );
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                    .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                    .orderByDesc(KwtWaybillOrder::getCreateTime)
            );
            if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
                for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                    CarWaybillVO carWaybillVo = new CarWaybillVO();
                    KwtWaybillOrderTicket loadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE)
                            .eq(KwtWaybillOrderTicket::getUnit, kwtWaybillOrder.getUnit())
                    );
                    KwtWaybillOrderTicket unloadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO)
                            .eq(KwtWaybillOrderTicket::getUnit, kwtWaybillOrder.getUnit())
                    );
                    //合理损耗
                    BigDecimal loss = order.getLoss() == null ? NumberConstant.ZERO_TWO : order.getLoss();
                    /**亏吨量/吨->装货量-卸货量
                     * 合理损耗值=装货量*合理损耗
                     扣亏量/吨->亏吨量-合理损耗值
                     */
                    BigDecimal loadAmount = kwtWaybillOrder.getLoadAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getLoadAmount();
                    //已委托量
//                    BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                    //合理损耗值
//                    BigDecimal multiply = loadAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                    //亏吨量
                    BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getDeficitAmount();
                    //扣亏量/吨
//                    BigDecimal deduct = defectiveWeigh.compareTo(NumberConstant.ZERO_TWO) == 0 ? NumberConstant.ZERO_TWO : defectiveWeigh.subtract(multiply);
                    BigDecimal deduct = commonService.deficitLossAmount(loadAmount, defectiveWeigh, loss, order.getLossUnit());
                    carWaybillVo.setLOrderId(String.valueOf(kwtWaybillOrder.getLOrderId()));
                    carWaybillVo.setLOrderNo(order.getLOrderNo());
                    carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                    carWaybillVo.setWOrderNo(kwtWaybillOrder.getWOrderNo());
                    carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                    carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setStatusLabel(CarWaybillEnum.getName(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setWaybillType(kwtWaybillOrder.getType());
                    carWaybillVo.setDriverName(kwtWaybillOrder.getDriverName());
                    carWaybillVo.setDriverPhone(kwtWaybillOrder.getDriverPhone());
                    carWaybillVo.setUnit(kwtWaybillOrder.getUnit());
                    carWaybillVo.setUnitLabel(kwtWaybillOrder.getUnit() == null ? null :
                            (unitDictData == null ? kwtWaybillOrder.getUnit() : unitDictData.get(kwtWaybillOrder.getUnit())));
                    //todo 取mongo
//                SckwWaybillOrder sckwWaybillOrder = mongoTemplate.findById(kwtWaybillOrder.getId(), SckwWaybillOrder.class);
                    /** 2023-07-24 原值为承运车队-去除后更换展示为承运公司*/
//                carWaybillVo.setConsignMotorcade(sckwWaybillOrder == null ? null : sckwWaybillOrder.getCarrierFirmName());
                    //派车量
                    carWaybillVo.setSendCarWeigh(kwtWaybillOrder.getEntrustAmount() == null ? null : String.valueOf(kwtWaybillOrder.getEntrustAmount()));
                    carWaybillVo.setSendCarDate(DateUtil.getDateTime(kwtWaybillOrder.getCreateTime()));
                    if (loadTicket != null) {
                        carWaybillVo.setLoadAmount(loadTicket.getAmount() == null ? null : String.valueOf(loadTicket.getAmount()));
                        carWaybillVo.setLoadDateTime(loadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(loadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setLoadAmount(null);
                        carWaybillVo.setLoadDateTime(null);
                    }
                    if (unloadTicket != null) {
                        carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                        carWaybillVo.setUnloadDateTime(unloadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setUnloadAmount(null);
                        carWaybillVo.setUnloadDateTime(null);
                    }
                    /**亏吨量/吨->装货量-卸货量
                     扣亏量/吨->亏吨量-合理损耗*/
                    carWaybillVo.setDefectiveWeigh(kwtWaybillOrder.getDeficitAmount() == null ? null : String.valueOf(kwtWaybillOrder.getDeficitAmount()));
                    carWaybillVo.setDeduct(deduct);
                    carWaybillVo.setCreateTime(kwtWaybillOrder.getCreateTime());
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                    carWaybillVo.setLOrderNo(order.getLOrderNo());
                    carWaybillVo.setLOrderId(String.valueOf(order.getId()));
                    carWaybillVo.setLoss(loss);
                    SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), order.getLossUnit());
                    carWaybillVo.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
                    returnList.add(carWaybillVo);
                }
            }
        }
        List<Long> lists = StringUtils.splitStrToList(orderDto.getIds(), Long.class);
        getLogisticsOrderCirculate(lists, returnList);
        List<CarWaybillVO> collect = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(returnList)) {
            collect = returnList.stream().sorted(Comparator.comparing(CarWaybillVO::getLOrderId).reversed()).collect(Collectors.toList());
            collect = collect.stream().skip((orderDto.getPage() - 1) * orderDto.getPageSize()).limit(orderDto.getPageSize()).collect(Collectors.toList());
        }
        PageResult result = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), returnList.stream().count(), collect);
        return HttpResult.ok(result);
    }

    /**
     * 托运订单-设置停止接单-针对循环单
     *
     * @param stopOrderTakingDTO
     * @return
     */
    public HttpResult consignStopDocumentCommit(StopOrderTakingDTO stopOrderTakingDTO) {
        List<JSONObject> returnList = new ArrayList<>();
        List<Long> list = StringUtils.splitStrToList(stopOrderTakingDTO.getIds(), Long.class);
        String lOrderId = stopOrderTakingDTO.getLOrderId();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(circulateId -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", circulateId);
//                KwtLogisticsOrderCirculate circulate = kwtLogisticsOrderCirculateMapper.selectOne(new LambdaUpdateWrapper<KwtLogisticsOrderCirculate>()
//                        .eq(KwtLogisticsOrderCirculate::getId, circulateId)
//                );
                List<KwtWaybillOrderSubtask> subtasks = waybillOrderSubtaskMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrderSubtask>()
                        .eq(KwtWaybillOrderSubtask::getId, circulateId)
                        .eq(KwtWaybillOrderSubtask::getDelFlag, 0)
                );
                if (subtasks == null) {
                    jsonObject.put("status", HttpStatus.GLOBAL_EXCEPTION_CODE);
                    jsonObject.put("message", "单据不存在或者单据异常");
                } else {
                    /**循环单逻辑失效 如果已生成趟次数据，则不处理趟次数据*/
                    waybillOrderSubtaskMapper.update(null, new LambdaUpdateWrapper<KwtWaybillOrderSubtask>()
                            .set(KwtWaybillOrderSubtask::getStatus, NumberConstant.ONE)
                            .set(KwtWaybillOrderSubtask::getUpdateBy, LoginUserHolder.getUserId())
                            .set(KwtWaybillOrderSubtask::getUpdateTime, new Date())
                            .eq(KwtWaybillOrderSubtask::getId, circulateId)
                            .eq(KwtWaybillOrderSubtask::getLOrderId, Long.parseLong(lOrderId))
                    );
//                    /**更新MongoDB*/
//                    if (circulate.getWOrderId() != null) {
//                        SckwWaybillOrder order = new SckwWaybillOrder();
//                        order.set_id(circulate.getWOrderId());
//                        order.setWOrderId(circulate.getWOrderId());
////                        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", "停止接单成功");
                }
                returnList.add(jsonObject);
            });
        }
        return HttpResult.ok(returnList);
    }

    /**
     * 托运订单-设置停止接单-物流订单id查询-针对循环单
     *
     * @param baseList
     * @return
     */
    public HttpResult consignStopDocumentDetailByOrderIds(BaseList baseList) {
        //todo 目前只支持单选
        HttpResult result = new HttpResult();
        result.setCode(HttpStatus.SUCCESS_CODE);
        List<Long> idsList = StringUtils.splitStrToList(baseList.getIds(), Long.class);
        if (CollectionUtils.isEmpty(idsList)) {
            return HttpResult.ok();
        }
        List<DriverListVo> list = kwtLogisticsOrderMapper.selectLoopOrderAndDriverListByOrderIds(idsList);
        Map<String, RTruckVo> truck = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> collect = list.stream().map(DriverListVo::getTruckNo).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                truck = fleetService.findTruck(collect);
            }
        }
        for (DriverListVo driverListVo : list) {
            if (driverListVo.getTruckNo() != null) {
                List<String> objects = new ArrayList<>();
                objects.add(driverListVo.getTruckNo());
                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) ? "空闲" : "任务中");
                    }
                    driverListVo.setCarType(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getTruckType());
                }
            }
        }
        result.setData(list);
        return result;
    }

    /**
     * 托运订单-设置停止接单-查询
     *
     * @param driverParam 页面请求数据
     * @return
     */
    public HttpResult consignStopDocumentDetail(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);
//        List<DriverListVo> list = kwtLogisticsOrderMapper.selectLoopOrderAndDriverListByOrderId(driverParam);
        List<Integer> orderStatus = new ArrayList<>() {{
            add(CarWaybillEnum.APPROVAL_PASS.getCode());
            add(CarWaybillEnum.APPROVAL_IN.getCode());
            add(CarWaybillEnum.APPROVAL_NO_PASS.getCode());
            add(CarWaybillEnum.APPROVAL_TREAT.getCode());
        }};
        List<DriverListVo> list = waybillOrderSubtaskMapper.selectLoopOrderAndDriverListByOrderId(driverParam, Integer.valueOf(driverParam.getType()), orderStatus);
        Map<String, RTruckVo> truck = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> collect = list.stream().map(DriverListVo::getTruckNo).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                truck = fleetService.findTruck(collect);
            }
        }
        for (DriverListVo driverListVo : list) {
            if (!driverListVo.getCirculateId().isEmpty()) {
//                driverListVo.setStatus(1);
                driverListVo.setStatusLabel(CarWaybillEnum.PENDING_ORDER.getDestination());
            }
            List<String> objects = new ArrayList<>();
            objects.add(driverListVo.getTruckNo());
            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) ? "空闲" : "任务中");
                }
                driverListVo.setCarType(truck.get(driverListVo.getTruckNo()) == null ? null : truck.get(driverListVo.getTruckNo()).getTruckType());
            }
        }
        result.setData(list);
        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("司机姓名格式不正确");
            }
        }
        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("手机号格式不正确");
            }
        }
    }

    /**
     * 通过订单ids+类型 查询托运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByConsign(OrderDTO orderDto) {
        List<Long> list = StringUtils.splitStrToList(orderDto.getIds(), Long.class);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        List<CarWaybillVO> returnList = new ArrayList<>();
        list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        /**计量单位*/
        Map<String, String> unitDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**趟次数据*/
        for (Long id : list) {
            KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(id), KwtLogisticsOrder::getId, id)
            );
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                    .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                    .orderByDesc(KwtWaybillOrder::getCreateTime)
            );
            if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
                for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                    CarWaybillVO carWaybillVo = new CarWaybillVO();
                    KwtWaybillOrderTicket loadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE)
                            .eq(KwtWaybillOrderTicket::getUnit, kwtWaybillOrder.getUnit())
                    );
                    KwtWaybillOrderTicket unloadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO)
                            .eq(KwtWaybillOrderTicket::getUnit, kwtWaybillOrder.getUnit())
                    );
                    //合理损耗
                    BigDecimal loss = order.getLoss() == null ? NumberConstant.ZERO_TWO : order.getLoss();
                    /**亏吨量/吨->装货量-卸货量
                     * 合理损耗值=装货量*合理损耗
                     扣亏量/吨->亏吨量-合理损耗值
                     */
                    BigDecimal loadAmount = kwtWaybillOrder.getLoadAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getLoadAmount();
                    //已委托量
//                    BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                    //合理损耗值
//                    BigDecimal multiply = loadAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                    //亏吨量
                    BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getDeficitAmount();
                    //扣亏量/吨
//                    BigDecimal deduct = defectiveWeigh.compareTo(NumberConstant.ZERO_TWO) == 0 ? NumberConstant.ZERO_TWO : defectiveWeigh.subtract(multiply);
//                    BigDecimal decimal = commonService.deficitAmount();
                    BigDecimal deduct = commonService.deficitLossAmount(loadAmount, defectiveWeigh, loss, order.getLossUnit());
                    carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                    carWaybillVo.setWOrderNo(kwtWaybillOrder.getWOrderNo());
                    carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                    carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setStatusLabel(CarWaybillEnum.getName(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setWaybillType(kwtWaybillOrder.getType());
                    carWaybillVo.setDriverName(kwtWaybillOrder.getDriverName());
                    carWaybillVo.setDriverPhone(kwtWaybillOrder.getDriverPhone());
                    carWaybillVo.setUnit(kwtWaybillOrder.getUnit());
                    carWaybillVo.setUnitLabel(kwtWaybillOrder.getUnit() == null ? null :
                            (unitDictData == null ? kwtWaybillOrder.getUnit() : unitDictData.get(kwtWaybillOrder.getUnit())));
                    //todo 取mongo
//                SckwWaybillOrder sckwWaybillOrder = mongoTemplate.findById(kwtWaybillOrder.getId(), SckwWaybillOrder.class);
                    /** 2023-07-24 原值为承运车队-去除后更换展示为承运公司*/
//                carWaybillVo.setConsignMotorcade(sckwWaybillOrder == null ? null : sckwWaybillOrder.getCarrierFirmName());
                    //派车量
                    carWaybillVo.setSendCarWeigh(kwtWaybillOrder.getEntrustAmount() == null ? null : String.valueOf(kwtWaybillOrder.getEntrustAmount()));
                    carWaybillVo.setSendCarDate(DateUtil.getDateTime(kwtWaybillOrder.getCreateTime()));
                    if (loadTicket != null) {
                        carWaybillVo.setLoadAmount(loadTicket.getAmount() == null ? null : String.valueOf(loadTicket.getAmount()));
                        carWaybillVo.setLoadDateTime(loadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(loadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setLoadAmount(null);
                        carWaybillVo.setLoadDateTime(null);
                    }
                    if (unloadTicket != null) {
                        carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                        carWaybillVo.setUnloadDateTime(unloadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setUnloadAmount(null);
                        carWaybillVo.setUnloadDateTime(null);
                    }
                    /**亏吨量/吨->装货量-卸货量
                     扣亏量/吨->亏吨量-合理损耗*/
                    carWaybillVo.setDefectiveWeigh(kwtWaybillOrder.getDeficitAmount() == null ? null : String.valueOf(kwtWaybillOrder.getDeficitAmount()));
                    carWaybillVo.setDeduct(deduct);
                    carWaybillVo.setCreateTime(kwtWaybillOrder.getCreateTime());
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                    carWaybillVo.setLOrderNo(order.getLOrderNo());
                    carWaybillVo.setLOrderId(String.valueOf(order.getId()));
                    carWaybillVo.setLoss(loss);
                    SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), order.getLossUnit());
                    carWaybillVo.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
                    returnList.add(carWaybillVo);
                }
            }
        }
        /**循环数据*/
        getLogisticsOrderCirculate(list, returnList);
        List<CarWaybillVO> collect = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(returnList)) {
            collect = returnList.stream().sorted(Comparator.comparing(CarWaybillVO::getLOrderId).reversed()).collect(Collectors.toList());
            collect = collect.stream().skip((orderDto.getPage() - 1) * orderDto.getPageSize()).limit(orderDto.getPageSize()).collect(Collectors.toList());
        }
        PageResult result = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), returnList.stream().count(), collect);
        return HttpResult.ok(result);
    }

    private void getLogisticsOrderCirculate(List<Long> list, List<CarWaybillVO> returnList) {
        for (Long lOrderId : list) {
            KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(lOrderId), KwtLogisticsOrder::getId, lOrderId)
            );
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtLogisticsOrderCirculate> logisticsOrderCirculates = kwtLogisticsOrderCirculateMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderCirculate>()
                    .in(KwtLogisticsOrderCirculate::getLOrderId, lOrderId)
                    .eq(KwtLogisticsOrderCirculate::getStatus, 0)
                    .eq(KwtLogisticsOrderCirculate::getDelFlag, 0)
                    .isNotNull(KwtLogisticsOrderCirculate::getWOrderId)
            );
            if (CollectionUtils.isNotEmpty(logisticsOrderCirculates)) {
                for (KwtLogisticsOrderCirculate circulate : logisticsOrderCirculates) {
                    CarWaybillVO carWaybillVo = new CarWaybillVO();
                    carWaybillVo.setLOrderNo(order.getLOrderNo());
                    carWaybillVo.setLOrderId(String.valueOf(lOrderId));
                    carWaybillVo.setWOrderId(circulate.getWOrderId() == null ? null : String.valueOf(circulate.getWOrderId()));
//                    carWaybillVo.setWOrderNo();
                    carWaybillVo.setTruckNo(circulate.getTruckNo());
                    carWaybillVo.setStatus(CarWaybillEnum.PENDING_ORDER.getStatus());
                    carWaybillVo.setStatusLabel(CarWaybillEnum.PENDING_ORDER.getDestination());
                    carWaybillVo.setWaybillType(circulate.getType());
                    carWaybillVo.setDriverName(circulate.getDriverName());
//                    carWaybillVo.setConsignMotorcade();
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    carWaybillVo.setSendCarWeigh(circulate.getEntrustAmount() == null ? null : decimalFormat.format(circulate.getEntrustAmount()));
                    carWaybillVo.setSendCarDate(circulate.getCreateTime() == null ? null : DateUtil.getDateTime(circulate.getCreateTime()));
                    KwtWaybillOrderTicket loadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(circulate.getId()), KwtWaybillOrderTicket::getWOrderId, circulate.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE));
                    KwtWaybillOrderTicket unloadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(circulate.getId()), KwtWaybillOrderTicket::getWOrderId, circulate.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO));
                    if (loadTicket != null) {
                        carWaybillVo.setLoadAmount(loadTicket.getAmount() == null ? null : String.valueOf(loadTicket.getAmount()));
                        carWaybillVo.setLoadDateTime(loadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(loadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setLoadAmount(null);
                        carWaybillVo.setLoadDateTime(null);
                    }
                    if (unloadTicket != null) {
                        carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                        carWaybillVo.setUnloadDateTime(unloadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setUnloadAmount(null);
                        carWaybillVo.setUnloadDateTime(null);
                    }
                    carWaybillVo.setDefectiveWeigh("0.00");
                    carWaybillVo.setDeduct(NumberConstant.ZERO_TWO);
                    carWaybillVo.setLoss(order.getLoss());
                    SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), order.getLossUnit());
                    carWaybillVo.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
                    carWaybillVo.setCreateTime(circulate.getCreateTime());
                    returnList.add(carWaybillVo);
                }
            }
        }
    }

    /**
     * 托运订单/承运订单-获取车辆信息
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarListByOrder(OrderDTO orderDto, String type) {
        HttpResult httpResult = new HttpResult();
        if (String.valueOf(NumberConstant.ONE).equals(type)) {
            //托运
            httpResult = getAcceptCarListByOrder(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(type)) {
            //承运
            httpResult = getAcceptCarListByOrder(orderDto);
        } else {
            return HttpResult.error("单据类型错误！");
        }
        return httpResult;
    }

    private HttpResult getAcceptCarListByOrder(OrderDTO orderDto) {
        /**
         * 除了已作废的运单对应的车辆不查出（已作废：拒绝接单、拒绝出车、单趟撤回），其他状态的运单对应的车辆带出去重
         * */
        List<String> stringList = StringUtils.splitStrToList(orderDto.getIds(), String.class);
        if (CollectionUtils.isEmpty(stringList)) {
            return HttpResult.ok();
        }
        List<Integer> statusList = new ArrayList<>();
        statusList.add(CarWaybillEnum.REFUSE_TRAFFIC.getCode());
        statusList.add(CarWaybillEnum.REJECT_ORDER.getCode());
        statusList.add(CarWaybillEnum.REVOKED.getCode());
//        List<OrderCarDTO> list = kwtWaybillOrderMapper.selectWaybillOrderCarListGroupByTruckNo(stringList, statusList, orderDto.getPage() - 1, orderDto.getPageSize());
        List<OrderCarDTO> list = kwtWaybillOrderMapper.selectInvalidWaybillOrderCarListGroupByTruckNo(stringList, statusList, orderDto.getPage() - 1, orderDto.getPageSize());
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> stringLists = list.stream().map(OrderCarDTO::getTruckNo).distinct().collect(Collectors.toList());
            Map<String, RTruckVo> truck = remoteFleetService.findTruck(stringLists);
            for (OrderCarDTO dto : list) {
                dto.setLoadAmount(truck.get(dto.getTruckNo()) == null ?
                        null : (truck.get(dto.getTruckNo()).getActualWeight() == null ?
                        null : (String.valueOf(truck.get(dto.getTruckNo()).getActualWeight()))));
            }
        }
        PageResult build = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), (long) list.size(), list);
        return HttpResult.ok(build);
    }

    /**
     * 托运订单查看驳回原因
     *
     * @param id
     * @return
     */
    public HttpResult getRejectReasonById(String id, Integer status) {
        Map<String, String> map = kwtLogisticsOrderMapper.getRejectReason(id, status);
        return HttpResult.ok(map);
    }

    /**
     * 托运订单-完结订单
     *
     * @param orderFinishDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult commitConsignOrderFinish(OrderFinishDTO orderFinishDTO) {
        /** 订单完结 物流运单状态为【待派车】、【运输中】可操作*/
        /**完结拦截 必须车辆运单无正在运输中的单据才能完结 状态有 待接单之后已核弹之前的状态 都不能完结*/
        /**完结订单-对应物流订单下子订单都要进行完结*/
        /**完结订单 不做页面填写数量与数据库数量进行计算验证-直接获取页面填写数据进行保存处理*/
        //物流订单id
        String id = orderFinishDTO.getId();
        String key = String.format(RedisConstant.LOGISTICS_ORDER_FINISH_KEY, orderFinishDTO.getId());
        if (redisLockUtil.tryLock(key)) {
            try {
                KwtLogisticsOrder logisticsOrder = kwtLogisticsOrderMapper.selectById(id);
                if (logisticsOrder == null) {
                    throw new BusinessException("采购订单-完结订单-物流单据不存在!");
                }
                /*BigDecimal totalLoadAmount = logisticsOrder.getTotalLoadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getTotalLoadAmount();
                if (totalLoadAmount.compareTo(orderFinishDTO.getLoadAmount()) < 0) {
                    throw new BusinessException("完结订单,实装量不能大于分配量");
                }
                //todo 2023-09-01 根据要求去除校验 物流订单手动完结，实装量可大于分配量，实卸量目前暂定不可大于实装量；根据计费方式，当对应实装或实卸大于分配量时自然完结
                BigDecimal amount = logisticsOrder.getAmount() == null ? NumberConstant.ZERO_TWO : 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 BusinessException("当前订单并不属于【待派车】,【运输中】状态");
                }
                //验证当前物流订单是否还存在进行的车辆运单
                boolean flag = commonService.judgmentWaybillOrderIsFinish(id);
                if (flag) {
                    throw new BusinessException("检测您现在有运单正在执行中，该订单目前不可完结，请先将运单执行完毕！");
                }
                //修改单据本身数据
                BigDecimal ignoreAmount = logisticsOrder.getAmount().subtract(orderFinishDTO.getLoadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getLoadAmount());
                logisticsOrder.setTotalLoadAmount(orderFinishDTO.getLoadAmount());
                logisticsOrder.setTotalUnloadAmount(orderFinishDTO.getUnloadAmount());
                logisticsOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
                logisticsOrder.setUpdateTime(new Date());
                logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
                logisticsOrder.setIgnoreAmount(ignoreAmount);
                kwtLogisticsOrderMapper.updateById(logisticsOrder);
                updateLogisticOrderTrack(logisticsOrder.getId(), LogisticsOrderEnum.HAVE_FINISHED, orderFinishDTO.getRemark());

                //获取物流订单下的子单
                /**完结订单-对应物流订单下子订单都要进行完结*/
                List<KwtLogisticsOrder> kwtLogisticsOrders = kwtLogisticsOrderMapper.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)) {
                    //修改单据剩余运输量
                    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);
                    });
                }

                /**是否是一级订单,是->推送至贸易,否,数据推送至物流订单上级*/
                if (logisticsOrder.getPid() == null && "1".equals(logisticsOrder.getType())) {
                    //数据推送至贸易订单
                    CompleteLogisticsOrderParam tradeOrder = new CompleteLogisticsOrderParam();
                    tradeOrder.setTOrderId(logisticsOrder.getTOrderId());
                    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(logisticsOrder.getTOrderId());
                    param.setEntrustAmount(orderFinishDTO.getLoadAmount().subtract(logisticsOrder.getAmount()));
                    param.setUpdateBy(LoginUserHolder.getUserId());
                    param.setUpdateByName(LoginUserHolder.getUserName());
                    HttpResult result1 = tradeOrderInfoService.createOrCancelLogisticsOrder(param);*/
                    List<GoodsLoadingParam> goodsLoading = logisticsOrderGoodsService.goodsLoadingParams(logisticsOrder, true);
//                    HttpResult result1 = tradeOrderInfoService.createOrCancelLogisticsOrderV1(logisticsOrder.getTOrderId(), goodsLoading);
                    HttpResult result1 = tradeOrderInfoService.createOrCancelLogisticsOrderV1(LoginUserHolder.getUserId(), LoginUserHolder.getUserName(), logisticsOrder.getTOrderId(), goodsLoading);
                    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()));
                    }
                }

                transportCommonService.closeHandle(logisticsOrder.getId());
                waybillOrderService.cancelSendCar(logisticsOrder.getId());
            } finally {
                redisLockUtil.unlock(key);
            }
        } else {
            HttpResult.error("当前数据正在处理，请稍后再试");
        }
        return HttpResult.ok("托运订单-完结订单成功");
    }

    /**
     * 物流订单完结订单-修改物流表+新增物流状态记录
     *
     * @param lOrderId
     * @param orderFinishDTO
     * @param ignoreAmount
     */
    private void updateLogisticOrderAndTrack(Long lOrderId, OrderFinishDTO orderFinishDTO, BigDecimal ignoreAmount) {
        Integer code = LogisticsOrderEnum.HAVE_FINISHED.getCode();
        kwtLogisticsOrderMapper.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 = kwtLogisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, lOrderId).eq(KwtLogisticsOrderTrack::getStatus, code)
        );
        if (track != null) {
            kwtLogisticsOrderTrackMapper.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);
            kwtLogisticsOrderTrackMapper.insert(orderTrack);
        }
    }


    /**
     * 修改物流表+新增物流状态记录
     *
     * @param lOrderId
     * @param logisticsOrderEnum
     */
    private void updateLogisticOrderTrack(Long lOrderId, LogisticsOrderEnum logisticsOrderEnum, String remark) {
        KwtLogisticsOrderTrack track = kwtLogisticsOrderTrackMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderTrack>()
                .eq(KwtLogisticsOrderTrack::getLOrderId, lOrderId).eq(KwtLogisticsOrderTrack::getStatus, logisticsOrderEnum.getCode())
        );
        if (track != null) {
            kwtLogisticsOrderTrackMapper.update(null, new LambdaUpdateWrapper<KwtLogisticsOrderTrack>()
                    .set(KwtLogisticsOrderTrack::getUpdateBy, LoginUserHolder.getUserId())
                    .set(KwtLogisticsOrderTrack::getUpdateTime, new Date())
                    .set(KwtLogisticsOrderTrack::getRemark, remark)
                    .eq(KwtLogisticsOrderTrack::getId, track.getId())
            );
        } else {
            KwtLogisticsOrderTrack orderTrack = new KwtLogisticsOrderTrack();
            orderTrack.setId(new IdWorker(NumberConstant.ONE).nextId());
            orderTrack.setLOrderId(lOrderId);
            orderTrack.setRemark(remark);
            orderTrack.setStatus(logisticsOrderEnum.getCode());
            orderTrack.setCreateBy(LoginUserHolder.getUserId());
            orderTrack.setCreateTime(new Date());
            orderTrack.setUpdateBy(LoginUserHolder.getUserId());
            orderTrack.setUpdateTime(new Date());
            orderTrack.setDelFlag(NumberConstant.ZERO);
            kwtLogisticsOrderTrackMapper.insert(orderTrack);
        }
    }

    /**
     * 验证当前物流订单是否存在未完结的车辆运单
     *
     * @param id 对应物流订单id
     */
    private boolean judgmentWaybillOrderIsFinish(String id) {
        boolean flag = false;
        List<Integer> statusList = new ArrayList<>();
//        statusList.add(CarWaybillEnum.PENDING_ORDER.getCode());
        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());
//        statusList.add(CarWaybillEnum.APPROVAL_PASS.getCode());
        int count = kwtWaybillOrderMapper.selectDataByLorderId(id, statusList);
        if (count > NumberConstant.ZERO) {
            flag = true;
        }
        return flag;
    }

    /**
     * 根据物流订单修改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 orderFinishDTO 页面传递数据dto
//     * @return
//     */
//    public HttpResult commitConsignOrderFinish(OrderFinishDTO orderFinishDTO) {
//        /** 订单完结 物流运单状态为【待派车】、【运输中】可操作*/
//        /**完结拦截 必须车辆运单无正在运输中的单据才能完结 状态有 待接单之后已核弹之前的状态 都不能完结*/
//        /**完结订单-对应物流订单下子订单都要进行完结*/
//        /**完结订单 不做页面填写数量与数据库数量进行计算验证-直接获取页面填写数据进行保存处理*/
//        //物流订单id
//        String id = orderFinishDTO.getId();
//        KwtLogisticsOrder logisticsOrder = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
//                .eq(KwtLogisticsOrder::getId, id));
//        if (logisticsOrder == null) {
//            throw new RuntimeException("托运订单-完结订单-物流单据不存在!");
//        }
//        if (logisticsOrder.getLoadAmount().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());
//        int count = kwtWaybillOrderMapper.selectDataByLorderId(id, statusList);
//        if (count > NumberConstant.ZERO) {
//            throw new RuntimeException("检测您现在有运单正在执行中,该订单目前不可完结,请先将运单执行完毕");
//        }
//        /**完结订单-对应物流订单下子订单都要进行完结*/
//        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);
//                }
//            }
//        }
//        return HttpResult.ok("承运订单-分包托运完结订单成功");
//    }

    /**
     * 托运订单-完结订单-修改本身数据
     *
     * @param logisticsOrder 本身物流订单数据
     * @param orderFinishDTO 页面传递数据
     */
    private void updateDataByItself(KwtLogisticsOrder logisticsOrder, OrderFinishDTO orderFinishDTO) {
        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());
        kwtLogisticsOrderMapper.updateById(logisticsOrder);
        KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
        track.setId(new IdWorker(NumberConstant.ONE).nextId());
        track.setLOrderId(logisticsOrder.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());
        kwtLogisticsOrderTrackMapper.insert(track);
        /**单据完结修改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 = kwtLogisticsOrderMapper.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());
            kwtLogisticsOrderMapper.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());
            kwtLogisticsOrderTrackMapper.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 orderId 物流订单id
     * @return
     */
    public HttpResult consignOrderFinishDetail(String orderId) {
        Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN) {{
            put("upperlOrderId", orderId);
            put("passStatus", Global.NUMERICAL_ONE);
        }};
        //WaybillCountVo waybillOrderCount = kwtWaybillOrderMapper.findWaybillOrderCount(map);
        OrderFinishVO orderFinishVO = new OrderFinishVO();
        List<OrderGoodsLoadingVo> assistUnit = new ArrayList<>();
        //单位
        Map<String, Map<String, String>> dict = remoteSystemService.queryDictByType(List.of(DictTypeEnum.UNIT_TYPE.getType()));
        Map<String, Map<String, String>> chargingType = remoteSystemService.queryDictByType(List.of(DictTypeEnum.CHARGING_TYPE.getType()));
        Map<String, String> unitMap = dict != null ? dict.get(DictTypeEnum.UNIT_TYPE.getType()) : null;
        Map<String, String> chargingTypeMap = chargingType != null ? dict.get(DictTypeEnum.CHARGING_TYPE.getType()) : null;
        //物流订单
        KwtLogisticsOrder logisticsOrder = kwtLogisticsOrderMapper.selectById(orderId);
        //物流订单辅助单位信息
        List<KwtLogisticsOrderGoodsUnit> goodsUnits = logisticsOrderGoodsService.findGoodsUnit(logisticsOrder.getId());
        if (CollectionUtils.isNotEmpty(goodsUnits)) {
            goodsUnits.forEach(e -> {
                assistUnit.add(new OrderGoodsLoadingVo(e.getUnit(), unitMap != null ? unitMap.get(e.getUnit()) : null, e.getTotalLoadAmount(), e.getTotalUnloadAmount()));
            });
        }

//        orderFinishVO.setNumber(waybillOrderCount == null ? NumberConstant.ZERO : waybillOrderCount.getTotalComplete());
        List<Integer> orderStatus = new ArrayList<>() {{
            add(CarWaybillEnum.APPROVAL_PASS.getCode());
        }};
        orderFinishVO.setNumber(waybillOrderSubtaskMapper.selectCount(
                new LambdaQueryWrapper<KwtWaybillOrderSubtask>()
                        .eq(KwtWaybillOrderSubtask::getLOrderId, Long.parseLong(orderId))
                        .eq(KwtWaybillOrderSubtask::getDelFlag, 0)
                        .in(KwtWaybillOrderSubtask::getStatus,orderStatus)).intValue());
        orderFinishVO.setUnit(logisticsOrder.getUnit());
        orderFinishVO.setUnitName(unitMap != null ? unitMap.get(logisticsOrder.getUnit()) : null);
        orderFinishVO.setAmount(logisticsOrder.getAmount());
        orderFinishVO.setLoadAmount(logisticsOrder.getTotalLoadAmount());
        orderFinishVO.setUnloadAmount(logisticsOrder.getTotalUnloadAmount());
        orderFinishVO.setAssistUnit(assistUnit);
        orderFinishVO.setLineFreightRate(lineFreightRateMapper.selectListByOrderId(Long.parseLong(orderId)));
        orderFinishVO.setChargingType(logisticsOrder.getBillingMode());
        orderFinishVO.setChargingTypeName(chargingTypeMap != null ? chargingTypeMap.get(logisticsOrder.getBillingMode()) : "");
        return HttpResult.ok(orderFinishVO);
    }

    /**
     * 托运订单-新建订单
     *
     * @param addOrderDTO 页面传递数据
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult addOrder(AddOrderDTO addOrderDTO) {
        commonService.getRedisGenerateOrderNo();
        /**生成订单编号*/
        String lOrderNo = OrderGenerateSeqNoUtils.getSeqNo(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER, "2", "0", "0");
        HttpResult httpResult = ValidUtil.serviceValid(addOrderDTO);
        if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
            return HttpResult.error(httpResult.getMsg());
        }
        checkAddOrderParam(addOrderDTO);
        /**2023-08-16 新增校验承运企业与托运企业是否存在合作关系*/
        String consignCompanyId = addOrderDTO.getConsignCompanyId();
        String acceptCompanyId = addOrderDTO.getAcceptCompanyId();
        List<FindEntCooperateResVo> entCooperate = remoteManageService.findEntCooperate(Long.parseLong(consignCompanyId), Long.parseLong(acceptCompanyId), CooperateTypeEnum.CARRIAGE.getCode());
        if (entCooperate == null) {
            return HttpResult.error("该承运企业与我方企业并无合作关系!");
        }
        /**保存新建数据*/
        Long lOrderId = new IdWorker(NumberConstant.ONE).nextId();
        /**根据合同计算当前单据状态*/
        /**判断生成物流订单应生成哪一种单据状态*/
        List<Long> contractList = new ArrayList<>();
        contractList.add(Long.parseLong(addOrderDTO.getContractId()));
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = remoteContractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new BusinessException("托运订单新建订单-并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId())) == null) {
            throw new BusinessException("托运订单新建订单-并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId()));
        /**状态判断
         * 是否是已签约合同
         * */
        // 0 已签约 1待签约
        Integer status = infoResDto.getStatus();
        Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        if (NumberConstant.ONE == status) {
            orderStatus = LogisticsOrderEnum.TO_BE_PLANNED.getCode();
        } else if (NumberConstant.ZERO == status) {
            orderStatus = LogisticsOrderEnum.WAIT_DELIVERY.getCode();
        } else {
            log.info("托运订单创建订单异常");
            throw new BusinessException("自建订单异常");
        }
        /**数据保存*/
        saveConsignLogisticsOrder(addOrderDTO, lOrderId, orderStatus, lOrderNo);
        saveConsignLogisticsOrderAddress(addOrderDTO, lOrderId);
        saveConsignLogisticsOrderGoods(addOrderDTO, lOrderId, lOrderNo);
        saveConsignLogisticsOrderContract(addOrderDTO, lOrderId, infoResDto);
        saveConsignLogisticsOrderTrack(lOrderId, orderStatus);
        saveConsignLogisticsOrderUnit(addOrderDTO, lOrderId);
        /**保存mongodb*/
        saveMongoDb(addOrderDTO, orderStatus, lOrderId, lOrderNo, infoResDto);
        /**消息主体*/
        commonService.newLogisticsOrder(addOrderDTO, lOrderNo, LoginUserHolder.getUserId(), LoginUserHolder.getEntId());
        return HttpResult.ok();
    }

    /**
     * 校验请求参数
     *
     * @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("扣亏货值填写格式错误!");
            }
        }
    }

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

    /**
     * 托运订单-页面新增订单-订单主体
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     * @param orderStatus 订单状态
     * @param lOrderNo    主体订单编号
     */
    private void saveConsignLogisticsOrder(AddOrderDTO addOrderDTO, 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(addOrderDTO.getSettlementCycle());
        order.setBillingMode(addOrderDTO.getBillingMode());
        order.setPrice(addOrderDTO.getPrice());
        order.setPayment(addOrderDTO.getPayment());
        order.setPriceType(addOrderDTO.getPriceType());
        order.setAmount(addOrderDTO.getAmount());
        order.setUnit(addOrderDTO.getAmountUnit());
        order.setLoss(addOrderDTO.getLoss() == null ? null : addOrderDTO.getLoss());
        order.setLossUnit(addOrderDTO.getLossUnit());
        order.setGoodsPrice(addOrderDTO.getGoodsPrice() == null ? null : addOrderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(addOrderDTO.getGoodsPriceUnit());
        order.setStartTime(org.apache.commons.lang3.ObjectUtils.isEmpty(addOrderDTO.getStartTime()) ?
                null : DateUtil.localDateToLocalDateTimeStart(addOrderDTO.getStartTime()));
        order.setEndTime(org.apache.commons.lang3.ObjectUtils.isEmpty(addOrderDTO.getEndTime()) ?
                null : DateUtil.localDateToLocalDateTimeEnd(addOrderDTO.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(addOrderDTO.getTaxRate());
        order.setRemark(addOrderDTO.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);
        kwtLogisticsOrderMapper.insert(order);
    }

    /**
     * 托运订单-新建订单-地址信息保存
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderAddress(AddOrderDTO addOrderDTO, Long lOrderId) {
        KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
        loadAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
        loadAddress.setLOrderId(lOrderId);
        loadAddress.setAddressType(NumberConstant.ONE);
        loadAddress.setName(addOrderDTO.getLoadName() == null ? null : addOrderDTO.getLoadName());
//        loadAddress.setType();
        loadAddress.setContacts(addOrderDTO.getLoadContacts());
        loadAddress.setPhone(addOrderDTO.getLoadPhone());
        loadAddress.setCityCode(addOrderDTO.getLoadCityCode());
        loadAddress.setCityName(addOrderDTO.getLoadCityName());
        loadAddress.setDetailAddress(addOrderDTO.getLoadDetailAddress());
        loadAddress.setLat(addOrderDTO.getLoadLat());
        loadAddress.setLng(addOrderDTO.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(addOrderDTO.getUnloadName() == null ? null : addOrderDTO.getUnloadName());
//        unloadAddress.setType();
        unloadAddress.setContacts(addOrderDTO.getUnloadContacts());
        unloadAddress.setPhone(addOrderDTO.getUnloadPhone());
        unloadAddress.setCityCode(addOrderDTO.getUnloadCityCode());
        unloadAddress.setCityName(addOrderDTO.getUnloadCityName());
        unloadAddress.setDetailAddress(addOrderDTO.getUnloadDetailAddress());
        unloadAddress.setLat(addOrderDTO.getUnloadLat());
        unloadAddress.setLng(addOrderDTO.getUnloadLng());
        unloadAddress.setEntryType(NumberConstant.FOUR);
        unloadAddress.setStatus(NumberConstant.ZERO);
        unloadAddress.setCreateBy(LoginUserHolder.getUserId());
        unloadAddress.setCreateTime(date);
        unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
        unloadAddress.setUpdateTime(date);
        kwtLogisticsOrderAddressMapper.insert(loadAddress);
        kwtLogisticsOrderAddressMapper.insert(unloadAddress);
    }

    /**
     * 托运订单-新建订单-合体主体
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderContract(AddOrderDTO addOrderDTO, Long lOrderId, ContractCommonInfoResDto infoResDto) {
        //托运
        KwtLogisticsOrderContract consignContract = new KwtLogisticsOrderContract();
        consignContract.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignContract.setContractId(Long.parseLong(addOrderDTO.getContractId()));
        consignContract.setLOrderId(lOrderId);
        consignContract.setContractNo(addOrderDTO.getContractNo() == null ? infoResDto.getContractCode() : addOrderDTO.getContractNo());
        consignContract.setContractName(addOrderDTO.getContractName() == null ? infoResDto.getContactName() : addOrderDTO.getContractName());
        consignContract.setSigningWay(addOrderDTO.getSigningWay() == null ? String.valueOf(infoResDto.getSigningWay()) : addOrderDTO.getSigningWay());
        consignContract.setStatus(NumberConstant.ZERO);
        consignContract.setCreateBy(LoginUserHolder.getUserId());
        consignContract.setCreateTime(new Date());
        consignContract.setUpdateBy(LoginUserHolder.getUserId());
        consignContract.setUpdateTime(new Date());
        logisticsOrderContractMapper.insert(consignContract);
    }

    /**
     * 托运订单-页面新增订单-订单状态
     *
     * @param lOrderId    主体id
     * @param orderStatus 主体单据状态
     */
    private void saveConsignLogisticsOrderTrack(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());
        kwtLogisticsOrderTrackMapper.insert(track);
    }

    /**
     * 托运订单-页面新增订单-订单对应企业单位
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderUnit(AddOrderDTO addOrderDTO, Long lOrderId) {
        //托运
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignUnit.setLOrderId(lOrderId);
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        Map<Long, EntCacheResDto> dtoMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(addOrderDTO.getConsignCompanyId())));
        if (dtoMap == null || dtoMap.get(Long.parseLong(addOrderDTO.getConsignCompanyId())) == null) {
            throw new BusinessException("该【" + addOrderDTO.getConsignCompany() + "】一级企业不存在!");
        }
        consignUnit.setTopEntId(dtoMap.get(Long.parseLong(addOrderDTO.getConsignCompanyId())).getId());
        consignUnit.setFirmName(addOrderDTO.getConsignCompany());
        consignUnit.setContacts(addOrderDTO.getConsignContacts());
        consignUnit.setPhone(addOrderDTO.getConsignContactPhone());
        consignUnit.setContactsId(Long.parseLong(addOrderDTO.getConsignContactsId()));
//        consignUnit.setRemark(addOrderDTO.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(addOrderDTO.getAcceptCompanyId()));
        Map<Long, EntCacheResDto> dtoMap1 = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(addOrderDTO.getAcceptCompanyId())));
        if (dtoMap1 == null || dtoMap1.get(Long.parseLong(addOrderDTO.getAcceptCompanyId())) == null) {
            throw new BusinessException("该【" + addOrderDTO.getAcceptCompany() + "】一级企业不存在!");
        }
        unit.setTopEntId(dtoMap1.get(Long.parseLong(addOrderDTO.getAcceptCompanyId())).getId());
        unit.setFirmName(addOrderDTO.getAcceptCompany());
        unit.setContacts(addOrderDTO.getAcceptContacts());
        unit.setPhone(addOrderDTO.getAcceptContactPhone());
//        unit.setRemark(addOrderDTO.getRemark());
        unit.setStatus(NumberConstant.ZERO);
        unit.setContactsId(Long.parseLong(addOrderDTO.getAcceptContactsId()));
        unit.setCreateBy(LoginUserHolder.getUserId());
        unit.setCreateTime(new Date());
        unit.setUpdateBy(LoginUserHolder.getUserId());
        unit.setUpdateTime(new Date());
        kwtLogisticsOrderUnitMapper.insert(consignUnit);
        kwtLogisticsOrderUnitMapper.insert(unit);
    }

    /**
     * 托运订单-新建订单-保存mongodb
     *
     * @param addOrderDTO 页面请求参数
     * @param orderStatus 主体单据状态
     * @param lOrderId    主体订单id
     * @param lOrderNo    主体订单编号
     * @param infoResDto  合同信息
     */
    private void saveMongoDb(AddOrderDTO addOrderDTO, 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(addOrderDTO.getSettlementCycle());
        order.setPrice(addOrderDTO.getPrice());
        order.setPriceType(order.getPriceType());
        order.setAmount(addOrderDTO.getAmount());
        order.setUnit(addOrderDTO.getAmountUnit());
        order.setLoss(addOrderDTO.getLoss());
        order.setLossUnit(addOrderDTO.getLossUnit());
        order.setGoodsPrice(addOrderDTO.getGoodsPrice() == null ? null : addOrderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(addOrderDTO.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(addOrderDTO.getPayment());
        order.setTaxRate(addOrderDTO.getTaxRate());
        order.setRemark(addOrderDTO.getRemark());
        order.setStatus(String.valueOf(orderStatus));
        order.setEntId(LoginUserHolder.getEntId());
        order.setFirmName(LoginUserHolder.getEntName());
//        order.setGoodsId(Long.parseLong(addOrderDTO.getGoodsId()));
//        order.setGoodsCode(goods == null ? null : goods.getCode());
        order.setGoodsName(addOrderDTO.getGoodsName());
//        order.setGoodsType(goods == null ? null : goods.getGoodsType());
//        order.setGoodsIndustry(goods == null ? null : goods.get);
//        order.setGoodsSpec(goods == null ? null : goods.getSpec());
        order.setContractId(addOrderDTO.getContractId());
        order.setContractNo(infoResDto.getContractCode());
        order.setContractName(infoResDto.getContactName());
        order.setContractSigningWay(String.valueOf(infoResDto.getSigningWay()));
        order.setCheckEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        Map<Long, EntCacheResDto> dtoMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(addOrderDTO.getConsignCompanyId())));
        if (dtoMap == null || dtoMap.get(Long.parseLong(addOrderDTO.getConsignCompanyId())) == null) {
            throw new BusinessException("该【" + addOrderDTO.getConsignCompany() + "】一级企业不存在!");
        }
        order.setCheckTopEntId(dtoMap.get(Long.parseLong(addOrderDTO.getConsignCompanyId())).getId());
        order.setCheckFirmName(addOrderDTO.getConsignCompany());
        order.setCheckContacts(addOrderDTO.getConsignContacts());
        order.setCheckPhone(addOrderDTO.getConsignContactPhone());
        order.setCarrierEntId(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
        Map<Long, EntCacheResDto> dtoMap1 = remoteSystemService.queryEntTreeByIds(Collections.singletonList(Long.parseLong(addOrderDTO.getAcceptCompanyId())));
        if (dtoMap1 == null || dtoMap1.get(Long.parseLong(addOrderDTO.getAcceptCompanyId())) == null) {
            throw new BusinessException("该【" + addOrderDTO.getAcceptCompany() + "】一级企业不存在!");
        }
        order.setCarrierTopEntId(dtoMap1.get(Long.parseLong(addOrderDTO.getAcceptCompanyId())).getId());
        order.setCarrierFirmName(addOrderDTO.getAcceptCompany());
        order.setCarrierContacts(addOrderDTO.getAcceptContacts());
        order.setCarrierPhone(addOrderDTO.getAcceptContactPhone());
//        order.setLoadType();
        order.setLoadContacts(addOrderDTO.getLoadContacts());
        order.setLoadPhone(addOrderDTO.getLoadPhone());
        order.setLoadCityCode(addOrderDTO.getLoadCityCode());
        order.setLoadCityName(addOrderDTO.getLoadCityName());
        order.setLoadDetailAddress(addOrderDTO.getLoadDetailAddress());
        order.setLoadLat(addOrderDTO.getLoadLat());
        order.setLoadLng(addOrderDTO.getLoadLng());
//        order.setUnloadType();
        order.setUnloadContacts(addOrderDTO.getUnloadContacts());
        order.setUnloadPhone(addOrderDTO.getUnloadPhone());
        order.setUnloadCityCode(addOrderDTO.getUnloadCityCode());
        order.setUnloadCityName(addOrderDTO.getUnloadCityName());
        order.setUnloadDetailAddress(addOrderDTO.getUnloadDetailAddress());
        order.setUnloadLat(addOrderDTO.getUnloadLat());
        order.setUnloadLng(addOrderDTO.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(addOrderDTO.getAmount());
        order.setBillingMode(addOrderDTO.getBillingMode());
        order.setDelFlag(String.valueOf(NumberConstant.ZERO));
        order.setStartTime(addOrderDTO.getStartTime() == null ? null : DateUtil.localDateToLocalDateTimeStart(addOrderDTO.getStartTime()));
        order.setEndTime(addOrderDTO.getEndTime().atStartOfDay());
        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));
    }

    /**
     * 承运订单/托运订单-获取地址信息
     *
     * @return
     */
    public HttpResult getLogisticsOrderAddressList() {
        Long entId = LoginUserHolder.getEntId();
        AddressDropListDTO res = new AddressDropListDTO();
        List<KwtLogisticsOrderUnit> list = kwtLogisticsOrderUnitMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(KwtLogisticsOrderUnit::getTopEntId, entId)
        );
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok(res);
        }
        Set<Long> lOrderIds = list.stream().map(KwtLogisticsOrderUnit::getLOrderId).distinct().collect(Collectors.toSet());
        //订单ids获取地址信息
        List<KwtLogisticsOrderAddress> addressList = kwtLogisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .in(KwtLogisticsOrderAddress::getLOrderId, lOrderIds));
        if (CollectionUtils.isEmpty(addressList)) {
            return HttpResult.ok(res);
        }
        //装卸货地址类型分组获取装卸货cityCodes
        Map<Integer, List<Integer>> map = addressList.stream().collect(Collectors.
                groupingBy(KwtLogisticsOrderAddress::getAddressType, Collectors.mapping(KwtLogisticsOrderAddress::getCityCode, Collectors.toList())));
        //装货地址下拉列表树
        List<AreaTreeFrontResDto> loadTree = remoteSystemService.queryAreaTreeFrontByCodeList(map.get(NumberConstant.ONE));
        //卸货地址下拉列表树
        List<AreaTreeFrontResDto> unloadTree = remoteSystemService.queryAreaTreeFrontByCodeList(map.get(NumberConstant.TWO));
        res.setLoadAddressList(loadTree).setUnloadAddressList(unloadTree);
        return HttpResult.ok(res);
    }

    public PageRes selectConsignOrderList(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());
        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getIds())) {
            idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        }
        List<AcceptCarriageOrderVO> list = kwtLogisticsOrderMapper.selectLogisticsOrderListByConsign(query, orderList, type, entId, longList, longList, idsList);
        PageInfo<AcceptCarriageOrderVO> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(pageInfo, list);
        }

        /*计量单位*/
        Map<String, String> unitTypeDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /*运价方式*/
        Map<String, String> priceDictData = commonService.getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /*计费方式*/
        Map<String, String> chargingDictData = commonService.getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /*结算周期*/
        Map<String, String> settlementDictData = commonService.getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /*签约方式*/
        Map<String, String> signingWay = commonService.getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        Map<String, String> orderSource = commonService.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<AcceptCarriageOrderVO> collect = list.stream().filter(item -> item.getBillingMode().equals(DictEnum.CHARGING_TYPE_4.getValue())).collect(Collectors.toList());
        Map<Long, List<KwtLogisticsOrderLineFreightRate>> collect1 = new HashMap<>();
        if (CollectionUtils.isNotEmpty(collect)) {
            List<KwtLogisticsOrderLineFreightRate> kwtLogisticsOrderLineFreightRates = lineFreightRateMapper.selectListByOrderIdList(collect.stream().map(AcceptCarriageOrderVO::getLOrderId).map(Long::parseLong).toList());
            if (CollectionUtils.isNotEmpty(kwtLogisticsOrderLineFreightRates)) {
                collect1 = kwtLogisticsOrderLineFreightRates.stream().collect(Collectors.groupingBy(KwtLogisticsOrderLineFreightRate::getLOrderId));
            }
        }

        for (AcceptCarriageOrderVO vo : list) {
            List<KwtLogisticsOrderLineFreightRate> kwtLogisticsOrderLineFreightRates = collect1.get(Long.parseLong(vo.getLOrderId()));
            if (CollectionUtils.isNotEmpty(kwtLogisticsOrderLineFreightRates)) {
                vo.setPrices(kwtLogisticsOrderLineFreightRates.stream().map(item -> item.getName() + " " + item.getTransportPrice()).toList());
            }

            vo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
            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.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));
            vo.setPriceLabel(vo.getPriceType() == null ? null : priceDictData.get(vo.getPriceType()));
            vo.setUnitLabel(unitTypeDictData == null ? vo.getUnit() : (unitTypeDictData.get(vo.getUnit()) == null ? vo.getUnit() : unitTypeDictData.get(vo.getUnit())));
            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 (Exception e) {
                    log.info(vo.getTOrderId() + "查询错误:{}", e.getMessage(), e);
                }
            }
            String lOrderId = vo.getLOrderId();
            List<KwtLogisticsOrderAddress> loadAddresses = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, Long.parseLong(lOrderId))
            );
            List<KwtLogisticsOrderAddress> unloadAddresses = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, Long.parseLong(lOrderId))
            );
            //装货地点名称
            List<String> loadName = loadAddresses.stream().map(KwtLogisticsOrderAddress::getCityName).toList();
            //装货地点
            List<String> loadAddress = loadAddresses.stream().map(KwtLogisticsOrderAddress::getDetailAddress).toList();
            //卸货地点点名称
            List<String> unloadName = unloadAddresses.stream().map(KwtLogisticsOrderAddress::getCityName).toList();
            //卸货地点
            List<String> unloadAddress = unloadAddresses.stream().map(KwtLogisticsOrderAddress::getDetailAddress).toList();
            List<LoadAddressVo> loadAddressAmount = logisticsOrderAddressMapper.findByAddressAndLoadAmount(Long.parseLong(lOrderId), NumberConstant.ONE);
            List<UnLoadAddressVo> unloadAddressAmount = logisticsOrderAddressMapper.findByAddressAndUnLoadAmount(Long.parseLong(lOrderId), NumberConstant.TWO);

            vo.setLoadNames(loadName);
            vo.setLoadAddresses(loadAddress);
            vo.setUnloadNames(unloadName);
            vo.setUnloadAddresses(unloadAddress);
            vo.setLoading(loadAddressAmount);
            vo.setUnloading(unloadAddressAmount);
        }
        return PageRes.build(pageInfo, list);
    }

    public HttpResult statisticsConsign(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 = kwtLogisticsOrderMapper.countLogisticsOrderListByConsignStatus(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 statisticsConsignByApp(AcceptCarriageOrderQuery query) {
        String type = "1";
        HttpResult httpResult = statisticsConsign(query, type);
        return httpResult;
    }

    public HttpResult getOrderTrackByOrderId(String orderId, String number) {
        List<KwtLogisticsOrderTrack> list = kwtLogisticsOrderTrackMapper.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);
    }

    public List<ConsignOrderExcelVo> exportConsign(ConsignOrderQuery 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());
        List<Long> idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
//        List<ConsignOrderVO> list = kwtLogisticsOrderMapper.selectConsignLogisticsOrderList(query, orderList, type, entId, longList, longList,idsList);
        List<ConsignOrderVO> list = kwtLogisticsOrderMapper.selectConsignLogisticsOrderListByConsign(query, orderList, type, entId, longList, longList, idsList);
//        List<ConsignOrderVO> list = kwtLogisticsOrderMapper.selectLogisticsOrderListByConsign(query, orderList, type, entId, longList, longList,idsList);
        /**计量单位*/
        Map<String, String> unitTypeDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**计费方式*/
        Map<String, String> chargingDictData = commonService.getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = commonService.getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
//        Map<String, String> signingWay = commonService.getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗单位*/
        Map<String, String> taxRate = commonService.getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        /**运价方式*/
        Map<String, String> priceType = commonService.getDictData(DictTypeEnum.PRICE_TYPE.getType());
        Map<String, String> orderSource = commonService.getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        Map<Long, UserCacheResDto> longUserMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(ConsignOrderVO::getCreateBy).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                longUserMap = remoteSystemService.queryUserCacheMapByIds(collect);
            }
        }
        List<ConsignOrderExcelVo> exportList = new ArrayList<>();
        for (ConsignOrderVO vo : list) {
            ConsignOrderExcelVo consignOrderExcelVo = new ConsignOrderExcelVo();
            BeanUtils.copyProperties(vo, consignOrderExcelVo);
            consignOrderExcelVo.setCarryingCapacity(vo.getCarryingCapacity().toString());
            consignOrderExcelVo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
            consignOrderExcelVo.setPriceLabel(vo.getPrice() == null ? null : vo.getPrice().toString() + priceType.get(vo.getPriceType()));
            consignOrderExcelVo.setLossUnitLabel(vo.getLoss() == null ? null : vo.getLoss().toString() + taxRate.get(vo.getLossUnit()));
//            consignOrderExcelVo.setGoodsPriceLabel(vo.getGoodsPrice() == null ? null : vo.getGoodsPrice().toString() + priceType.get(vo.getGoodsPriceUnit()));
            consignOrderExcelVo.setAccountsCycleLabel(settlementDictData.get(vo.getAccountsCycle()));
            consignOrderExcelVo.setAppointor(longUserMap.get(vo.getCreateBy()) == null ? null : longUserMap.get(vo.getCreateBy()).getName());
            consignOrderExcelVo.setBillingModeLabel(chargingDictData.get(vo.getBillingMode()));
//            consignOrderExcelVo.setSigningLabel(signingWay.get(vo.getSigning()));
            consignOrderExcelVo.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));

//            consignOrderExcelVo.setLoadAddress(vo.getLoadCityName() + vo.getLoadAddress());
//            consignOrderExcelVo.setUnloadAddress(vo.getUnloadCityName() + vo.getUnloadAddress());
//            consignOrderExcelVo.setLoadName(vo.getLoadName());
//            consignOrderExcelVo.setUnloadName(vo.getUnloadName());

            String lOrderId = vo.getLOrderId();
            List<String> loadName = new ArrayList<String>();
            List<String> loadAddressList = new ArrayList<String>();
            List<KwtLogisticsOrderAddress> loadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            loadAddress.forEach(address -> {
                loadName.add(address.getName());
                loadAddressList.add(address.getDetailAddress());
            });

            List<String> unloadName = new ArrayList<String>();
            List<String> unloadAddressList = new ArrayList<String>();
            List<KwtLogisticsOrderAddress> unloadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            unloadAddress.forEach(address -> {
                unloadName.add(address.getName());
                unloadAddressList.add(address.getDetailAddress());
            });

            consignOrderExcelVo.setLoadAddress(StringUtils.stringListSpliceToString(loadAddressList));
            consignOrderExcelVo.setUnloadAddress(StringUtils.stringListSpliceToString(unloadAddressList));
            consignOrderExcelVo.setLoadName(StringUtils.stringListSpliceToString(loadName));
            consignOrderExcelVo.setUnloadName(StringUtils.stringListSpliceToString(unloadName));

            String unitLabel = unitTypeDictData == null ? vo.getUnit() : (unitTypeDictData.get(vo.getUnit()) == null ? vo.getUnit() : unitTypeDictData.get(vo.getUnit()));
            consignOrderExcelVo.setLoadAmount(consignOrderExcelVo.getLoadAmount() + unitLabel);
            consignOrderExcelVo.setUnloadAmount(consignOrderExcelVo.getUnloadAmount() + unitLabel);

            BigDecimal subtract = vo.getCarryingCapacity().subtract(vo.getSubcontractAmount()).subtract(vo.getEntrustAmount());
            DecimalFormat df = new DecimalFormat("0.00");
            consignOrderExcelVo.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())) {
                                    consignOrderExcelVo.setReceiveGoodsUnit(detailRes.getFirmName());
                                }
                                if ("2".equals(detailRes.getUnitType())) {
                                    consignOrderExcelVo.setShipmentsUnit(detailRes.getFirmName());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("tradeOrderInfoService.getOrderDetailById error id:{},errorMessage:{}", tOrderId, e.getMessage(), e);
                }
            }
//            consignOrderExcelVo.setSubcontractAmount(Objects.isNull(vo.getSubcontractAmount()) ? null : df.format(vo.getSubcontractAmount()) + priceType.get(vo.getPriceType()));
//            consignOrderExcelVo.setEntrustAmount(Objects.isNull(vo.getEntrustAmount()) ? null : df.format(vo.getEntrustAmount()) + priceType.get(vo.getPriceType()));
            consignOrderExcelVo.setLoadAmount(Objects.isNull(vo.getLoadAmount()) ? null : df.format(vo.getLoadAmount()) + priceType.get(vo.getPriceType()));
            consignOrderExcelVo.setUnloadAmount(Objects.isNull(vo.getUnloadAmount()) ? null : df.format(vo.getUnloadAmount()) + priceType.get(vo.getPriceType()));
            exportList.add(consignOrderExcelVo);
        }
        return exportList;
    }

    public HttpResult workbenchStatistics(String dateType) {
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(LoginUserHolder.getEntId());
        if (entCacheResDto == null) {
            return HttpResult.ok(new StatisticsByOrderVO());
        }
        //周
        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(entCacheResDto.getId(), 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(entCacheResDto.getId(), monthDateStart, monthDateEnd, lastMonthDateStart, lastMonthDateEnd, 3);
        } else if (String.valueOf(NumberConstant.THREE).equals(dateType)) {
            //年

        } 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.HAVE_FINISHED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_RECONCILED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getCode());
        StatisticsByOrderVO currentFinish = kwtLogisticsOrderMapper.selectAcceptCarriageFinishOrder(statusList, weekDateStart, weekDateEnd, id, OrderTypeEnum.CONSIGN_ORDER.getType());
        //获取完结中的单据
        statusList.clear();
        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());
        StatisticsByOrderVO currentFinishIng = kwtLogisticsOrderMapper.selectAcceptCarriageAwaitFinishOrder(statusList, weekDateStart, weekDateEnd, id, OrderTypeEnum.CONSIGN_ORDER.getType());
        //全部的未履约量
        BigDecimal waitingAmount = currentFinish.getWaitingAmount().add(currentFinishIng.getWaitingAmount());
        BigDecimal amount = currentFinish.getAmount().add(currentFinishIng.getAmount());
        BigDecimal entrustAmount = currentFinish.getEntrustAmount().add(currentFinishIng.getEntrustAmount());
        BigDecimal subcontractAmount = currentFinish.getSubcontractAmount().add(currentFinishIng.getSubcontractAmount());
        BigDecimal totalPrice = currentFinish.getTotalPrice().add(currentFinishIng.getTotalPrice());


        StatisticsByOrderVO current = new StatisticsByOrderVO();
        current.setWaitingAmount(waitingAmount);
        current.setAmount(amount);
        current.setEntrustAmount(entrustAmount);
        current.setSubcontractAmount(subcontractAmount);
        current.setTotalPrice(totalPrice);

        //上周

        //获取完结的单据
        statusList.clear();
        statusList.add(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_RECONCILED.getCode());
        statusList.add(LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getCode());
        StatisticsByOrderVO lastStatistics = kwtLogisticsOrderMapper.selectAcceptCarriageFinishOrder(statusList, lastWeekDateStart, lastWeekDateEnd, id, OrderTypeEnum.CONSIGN_ORDER.getType());
        //获取完结中的单据
        statusList.clear();
        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());
        StatisticsByOrderVO lastStatisticsByOrderVO = kwtLogisticsOrderMapper.selectAcceptCarriageAwaitFinishOrder(statusList, lastWeekDateStart, lastWeekDateEnd, id, OrderTypeEnum.CONSIGN_ORDER.getType());
        //全部的未履约量
        BigDecimal lastWaitingAmount = lastStatistics.getWaitingAmount().add(lastStatisticsByOrderVO.getWaitingAmount());
        BigDecimal lastAmount = lastStatistics.getAmount().add(lastStatisticsByOrderVO.getAmount());
        BigDecimal lastEntrustAmount = lastStatistics.getEntrustAmount().add(lastStatisticsByOrderVO.getEntrustAmount());
        BigDecimal lastSubcontractAmount = lastStatistics.getSubcontractAmount().add(lastStatisticsByOrderVO.getSubcontractAmount());
        BigDecimal lastTotalPrice = lastStatistics.getTotalPrice().add(lastStatisticsByOrderVO.getTotalPrice());

        StatisticsByOrderVO last = new StatisticsByOrderVO();
        last.setWaitingAmount(lastWaitingAmount);
        last.setAmount(lastAmount);
        last.setEntrustAmount(lastEntrustAmount);
        last.setSubcontractAmount(lastSubcontractAmount);
        last.setTotalPrice(lastTotalPrice);

        /**计算待承运量*/
        computeCompareWaitingAmount(resultVO, current, last);

        /**承运量*/
        computeCompareAmount(resultVO, current, last);

        /**总金额（费用）*/
        computeCompareTotalPrice(resultVO, current, last);

        /**待处理的金额*/
        SettlementMoney settlementMoney = paymentDubboService.countShipper(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 = NumberConstant.ZERO_TWO;
        if (currentWeek.getTotalPrice().compareTo(NumberConstant.ZERO_TWO) == 0
                && lastWeek.getTotalPrice().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = NumberConstant.ZERO_TWO;
        } else if (currentWeek.getTotalPrice().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = chainRatio.subtract(new BigDecimal("100.00"));
            flag = 2;
        } else if (lastWeek.getTotalPrice().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = new BigDecimal("100.00").subtract(chainRatio);
        } else {
            chainRatio = (currentWeek.getTotalPrice().subtract(lastWeek.getTotalPrice())).divide(lastWeek.getTotalPrice(), NumberConstant.SIX, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, RoundingMode.HALF_UP);
        }
        if (chainRatio.compareTo(NumberConstant.ZERO_TWO) == -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 = NumberConstant.ZERO_TWO;
        if (currentWeek.getAmount().compareTo(NumberConstant.ZERO_TWO) == 0
                && lastWeek.getAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            amountChainRatio = NumberConstant.ZERO_TWO;
        } else if (currentWeek.getAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            amountChainRatio = amountChainRatio.subtract(new BigDecimal("100.00"));
            amountFlag = 2;
        } else if (lastWeek.getAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            amountChainRatio = new BigDecimal("100.00").subtract(amountChainRatio);
        } else {
            amountChainRatio = (currentWeek.getAmount().subtract(lastWeek.getAmount())).divide(lastWeek.getAmount(), NumberConstant.SIX, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, RoundingMode.HALF_UP);
        }
        if (amountChainRatio.compareTo(NumberConstant.ZERO_TWO) == -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 = NumberConstant.ZERO_TWO;
        if (currentWeek.getWaitingAmount().compareTo(NumberConstant.ZERO_TWO) == 0
                && lastWeek.getWaitingAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = NumberConstant.ZERO_TWO;
        } else if (currentWeek.getWaitingAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = chainRatio.subtract(new BigDecimal("100.00"));
            flag = 2;
        } else if (lastWeek.getWaitingAmount().compareTo(NumberConstant.ZERO_TWO) == 0) {
            chainRatio = new BigDecimal("100.00").subtract(chainRatio);
        } else {
            chainRatio = (currentWeek.getWaitingAmount().subtract(lastWeek.getWaitingAmount())).divide(lastWeek.getWaitingAmount(), NumberConstant.SIX, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100.00")).setScale(NumberConstant.TWO, RoundingMode.HALF_UP);
        }
        if (chainRatio.compareTo(NumberConstant.ZERO_TWO) == -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 = kwtLogisticsOrderMapper.workbenchLogisticsOrderStatisticsByMonth(id, statusList,
                    OrderTypeEnum.CONSIGN_ORDER.getType(), dateStart, dateEnd, logisticsOrderStatistics.getTypeOne(), logisticsOrderStatistics.getTypeTwo());
            if ("2".equals(logisticsOrderStatistics.getTypeOne())) {
                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 ("2".equals(logisticsOrderStatistics.getTypeTwo())) {
                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 = kwtLogisticsOrderMapper.workbenchLogisticsOrderStatisticsByDays(id, statusList,
                    OrderTypeEnum.CONSIGN_ORDER.getType(), dateStart, dateEnd, logisticsOrderStatistics.getTypeOne(), logisticsOrderStatistics.getTypeTwo());
            if ("2".equals(logisticsOrderStatistics.getTypeOne())) {
                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 ("2".equals(logisticsOrderStatistics.getTypeTwo())) {
                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;
    }
}
