package com.sckw.fleet.service;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.fleet.model.KwfDriverConductRules;
import com.sckw.fleet.model.KwfDriverConductRulesLog;
import com.sckw.fleet.model.KwfTruckDispatchCoefficient;
import com.sckw.fleet.model.request.DriverConductRulesLogRequest;
import com.sckw.fleet.model.request.DriverConductRulesRequest;
import com.sckw.fleet.model.request.DriverConductRulesUpdateRequest;
import com.sckw.fleet.model.request.TruckDispatchCoefficientUpdateRequest;
import com.sckw.fleet.model.vo.KwfDriverConductRulesLogVO;
import com.sckw.fleet.model.vo.KwfDriverConductRulesVO;
import com.sckw.fleet.model.vo.KwfTruckDispatchCoefficientVO;
import com.sckw.fleet.repository.KwfDriverConductRulesLogRepository;
import com.sckw.fleet.repository.KwfDriverConductRulesRepository;
import com.sckw.fleet.repository.KwfTruckDispatchCoefficientRepository;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
*Author: donglang
*Time: 2025-12-04
*Des: 司机行为规则
*Version: 1.0
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class KwfAutoDispatchService {

    private final KwfDriverConductRulesRepository driverConductRulesRepository;

    private final KwfDriverConductRulesLogRepository driverConductRulesLogRepository;

    private final KwfTruckDispatchCoefficientRepository truckDispatchCoefficientRepository;

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


    /**
     * 查询自动派车系数
     * @param request
     * @return
     */
    public KwfTruckDispatchCoefficientVO queryAutoTruckDispatch(DriverConductRulesRequest request) {
        log.info("查询自动派车系数：{}", JSON.toJSONString(request));
        Long entId = LoginUserHolder.getEntId();
        if (entId == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "当前登录用户未关联企业ID，无法查询规则");
        }
        KwfTruckDispatchCoefficient dispatchCoefficient = truckDispatchCoefficientRepository.getOne(Wrappers.<KwfTruckDispatchCoefficient>lambdaQuery()
                .eq(KwfTruckDispatchCoefficient::getEntId, LoginUserHolder.getEntId()));
        //无数据则初始化
        if (dispatchCoefficient == null && request.getIsInit()) {
            dispatchCoefficient = initAutoDispatchCoefficient(entId);
        }
        KwfTruckDispatchCoefficientVO driverConductRulesVO = KwfTruckDispatchCoefficientVO.toVO(dispatchCoefficient);
        log.info("查询自动派车系数完成，企业ID：{}，规则数据：{}", entId, JSON.toJSONString(driverConductRulesVO));
        return driverConductRulesVO;
    }

    /**
     * 初始化自动派车系数
     */
    private KwfTruckDispatchCoefficient initAutoDispatchCoefficient(Long entId) {
        log.info("当前企业[{}]无自动派车系数数据，执行初始化", entId);
        KwfTruckDispatchCoefficient dispatchCoefficient = new KwfTruckDispatchCoefficient();
        dispatchCoefficient.setEntId(entId);
        dispatchCoefficient.setVehicleWorkHours(10);
        dispatchCoefficient.setVehicleLoadingHours(60);
        dispatchCoefficient.setVehicleUnloadingHours(60);
        dispatchCoefficient.setDriverTimeoutLimit(120);
        dispatchCoefficient.setVehicleAvgLoad(26);
        dispatchCoefficient.setVehicleAvgSpeed(50);
        dispatchCoefficient.setVehicleMaxTasks(3);
        dispatchCoefficient.setDriverOrderLimit(10);
        dispatchCoefficient.setYardVehicleCapacity(70);
        dispatchCoefficient.setMaxRatio(50);
        dispatchCoefficient.setBufferCoefficient(new BigDecimal("1.20"));
        dispatchCoefficient.setCreateUser(LoginUserHolder.getUserId());
        dispatchCoefficient.setUpdateUser(LoginUserHolder.getUserId());
        return dispatchCoefficient;
    }


    /**
     * 修改自动派车系数
     * @param request
     * @return
     */
    public void updateAutoDispatch(TruckDispatchCoefficientUpdateRequest request) {
        log.info("更新自动派车系数：{}", JSON.toJSONString(request));
        Long entId = LoginUserHolder.getEntId();
        if (entId == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "当前登录用户未关联企业ID，无法查询规则");
        }
        //如果id为空则是新增
        if (request.getId() == null) {
            saveAutoDispatch(request, entId);
            return;
        }
        // 修改
        KwfTruckDispatchCoefficient oldDispatchCoefficient = truckDispatchCoefficientRepository.getById(request.getId());
        if (oldDispatchCoefficient == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_NOT_EXIST, "查询自动派车系数数据不存在!");
        }

        // 生成差异化修改文案
        String modifyDesc = getAutoDispatchModifyDesc(oldDispatchCoefficient, request);
        if (StringUtils.isEmpty(modifyDesc)) {
            return;
        }

        KwfTruckDispatchCoefficient newDispatchCoefficient = new KwfTruckDispatchCoefficient();
        BeanUtils.copyProperties(oldDispatchCoefficient, newDispatchCoefficient);

        newDispatchCoefficient.setVehicleWorkHours(request.getVehicleWorkHours());
        newDispatchCoefficient.setVehicleLoadingHours(request.getVehicleLoadingHours());
        newDispatchCoefficient.setVehicleUnloadingHours(request.getVehicleUnloadingHours());
        newDispatchCoefficient.setDriverTimeoutLimit(request.getDriverTimeoutLimit());
        newDispatchCoefficient.setVehicleAvgLoad(request.getVehicleAvgLoad());
        newDispatchCoefficient.setVehicleAvgSpeed(request.getVehicleAvgSpeed());
        newDispatchCoefficient.setVehicleMaxTasks(request.getVehicleMaxTasks());
        newDispatchCoefficient.setDriverOrderLimit(request.getDriverOrderLimit());
        newDispatchCoefficient.setYardVehicleCapacity(request.getYardVehicleCapacity());
        newDispatchCoefficient.setMaxRatio(request.getMaxRatio());
        newDispatchCoefficient.setBufferCoefficient(request.getBufferCoefficient());
        newDispatchCoefficient.setUpdateUser(LoginUserHolder.getUserId());

        boolean updateResult = truckDispatchCoefficientRepository.updateById(newDispatchCoefficient);
        if (!updateResult) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_UPDATE_FAIL, "更新自动派车系数失败");
        }

        //生成规则更新日志
        KwfDriverConductRulesLog rulesLog = new KwfDriverConductRulesLog();
        rulesLog.setBizId(request.getId());
        rulesLog.setDescription(modifyDesc);
        rulesLog.setStatus(0);
        rulesLog.setCreateUser(LoginUserHolder.getUserId());
        rulesLog.setUpdateUser(LoginUserHolder.getUserId());

        boolean saveResult = driverConductRulesLogRepository.save(rulesLog);
        if (!saveResult) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_SAVE_FAIL, "新增自动派车系数日志失败");
        }
        log.info("更新自动派车系数成功!修改内容：{}", modifyDesc);
    }

    /**
     * 保存自动派车系数表
     * @param request
     */
    private void saveAutoDispatch(TruckDispatchCoefficientUpdateRequest request, Long entId) {
        log.info("新增自动派车系数：{}", JSON.toJSONString(request));
        KwfTruckDispatchCoefficient dispatchCoefficient = new KwfTruckDispatchCoefficient();
        dispatchCoefficient.setEntId(entId);
        dispatchCoefficient.setVehicleWorkHours(request.getVehicleWorkHours());
        dispatchCoefficient.setVehicleLoadingHours(request.getVehicleLoadingHours());
        dispatchCoefficient.setVehicleUnloadingHours(request.getVehicleUnloadingHours());
        dispatchCoefficient.setDriverTimeoutLimit(request.getDriverTimeoutLimit());
        dispatchCoefficient.setVehicleAvgLoad(request.getVehicleAvgLoad());
        dispatchCoefficient.setVehicleAvgSpeed(request.getVehicleAvgSpeed());
        dispatchCoefficient.setVehicleMaxTasks(request.getVehicleMaxTasks());
        dispatchCoefficient.setDriverOrderLimit(request.getDriverOrderLimit());
        dispatchCoefficient.setYardVehicleCapacity(request.getYardVehicleCapacity());
        dispatchCoefficient.setMaxRatio(request.getMaxRatio());
        dispatchCoefficient.setBufferCoefficient(request.getBufferCoefficient());
        dispatchCoefficient.setCreateUser(LoginUserHolder.getUserId());
        dispatchCoefficient.setUpdateUser(LoginUserHolder.getUserId());
        truckDispatchCoefficientRepository.save(dispatchCoefficient);
    }

    /**
     * 生成司机行为规则修改的差异化文案
     * @param oldDispatch 旧派车系数
     * @param request 新的更新入参
     * @return 差异化修改文案
     */
    private String getAutoDispatchModifyDesc(KwfTruckDispatchCoefficient oldDispatch, TruckDispatchCoefficientUpdateRequest request) {
        if (oldDispatch == null || request == null) {
            return "";
        }
        List<String> changeItems = new ArrayList<>();
        // 对比所有字段
        compareAndAddItem(changeItems, "车辆工作时长", oldDispatch.getVehicleWorkHours(), request.getVehicleWorkHours());
        compareAndAddItem(changeItems, "车辆装货时长", oldDispatch.getVehicleLoadingHours(), request.getVehicleLoadingHours());
        compareAndAddItem(changeItems, "车辆卸货时长", oldDispatch.getVehicleUnloadingHours(), request.getVehicleUnloadingHours());
        compareAndAddItem(changeItems, "司机超时限制", oldDispatch.getDriverTimeoutLimit(), request.getDriverTimeoutLimit());
        compareAndAddItem(changeItems, "车辆平均载重", oldDispatch.getVehicleAvgLoad(), request.getVehicleAvgLoad());
        compareAndAddItem(changeItems, "车辆平均速度", oldDispatch.getVehicleAvgSpeed(), request.getVehicleAvgSpeed());
        compareAndAddItem(changeItems, "车辆最大任务数", oldDispatch.getVehicleMaxTasks(), request.getVehicleMaxTasks());
        compareAndAddItem(changeItems, "司机接单限制", oldDispatch.getDriverOrderLimit(), request.getDriverOrderLimit());
        compareAndAddItem(changeItems, "场内车辆容量", oldDispatch.getYardVehicleCapacity(), request.getYardVehicleCapacity());
        compareAndAddItem(changeItems, "最大占比", oldDispatch.getMaxRatio(), request.getMaxRatio());
        compareAndAddItem(changeItems, "缓冲系数", oldDispatch.getBufferCoefficient(), request.getBufferCoefficient());

        if (changeItems.isEmpty()) {
            return "";
        }
        // 修改项拼接
        return StringUtils.join(changeItems, "，");
    }

    /**
     * 对比单个字段值，有变化则添加到文案列表
     * @param items 文案列表
     * @param fieldName 字段业务名称
     * @param oldValue 旧值
     * @param newValue 新值
     */
    private void compareAndAddItem(List<String> items, String fieldName, Integer oldValue, Integer newValue) {
        // 仅当值不同时添加文案
        if (!Objects.equals(oldValue, newValue)) {
            items.add(String.format("%s由【%s】设置为【%s】", fieldName, oldValue, newValue));
        }
    }

    /**
     * 对比单个字段值，有变化则添加到文案列表
     * @param items 文案列表
     * @param fieldName 字段业务名称
     * @param oldValue 旧值
     * @param newValue 新值
     */
    private void compareAndAddItem(List<String> items, String fieldName, BigDecimal oldValue, BigDecimal newValue) {
        // 仅当值不同时添加文案
        if (oldValue.compareTo(newValue) != 0) {
            items.add(String.format("%s由【%s】设置为【%s】", fieldName, oldValue, newValue));
        }
    }

    /**
     * 查询司机行为规则
     * @param request
     * @return
     */
    public KwfDriverConductRulesVO queryDriverConductRules(DriverConductRulesRequest request) {
        log.info("查询司机行为规则：{}", JSON.toJSONString(request));
        Long entId = LoginUserHolder.getEntId();
        if (entId == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "当前登录用户未关联企业ID，无法查询规则");
        }
        KwfDriverConductRules driverConductRules = driverConductRulesRepository.getOne(Wrappers.<KwfDriverConductRules>lambdaQuery()
                .eq(KwfDriverConductRules::getEntId, LoginUserHolder.getEntId()));
        //无数据则初始化
        if (driverConductRules == null && request.getIsInit()) {
            driverConductRules = initDriverConductRules(entId);
        }
        KwfDriverConductRulesVO resultVO = KwfDriverConductRulesVO.toVO(driverConductRules);
        log.info("查询司机行为规则完成，企业ID：{}，规则数据：{}", entId, JSON.toJSONString(resultVO));
        return resultVO;
    }

    /**
     * 初始化司机行为规则
     */
    private KwfDriverConductRules initDriverConductRules(Long entId) {
        log.info("当前企业[{}]无司机行为规则数据，执行初始化", entId);
        KwfDriverConductRules rules = new KwfDriverConductRules();
        rules.setEntId(entId);
        rules.setUnloadSeriousTimeoutScore(5);
        rules.setUnloadSeriousTimeoutMultiple(new BigDecimal("2.00"));
        rules.setDocumentErrorMissingScore(2);
        rules.setNotOnTimeArriveScore(2);
        rules.setFakeUnloadScore(5);
        rules.setFakeUnloadDistance(5);
        rules.setIllegalCancelOrderScore(1);
        rules.setIllegalCancelOrderMinutes(60);
        rules.setContinuousOnTimeArriveScore(5);
        rules.setContinuousOnTimeArriveTimes(10);
        rules.setContinuousOnTimeUnloadScore(5);
        rules.setContinuousOnTimeUnloadTimes(10);
        rules.setContinuousAccurateUnloadScore(5);
        rules.setContinuousAccurateUnloadTimes(10);
        rules.setCreateUser(LoginUserHolder.getUserId());
        rules.setUpdateUser(LoginUserHolder.getUserId());
        return rules;
    }

    /**
     * 更新司机行为规则
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDriverConduct(DriverConductRulesUpdateRequest request) {
        log.info("更新司机行为规则：{}", JSON.toJSONString(request));
        Long entId = LoginUserHolder.getEntId();
        if (entId == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "当前登录用户未关联企业ID，无法查询规则");
        }
        // 新增
        if (request.getId() == null) {
            saveDriverConductRules(request, entId);
            return;
        }
        // 修改
        KwfDriverConductRules oldDriverConductRules = driverConductRulesRepository.getById(request.getId());
        if (oldDriverConductRules == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_NOT_EXIST, "查询司机行为规则数据不存在!");
        }

        // 生成差异化修改文案
        String modifyDesc = getDriverModifyDesc(oldDriverConductRules, request);
        if (StringUtils.isEmpty(modifyDesc)) {
            return;
        }

        KwfDriverConductRules newDriverConductRules = new KwfDriverConductRules();
        BeanUtils.copyProperties(oldDriverConductRules, newDriverConductRules);

        newDriverConductRules.setUnloadSeriousTimeoutScore(request.getUnloadSeriousTimeoutScore());
        newDriverConductRules.setUnloadSeriousTimeoutMultiple(request.getUnloadSeriousTimeoutMultiple());
        newDriverConductRules.setDocumentErrorMissingScore(request.getDocumentErrorMissingScore());
        newDriverConductRules.setNotOnTimeArriveScore(request.getNotOnTimeArriveScore());
        newDriverConductRules.setFakeUnloadScore(request.getFakeUnloadScore());
        newDriverConductRules.setFakeUnloadDistance(request.getFakeUnloadDistance());
        newDriverConductRules.setIllegalCancelOrderScore(request.getIllegalCancelOrderScore());
        newDriverConductRules.setIllegalCancelOrderMinutes(request.getIllegalCancelOrderMinutes());
        newDriverConductRules.setContinuousOnTimeArriveScore(request.getContinuousOnTimeArriveScore());
        newDriverConductRules.setContinuousOnTimeArriveTimes(request.getContinuousOnTimeArriveTimes());
        newDriverConductRules.setContinuousOnTimeUnloadScore(request.getContinuousOnTimeUnloadScore());
        newDriverConductRules.setContinuousOnTimeUnloadTimes(request.getContinuousOnTimeUnloadTimes());
        newDriverConductRules.setContinuousAccurateUnloadScore(request.getContinuousAccurateUnloadScore());
        newDriverConductRules.setContinuousAccurateUnloadTimes(request.getContinuousAccurateUnloadTimes());
        newDriverConductRules.setUpdateUser(LoginUserHolder.getUserId());

        boolean updateResult = driverConductRulesRepository.updateById(newDriverConductRules);
        if (!updateResult) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_UPDATE_FAIL, "更新司机行为规则失败");
        }

        //生成规则更新日志
        KwfDriverConductRulesLog rulesLog = new KwfDriverConductRulesLog();
        rulesLog.setBizId(request.getId());
        rulesLog.setDescription(modifyDesc);
        rulesLog.setStatus(1);
        rulesLog.setCreateUser(LoginUserHolder.getUserId());
        rulesLog.setUpdateUser(LoginUserHolder.getUserId());

        boolean saveResult = driverConductRulesLogRepository.save(rulesLog);
        if (!saveResult) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_SAVE_FAIL, "新增司机行为规则日志失败");
        }
        log.info("更新司机行为规则成功!修改内容：{}", modifyDesc);
    }

    private void saveDriverConductRules(DriverConductRulesUpdateRequest request, Long entId) {
        KwfDriverConductRules driverConductRules = new KwfDriverConductRules();
        driverConductRules.setEntId(entId);
        driverConductRules.setUnloadSeriousTimeoutScore(request.getUnloadSeriousTimeoutScore());
        driverConductRules.setUnloadSeriousTimeoutMultiple(request.getUnloadSeriousTimeoutMultiple());
        driverConductRules.setDocumentErrorMissingScore(request.getDocumentErrorMissingScore());
        driverConductRules.setNotOnTimeArriveScore(request.getNotOnTimeArriveScore());
        driverConductRules.setFakeUnloadScore(request.getFakeUnloadScore());
        driverConductRules.setFakeUnloadDistance(request.getFakeUnloadDistance());
        driverConductRules.setIllegalCancelOrderScore(request.getIllegalCancelOrderScore());
        driverConductRules.setIllegalCancelOrderMinutes(request.getIllegalCancelOrderMinutes());
        driverConductRules.setContinuousOnTimeArriveScore(request.getContinuousOnTimeArriveScore());
        driverConductRules.setContinuousOnTimeArriveTimes(request.getContinuousOnTimeArriveTimes());
        driverConductRules.setContinuousOnTimeUnloadScore(request.getContinuousOnTimeUnloadScore());
        driverConductRules.setContinuousOnTimeUnloadTimes(request.getContinuousOnTimeUnloadTimes());
        driverConductRules.setContinuousAccurateUnloadScore(request.getContinuousAccurateUnloadScore());
        driverConductRules.setContinuousAccurateUnloadTimes(request.getContinuousAccurateUnloadTimes());
        driverConductRules.setCreateUser(LoginUserHolder.getUserId());
        driverConductRules.setUpdateUser(LoginUserHolder.getUserId());
        driverConductRulesRepository.save(driverConductRules);
    }

    /**
     * 生成司机行为规则修改的差异化文案
     * @param oldRule 旧规则数据
     * @param request 新的更新入参
     * @return 差异化修改文案
     */
    private String getDriverModifyDesc(KwfDriverConductRules oldRule, DriverConductRulesUpdateRequest request) {
        if (oldRule == null || request == null) {
            return "";
        }
        List<String> changeItems = new ArrayList<>();
        // 对比所有字段
        compareAndAddItem(changeItems, "单趟严重超时", oldRule.getUnloadSeriousTimeoutScore(), request.getUnloadSeriousTimeoutScore());
        compareAndAddItem(changeItems, "单趟严重超时倍数", oldRule.getUnloadSeriousTimeoutMultiple(), request.getUnloadSeriousTimeoutMultiple());
        compareAndAddItem(changeItems, "单据错误/缺失", oldRule.getDocumentErrorMissingScore(), request.getDocumentErrorMissingScore());
        compareAndAddItem(changeItems, "未按时到场", oldRule.getNotOnTimeArriveScore(), request.getNotOnTimeArriveScore());
        compareAndAddItem(changeItems, "虚假卸货", oldRule.getFakeUnloadScore(), request.getFakeUnloadScore());
        compareAndAddItem(changeItems, "虚假卸货偏差距离", oldRule.getFakeUnloadDistance(), request.getFakeUnloadDistance());
        compareAndAddItem(changeItems, "违规取消运单", oldRule.getIllegalCancelOrderScore(), request.getIllegalCancelOrderScore());
        compareAndAddItem(changeItems, "违规取消运单分钟数", oldRule.getIllegalCancelOrderMinutes(), request.getIllegalCancelOrderMinutes());
        compareAndAddItem(changeItems, "连续按时到场", oldRule.getContinuousOnTimeArriveScore(), request.getContinuousOnTimeArriveScore());
        compareAndAddItem(changeItems, "连续按时到场次数", oldRule.getContinuousOnTimeArriveTimes(), request.getContinuousOnTimeArriveTimes());
        compareAndAddItem(changeItems, "连续准时卸货", oldRule.getContinuousOnTimeUnloadScore(), request.getContinuousOnTimeUnloadScore());
        compareAndAddItem(changeItems, "连续准时卸货次数", oldRule.getContinuousOnTimeUnloadTimes(), request.getContinuousOnTimeUnloadTimes());
        compareAndAddItem(changeItems, "连续准确填写卸货信息", oldRule.getContinuousAccurateUnloadScore(), request.getContinuousAccurateUnloadScore());
        compareAndAddItem(changeItems, "连续准确填写卸货信息次数", oldRule.getContinuousAccurateUnloadTimes(), request.getContinuousAccurateUnloadTimes());

        if (changeItems.isEmpty()) {
            return "";
        }
        // 修改项拼接
        return StringUtils.join(changeItems, "，");
    }

    /**
     * 查询司机行为规则
     * @param request
     * @return
     */
    public PageDataResult<KwfDriverConductRulesLogVO> queryDriverRulesLogPage(DriverConductRulesLogRequest request) {
        if (request.getBizId() == null) {
            return PageDataResult.empty(request.getPageNum(), request.getPageSize());
        }
        log.info("查询司机行为规则日志：{}", JSON.toJSONString(request));
        LambdaQueryWrapper<KwfDriverConductRulesLog> queryWrapper = Wrappers.<KwfDriverConductRulesLog>lambdaQuery()
                .eq(KwfDriverConductRulesLog::getBizId, request.getBizId())
                .eq(KwfDriverConductRulesLog::getStatus, request.getStatus())
                .like(StringUtils.isNotBlank(request.getDescription()), KwfDriverConductRulesLog::getDescription, request.getDescription())
                .orderByDesc(KwfDriverConductRulesLog::getCreateTime);
        //查询司机行为规则日志
        Page<KwfDriverConductRulesLog> driverConductRulesLog = driverConductRulesLogRepository.page(
                new Page<>(request.getPageNum(), request.getPageSize()), queryWrapper);
        List<KwfDriverConductRulesLog> records = driverConductRulesLog.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.info("当前无司机行为规则日志数据，bizId:{}", request.getBizId());
            return PageDataResult.empty(request.getPageNum(), request.getPageSize());
        }
        List<KwfDriverConductRulesLogVO> rulesLogVOS = records.stream().map(KwfDriverConductRulesLogVO::toVO).collect(Collectors.toList());
        // 提取所有createUser
        Set<Long> userIds = rulesLogVOS.stream().map(KwfDriverConductRulesLogVO::getCreateUser)
                .filter(Objects::nonNull).collect(Collectors.toSet());

        // 批量查询用户信息
        List<UserCacheResDto> userDtoList = remoteSystemService.queryUserCacheByIds(new ArrayList<>(userIds));
        Map<Long, String> userMap = userDtoList.stream()
                    .collect(Collectors.toMap(UserCacheResDto::getId, UserCacheResDto::getName, (v1, v2) -> v1));

        List<KwfDriverConductRulesLogVO> result = rulesLogVOS.stream()
                .peek(relu -> {
                    relu.setCreateUserName(userMap.getOrDefault(relu.getCreateUser(), "未知用户"));
                }).collect(Collectors.toList());

        log.info("查询司机行为规则日志成功！");
        return PageDataResult.success(request.getPageNum(), request.getPageSize(), driverConductRulesLog.getTotal(), result);
    }

}
