package com.sckw.transport.service.app;


import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.AddressTypeEnum;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.core.model.enums.LogisticsOrderV1Enum;
import com.sckw.core.model.enums.UnitTypeEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.DateUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.fleet.api.model.vo.RDriverVo;
import com.sckw.fleet.api.model.vo.RTruckVo;
import com.sckw.order.api.dubbo.RemoteTradeOrderAmountService;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.OrderDetailVo;
import com.sckw.order.api.model.OrderUnitInfoDetailVO;
import com.sckw.order.api.model.UpdateActualAmountParam;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.product.api.model.KwpGoods;
import com.sckw.redis.config.RedisLockUtil;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.transport.common.config.MessageUrlConfig;
import com.sckw.transport.dao.*;
import com.sckw.transport.handler.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.param.*;
import com.sckw.transport.model.vo.OrderCirculateTotalTakeVo;
import com.sckw.transport.model.vo.OrderStatusStatisticsResp;
import com.sckw.transport.model.vo.StatisticsWaybillResp;
import com.sckw.transport.repository.*;
import com.sckw.transport.service.*;
import com.sckw.transport.utils.DistanceUtils;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author zk
 * @desc 司机app接单Service
 * @date 2023/7/19 0019
 */
@Slf4j
@Service
@SuppressWarnings("all")
@RequiredArgsConstructor
public class WaybillOrderService {

    private final KwtLogisticsOrderRepository logisticsOrderRepository;
    private final KwtLogisticsOrderCirculateRepository logisticsOrderCirculateRepository;
    private final KwtLogisticsOrderGoodsRepository logisticsOrderGoodsRepository;
    private final KwtLogisticsOrderAddressRepository logisticsOrderAddressRepository;
    private final KwtLogisticsOrderUnitRepository logisticsOrderUnitRepository;

