package com.sckw.transport.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.feign.LogisticsScoreFeignService;
import com.sckw.contract.api.model.dto.req.LogisticsScoreDetailFeignDto;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.core.model.enums.DispatchWayEnums;
import com.sckw.core.model.enums.LogisticsOrderV1Enum;
import com.sckw.core.utils.DateUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.BaseResult;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.fleet.api.model.dto.RUpdateDriverScoreDto;
import com.sckw.fleet.api.model.vo.DriverConductRulesVO;
import com.sckw.fleet.api.model.vo.TruckDispatchCoefficientVO;
import com.sckw.payment.api.feign.PaymentFeignService;
import com.sckw.payment.api.model.feign.WalletPayableDto;
import com.sckw.transport.model.*;
import com.sckw.transport.repository.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @desc: 物流订单自动完成定时任务
 * @desc: 查询状态为"完结中"的物流订单，如果该订单下的所有运单状态都是"已完成"，则将物流订单状态更新为"已完成"
 * @author: cxf
 * @date: 2025-12-19
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LogisticsOrderCompletionTask {

    private final KwtLogisticsOrderRepository logisticsOrderRepository;
    private final KwtWaybillOrderSubtaskRepository waybillOrderSubtaskRepository;
    private final KwtWaybillOrderRepository waybillOrderRepository;
    private final KwtLogisticsOrderUnitRepository logisticsOrderUnitRepository;
    private final KwtLogisticsOrderContractRepository logisticsOrderContractRepository;
    private final KwtWaybillOrderNodeRepository waybillOrderNodeRepository;

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

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

    @Autowired
    LogisticsScoreFeignService logisticsScoreFeignService;


    @Autowired
    private KwtLogisticsOrderUnitRepository kwtLogisticsOrderUnitRepository;

    @Autowired
    private PaymentFeignService paymentFeignService;


    /**
     * 定时任务：每5分钟执行一次
     * cron表达式：0 0/5 * * * ? 表示每5分钟执行一次
     * 可以根据实际需求调整执行频率
     */
    @Scheduled(cron = "${schedule.logistics-order-completion-cron}")
    public void process() {
        log.info("物流订单自动完成定时任务开始...");

        try {
            // 查询状态为"完结中"的物流订单
            List<KwtLogisticsOrder> nearingCompletionOrders = logisticsOrderRepository.list(
                    new LambdaQueryWrapper<KwtLogisticsOrder>()
                            .eq(KwtLogisticsOrder::getStatus, LogisticsOrderV1Enum.NEARING_COMPLETION.getCode())
                            .eq(KwtLogisticsOrder::getDelFlag, 0)
            );

            if (CollectionUtils.isEmpty(nearingCompletionOrders)) {
                log.info("没有状态为'完结中'的物流订单需要处理");
                return;
            }

            log.info("查询到{}条状态为'完结中'的物流订单", nearingCompletionOrders.size());

            // 提取物流订单ID列表
            List<Long> logisticOrderIds = nearingCompletionOrders
                    .stream()
                    .map(KwtLogisticsOrder::getId)
                    .collect(Collectors.toList());

            Map<Long, KwtLogisticsOrder> logisticOrderMap = nearingCompletionOrders.stream().collect(Collectors.toMap(KwtLogisticsOrder::getId, Function.identity()));

            // 根据物流订单ID查询相关运单子任务
            List<KwtWaybillOrderSubtask> subtasks = waybillOrderSubtaskRepository.queryByLogIds(logisticOrderIds);

            // 按照物流订单ID分组运单子任务
            Map<Long, List<KwtWaybillOrderSubtask>> logOrderSubtasksMap = Optional.ofNullable(subtasks)
                    .orElse(Collections.emptyList()).stream().collect(Collectors.groupingBy(KwtWaybillOrderSubtask::getLOrderId));

            // 准备需要更新的物流订单列表
            List<KwtLogisticsOrder> updateLogisticOrders = new ArrayList<>();
            //已完结需要计算运费的物流订单
            List<KwtLogisticsOrder> completeLogisticOrders = new ArrayList<>();

            // 遍历每个物流订单及其关联的运单子任务
            logOrderSubtasksMap.forEach((logOrderId, subtaskList) -> {
                try {
                    // 如果没有运单，跳过
                    if (CollectionUtils.isEmpty(subtaskList)) {
                        log.warn("物流订单[{}]下没有运单，跳过处理", logOrderId);
                        return;
                    }

                    // 检查所有运单状态是否都是"已完成"（COMPLETED）和已取消（CANCELLED）

                    List<Integer> statusList = Arrays.asList(CarWaybillV1Enum.COMPLETED.getCode(), CarWaybillV1Enum.CANCELLED.getCode());
                    boolean allCompleted = subtaskList.stream()
                            .allMatch(subtask -> statusList.contains(subtask.getStatus()));

                    if (allCompleted) {
                        // 更新物流订单状态为"已完成"
                        KwtLogisticsOrder updateOrder = new KwtLogisticsOrder();
                        updateOrder.setId(logOrderId);
                        updateOrder.setStatus(LogisticsOrderV1Enum.COMPLETED.getCode());
                        updateOrder.setUpdateTime(new Date());
                        // 定时任务更新，updateBy 可以设置为系统用户或0
                        updateOrder.setUpdateBy(0L);
                        updateLogisticOrders.add(updateOrder);
                        completeLogisticOrders.add(logisticOrderMap.get(logOrderId));

                    } else {
                        // 存在未完成的运单，记录日志
                        long completedCount = subtaskList.stream()
                                .filter(subtask -> Objects.equals(subtask.getStatus(), CarWaybillV1Enum.COMPLETED.getCode()))
                                .count();
                        log.debug("物流订单下还有未完成的运单，已完成运单数:{}/{}，订单ID:{}",
                                completedCount, subtaskList.size(), logOrderId);
                    }
                } catch (Exception e) {
                    log.error("处理物流订单时发生异常，订单ID:{}", logOrderId, e);
                }
            });
            // 如果没有需要更新的物流订单，则直接返回
            if (CollectionUtils.isEmpty(updateLogisticOrders)){
                log.info("没有需要更新状态的物流订单");
                return;
            }

            // 批量更新物流订单状态
            boolean updated = logisticsOrderRepository.updateBatchById(updateLogisticOrders);
            //计算运费
            calculateFreight(completeLogisticOrders);
            Set<Long> logOrderIds = updateLogisticOrders.stream().map(KwtLogisticsOrder::getId).collect(Collectors.toSet());

            // 记录更新结果日志
            if (updated) {
                log.info("物流订单自动完成定时任务结束,物流订单已更新为'已完成'，订单ID:{},成功:{}条", JSON.toJSONString(logOrderIds), logOrderIds.size());
            } else {
                log.error("物流订单自动完成定时任务结束,物流订单状态更新失败，订单ID:{},失败:{}条", JSON.toJSONString(logOrderIds), logOrderIds.size());
            }
        } catch (Exception e) {
            log.error("物流订单自动完成定时任务执行异常", e);
            throw new BusinessException("物流订单自动完成定时任务执行异常", e);
        }
    }

    private void calculateFreight(List<KwtLogisticsOrder> completeLogisticOrders){
        for (KwtLogisticsOrder logisticsOrder : completeLogisticOrders) {
            //物流订单已完结，计算待付运费
            if(Objects.equals(logisticsOrder.getSettlement(),1)){
                //todo 普通结算

            }else if(Objects.equals(logisticsOrder.getSettlement(),2)) {
                //记账模式
                //1解冻运费
                List<KwtLogisticsOrderUnit> orderUnits = kwtLogisticsOrderUnitRepository.queryByLOrderId(logisticsOrder.getId());
                Map<Integer, Long> map = orderUnits.stream().collect(Collectors.toMap(KwtLogisticsOrderUnit::getUnitType, KwtLogisticsOrderUnit::getEntId, (v1, v2) -> v1));
                WalletPayableDto unFreezePayableDto = new WalletPayableDto();
                unFreezePayableDto.setConsignEntId(map.get(1));
                unFreezePayableDto.setCarriageEntId(map.get(2));
                unFreezePayableDto.setOrderNo(logisticsOrder.getLOrderNo());
                unFreezePayableDto.setOrderType(5);
                unFreezePayableDto.setTradeType(5);
                unFreezePayableDto.setRemark("物流订单号：" + unFreezePayableDto.getOrderNo() + "，订单完结解冻");
                log.info("物流订单号：{}，订单完结解冻进行中运费，参数：{}", unFreezePayableDto.getOrderNo(),JSON.toJSONString(unFreezePayableDto));
                BaseResult<Object> unFreezeResult = paymentFeignService.updatePayable(unFreezePayableDto);
                if(unFreezeResult.getCode()!= HttpStatus.SUCCESS_CODE){
                    log.error("物流订单号：{}，订单完结解冻失败,异常信息为：{}",unFreezePayableDto.getOrderNo(),unFreezeResult.getMessage());
                    throw new BusinessException("物流订单号："+unFreezePayableDto.getOrderNo()+"，订单完结解冻失败");
                }
                //2计算待付运费
                WalletPayableDto consumePayableDto = new WalletPayableDto();
                consumePayableDto.setConsignEntId(map.get(1));
                consumePayableDto.setCarriageEntId(map.get(2));
                consumePayableDto.setOrderNo(logisticsOrder.getLOrderNo());
                consumePayableDto.setOrderType(5);
                consumePayableDto.setTradeType(6);
                if (org.apache.commons.lang3.StringUtils.equals(logisticsOrder.getBillingMode(), DictEnum.CHARGING_TYPE_1.getValue())) {
                    BigDecimal actualPrice = Objects.nonNull(logisticsOrder.getPrice()) && Objects.nonNull(logisticsOrder.getTotalLoadAmount()) ?
                            logisticsOrder.getPrice().multiply(logisticsOrder.getTotalLoadAmount()) : BigDecimal.ZERO;
                    consumePayableDto.setTradeAmount(actualPrice);
                } else if (org.apache.commons.lang3.StringUtils.equals(logisticsOrder.getBillingMode(), DictEnum.CHARGING_TYPE_2.getValue())) {
                    BigDecimal actualPrice = Objects.nonNull(logisticsOrder.getPrice()) && Objects.nonNull(logisticsOrder.getTotalUnloadAmount()) ?
                            logisticsOrder.getPrice().multiply(logisticsOrder.getTotalUnloadAmount()) : BigDecimal.ZERO;
                    consumePayableDto.setTradeAmount(actualPrice);
                }
                consumePayableDto.setRemark("物流订单号：" + consumePayableDto.getOrderNo() + "，订单完结消费");
                log.info("物流订单号：{}，订单完结消费，参数：{}", consumePayableDto.getOrderNo(),JSON.toJSONString(consumePayableDto));
                BaseResult<Object> consumeResult = paymentFeignService.updatePayable(consumePayableDto);
                if(consumeResult.getCode()!= HttpStatus.SUCCESS_CODE){
                    log.error("物流订单号：{}，订单完结消费失败,异常信息为：{}",consumePayableDto.getOrderNo(),consumeResult.getMessage());
                    throw new BusinessException("物流订单号："+consumePayableDto.getOrderNo()+"，订单完结消费失败");
                }
            }
        }

    }


    /**
     * 定时任务：每2分钟执行一次
     * cron表达式：0 0/2 * * * ? 表示每2分钟执行一次
     * 可以根据实际需求调整执行频率
     */
    @Scheduled(cron = "${schedule.waybill-order-completion-cron}")
    public void processWaybillOrder() {
        log.info("超时取消运单定时任务开始...");
        try {
            // 查询状态为"已接单"的物流运单
            List<KwtWaybillOrder> waybillOrderOrders = waybillOrderRepository.list(
                    new LambdaQueryWrapper<KwtWaybillOrder>()
                            .eq(KwtWaybillOrder::getStatus, CarWaybillV1Enum.PENDING_VEHICLE.getCode())
                            .eq(KwtWaybillOrder::getDispatchWay, DispatchWayEnums.AUTO_DISPATCH.getCode())
                            .eq(KwtWaybillOrder::getDelFlag, 0)
            );
            if (CollectionUtils.isEmpty(waybillOrderOrders)) {
                log.info("没有状态为'已接单'的物流运单需要处理");
                return;
            }

            //运单根据物流订单id分组
            Map<Long, List<KwtWaybillOrder>> waybillOrderAndLogOrderMap = waybillOrderOrders.stream()
                    .collect(Collectors.groupingBy(KwtWaybillOrder::getLOrderId));

            //提取物流订单id
            Set<Long> logisticOrderIds = waybillOrderOrders.stream().map(KwtWaybillOrder::getLOrderId).collect(Collectors.toSet());

            //物流订单和企业映射
            List<KwtLogisticsOrderUnit> logisticsOrderUnits = logisticsOrderUnitRepository.queryByLOrderIdsAndUnitType(logisticOrderIds, 1);
            Map<Long, KwtLogisticsOrderUnit> logisticsOrderAndUnitMap = logisticsOrderUnits.stream()
                    .collect(Collectors.toMap(KwtLogisticsOrderUnit::getLOrderId, Function.identity(), (x, y) -> x));
            if (MapUtils.isEmpty(logisticsOrderAndUnitMap)) {
                throw new BusinessPlatfromException(ErrorCodeEnum.DATA_NOT_EXIST, "未找的物流订单和企业映射信息！");
            }

            // 过滤超时的运单
            List<KwtWaybillOrder> nearingCompletionOrders = getKwtWaybillOrders(waybillOrderAndLogOrderMap, logisticsOrderAndUnitMap);

            // 如果没有需要更新的物流运单，则直接返回
            if (CollectionUtils.isEmpty(nearingCompletionOrders)){
                log.info("没有需要超时取消运单物流运单");
                return;
            }

            List<KwtWaybillOrder> successOrders = new ArrayList<>();
            for (KwtWaybillOrder waybillOrder : nearingCompletionOrders) {
                try {
                    //执行取消运单
                    processSingleWaybillOrder(waybillOrder, logisticsOrderAndUnitMap);
                    //异步处理
                    handleCancelActions(waybillOrder, logisticsOrderAndUnitMap);
                    successOrders.add(waybillOrder);
                } catch (Exception e) {
                    log.error("处理运单ID:{} 失败", waybillOrder.getId(), e);
                }
            }

            log.info("查询到{}条状态为'已接单'的物流运单", nearingCompletionOrders.size());
        } catch (Exception e) {
            log.error("超时取消运单定时任务执行异常", e);
            throw new BusinessException("超时取消运单定时任务执行异常", e);
        }
    }

    /**
     * 过滤超时的运单
     * @param waybillOrderAndLogOrderMap
     * @param logisticsOrderAndUnitMap
     * @return
     */
    private List<KwtWaybillOrder> getKwtWaybillOrders(Map<Long, List<KwtWaybillOrder>> waybillOrderAndLogOrderMap,
                                                      Map<Long, KwtLogisticsOrderUnit> logisticsOrderAndUnitMap) {
        //过滤超时的运单
        List<KwtWaybillOrder> nearingCompletionOrders = new ArrayList<>();

        //供应商企业id
        List<Long> entIds = logisticsOrderAndUnitMap.values().stream().map(KwtLogisticsOrderUnit::getEntId).distinct().collect(Collectors.toList());
        //查询自动派车系数
        List<TruckDispatchCoefficientVO> dispatchList = remoteFleetService.findAutoTruckDispatchByEntIds(entIds);
        Map<Long, TruckDispatchCoefficientVO> entIdToDispatchMap = dispatchList.stream().collect(
                Collectors.toMap(TruckDispatchCoefficientVO::getEntId, Function.identity()));

        for (Map.Entry<Long, List<KwtWaybillOrder>> entry : waybillOrderAndLogOrderMap.entrySet()) {
            Long logisticOrderId = entry.getKey();
            //物流运单
            List<KwtWaybillOrder> waybillOrderList = entry.getValue();
            //供应商企业信息
            KwtLogisticsOrderUnit unit = logisticsOrderAndUnitMap.get(logisticOrderId);
            //自动派车系数
            TruckDispatchCoefficientVO truckDispatchVO = entIdToDispatchMap.get(unit.getEntId());
            if (truckDispatchVO == null) {
                continue;
            }
            //司机超时限制分钟数
            Integer driverTimeout = truckDispatchVO.getDriverTimeoutLimit();
            for (KwtWaybillOrder waybillOrder : waybillOrderList) {
                //两时间的秒差值
                Long timeDiffMinutes = DateUtils.calculateTimeDiffMinutes(waybillOrder.getCreateTime(), new Date());
                if (timeDiffMinutes > TimeUnit.MINUTES.toSeconds(driverTimeout)) {
                    nearingCompletionOrders.add(waybillOrder);
                }
            }
        }
        return nearingCompletionOrders;
    }

    @Transactional(rollbackFor = Exception.class)
    public void processSingleWaybillOrder(KwtWaybillOrder waybillOrder, Map<Long, KwtLogisticsOrderUnit> logisticsOrderAndUnitMap) {
        try {
            //1.获取子运单任务量
            KwtWaybillOrderSubtask subtask = waybillOrderSubtaskRepository.queryByWOrderId(waybillOrder.getId());
            if (subtask == null) {
                throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_SUB_NOT_FOUND, "未找到关联的子运单！");
            }
            BigDecimal entrustAmount = subtask.getEntrustAmount();

            //2.更新上游订单：更新物流订单运输量
            updateLogOrder(waybillOrder, entrustAmount);

            //3. 更新状态
            updateStatus(waybillOrder, subtask);

            //4. 生成节点轨迹
            createNodeTrace(waybillOrder, subtask);
        } catch (Exception e) {
            throw e; // 抛出异常，触发Seata全局回滚
        }

    }

    /**
     * 更新上游物流订单 - 减运输量
     * @param waybillOrder
     * @param entrustAmount
     * @return
     */
    public KwtLogisticsOrder updateLogOrder(KwtWaybillOrder waybillOrder, BigDecimal entrustAmount) {
        KwtLogisticsOrder logOrder = logisticsOrderRepository.queryByLogisticsOrderId(waybillOrder.getLOrderId());
        if (logOrder == null) {
            log.info("当前物流运单无关联物流订单数据：{}", waybillOrder.getLOrderId());
            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;
    }

    // 更新状态
    public void updateStatus(KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask subtask) {
        // 修改运单状态
        waybillOrder.setStatus(CarWaybillV1Enum.CANCELLED.getCode());
        waybillOrderRepository.updateById(waybillOrder);

        //修改子运单状态
        subtask.setStatus(CarWaybillV1Enum.CANCELLED.getCode());
        waybillOrderSubtaskRepository.updateById(subtask);
    }

    // 生成节点轨迹
    public void createNodeTrace(KwtWaybillOrder waybillOrder, KwtWaybillOrderSubtask subtask) {
        if (waybillOrder == null) {
            return;
        }
        KwtWaybillOrderNode node = new KwtWaybillOrderNode();
        node.setWOrderId(waybillOrder.getId());
        node.setWSubtaskId(subtask.getId());
        node.setOrderStatus(waybillOrder.getStatus());
        node.setTruckId(waybillOrder.getTruckId());
        node.setTruckNo(waybillOrder.getTruckNo());
        node.setDriverId(waybillOrder.getDriverId());
        node.setDriverName(waybillOrder.getDriverName());
        node.setRemark("司机[" + waybillOrder.getDriverName() + "]取消订单");
        waybillOrderNodeRepository.save(node);
        log.info("记录取消接单节点轨迹成功，节点ID：{}", node.getId());
    }



    @Async
    public void handleCancelActions(KwtWaybillOrder waybillOrder, Map<Long, KwtLogisticsOrderUnit> logisticsOrderAndUnitMap) {
        try {
            unbindTruck(waybillOrder);
            checkArrivedLoadingPointTimeout(waybillOrder, logisticsOrderAndUnitMap);
        } catch (Exception e) {
            log.error("异步处理取消后动作失败", e);
        }
    }


    /**
     * 解绑车辆
     * @param waybillOrder
     */
    private void unbindTruck(KwtWaybillOrder waybillOrder) {
        remoteFleetService.unbindTruck(waybillOrder.getEntId(), waybillOrder.getDriverId());
        log.info("解绑完成，解绑司机与车辆关系，运单id：{},企业id:{},司机id：{}", waybillOrder.getId(), waybillOrder.getEntId(), waybillOrder.getDriverId());
    }

    /**
     * 司机超时到达装货点扣分
     * @param waybillOrder
     */
    private void checkArrivedLoadingPointTimeout(KwtWaybillOrder waybillOrder, Map<Long, KwtLogisticsOrderUnit> logisticsOrderAndUnitMap) {
        KwtLogisticsOrderUnit logisticsOrderUnit = logisticsOrderAndUnitMap.get(waybillOrder.getLOrderId());
        //供应商id
        Long supEntId = logisticsOrderUnit.getEntId();
        DriverConductRulesVO driverRulesVO = remoteFleetService.findDriverConductRulesByEntId(logisticsOrderUnit.getEntId());
        if (driverRulesVO == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_NOT_EXIST, "未找到司机行为规则数据！");
        }
        Integer notOnTimeArrive = driverRulesVO.getNotOnTimeArriveScore();
        if (notOnTimeArrive <= 0) {
            log.warn("【司机未按时到场】司机扣分失败，企业{}的司机未按时到场分数配置异常，运单ID：{}", waybillOrder.getEntId(), waybillOrder.getId());
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_NOT_EXIST, "【司机未按时到场】分数配置需大于0!");
        }
        //1、更新司机分数（减分）
        notOnTimeArrive = -Math.abs(notOnTimeArrive);
        updateDriverScore(supEntId, waybillOrder.getEntId(), waybillOrder.getDriverId(), notOnTimeArrive, "司机未按时到场(超时)");

        //2、更新企业分数（减分）
        updateLogEntScore(waybillOrder, supEntId, notOnTimeArrive, "司机未按时到场");

    }

    /**
     * 修改司机评分
     * @param supeEntId
     * @param entId
     * @param driverId
     * @param score
     */
    public void updateDriverScore(Long supeEntId, Long entId, Long driverId, Integer score, String action) {
        RUpdateDriverScoreDto dto = new RUpdateDriverScoreDto();
        dto.setSupEntId(supeEntId);
        dto.setLogEntId(entId);
        dto.setDriverId(driverId);
        dto.setScore(BigDecimal.valueOf(score));
        dto.setAction(action);

        remoteFleetService.updateDriverScoreByEntId(dto);
    }

    /**
     * 更新企业评分
     * @param waybillOrder
     * @param supplierId
     * @param score
     */
    public void updateLogEntScore(KwtWaybillOrder waybillOrder, Long supplierId, Integer score, String remark) {
        LogisticsScoreDetailFeignDto detailDto = new LogisticsScoreDetailFeignDto();
        detailDto.setProviderEntId(supplierId);
        detailDto.setLogisticsEntId(waybillOrder.getEntId());
        detailDto.setPhone(waybillOrder.getDriverPhone());
        detailDto.setAction(remark);
        detailDto.setScoreChange(BigDecimal.valueOf(score));
        logisticsScoreFeignService.updateLogisticsScore(detailDto);
    }

}