    private final KwtWaybillOrderSubtaskRepository waybillOrderSubtaskRepository;
    private final KwtWaybillOrderRepository waybillOrderRepository;
    private final KwtWaybillOrderAddressRepository waybillOrderAddressRepository;
    private final KwtWaybillOrderTicketRepository waybillOrderTicketRepository;
    private final KwtWaybillOrderNodeRepository waybillOrderNodeRepository;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteSystemService remoteSystemService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 80000)
    TradeOrderInfoService tradeOrderInfoService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteFleetService remoteFleetService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    GoodsInfoService goodsInfoService;

    private final TakingOrderHandler takingOrderHandler;
    private final CancelHandler cancelHandler;
    private final ComeIntoHandler comeIntoHandler;
    private final LoadingHandler loadingHandler;
    private final LeaveMockHandler leaveMockHandler;
    private final LeaveHandler leaveHandler;
    private final UnloadingHandler unloadingHandler;

    private final KwtWaybillOrderV1Service waybillOrderV1Service;

    //载重任务量浮动吨数
    private static final BigDecimal TWO_TONS = new BigDecimal("2");
    //载重任务量计算比例
    private static final BigDecimal EIGHTY_PERCENT = new BigDecimal("0.8");
    // 定义禁止运单接单的状态集合
    private static final List<Integer> FORBIDDEN_STATUSES = Arrays.asList(
            CarWaybillV1Enum.PENDING_VEHICLE.getCode(),
            CarWaybillV1Enum.REFUSE_TRAFFIC.getCode(),
            CarWaybillV1Enum.EXIT_COMPLETED.getCode(),
            CarWaybillV1Enum.WAIT_LOADING.getCode(),
            CarWaybillV1Enum.COMPLETION_UNLOADING.getCode()
    );

    // 定义进行中的状态集合
    private static final List<Integer> UNDER_WAY = Arrays.asList(
            CarWaybillV1Enum.PENDING_VEHICLE.getCode(),
            CarWaybillV1Enum.REFUSE_TRAFFIC.getCode(),
            CarWaybillV1Enum.EXIT_COMPLETED.getCode(),
            CarWaybillV1Enum.WAIT_LOADING.getCode());

    // 定义审核的状态集合
    private static final List<Integer> REVIEW = Arrays.asList(
            CarWaybillV1Enum.COMPLETION_LOADING.getCode(),
            CarWaybillV1Enum.COMPLETION_UNLOADING.getCode());

    // 定义已完成的状态集合
    private static final List<Integer> COMPLETED = Arrays.asList(
            CarWaybillV1Enum.WAIT_UNLOADING.getCode(),
            CarWaybillV1Enum.APPROVAL_TREAT.getCode());




    /**
     * 查询司机关联完成运单和累计运输量
     * @param param
     * @return
     */
    public OrderCirculateTotalTakeVo queryTotalTake(OrderCirculateTotalTakeParam param) {
        log.info("查询司机关联完成运单和累计运输量：{}", JSON.toJSONString(param));
        LambdaQueryWrapper<KwtLogisticsOrderCirculate> queryWrapper = Wrappers.<KwtLogisticsOrderCirculate>lambdaQuery()
                .eq(KwtLogisticsOrderCirculate::getEntId, param.getEntId())
                .eq(KwtLogisticsOrderCirculate::getDriverId, param.getDriverId())
                .eq(KwtLogisticsOrderCirculate::getDelFlag,0)
                .orderByDesc(KwtLogisticsOrderCirculate::getCreateTime)
                .orderByDesc(KwtLogisticsOrderCirculate::getId);
        List<KwtLogisticsOrderCirculate> circulateList = logisticsOrderCirculateRepository.list(queryWrapper);
        if (CollectionUtils.isEmpty(circulateList)) {
            log.info("当前司机的无运单,driverId: {}", JSON.toJSONString(param));
            return new OrderCirculateTotalTakeVo();
        }

        //总运单量
        int totalTake = circulateList.stream()
                .filter(cr -> cr.getTotalTake() != null)
                .mapToInt(KwtLogisticsOrderCirculate::getTotalTake)
                .sum();
        //总运输量
        BigDecimal toalEntrustAmount = circulateList.stream().map(KwtLogisticsOrderCirculate::getEntrustAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //单位
        String unit = circulateList.stream().map(KwtLogisticsOrderCirculate::getUnit)
                .filter(Objects::nonNull)
                .findFirst().orElse(null);

        OrderCirculateTotalTakeVo totalTakeVo = new OrderCirculateTotalTakeVo();
        totalTakeVo.setTotalTake(totalTake);
        totalTakeVo.setEntrustAmount(toalEntrustAmount);
        totalTakeVo.setUnit(unit);
        log.info("查询司机关联完成运单和累计运输量成功，结果：{}", JSON.toJSONString(totalTakeVo));

        return totalTakeVo;

    }

    /**
     * 查询司机关联车辆的物流订单
     * @param param
     * @return
     */
    public PageDataResult<LogisticsOrderResp> queryTruckLogisticsOrder(OrderCirculateQueryParam param) {
        log.info("查询司机关联车辆的物流订单：{}", JSON.toJSONString(param));
        LambdaQueryWrapper<KwtLogisticsOrderCirculate> queryWrapper = Wrappers.<KwtLogisticsOrderCirculate>lambdaQuery()
                .eq(KwtLogisticsOrderCirculate::getEntId, param.getEntId())
                .eq(KwtLogisticsOrderCirculate::getTruckNo, param.getTruckNo())
                .eq(KwtLogisticsOrderCirculate::getDelFlag, 0)
                .orderByDesc(KwtLogisticsOrderCirculate::getCreateTime)
                .orderByDesc(KwtLogisticsOrderCirculate::getId);//TODO donglang 运单状态
        //车牌映射的物流订单
        Page<KwtLogisticsOrderCirculate> logOrderCirculateList = logisticsOrderCirculateRepository.page(new Page<>(param.getPageNum(), param.getPageSize()), queryWrapper);
        List<KwtLogisticsOrderCirculate> records = logOrderCirculateList.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.info("当前车辆无派单订单，truckNo:{}", param.getTruckNo());
            return PageDataResult.empty(param.getPageNum(), param.getPageSize());
        }
        //车牌关联物流订单
        Map<Long, KwtLogisticsOrderCirculate> logOrderIdAndCirculateMap = records.stream().collect(Collectors.toMap(KwtLogisticsOrderCirculate::getLOrderId,
                Function.identity(), (x, y) -> x));

        List<Long> logOrderIdList = records.stream().map(KwtLogisticsOrderCirculate::getLOrderId)
                .filter(Objects::nonNull).collect(Collectors.toList());

        //物流订单
        List<KwtLogisticsOrder> logOrderList = logisticsOrderRepository.queryByLogisticsOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderList)) {
            log.info("当前车辆无物流订单，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.DRIVER_STATUS_ERROR, "当前车辆无物流订单");
        }

        //商品
        List<KwtLogisticsOrderGoods> logOrderGoods = logisticsOrderGoodsRepository.queryByLogOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderGoods)) {
            log.info("当前车辆的物流订单无商品信息，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_GOODS, "当前车辆的物流订单无商品信息");
        }

        //物流id映射物流商品
        Map<Long, KwtLogisticsOrderGoods> logOrderIdAndGoodsMap = logOrderGoods.stream().collect(Collectors.toMap(KwtLogisticsOrderGoods::getLOrderId,
                Function.identity(), (x, y) -> x));
        List<Long> goodsIds = logOrderGoods.stream().map(KwtLogisticsOrderGoods::getGoodsId).distinct().collect(Collectors.toList());

        //交易商品信息
        Map<Long, KwpGoods> goodsIdAndGoodsMap = goodsInfoService.getGoodsByIds(goodsIds);
        if (MapUtil.isEmpty(goodsIdAndGoodsMap)) {
            log.info("物流订单无关联商品信息，logOrderId:{}", JSON.toJSONString(logOrderIdList));
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_GOODS, "物流订单无关联商品信息");
        }

        //承运托运企业
        List<KwtLogisticsOrderUnit> logOrderUnits = logisticsOrderUnitRepository.queryByLogOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderUnits)) {
            log.info("物流订单无关联承运托运企业，logOrderId:{}", JSON.toJSONString(logOrderIdList));
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_ENT, "物流订单无关联承运托运企业");
        }
        Map<String, KwtLogisticsOrderUnit> logOrderIdAndUnitMap = logOrderUnits.stream()
                .collect(Collectors.toMap(unit -> unit.getLOrderId() + "-" + unit.getUnitType(),
                        Function.identity(), (x, y) -> x));

        //供应企业
        Set<Long> tradeOrderIds = logOrderList.stream().map(KwtLogisticsOrder::getTOrderId).collect(Collectors.toSet());
        List<OrderUnitInfoDetailVO> orderUnitDetailVOS = tradeOrderInfoService.queryOrderUnitInfByTOrderId(tradeOrderIds);
        if (CollectionUtils.isEmpty(orderUnitDetailVOS)) {
            log.info("交易订单无关联采取/销售企业，tradeOrderIds:{}", JSON.toJSONString(tradeOrderIds));
            throw new BusinessPlatfromException(ErrorCodeEnum.TRADE_ORDER_NOT_ENT, "交易订单无关联采取/销售企业");
        }
        //交易订单Map
        Map<String, OrderUnitInfoDetailVO> tOrderIdAndUnitMap = orderUnitDetailVOS.stream()
                .collect(Collectors.toMap(unit -> unit.getTOrderId() + "-" + unit.getUnitType(),
                        Function.identity(), (x, y) -> x));

        //地址
        Map<String, KwtLogisticsOrderAddress> logOrderIdAndAddressMap = getKwtLogisticsOrderAddressMap(logOrderIdList);

        //组装数据
        List<LogisticsOrderResp> ordderList = logOrderList.stream()
                .map(order -> {
                    return getLogisticsOrderResp(order, logOrderIdAndGoodsMap, goodsIdAndGoodsMap, logOrderIdAndUnitMap,
                            tOrderIdAndUnitMap, logOrderIdAndAddressMap, logOrderIdAndCirculateMap);
                }).collect(Collectors.toList());
        log.info("查询司机关联车辆的物流订单成功！");
        return PageDataResult.success(param.getPageNum(), param.getPageSize(), (long) ordderList.size(), ordderList);
    }

    /**
     * 装卸货地址
     * @param logOrderIdList
     * @return
     */
    private Map<String, KwtLogisticsOrderAddress> getKwtLogisticsOrderAddressMap(List<Long> logOrderIdList) {
        List<KwtLogisticsOrderAddress> logOrderAddressList = logisticsOrderAddressRepository.queryByLogOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderAddressList)) {
            log.info("物流订单无装卸货地址信息，logOrderIdList:{}", JSON.toJSONString(logOrderIdList));
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_ADDRESS, "物流订单无装卸货地址信息");
        }
        return logOrderAddressList.stream().collect(Collectors
                .toMap(address -> address.getLOrderId() + "-" + address.getAddressType(),
                        Function.identity(), (x, y) -> x));
    }

    /**
     * 组装订单列表信息
     * @param order
     * @param logOrderIdAndGoodsMap
     * @param goodsIdAndGoodsMap
     * @param logOrderIdAndUnitMap
     * @param tOrderIdAndUnitMap
     * @param logOrderIdAndAddressMap
     * @param logOrderIdAndCirculateMap
     * @return
     */
    private LogisticsOrderResp getLogisticsOrderResp(KwtLogisticsOrder order, Map<Long, KwtLogisticsOrderGoods> logOrderIdAndGoodsMap,
                                                     Map<Long, KwpGoods> goodsIdAndGoodsMap,
                                                     Map<String, KwtLogisticsOrderUnit> logOrderIdAndUnitMap,
                                                     Map<String, OrderUnitInfoDetailVO> tOrderIdAndUnitMap,
                                                     Map<String, KwtLogisticsOrderAddress> logOrderIdAndAddressMap,
                                                     Map<Long, KwtLogisticsOrderCirculate> logOrderIdAndCirculateMap) {
        LogisticsOrderResp orderResp = new LogisticsOrderResp();
        orderResp.setLogisticsOrderId(Optional.ofNullable(order.getId()).map(String::valueOf).orElse(null));
        orderResp.setLogisticsOrderNo(order.getLOrderNo());
        //商品
        KwtLogisticsOrderGoods orderGoods = logOrderIdAndGoodsMap.getOrDefault(order.getId(), new KwtLogisticsOrderGoods());
        KwpGoods goods = goodsIdAndGoodsMap.getOrDefault(orderGoods.getGoodsId(), new KwpGoods());
        orderResp.setGoodsId(String.valueOf(goods.getId()));
        orderResp.setGoodsName(goods.getName());

        //托运企业
        KwtLogisticsOrderUnit consignEnt = logOrderIdAndUnitMap.getOrDefault(order.getId() + "-" + UnitTypeEnum.CONSIGN.getCode(), new KwtLogisticsOrderUnit());
        orderResp.setConsignCompanyId(Optional.ofNullable(consignEnt.getEntId()).map(String::valueOf).orElse(null));
        orderResp.setConsignCompanyName(consignEnt.getFirmName());
        //承运企业
        KwtLogisticsOrderUnit carriageEnt = logOrderIdAndUnitMap.getOrDefault(order.getId() + "-" + UnitTypeEnum.CONSIGN.getCode(), new KwtLogisticsOrderUnit());
        orderResp.setCarriageCompanyId(Optional.ofNullable(carriageEnt.getEntId()).map(String::valueOf).orElse(null));
        orderResp.setCarriageCompanyName(carriageEnt.getFirmName());
        //供应企业
        OrderUnitInfoDetailVO supplierEnt = tOrderIdAndUnitMap.getOrDefault(order.getTOrderId() + "-" + "2", new OrderUnitInfoDetailVO());
        orderResp.setSupplierCompanyId(Optional.ofNullable(supplierEnt.getEntId()).map(String::valueOf).orElse(null));
        orderResp.setSupplierCompanyName(supplierEnt.getFirmName());

        //装货地址
        KwtLogisticsOrderAddress shipmentAddress = logOrderIdAndAddressMap.getOrDefault(order.getId() + "-" + AddressTypeEnum.SHIPMENT.getCode(), new KwtLogisticsOrderAddress());
        orderResp.setLoadAddress(shipmentAddress.getDetailAddress());
        //卸货地址
        KwtLogisticsOrderAddress takeAddress = logOrderIdAndAddressMap.getOrDefault(order.getId() + "-" + AddressTypeEnum.TAKE.getCode(), new KwtLogisticsOrderAddress());
        orderResp.setUnloadAddress(takeAddress.getDetailAddress());
        //装卸地之间距离
        double distanceKm = DistanceUtils.calculateDistance(
                Optional.ofNullable(shipmentAddress.getLat()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(shipmentAddress.getLng()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(takeAddress.getLat()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(takeAddress.getLng()).map(Double::valueOf).orElse(null));
        orderResp.setDistanceKm(distanceKm);

        //时间
        orderResp.setStartTime(DateUtils.format(order.getStartTime(), DateUtils.DATE_PATTERN));
        orderResp.setEndTime(DateUtils.format(order.getEndTime(), DateUtils.DATE_PATTERN));
        KwtLogisticsOrderCirculate orderCirculate = logOrderIdAndCirculateMap.getOrDefault(order.getId(), new KwtLogisticsOrderCirculate());
        orderResp.setSendTime(DateUtils.format(orderCirculate.getCreateTime(), DateUtils.DATE_PATTERN));

        //派单人信息
        UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(orderCirculate.getCreateBy());
        orderResp.setSendOperator(Optional.ofNullable(userCacheResDto).map(UserCacheResDto::getName).orElse(null));
        orderResp.setSendPhone(Optional.ofNullable(userCacheResDto).map(UserCacheResDto::getPhone).orElse(null));
        orderResp.setStatus(Optional.ofNullable(order.getStatus()).map(String::valueOf).orElse(null));
        orderResp.setStatusDesc(LogisticsOrderV1Enum.getDesc(order.getStatus()));

        return orderResp;
    }

    /**
     * 查询司机关联车辆的物流订单
     * @param param
     * @return
     */
    public PageDataResult<WaybillOrderStatusResp> queryWaybillOrder(WaybillOrderQueryParam param) {
        log.info("查询司机的物流运单：{}", JSON.toJSONString(param));
        LambdaQueryWrapper<KwtWaybillOrder> queryWrapper = Wrappers.<KwtWaybillOrder>lambdaQuery()
                .eq(KwtWaybillOrder::getEntId, param.getEntId())
                .eq(KwtWaybillOrder::getTruckNo, param.getTruckNo())
                .eq(KwtWaybillOrder::getDelFlag, 0)
                .orderByDesc(KwtWaybillOrder::getCreateTime)
                .orderByDesc(KwtWaybillOrder::getId);
        //进行中
        if (Objects.equals(param.getStatus(), Global.NUMERICAL_ONE)) {
            queryWrapper.in(KwtWaybillOrder::getStatus, UNDER_WAY);
        } else if (Objects.equals(param.getStatus(), Global.NUMERICAL_TWO)) {
            //单证审核
            queryWrapper.in(KwtWaybillOrder::getStatus, REVIEW);
        } else if (Objects.equals(param.getStatus(), Global.NUMERICAL_THREE)) {
            //已完成
            queryWrapper.in(KwtWaybillOrder::getStatus, COMPLETED);
        }

        //当前车辆的运单
        Page<KwtWaybillOrder> waybillOrderList = waybillOrderRepository.page(new Page<>(param.getPageNum(), param.getPageSize()), queryWrapper);
        List<KwtWaybillOrder> records = waybillOrderList.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.info("当前车辆辆的无物流运单，truckNo:{}", param.getTruckNo());
            return PageDataResult.empty(param.getPageNum(), param.getPageSize());
        }

        //物流运单id
        List<Long>  wbOrderIdList = records.stream().map(KwtWaybillOrder::getId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        //物流订单id
        List<Long> logOrderIdList = records.stream().map(KwtWaybillOrder::getLOrderId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());

        //子运单
        List<KwtWaybillOrderSubtask> orderSubtaskList = waybillOrderSubtaskRepository.queryByWOrderIds(wbOrderIdList);
        if (CollectionUtils.isEmpty(orderSubtaskList)) {
            log.info("当前车辆辆的无物流子运单，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_SUB_NOT_FOUND, "当前物流子运单不存在");
        }
        Map<Long, KwtWaybillOrderSubtask> subtaskMap = orderSubtaskList.stream().collect(Collectors.toMap(subtask -> subtask.getWOrderId(),
                Function.identity(), (x, y) -> x));

        //派单信息
        List<KwtLogisticsOrderCirculate> logOrderCirculateList = logisticsOrderCirculateRepository.queryByLogOrderIdsAndTruckNo(logOrderIdList, param.getTruckNo());
        if (CollectionUtils.isEmpty(logOrderCirculateList)) {
            log.info("当前车辆无派单订单，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_FOUND, "当前车辆无派单订单");
        }
        //车牌关联物流订单
        Map<Long, KwtLogisticsOrderCirculate> logOrderIdAndCirculateMap = logOrderCirculateList.stream().collect(
                Collectors.toMap(KwtLogisticsOrderCirculate::getLOrderId, Function.identity(), (x, y) -> x));

        //物流订单
        List<KwtLogisticsOrder> logOrderList = logisticsOrderRepository.queryByLogisticsOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderList)) {
            log.info("当前车辆无物流订单，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.DRIVER_STATUS_ERROR, "当前车辆无物流订单");
        }
        Map<Long, KwtLogisticsOrder> logOrderMap = logOrderList.stream().collect(Collectors.toMap(logOrder -> logOrder.getId(),
                Function.identity(), (x, y) -> x));

        //物流订单商品
        List<KwtLogisticsOrderGoods> logOrderGoods = logisticsOrderGoodsRepository.queryByLogOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderGoods)) {
            log.info("当前车辆的物流订单无商品信息，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_GOODS, "当前车辆的物流订单无商品信息");
        }
        //物流id映射商品
        Map<Long, KwtLogisticsOrderGoods> logOrderIdAndGoodsMap = logOrderGoods.stream().collect(
                Collectors.toMap(KwtLogisticsOrderGoods::getLOrderId, Function.identity(), (x, y) -> x));


        //承运托运企业
        List<KwtLogisticsOrderUnit> logOrderUnits = logisticsOrderUnitRepository.queryByLogOrderIds(logOrderIdList);
        if (CollectionUtils.isEmpty(logOrderUnits)) {
            log.info("物流订单无关联承运托运企业，logOrderId:{}", JSON.toJSONString(logOrderIdList));
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_ENT, "物流订单无关联承运托运企业");
        }
        Map<String, KwtLogisticsOrderUnit> logOrderIdAndUnitMap = logOrderUnits.stream().collect(
                Collectors.toMap(unit -> unit.getLOrderId() + "-" + unit.getUnitType(),
                        Function.identity(), (x, y) -> x));
        //地址
        Map<String, KwtLogisticsOrderAddress> logOrderIdAndAddressMap = getKwtLogisticsOrderAddressMap(logOrderIdList);

        //装卸货信息
        List<KwtWaybillOrderTicket> orderTicketList = waybillOrderTicketRepository.queryByWOrderIds(wbOrderIdList);
        if (CollectionUtils.isEmpty(orderTicketList)) {
            log.info("当前车辆无物流运单装卸货信息，truckNo:{}", param.getTruckNo());
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_TICKET, "当前车辆无物流运单装卸货信息");
        }
        Map<String, KwtWaybillOrderTicket> ticketMap = orderTicketList.stream().collect(
                Collectors.toMap(ticket -> ticket.getWOrderId() + "-" + ticket.getType(),
                        Function.identity(), (x, y) -> x));

        List<WaybillOrderStatusResp> ordderList = records.stream().map(
                billOrder -> {
                    return getWaybillOrderResp(billOrder, subtaskMap, logOrderMap, logOrderIdAndCirculateMap,
                            logOrderIdAndGoodsMap, logOrderIdAndUnitMap, logOrderIdAndAddressMap, ticketMap);
                }).collect(Collectors.toList());
        log.info("查询司机的物流运单成功！");
        return PageDataResult.success(param.getPageNum(), param.getPageSize(), (long) ordderList.size(), ordderList);

    }


    /**
     * 组装运单列表信息
     * @param order
     * @param logOrderIdAndGoodsMap
     * @param logOrderIdAndUnitMap
     * @param logOrderIdAndAddressMap
     * @return
     */
    private WaybillOrderStatusResp getWaybillOrderResp(KwtWaybillOrder wbOrder,  Map<Long, KwtWaybillOrderSubtask> subtaskMap,
                                                       Map<Long, KwtLogisticsOrder> logOrderMap,
                                                       Map<Long, KwtLogisticsOrderCirculate> logOrderIdAndCirculateMap,
                                                       Map<Long, KwtLogisticsOrderGoods> logOrderIdAndGoodsMap,
                                                       Map<String, KwtLogisticsOrderUnit> logOrderIdAndUnitMap,
                                                       Map<String, KwtLogisticsOrderAddress> logOrderIdAndAddressMap,
                                                       Map<String, KwtWaybillOrderTicket> ticketMap) {
        WaybillOrderStatusResp wbOrderResp = new WaybillOrderStatusResp();

        //装货、卸货净重、任务量
        KwtWaybillOrderSubtask subtask = subtaskMap.getOrDefault(wbOrder.getId(), new KwtWaybillOrderSubtask());
        wbOrderResp.setLoadingNetWeight(subtask.getLoadAmount());
        wbOrderResp.setUnloadingNetWeight(subtask.getUnloadAmount());
        wbOrderResp.setTaskNum(subtask.getEntrustAmount());

        //物流订单信息
        KwtLogisticsOrder logOrder = logOrderMap.getOrDefault(wbOrder.getLOrderId(), new KwtLogisticsOrder());
        wbOrderResp.setLogisticsOrderNo(logOrder.getLOrderNo());
        wbOrderResp.setChargeType(logOrder.getBillingMode());
        wbOrderResp.setChargeTypeDesc(DictEnum.getLabel(DictTypeEnum.CHARGING_TYPE.getType(), logOrder.getBillingMode()));

        //托运企业
        KwtLogisticsOrderUnit consignEnt = logOrderIdAndUnitMap.getOrDefault(wbOrder.getLOrderId() + "-" + UnitTypeEnum.CONSIGN.getCode(), new KwtLogisticsOrderUnit());
        wbOrderResp.setConsignCompanyId(Optional.ofNullable(consignEnt.getEntId()).map(String::valueOf).orElse(null));
        wbOrderResp.setConsignCompanyName(consignEnt.getFirmName());

        //商品
        KwtLogisticsOrderGoods orderGoods = logOrderIdAndGoodsMap.getOrDefault(wbOrder.getLOrderId(), new KwtLogisticsOrderGoods());
        wbOrderResp.setGoodsId(Optional.ofNullable(orderGoods.getId()).map(String::valueOf).orElse(null));
        wbOrderResp.setGoodsName(orderGoods.getGoodsName());

        //装货地址
        KwtLogisticsOrderAddress shipmentAddress = logOrderIdAndAddressMap.getOrDefault(wbOrder.getLOrderId() + "-" + AddressTypeEnum.SHIPMENT.getCode(), new KwtLogisticsOrderAddress());
        wbOrderResp.setLoadAddress(shipmentAddress.getDetailAddress());
        //卸货地址
        KwtLogisticsOrderAddress takeAddress = logOrderIdAndAddressMap.getOrDefault(wbOrder.getLOrderId() + "-" + AddressTypeEnum.TAKE.getCode(), new KwtLogisticsOrderAddress());
        wbOrderResp.setUnloadAddress(takeAddress.getDetailAddress());
        //装卸地之间距离
        double distanceKm = DistanceUtils.calculateDistance(
                Optional.ofNullable(shipmentAddress.getLat()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(shipmentAddress.getLng()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(takeAddress.getLat()).map(Double::valueOf).orElse(null),
                Optional.ofNullable(takeAddress.getLng()).map(Double::valueOf).orElse(null));
        wbOrderResp.setDistanceKm(distanceKm);

        //皮重
        KwtWaybillOrderTicket tareAmountTicket = ticketMap.getOrDefault(wbOrder.getId() + "-" + AddressTypeEnum.SHIPMENT.getCode(), new KwtWaybillOrderTicket());
        wbOrderResp.setTareAmount(tareAmountTicket.getTareAmount());
        //毛重
        KwtWaybillOrderTicket grossAmountTicket = ticketMap.getOrDefault(wbOrder.getId() + "-" + AddressTypeEnum.TAKE.getCode(), new KwtWaybillOrderTicket());
        wbOrderResp.setGrossAmount(grossAmountTicket.getTareAmount());

        //司机信息
        wbOrderResp.setDriverId(wbOrder.getDriverId());
        wbOrderResp.setDriverName(wbOrder.getDriverName());
        wbOrderResp.setDriverPhone(wbOrder.getDriverPhone());

        //派车信息
        KwtLogisticsOrderCirculate orderCirculate = logOrderIdAndCirculateMap.getOrDefault(wbOrder.getLOrderId(), new KwtLogisticsOrderCirculate());
        wbOrderResp.setSendTime(DateUtils.format(orderCirculate.getCreateTime(), DateUtils.DATE_PATTERN));
        //法定载重
        RTruckVo truckByTruckNo = remoteFleetService.findTruckByTruckNo(orderCirculate.getTruckNo());
        if (truckByTruckNo != null) {
            wbOrderResp.setLegalLoad(truckByTruckNo.getActualWeight());
        }

        //派单人信息
        UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(orderCirculate.getCreateBy());
        wbOrderResp.setSendOperator(Optional.ofNullable(userCacheResDto).map(UserCacheResDto::getName).orElse(null));
        wbOrderResp.setSendPhone(Optional.ofNullable(userCacheResDto).map(UserCacheResDto::getPhone).orElse(null));

        //状态
        wbOrderResp.setStatus(wbOrder.getStatus());
        wbOrderResp.setStatusDesc(CarWaybillV1Enum.geDesc(wbOrder.getStatus()));
        return wbOrderResp;

    }

    public StatisticsWaybillResp statisticsWaybillOrder() {
        StatisticsWaybillResp waybillResp = new StatisticsWaybillResp();
        log.info("运单状态统计");
        WaybillOrderReq waybillOrderReq = new WaybillOrderReq();
        StatisticsWaybillResp statisticsWaybillResp = waybillOrderV1Service.statisticsWaybillOrder(waybillOrderReq);
        if (statisticsWaybillResp == null || CollectionUtils.isEmpty(statisticsWaybillResp.getOrderStatusStatistics())) {
            return new StatisticsWaybillResp();
        }
        // 定义状态码聚合规则
        Map<List<String>, String[]> aggregateRules = Map.of(
                Arrays.asList("1", "5", "10", "15"), new String[]{"1", "进行中"},
                Arrays.asList("20", "30"), new String[]{"2", "单证审核"},
                Arrays.asList("25", "99"), new String[]{"3", "已完成"}
        );
        List<StatisticsWaybillResp.OrderBillStatusStatistics> orderStatusStatistics = statisticsWaybillResp.getOrderStatusStatistics();

        List<StatisticsWaybillResp.OrderBillStatusStatistics> aggregatedList = aggregateRules.entrySet()
                .stream().map(rule -> {
                    List<String> originalStatuses = rule.getKey();
                    String[] aggregateInfo = rule.getValue();
                    // 过滤并汇总对应状态的数量
                    int totalNum = orderStatusStatistics.stream()
                            .filter(stat -> originalStatuses.contains(stat.getOrderStatus()))
                            .mapToInt(stat -> Integer.parseInt(stat.getOrderNum()))
                            .sum();
            // 构建聚合结果对象
            StatisticsWaybillResp.OrderBillStatusStatistics aggregateStat = new StatisticsWaybillResp.OrderBillStatusStatistics();
            aggregateStat.setOrderStatus(aggregateInfo[0]); // 聚合状态编码
            aggregateStat.setOrderStatusDesc(aggregateInfo[1]); // 聚合状态描述
            aggregateStat.setOrderNum(String.valueOf(totalNum)); // 汇总数量
            return aggregateStat;
        }).collect(Collectors.toList());
        aggregatedList.sort(Comparator.comparing(StatisticsWaybillResp.OrderBillStatusStatistics::getOrderStatus));

        waybillResp.setOrderStatusStatistics(aggregatedList);
        return waybillResp;
    }

    /**
     * 物流订单接单
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void orderTaking(OrderCirculateTakingQueryParam param) {
        takingOrderHandler.handler(param);
    }

    /**
     * 取消订单接单
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelWaybillOrder(WaybillOrderCancelParam param) {
        cancelHandler.handler(param);
    }

    /**
     * 到达装货地点-手动推推送数据
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void comeInto(WaybillOrderCmeIntoWeighParam param) {
        comeIntoHandler.handler(param);
    }

    /**
     * 已装货 -手动推推送数据
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void loading(WaybillOrderLoadingParam param) {
        loadingHandler.handler(param);
    }

    /**
     * 场过磅（计算毛重和净重）-手动推推送数据
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void leave(WaybillOrderLeaveMockParam param) {
        leaveMockHandler.handler(param);
    }

    /**
     * 离场
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void leavedWaybillOrder(WaybillOrderLeaveParam param) {
        leaveHandler.handler(param);
    }

    /**
     * 卸货
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void unloadingWaybillOrder(WaybillOrderUnloadParam param) {
        unloadingHandler.handler(param);
    }



//    /**
//     * 物流订单接单
//     * @param param
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public void orderTaking(OrderCirculateTakingQueryParam param){
//        log.info("物流订单接单入参参数：{}", JSON.toJSONString(param));
//
//        //1.校验物流订单
//        KwtLogisticsOrder logOrder = checkLogOrder(param);
//        //2.校验交易订单
//        OrderDetailVo orderDetail = checkTradeOrder(param, logOrder);
//        //3.校验司机
//        RDriverVo driver = checkDriver(param);
//        //4.校验车辆
//        RTruckVo truckNo = checkTruck(param);
//        //5.校验车辆是否已有未完成运单
//        checkTruckUnfinished(param);
//
//        //计算任务量（含接单校验）
//        BigDecimal turckLoadVolume = queryCurTruckLoadVolume(truckNo, orderDetail);
//
//
//        //创建运单及关联数据
//
//        //1、生成物流运单
//        KwtWaybillOrder waybillOrder = createWaybillOrder(param, driver, truckNo);
//
//        //2、生成物流子运单
//        KwtWaybillOrderSubtask waybillOrderSubtask = createWaybillOrderSubtask(param, waybillOrder, turckLoadVolume);
//
//        //3、生成物流运单地址
//        List<KwtWaybillOrderAddress> waybillOrderAdderessList = createWaybillOrderAddress(param, waybillOrder, waybillOrderSubtask);
//
//        //4、生成车辆运单-装卸货信息
//        createWaybillOrderTicket(logOrder, waybillOrder, waybillOrderSubtask, waybillOrderAdderessList, truckNo);
//
//        //5.生成车运单接单节点轨迹
//        createWaybillOrderNode(param, waybillOrder, waybillOrderSubtask);
//
//        //6、更新上游订单：回写贸易订单
//        updateTradeOrder(orderDetail, turckLoadVolume);
//
//        //7、更新上游订单：回写物流订单
//        updateLogOrder(logOrder, turckLoadVolume);
//
//        log.info("物流订单接单完成，运单ID：{}", waybillOrder.getId());
//
//    }
//
//
//
//    /**
//     * 校验物流订单是否是可接单状态
//     * @param param
//     * @return
//     */
//    private KwtLogisticsOrder checkLogOrder(OrderCirculateTakingQueryParam param) {
//        KwtLogisticsOrder logOrder = logisticsOrderRepository.queryByLogOrderIdAndStatus(param.getLogOrderId(), LogisticsOrderV1Enum.IN_TRANSIT.getCode());
//        if (logOrder == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_STATUS_ERROR, "物流订单非可接单状态");
//        }
//        return logOrder;
//    }
//
//    /**
//     * 校验交易订单状态
//     * @param param
//     * @param logOrder
//     * @return
//     */
//    private OrderDetailVo checkTradeOrder(OrderCirculateTakingQueryParam param, KwtLogisticsOrder logOrder) {
//        OrderDetailVo orderDetail = tradeOrderInfoService.queryByTradeOrderId(logOrder.getTOrderId());
//        if (orderDetail == null || orderDetail.getStatus() == Global.NUMERICAL_ONE) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.TRADE_ORDER_STATUS_ERROR, "当前物流订单的交易订单已锁定");
//        }
//        return orderDetail;
//    }
//
//    /**
//     * 校验司机状态
//     * @param param
//     * @return
//     */
//    private RDriverVo checkDriver(OrderCirculateTakingQueryParam param) {
//        RDriverVo driver = remoteFleetService.findDriver(param.getDriverId());
//        if (driver == null || driver.getStatus() == Global.NUMERICAL_ONE) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.DRIVER_STATUS_ERROR, "当前司机已锁定");
//        }
//        return driver;
//    }
//
//    /**
//     * 校验车辆状态
//     * @param param
//     * @return
//     */
//    private RTruckVo checkTruck(OrderCirculateTakingQueryParam param) {
//        RTruckVo truckNo = remoteFleetService.findTruckByTruckNo(param.getTruckNo());
//        if (truckNo == null || truckNo.getStatus() == Global.NUMERICAL_ONE) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "当前车辆已锁定");
//        }
//        //核定载重
//        if (truckNo.getActualWeight() == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.RESOURCE_NOT_FOUND, "车辆核定载重不能为空！");
//        }
//        return truckNo;
//    }
//
//    /**
//     * 校验车辆是否已有未完成运单(不可继续接单状态：已接单、已入场、已装货、已离场、审核驳回)
//     * @param param
//     */
//    private void checkTruckUnfinished(OrderCirculateTakingQueryParam param) {
//        List<KwtWaybillOrder> wbOrderByTruckNo = waybillOrderRepository.findWbOrderByTruckNoAndStatus(param.getTruckNo(), FORBIDDEN_STATUSES);
//        boolean hasForbidden  = wbOrderByTruckNo.stream()
//                .anyMatch(order -> order != null && FORBIDDEN_STATUSES.contains(order.getStatus()));
//        if (hasForbidden) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_UNFINISHED, "当前车辆有未完成的状态，不可继续接单");
//        }
//    }
//
//
//    /**
//     * 计算当前车辆任务量：
//     * 若有皮重：任务量 = 核定载重 - 皮重
//     * 若无皮重：任务量 = 核定载重 × 80%
//     * <p>
//     * 1.当订单余量>=车辆的（法定载重-首次皮重）且<（法定载重-首次皮重 + 2）时，接取的任务量为车辆的（法定载重-首次皮重）；
//     * 2.订单余量<车辆的（法定载重-首次皮重）时，该车辆无法接单；
//     * 3.当订单余量>= (法定载重-首次皮重 + 2)时，接取的任务量为 (法定载重-首次皮重 + 2)
//     *
//     * @param param
//     */
//    private BigDecimal queryCurTruckLoadVolume(RTruckVo truckNo, OrderDetailVo tradeOrder) {
//        //核定载重
//        BigDecimal actualWeight = truckNo.getActualWeight();
//        log.info("车辆核定载重：{}", actualWeight);
//        //首次皮重
//        BigDecimal tareWeight = truckNo.getTareWeight();
//        //任务量
//        BigDecimal loadVolume;
//        if (tareWeight != null) {
//            // 有皮重：任务量 = 核定载重 - 皮重
//            loadVolume = actualWeight.subtract(tareWeight);
//            log.info("车辆有皮重，皮重：{}， 任务量:{}", tareWeight, loadVolume);
//
//        } else {
//            // 无皮重：任务量 = 核定载重 × 80%
//            loadVolume = actualWeight.multiply(EIGHTY_PERCENT);
//            log.info("车辆无皮重，按80%核定载重计算，车辆任务量：{}", loadVolume);
//        }
//
//        //订单分配总量
//        BigDecimal entrustAmount = tradeOrder.getEntrustAmount();
//        //订单实际交付量
//        BigDecimal actualAmount = tradeOrder.getActualAmount();
//        if (entrustAmount == null || actualAmount == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "订单分配总量或订单实际交付量不能为空！");
//        }
//        //订单余量 = 分配总量 - 实际交付量
//        BigDecimal remainingAmount = entrustAmount.subtract(actualAmount);
//        log.info("订单余量 = 分配总量:{} - 实际交付量:{} = 车辆任务量:{}", entrustAmount, actualAmount, remainingAmount);
//
//        // 最终接取的任务量
//        BigDecimal taskAmount;
//        BigDecimal loadVolumePlus2 = loadVolume.add(TWO_TONS);
//        if (remainingAmount.compareTo(loadVolume) < 0) {
//            // 规则2：订单余量 < 任务量 → 无法接单
//            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, String.format("订单余量不足，无法接单, 订单余量:%s, 车辆任务量:%s", remainingAmount, loadVolume));
//        } else if (remainingAmount.compareTo(loadVolumePlus2) >= 0) {
//            // 规则3：订单余量 >= 任务量+2 → 接取任务量+2
//            taskAmount = loadVolumePlus2;
//            log.info("订单余量充足，按(任务量+2吨)接单,最终任务量: {}", taskAmount);
//        } else {
//            // 规则1：订单余量 >= 任务量 且 < 任务量+2 → 接取任务量
//            taskAmount = loadVolume;
//            log.info("订单余量适中，按基础任务量接单，最终任务量: {}", taskAmount);
//        }
//        log.info("最终任务量：{}", taskAmount);
//        return taskAmount;
//    }
//
//    /**
//     * 创建物流运单
//     *
//     * @param param
//     */
//    private KwtWaybillOrder createWaybillOrder(OrderCirculateTakingQueryParam param, RDriverVo driver, RTruckVo truckNo) {
//        log.info("创建物流运单入参参数：{}", JSON.toJSONString(param));
//        KwtWaybillOrder waybillOrder = new KwtWaybillOrder();
//
//        waybillOrder.setEntId(param.getEntId());
//        waybillOrder.setWOrderNo(null);
//        waybillOrder.setType(1);
//        waybillOrder.setTruckId(truckNo.getId());
//        waybillOrder.setTruckNo(param.getTruckNo());
//        waybillOrder.setDriverId(param.getDriverId());
//        waybillOrder.setDriverName(driver.getName());
//        waybillOrder.setDriverPhone(driver.getPhone());
//        waybillOrder.setDriverIdcard(driver.getIdcard());
//        waybillOrder.setStatus(CarWaybillV1Enum.PENDING_VEHICLE.getCode());
//        waybillOrder.setTaskStartTime(new Date());
//        waybillOrderRepository.save(waybillOrder);
//        log.info("创建物流运单成功，运单ID：{}", waybillOrder.getId());
//
//        return waybillOrder;
//
//    }
//
//    /**
//     * 创建物流子运单
//     *
//     * @param param
//     */
//    private KwtWaybillOrderSubtask createWaybillOrderSubtask(OrderCirculateTakingQueryParam param, KwtWaybillOrder waybillOrder,
//                                                             BigDecimal turckLoadVolume) {
//        log.info("创建物流子运单入参参数：{}", JSON.toJSONString(param));
//        KwtWaybillOrderSubtask subtask = new KwtWaybillOrderSubtask();
//
//        subtask.setEntId(param.getEntId());
//        subtask.setLOrderId(param.getLogOrderId());
//        subtask.setWOrderId(waybillOrder.getId());
//        subtask.setWOrderNo(waybillOrder.getWOrderNo());
//        subtask.setUnit(null);
//
//        subtask.setEntrustAmount(turckLoadVolume);
//        subtask.setLoadTime(waybillOrder.getTaskStartTime());
//        subtask.setUnloadTime(waybillOrder.getEndTime());
//        subtask.setStatus(CarWaybillV1Enum.PENDING_VEHICLE.getCode());
//        waybillOrderSubtaskRepository.save(subtask);
//        log.info("创建物流子运单成功，子运单ID：{}", subtask.getId());
//
//        return subtask;
//
//    }
//
//    /**
//     * 创建物流运单地址
//     *
//     * @param param
//     */
//    private List<KwtWaybillOrderAddress> createWaybillOrderAddress(OrderCirculateTakingQueryParam param, KwtWaybillOrder waybillOrder,
//                                                                    KwtWaybillOrderSubtask waybillOrderSubtask) {
//        log.info("创建物流运单地址入参参数，logOrderId：{}", param.getLogOrderId());
//        //地址
//        Map<String, KwtLogisticsOrderAddress> logOrderIdAndAddressMap = getKwtLogisticsOrderAddressMap(Lists.newArrayList(param.getLogOrderId()));
//        List<KwtWaybillOrderAddress> createdAddresses = new ArrayList<>();
//
//        //装货地址
//        KwtLogisticsOrderAddress shipmentSource = logOrderIdAndAddressMap.getOrDefault(
//                param.getLogOrderId() + "-" + AddressTypeEnum.SHIPMENT.getCode(), new KwtLogisticsOrderAddress());
//        KwtWaybillOrderAddress shipmentAddress = createAddress(waybillOrder, waybillOrderSubtask, shipmentSource, AddressTypeEnum.SHIPMENT);
//        createdAddresses.add(shipmentAddress);
//        log.info("创建物流运单装货地址成功，运单地址ID：{}", shipmentAddress.getId());
//
//        //卸货地址
//        KwtLogisticsOrderAddress takeSource = logOrderIdAndAddressMap.getOrDefault(
//                param.getLogOrderId() + "-" + AddressTypeEnum.TAKE.getCode(), new KwtLogisticsOrderAddress());
//        KwtWaybillOrderAddress takeAddress = createAddress(waybillOrder, waybillOrderSubtask, takeSource, AddressTypeEnum.TAKE);
//        createdAddresses.add(takeAddress);
//        log.info("创建物流运单卸货地址成功，运单地址ID：{}", takeAddress.getId());
//
//        log.info("成功创建{}个运单地址", createdAddresses.size());
//        return createdAddresses;
//    }
//
//    /**
//     * 装卸货地址
//     * @param logOrderIdList
//     * @return
//     */
//    private Map<String, KwtLogisticsOrderAddress> getKwtLogisticsOrderAddressMap(List<Long> logOrderIdList) {
//        List<KwtLogisticsOrderAddress> logOrderAddressList = logisticsOrderAddressRepository.queryByLogOrderIds(logOrderIdList);
//        if (CollectionUtils.isEmpty(logOrderAddressList)) {
//            log.info("物流订单无装卸货地址信息，logOrderIdList:{}", JSON.toJSONString(logOrderIdList));
//            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_ADDRESS, "物流订单无装卸货地址信息");
//        }
//        return logOrderAddressList.stream().collect(Collectors
//                .toMap(address -> address.getLOrderId() + "-" + address.getType(),
//                        Function.identity(), (x, y) -> x));
//    }
//
//    /**
//     * 保存运单物流地址
//     * @param waybillOrder
//     * @param waybillOrderSubtask
//     * @param shipmentAddress
//     */
//    private KwtWaybillOrderAddress createAddress(KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask subtask,
//                                                 KwtLogisticsOrderAddress orderAddress, AddressTypeEnum typeEnum) {
//        KwtWaybillOrderAddress address = new KwtWaybillOrderAddress();
//        address.setWOrderId(waybillOrder.getId());
//        address.setWSubtaskId(subtask.getId());
//        address.setLAddressId(orderAddress.getId());
//        address.setAddressType(typeEnum.getCode());
//        address.setName(orderAddress.getName());
//        address.setType(orderAddress.getType());
//        address.setContacts(orderAddress.getContacts());
//        address.setPhone(orderAddress.getPhone());
//        address.setCityCode(orderAddress.getCityCode());
//        address.setCityName(orderAddress.getCityName());
//        address.setDetailAddress(orderAddress.getDetailAddress());
//        address.setLat(orderAddress.getLat());
//        address.setLng(orderAddress.getLng());
//        address.setFence(orderAddress.getFence());
//        address.setEntryType(orderAddress.getEntryType());
//        address.setPlanTime(waybillOrder.getTaskStartTime());
//        address.setSort(Global.NUMERICAL_ONE);
//        address.setEntrustAmount(subtask.getEntrustAmount());
//
//        waybillOrderAddressRepository.save(address);
//        return address;
//
//    }
//
//    /**
//     * 生成车辆运单-装卸货信息
//     *
//     * @param param
//     * @param waybillOrder
//     */
//    private void createWaybillOrderTicket(KwtLogisticsOrder logOrder,
//                                          KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask waybillOrderSubtask,
//                                          List<KwtWaybillOrderAddress> waybillOrderAddresses, RTruckVo truckNo) {
//        log.info("创建车辆运单-装卸货信息入参参数， 运单ID{}",logOrder.getLOrderNo());
//
//        //装货地址
//        KwtWaybillOrderAddress shipmentAddress = getWaybillOrderAddress(waybillOrderAddresses, AddressTypeEnum.SHIPMENT);
//        createTicket(waybillOrder, waybillOrderSubtask, shipmentAddress, logOrder, truckNo);
//        log.info("创建车辆运单-装卸货信息成功！");
//
//        //卸货地址
//        KwtWaybillOrderAddress takeAddress = getWaybillOrderAddress(waybillOrderAddresses, AddressTypeEnum.TAKE);
//        createTicket(waybillOrder, waybillOrderSubtask, takeAddress, logOrder, truckNo);
//        log.info("创建车辆运单-装卸货信息成功！");
//
//    }
//
//
//    /**
//     * 运单地址(装货、卸货地址)
//     *
//     * @param waybillOrderAddresses
//     * @param typeEnum
//     * @return
//     */
//    private KwtWaybillOrderAddress getWaybillOrderAddress(List<KwtWaybillOrderAddress> waybillOrderAddresses, AddressTypeEnum typeEnum) {
//        return waybillOrderAddresses.stream()
//                .filter(address -> address != null && typeEnum.getCode() == address.getType())
//                .findFirst()
//                .orElseThrow(() -> new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_ADDRESS_NOT_FOUND, "未找到装货地址数据！"));
//    }
//
//    /**
//     * 保存车辆运单-装卸货信息
//     *
//     * @param waybillOrder
//     * @param waybillOrderSubtask
//     * @param shipmentAddress
//     */
//    private void createTicket(KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask waybillOrderSubtask,
//                              KwtWaybillOrderAddress shipmentAddress, KwtLogisticsOrder logOrder, RTruckVo truckNo) {
//        KwtWaybillOrderTicket ticket = new KwtWaybillOrderTicket();
//        ticket.setWOrderId(waybillOrder.getId());
//        ticket.setWSubtaskId(waybillOrderSubtask.getId());
//        ticket.setWAddressId(shipmentAddress.getId());
//        ticket.setType(shipmentAddress.getAddressType());
//        ticket.setUnit(logOrder.getUnit());
//        ticket.setAmount(BigDecimal.ZERO);
//        ticket.setGrossAmount(truckNo.getGrossWeight());
//        ticket.setTareAmount(truckNo.getTareWeight());
//        waybillOrderTicketRepository.save(ticket);
//    }
//
//
//    /**
//     * 生成车辆运单-节点轨迹
//     *
//     * @param param
//     * @param waybillOrder
//     */
//    private void createWaybillOrderNode(OrderCirculateTakingQueryParam param, KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask waybillOrderSubtask) {
//        log.info("创建车辆运单-节点轨迹入参参数：{}", JSON.toJSONString(param));
//        KwtWaybillOrderNode orderNode = new KwtWaybillOrderNode();
//        orderNode.setWOrderId(waybillOrder.getId());
//        orderNode.setWSubtaskId(waybillOrderSubtask.getWOrderId());
//        orderNode.setOrderStatus(waybillOrder.getStatus());
//        orderNode.setTruckId(waybillOrder.getTruckId());
//        orderNode.setTruckNo(waybillOrder.getTruckNo());
//        orderNode.setDriverId(waybillOrder.getDriverId());
//        orderNode.setDriverName(waybillOrder.getDriverName());
//        orderNode.setLng(param.getLng());
//        orderNode.setLat(param.getLat());
//        waybillOrderNodeRepository.save(orderNode);
//        log.info("创建车辆运单-节点轨迹成功，节点轨迹ID：{}", orderNode.getId());
//    }
//
//    /**
//     * 回写贸易订单数据
//     * @param param
//     */
//    private void updateTradeOrder(OrderDetailVo orderDetail, BigDecimal truckLoadVolume) {
//        log.info("更新上游贸易订单运输量数据，tradeOrderId：{}", orderDetail.getId());
//        // 计算当前车辆运输量
//        BigDecimal totalLoadVolume = Optional.ofNullable(orderDetail.getActualAmount())
//                .map(entrust -> entrust.add(truckLoadVolume))
//                .orElse(truckLoadVolume);
//
//        UpdateActualAmountParam tradeParam = new UpdateActualAmountParam();
//        tradeParam.setTOrderId(orderDetail.getId());
//        tradeParam.setActualLoadAmount(totalLoadVolume);
//        tradeOrderInfoService.updateOrderActualAmount(tradeParam);
//        log.info("更新上游贸易订单运输量成功, 贸易订单ID：{}", orderDetail.getId());
//    }
//
//
//    /**
//     * 回写物流订单数据
//     * @param param
//     */
//    private void updateLogOrder(KwtLogisticsOrder logOrder, BigDecimal truckLoadVolume) {
//        log.info("更新上游物流运输量数据，logOrderId：{}", logOrder);
//        // 计算当前车辆总运输量
//        BigDecimal totalLoadVolume = Optional.ofNullable(logOrder.getEntrustAmount())
//                .map(entrust -> entrust.add(truckLoadVolume))
//                .orElse(truckLoadVolume);
//
//        logOrder.setEntrustAmount(totalLoadVolume);
//        logisticsOrderRepository.updateById(logOrder);
//        log.info("更新上游物流运输量成功, 物流订单ID：{}", logOrder.getId());
//    }
//
//    /**
//     * 取消订单
//     *
//     * @param waybillOrderId
//     * @return
//     */
//    public void cancelWaybillOrder(WaybillOrderCancelParam param) {
//        log.info("取消订单接单入参参数：{}", JSON.toJSONString(param));
//        //1.取消物流运单
//        BigDecimal entrustAmount = updateWaybillOrder(param);
//
//        //2.更新上游订单：更新物流订单运输量
//        KwtLogisticsOrder logOrder = updateLogOrder(param, entrustAmount);
//
//        //3.更新上游订单：更新贸易订单运输量
//        updateTradeOrder(logOrder, entrustAmount);
//
//
//        log.info("取消接单成功！");
//    }
//
//    /**
//     * 更改物流运单状态
//     * @param param
//     * @return
//     */
//    private BigDecimal updateWaybillOrder(WaybillOrderCancelParam param) {
//        KwtWaybillOrder waybillOrder = waybillOrderRepository.queryByBillOrderId(param.getWaybillOrderId());
//        if (waybillOrder == null || CarWaybillV1Enum.PENDING_VEHICLE.getCode() != waybillOrder.getStatus()) {
//            log.info("当前物流运单状态不可取消， waybillOrderId：{}", param.getWaybillOrderId());
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "当前物流运单状态不可取消！");
//        }
//        waybillOrder.setStatus(CarWaybillV1Enum.APPROVAL_TREAT.getCode());
//        waybillOrderRepository.updateById(waybillOrder);
//        log.info("取消物流运单成功, 物流运单ID：{}", waybillOrder.getId());
//
//        //车辆本次运输量
//        KwtWaybillOrderSubtask orderSubtask = waybillOrderSubtaskRepository.queryByWOrderId(waybillOrder.getId());
//        BigDecimal entrustAmount = orderSubtask.getEntrustAmount();
//
//        //生成取消接单节点轨迹
//        createEnteredWaybillOrderNode(param.getLng(), param.getLat(), waybillOrder, CarWaybillV1Enum.APPROVAL_TREAT);
//
//        return entrustAmount;
//    }
//
//    /**
//     * 更新上游物流订单 - 减运输量
//     * @param param
//     * @param entrustAmoun
//     * @return
//     */
//    private KwtLogisticsOrder updateLogOrder(WaybillOrderCancelParam param, BigDecimal entrustAmount) {
//        KwtLogisticsOrder logOrder = logisticsOrderRepository.queryByLogisticsOrderId(param.getLogOrderId());
//        if (logOrder == null) {
//            log.info("当前物流运单无关联物流订单数据：{}", param.getLogOrderId());
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_LOG_ORDER, "当前物流运单无关联物流订单数据！");
//        }
//
//        //取消接单的物流订单的总运输量不能为空
//        if (logOrder.getEntrustAmount() == null || logOrder.getEntrustAmount().compareTo(BigDecimal.ZERO) <= 0) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_AMOUNT_ERROR, "已接单物订单的总运单量不能为空或0！");
//        }
//        logOrder.setEntrustAmount(logOrder.getEntrustAmount().subtract(entrustAmount));
//        logisticsOrderRepository.updateById(logOrder);
//        log.info("更新上游物流订单运输量成功, 物流订单ID：{}", logOrder.getId());
//        return logOrder;
//    }
//
//
//    /**
//     * 更新上游贸易订单 - 减运输量
//     * @param logOrder
//     * @param entrustAmount
//     */
//    private void updateTradeOrder(KwtLogisticsOrder logOrder, BigDecimal entrustAmount) {
//        OrderDetailVo tradeOrder = tradeOrderInfoService.queryByTradeOrderId(logOrder.getTOrderId());
//        //取消接单的物流订单的总运输量不能为空
//        if (tradeOrder.getActualAmount() == null || tradeOrder.getActualAmount().compareTo(BigDecimal.ZERO) <= 0) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.TRADE_ORDER_AMOUNT_ERROR, "已接单交易订单的总运输量不能为空或0！");
//        }
//
//        UpdateActualAmountParam tradeParam = new UpdateActualAmountParam();
//        tradeParam.setTOrderId(tradeOrder.getId());
//        tradeParam.setActualLoadAmount(tradeOrder.getActualAmount().subtract(entrustAmount));
//        tradeOrderInfoService.updateOrderActualAmount(tradeParam);
//        log.info("更新上游贸易订单运输量成功, 贸易订单ID：{}", tradeOrder.getId());
//    }
//
//
//    /**
//     * 到达装货地点
//     * @param waybillOrderId
//     * @return
//     */
//    public void comeInto(WaybillOrderCmeIntoWeighParam param){
//        log.info("推送物流运单状态到到达装货地点：{}", JSON.toJSONString(param));
//        //1.修改物流运单状态-到达装货地点
//        KwtWaybillOrder waybillOrder = updateWaybillOrderStayus(param.getWaybillOrderId(), CarWaybillV1Enum.PENDING_VEHICLE, CarWaybillV1Enum.REFUSE_TRAFFIC);
//        waybillOrderRepository.updateById(waybillOrder);
//
//        //2.填充运单皮重
//        LambdaQueryWrapper<KwtWaybillOrderTicket>  queryWrapper = Wrappers.<KwtWaybillOrderTicket>lambdaQuery()
//                .eq(KwtWaybillOrderTicket::getWOrderId, param.getWaybillOrderId())
//                .eq(KwtWaybillOrderTicket::getType, AddressTypeEnum.SHIPMENT.getCode());
//        KwtWaybillOrderTicket orderTicket = waybillOrderTicketRepository.getOne(queryWrapper);
//        orderTicket.setTareAmount(param.getTareAmount());
//        waybillOrderTicketRepository.save(orderTicket);
//
//        //3.填充首次皮重
//        RTruckVo truck = remoteFleetService.findTruckByTruckNo(param.getTruckNo());
//        if (truck != null && truck.getTareWeight() == null) {
//            RTruckVo truckNo = new RTruckVo();
//            truckNo.setId(truck.getId());
//            truckNo.setTareWeight(param.getTareAmount());
//            remoteFleetService.updateTruckTareAmount(truckNo);
//        }
//        //4.生成到达装货地点节点轨迹
//        createEnteredWaybillOrderNode(param.getLng(), param.getLat(), waybillOrder, CarWaybillV1Enum.REFUSE_TRAFFIC);
//
//        log.info("物流运单到达装货地点成功！");
//    }
//
//    /**
//     * 已装货
//     * @param waybillOrderId
//     * @return
//     */
//    public void loading(WaybillOrderLoadingParam param){
//        log.info("推送物流运单状态到已装货：{}", JSON.toJSONString(param));
//        //1.修改物流运单状态-已装货
//        KwtWaybillOrder waybillOrder = updateWaybillOrderStayus(param.getWaybillOrderId(), CarWaybillV1Enum.REFUSE_TRAFFIC, CarWaybillV1Enum.EXIT_COMPLETED);
//        waybillOrderRepository.updateById(waybillOrder);
//
//        //2.生成已已装货节点轨迹
//        createEnteredWaybillOrderNode(param.getLng(), param.getLat(), waybillOrder, CarWaybillV1Enum.EXIT_COMPLETED);
//        log.info("物流运单装货成功！");
//    }
//
//    /**
//     * 离场过磅-计算毛重和装货净重
//     * @param waybillOrderId
//     * @return
//     */
//    public void leave(WaybillOrderLeaveMockParam param){
//        log.info("离场过磅-计算毛重和净重, 入参参数：{}", JSON.toJSONString(param));
//        //校验运单状态
//        KwtWaybillOrder waybillOrder = waybillOrderRepository.queryByBillOrderId(param.getWaybillOrderId());
//        if (waybillOrder == null) {
//            log.warn("物流运单不存在，waybillOrderId：{}", param.getWaybillOrderId());
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_FOUND, "物流运单不存在！");
//        }
//        if (CarWaybillV1Enum.EXIT_COMPLETED.getCode() != waybillOrder.getStatus()) {
//            log.warn("运单状态不符合离场过磅条件，当前状态: {}, 要求状态: 已装货, waybillOrderId: {}", waybillOrder.getStatus(), waybillOrder.getId());
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "运单状态不符合离场过磅条件，无法推进下一节点！");
//        }
//
//        //记录毛重和装货净重
//        paddingGrossAndLoadAmount(param, waybillOrder);
//    }
//
//    /**
//     * 记录毛重和装货净重
//     * @param param
//     * @param waybillOrder
//     */
//    private void paddingGrossAndLoadAmount(WaybillOrderLeaveMockParam param, KwtWaybillOrder waybillOrder) {
//        List<KwtWaybillOrderTicket> ticketList = waybillOrderTicketRepository.queryByWOrderId(param.getWaybillOrderId());
//        // 按 type 分组
//        Map<Integer, KwtWaybillOrderTicket> ticketMap = ticketList.stream()
//                .collect(Collectors.toMap(KwtWaybillOrderTicket::getType, Function.identity(), (a, b) -> a));
//        //1.填充毛重
//        updateGrossAmount(param, ticketMap);
//        //2.填充装货净重
//        updateLoadAmount(param, waybillOrder, ticketMap);
//    }
//
//    /**
//     * 填充毛重
//     * @param param
//     * @param ticketMap
//     */
//    private void updateGrossAmount(WaybillOrderLeaveMockParam param, Map<Integer, KwtWaybillOrderTicket> ticketMap) {
//        //查询卸货信息，用于记录毛重
//        KwtWaybillOrderTicket takeTicket = ticketMap.getOrDefault(AddressTypeEnum.TAKE.getCode(), new KwtWaybillOrderTicket());
//        if (takeTicket == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_TICKET_NOT_FOUND, "当前物流运单装卸货信息不存在，无法记录毛重！");
//        }
//        takeTicket.setGrossAmount(param.getGrossAmount());
//        waybillOrderTicketRepository.updateById(takeTicket);
//    }
//
//    /**
//     * 填充装货净重
//     * @param param
//     * @param waybillOrder
//     * @param ticketMap
//     */
//    private void updateLoadAmount(WaybillOrderLeaveMockParam param, KwtWaybillOrder waybillOrder, Map<Integer, KwtWaybillOrderTicket> ticketMap) {
//        //查询卸货信息，用于获取皮重
//        KwtWaybillOrderTicket shipmentTicket  = ticketMap.getOrDefault(AddressTypeEnum.SHIPMENT.getCode(), new KwtWaybillOrderTicket());
//        if (shipmentTicket == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_TICKET_NOT_FOUND, "当前物流运单装卸货信息不存在，无法获取皮重！");
//        }
//        //皮重
//        BigDecimal tareAmount = shipmentTicket.getTareAmount();
//
//        //更新子运单的装货净重
//        KwtWaybillOrderSubtask subtask = waybillOrderSubtaskRepository.queryByWOrderId(waybillOrder.getId());
//        if (subtask == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_SUB_NOT_FOUND, "未找到关联的子运单！");
//        }
//        BigDecimal loadAmount = param.getGrossAmount().subtract(Optional.ofNullable(tareAmount).orElse(BigDecimal.ZERO));
//        subtask.setLoadAmount(loadAmount);
//        subtask.setLoadTime(new Date());
//        waybillOrderSubtaskRepository.updateById(subtask);
//        log.info("物流运单离场过磅成功！运单ID: {}, 毛重: {}, 皮重: {}, 装货净重: {}", param.getWaybillOrderId(), param.getGrossAmount(), tareAmount, loadAmount);
//    }
//
//
//    /**
//     * 离场
//     * @param waybillOrderId
//     * @return
//     */
//    public void leavedWaybillOrder(WaybillOrderLeaveParam param){
//        log.info("推送物流运单状态到已离场：{}", JSON.toJSONString(param));
//        //1.修改物流运单状态-离场
//        KwtWaybillOrder waybillOrder = updateWaybillOrderStayus(param.getWaybillOrderId(), CarWaybillV1Enum.EXIT_COMPLETED, CarWaybillV1Enum.WAIT_LOADING);
//        waybillOrderRepository.updateById(waybillOrder);
//
//        //2.生成已已装货节点轨迹
//        createEnteredWaybillOrderNode(param.getLng(), param.getLat(), waybillOrder, CarWaybillV1Enum.WAIT_LOADING);
//        log.info("物流运单离场成功！");
//    }
//
//    /**
//     * 卸货
//     * @param waybillOrderId
//     * @return
//     */
//    public void unloadingWaybillOrder(WaybillOrderUnloadParam param){
//        log.info("推送物流运单状态到已卸货：{}", JSON.toJSONString(param));
//        //1.修改物流运单状态-已卸货
//        KwtWaybillOrder waybillOrder = updateWaybillOrderStayus(param.getWaybillOrderId(), CarWaybillV1Enum.WAIT_LOADING, CarWaybillV1Enum.COMPLETION_LOADING);
//        waybillOrderRepository.updateById(waybillOrder);
//
//        //2.更新子运单卸货净重  TODO 审核通过后，贸易订单和物流订单的运输量需要已实际卸货净重为准
//        KwtWaybillOrderSubtask subtask = waybillOrderSubtaskRepository.queryByWOrderId(waybillOrder.getId());
//        if (subtask == null) {
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_SUB_NOT_FOUND, "未找到关联的子运单！");
//        }
//        subtask.setUnloadAmount(param.getUnloadAmount());
//        subtask.setUnloadTime(new Date());
//        waybillOrderSubtaskRepository.updateById(subtask);
//
//        //3.生成已卸货节点轨迹
//        createEnteredWaybillOrderNode(param.getLng(), param.getLat(), waybillOrder, CarWaybillV1Enum.COMPLETION_LOADING);
//        log.info("物流运单卸货成功！");
//    }
//
//    /**
//     * 更改物流订单状态
//     * @param param
//     * @param startTypeEnum
//     * @param endTypeEnum
//     */
//    private KwtWaybillOrder updateWaybillOrderStayus(Long waybillOrderId, CarWaybillV1Enum startTypeEnum, CarWaybillV1Enum endTypeEnum) {
//        KwtWaybillOrder waybillOrder = waybillOrderRepository.queryByBillOrderId(waybillOrderId);
//        if (waybillOrder == null) {
//            log.error("物流运单不存在，waybillOrderId：{}", waybillOrderId);
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_FOUND, "物流运单不存在！");
//        }
//
//        if (startTypeEnum.getCode() != waybillOrder.getStatus()) {
//            log.info("当前物流运单状态不正确，无法推进下一节点， waybillOrderId：{}", waybillOrderId);
//            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "当前物流运单状态不正确，无法推进下一节点！");
//        }
//        //更改物流运单状态
//        waybillOrder.setStatus(endTypeEnum.getCode());
//        return waybillOrder;
//    }
//
//    /**
//     *  生成运单节点轨迹
//     * @param param
//     * @param waybillOrder
//     */
//    private void createEnteredWaybillOrderNode(String lng, String lat, KwtWaybillOrder waybillOrder, CarWaybillV1Enum carWaybillV1Enum) {
//        log.info("创建车辆运单节点轨迹入参参数, wOrderId: {}", waybillOrder.getWOrderId());
//        List<KwtWaybillOrderSubtask> waybillOrderSubtaskList = waybillOrderSubtaskRepository.queryByLogId(waybillOrder.getLOrderId());
//        KwtWaybillOrderSubtask waybillOrderSubtask = Optional.ofNullable(waybillOrderSubtaskList)
//                .stream()
//                .flatMap(List::stream)
//                .filter(Objects::nonNull)
//                .findFirst()
//                .orElseThrow(() -> new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_SUB_NOT_FOUND, "未找到有效的子运单"));
//
//        KwtWaybillOrderNode orderNode = new KwtWaybillOrderNode();
//        orderNode.setWOrderId(waybillOrder.getId());
//        orderNode.setWSubtaskId(waybillOrderSubtask.getWOrderId());
//        orderNode.setOrderStatus(carWaybillV1Enum.getCode());
//        orderNode.setTruckId(waybillOrder.getTruckId());
//        orderNode.setTruckNo(waybillOrder.getTruckNo());
//        orderNode.setDriverId(waybillOrder.getDriverId());
//        orderNode.setDriverName(waybillOrder.getDriverName());
//        orderNode.setLng(lng);
//        orderNode.setLat(lat);
//        waybillOrderNodeRepository.save(orderNode);
//        log.info("创建车辆运单节点轨迹，节点轨迹ID：{}", orderNode.getId());
//    }


}
