package com.sckw.fleet.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.google.common.collect.Sets;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.common.enums.enums.FileEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.base.BaseModel;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.EntTypeEnum;
import com.sckw.core.model.enums.SystemTypeEnum;
import com.sckw.core.model.file.FileInfo;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginEntHolder;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.request.HttpClientUtil;
import com.sckw.core.web.response.BaseIotResult;
import com.sckw.core.web.response.HttpResult;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.excel.easyexcel.ExcelImportListener;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.fleet.config.UrlConfigProperties;
import com.sckw.fleet.dao.*;
import com.sckw.fleet.model.*;
import com.sckw.fleet.model.dto.*;
import com.sckw.fleet.model.enums.TruckEevEnum;
import com.sckw.fleet.model.enums.TruckEnergyTypeEnum;
import com.sckw.fleet.model.enums.TruckStatusEnum;
import com.sckw.fleet.model.enums.TruckTypeEnum;
import com.sckw.fleet.model.reponse.TruckDetailResp;
import com.sckw.fleet.model.request.*;
import com.sckw.fleet.model.reponse.TruckResp;
import com.sckw.fleet.model.vo.*;
import com.sckw.fleet.repository.*;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.feign.DataPermissionFeignService;
import com.sckw.system.api.model.dto.req.DataPermissionFilterReqDto;
import com.sckw.system.api.model.dto.res.*;
import com.sckw.transport.api.dubbo.TransportRemoteService;
import com.sckw.transport.api.feign.VehicleTraceClient;
import com.sckw.transport.api.model.dto.RWaybillOrderDto;
import com.sckw.transport.api.model.dto.VehicleDataDTO;
import com.sckw.transport.api.model.dto.VehicleReturnData;
import com.sckw.transport.api.model.vo.RTruckMonitorVo;
import com.sckw.transport.api.model.vo.RWaybillOrderVo;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author zk
 * @desc 车辆
 * @date 2023/7/6 0006
 */
@Slf4j
@Service
@SuppressWarnings("all")
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class KwfTruckService {

    @Autowired
    KwfTruckMapper truckDao;
    @Autowired
    KwfTruckEntMapper truckEntDao;
    @Autowired
    KwfTruckLicenseMapper truckLicenseDao;
    @Autowired
    KwfTransportLicenseMapper transportLicenseDao;
    @Autowired
    KwfTruckImportMapper kwfTruckImportDao;
    @Autowired
    KwfFleetTruckMapper fleetTruckDao;
    private final KwfDriverRepository kwfDriverRepository;
    private final KwfTruckReportRepository kwfTruckReportRepository;
    private final KwfTruckRepository kwfTruckRepository;
    private final KwfFleetRepository kwfFleetRepository;
    private final UrlConfigProperties urlConfigProperties;
    private final KwfFleetDriverRepository kwfFleetDriverRepository;
    private final KwfTruckAxleNumRepository truckAxleNumRepository;
    private final KwfTruckEntRepository truckEntRepository;

    private final KwfFleetTruckRepository kwfFleetTruckRepository;

    private final DataPermissionFeignService dataPermissionFeignService;
    private final VehicleTraceClient vehicleTraceClient;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    private RemoteSystemService remoteSystemService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    private RemoteUserService remoteUserService;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private TransportRemoteService transportRemoteService;

    /**
     * @param key 主键id
     * @desc 根据主键查询
     * @author zk
     * @date 2023/7/6
     **/
    public KwfTruck selectByKey(Long key) {
        return truckDao.selectById(key);
    }

    /**
     * @param truckId 车辆档案ID
     * @desc 车辆详情
     * @author zk
     * @date 2023/7/11
     **/
    public KwfTruckDetailVo detail(Long truckId, Long entId) {
        //车辆信息
        KwfTruck truck = this.selectByKey(truckId);
        KwfTruckDetailVo truckDetailVo = new KwfTruckDetailVo();
        BeanUtils.copyPropertiesValue(truck, truckDetailVo);

        //数据组装
        if (truck != null) {
            //车辆行驶证信息
            KwfTruckLicense truckLicense = this.findTruckLicenseByKey(truckId);
            KwfTruckLicenseVo truckLicenseVo = new KwfTruckLicenseVo();
            BeanUtils.copyPropertiesValue(truckLicense, truckLicenseVo);
            truckDetailVo.setTruckLicense(truckLicenseVo);

            //车辆道路运输许可证
            KwfTransportLicense transportLicense = this.findTransportLicenseByKey(truckId);
            KwfTransportLicenseVo transportLicenseVo = new KwfTransportLicenseVo();
            BeanUtils.copyPropertiesValue(transportLicense, transportLicenseVo);
            truckDetailVo.setTransportLicense(transportLicenseVo);

            //字典
            String value = getDictValue(DictTypeEnum.COLOR_TYPE.getType(), StringUtils.objectStr(truck.getColor()));
            truckDetailVo.setColorName(value);

            //数据字典
            List<String> dictKey = new ArrayList<>();
            dictKey.add(truck.getColor() != null ? DictTypeEnum.COLOR_TYPE.getType() + Global.POUND + truck.getColor() : null);
            Map<String, SysDictResDto> dicts = this.dict(dictKey);
            SysDictResDto color = dicts.get(DictTypeEnum.COLOR_TYPE.getType() + Global.POUND + truck.getColor());

            //车队班组
            KwfFleet fleet = this.findByFleetTruck(truckId, LoginUserHolder.getEntId());
            truckDetailVo.setFleetId(fleet != null ? fleet.getId() : null);
            truckDetailVo.setFleetName(fleet != null ? fleet.getName() : null);
            truckDetailVo.setColorName(color != null ? color.getLabel() : null);

            //关联司机
            KwfDriver driver = getDriverInfo(truckId, entId);
            truckDetailVo.setDriverName(driver.getName());

            //查询车辆轴数
            TmsTruckAxleNum axleNum = getCarAxisInfo(truck.getCarAxis());
            truckDetailVo.setCarAxisId(truck.getCarAxis());
            truckDetailVo.setCarAxis(axleNum.getName());

            return truckDetailVo;
        }
        return null;
    }

    /**
     * @param params 参数
     * @desc 统计
     * @author zk
     * @date 2023/7/11
     **/
    public Map statistics(Map<String, Object> params) {
        /**统计数据**/
        List<KwfTableTopCount> counts = statisticsHandle(params);
        long tatol = 0;
        for (KwfTableTopCount topCount : counts) {
            tatol += topCount.getTotal();
        }

        /**全部数据-处理**/
        List<KwfTableTopCount> countList = new ArrayList();
        KwfTableTopCount allCount = new KwfTableTopCount();
        allCount.setValue(String.valueOf(Global.NUMERICAL_ZERO));
        allCount.setTotal(tatol);
        allCount.setName("全部");
        countList.add(allCount);

        /**数据处理**/
        Map<String, Integer> authStatusMap = new HashMap() {{
            put("正常", 1);
            put("临时", 2);
            put("异常", 3);
        }};
        for (Map.Entry<String, Integer> entry : authStatusMap.entrySet()) {
            KwfTableTopCount count = new KwfTableTopCount();
            for (KwfTableTopCount topCount : counts) {
                if (Integer.parseInt(topCount.getValue()) == entry.getValue()) {
                    BeanUtils.copyProperties(topCount, count);
                }
            }
            count.setName(entry.getKey());
            count.setValue(String.valueOf(entry.getValue()));
            countList.add(count);
        }

        /**数据组装**/
        Map tableCount = new HashMap();
        tableCount.put("tableTop", countList);
        tableCount.put("tableBottom", tatol);
        return tableCount;
    }

    /**
     * @param params 参数
     * @desc 统计
     * @author zk
     * @date 2023/9/11
     **/
    public List<KwfTableTopCount> statisticsHandle(Map<String, Object> params) {
        int systemType = LoginUserHolder.getSystemType();
        /**统计数据**/
        if (systemType == SystemTypeEnum.MANAGE.getCode()) {
            //新增客户经理权限过滤
            List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return new ArrayList<>();
                }
                authEntIdList.addAll(ids);
            }
            List<KwfTableTopCount> counts = truckDao.statisticsAll(params,authEntIdList);
            return counts;
        } else {
            Object keywords = params.get("keywords");
            if (StringUtils.isNotBlank(keywords)) {
                //查询企业
                List<Integer> entTypes = new ArrayList<>() {{
                    add(EntTypeEnum.LOGISTICS3.getCode());
                    add(EntTypeEnum.LOGISTICS4.getCode());
                }};
                List<Long> entIds = remoteUserService.findEntIds(entTypes, StringUtils.objectStr(keywords));
                params.put("entIds", entIds);
                //查询用户
                List<Long> userIds = remoteUserService.findUserIds(new ArrayList<>() {{
                    add(LoginUserHolder.getEntId());
                }}, StringUtils.objectStr(keywords));
                params.put("createBys", userIds);
            }
            params.put("entId", LoginUserHolder.getEntId());
            List<KwfTableTopCount> counts = truckDao.statistics(params);
            return counts;
        }
    }

    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/7/6
     **/
    public List<KwfTruckVo> findPage(Map<String, Object> params) {
        /**查询分页数据**/
        List<KwfTruckVo> trucks = findPageHandle(params);
        if (CollectionUtils.isEmpty(trucks)) {
            return trucks;
        }

        /**获取查询数据**/
        String pound = Global.POUND;
        List<Long> createBys = new ArrayList<>();
        List<Long> entIds = new ArrayList<>();
        List<String> dictKey = new ArrayList<>();

        for (KwfTruckVo truck : trucks) {
            //创建人id
            createBys.add(Long.parseLong(truck.getCreateBy()));
            //企业id
            entIds.add(Long.parseLong(truck.getEntId()));
            //车牌颜色
            dictKey.add(truck.getColor() != null ? DictTypeEnum.COLOR_TYPE.getType() + pound + truck.getColor() : null);
            //车辆类型
            dictKey.add(truck.getType() != null ? DictTypeEnum.TRUCK_TYPE.getType() + pound + truck.getType() : null);
            //使用性质
            dictKey.add(truck.getUseType() != null ? DictTypeEnum.USE_TYPE.getType() + pound + truck.getUseType() : null);
            //能源类型
            dictKey.add(truck.getEnergyType() != null ? DictTypeEnum.ENERGY_TYPE.getType() + pound + truck.getEnergyType() : null);
        }
        //用户数据集
        createBys = createBys.stream().distinct().collect(Collectors.toList());
        Map<Long, UserCacheResDto> users = remoteSystemService.queryUserCacheMapByIds(createBys);
        //企业数据集
        entIds = entIds.stream().distinct().collect(Collectors.toList());
        Map<Long, EntCacheResDto> ents = remoteSystemService.queryEntCacheMapByIds(entIds);
        //数据字典
        Map<String, SysDictResDto> dicts = this.dict(dictKey);

        /**数据组装**/
        for (KwfTruckVo truck : trucks) {
            UserCacheResDto user = users == null ? null : users.get(Long.parseLong(truck.getCreateBy()));
            EntCacheResDto ent = ents == null ? null : ents.get(Long.parseLong(truck.getEntId()));
            SysDictResDto color = dicts.get(DictTypeEnum.COLOR_TYPE.getType() + pound + truck.getColor());
            SysDictResDto type = dicts.get(DictTypeEnum.TRUCK_TYPE.getType() + pound + truck.getType());
            SysDictResDto useType = dicts.get(DictTypeEnum.USE_TYPE.getType() + pound + truck.getUseType());
            SysDictResDto energyType = dicts.get(DictTypeEnum.ENERGY_TYPE.getType() + pound + truck.getEnergyType());
            truck.setCreateByName(user != null ? user.getName() : null);
            truck.setFirmName(ent != null ? ent.getFirmName() : null);
            truck.setColorName(color != null ? color.getLabel() : null);
            truck.setTruckTypeName(type != null ? type.getLabel() : null);
            truck.setUseTypeName(useType != null ? useType.getLabel() : null);
            truck.setEnergyTypeName(energyType != null ? energyType.getLabel() : null);

            //查询司机信息
            KwfDriver driver = getDriverInfo(Long.parseLong(truck.getId()), ent.getId());
            truck.setDriverName(driver.getName());

            //查询车辆轴数
            TmsTruckAxleNum axleNum = getCarAxisInfo(truck.getCarAxis());
            truck.setCarAxisId(truck.getCarAxis());
            truck.setCarAxis(axleNum.getName());
        }
        return trucks;
    }

    /**
     * 根据车轴id查询轴数信息
     *
     * @param truck
     * @param ents
     * @return
     */
    private TmsTruckAxleNum getCarAxisInfo(String axleNumId) {
        if (StringUtils.isEmpty(axleNumId)) {
            return new TmsTruckAxleNum();
        }
        //查询车辆关联司机信息
        TmsTruckAxleNum axleNum = truckAxleNumRepository.getOne(Wrappers.<TmsTruckAxleNum>lambdaQuery()
                .eq(TmsTruckAxleNum::getStatus, 1)
                .eq(TmsTruckAxleNum::getId, Long.parseLong(axleNumId)));
        if (axleNum == null) {
            return new TmsTruckAxleNum();
        }
        return axleNum;
    }

    /**
     * 根据企业id和车辆id查询绑定的司机信息
     *
     * @param truck
     * @param ents
     * @return
     */
    private KwfDriver getDriverInfo(Long truckId, Long entId) {
        //查询车辆关联司机信息
        KwfTruckReport truckReport = kwfTruckReportRepository.getOne(Wrappers.<KwfTruckReport>lambdaQuery()
                .eq(BaseModel::getDelFlag, 0)
                .eq(KwfTruckReport::getTruckId, truckId)
                .eq(KwfTruckReport::getEntId, entId)
                .eq(KwfTruckReport::getStatus, 1)
                .last("limit 1"));
        if (truckReport == null) {
            return new KwfDriver();
        }
        //查询司机信息
        KwfDriver driver = kwfDriverRepository.getOne(Wrappers.<KwfDriver>lambdaQuery()
                .eq(BaseModel::getDelFlag, 0)
                .eq(KwfDriver::getId, truckReport.getDriverId()));
        if (driver == null) {
            return new KwfDriver();
        }
        return driver;
    }


    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/7/6
     **/
    public List<KwfTruckVo> findPageHandle(Map<String, Object> params) {
        int systemType = LoginUserHolder.getSystemType();
        /**统计数据**/
        if (systemType == SystemTypeEnum.MANAGE.getCode()) {
            //新增客户经理权限过滤
            List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return new ArrayList<>();
                }
                authEntIdList.addAll(ids);
            }
            List<KwfTruckVo> counts = truckDao.findPageAll(params,authEntIdList);
            return counts;
        } else {
            Object keywords = params.get("keywords");
            String newKeywords = keywords == null ? null : StringUtils.objectStr(keywords).trim();
            if (StringUtils.isNotBlank(newKeywords)) {
                //查询企业
                List<Integer> entTypes = new ArrayList<>() {{
                    add(EntTypeEnum.LOGISTICS3.getCode());
                    add(EntTypeEnum.LOGISTICS4.getCode());
                }};
                List<Long> entIds = remoteUserService.findEntIds(entTypes,newKeywords);
                params.put("entIds", entIds);
                //查询用户
                List<Long> userIds = remoteUserService.findUserIds(new ArrayList<>() {{
                    add(LoginUserHolder.getEntId());
                }}, newKeywords);
                params.put("createBys", userIds);
            }
            params.put("entId", LoginUserHolder.getEntId());
            params.put("keywords", newKeywords);
            List<KwfTruckVo> counts = truckDao.findPage(params);
            return counts;
        }
    }

    /**
     * @param params 查询参数
     * @desc 查询
     * @author zk
     * @date 2023/7/6
     **/
    public List<Map<String, Object>> findList(Map<String, Object> params) {
        return truckDao.findList(params);
    }

    /**
     * @param {}
     * @desc 导出
     * @author zk
     * @date 2023/07/11
     **/
    public HttpResult importExcel(MultipartFile file) {/**文件存储**/
        importFileSave(file);

        /**参数校验**/
        HttpResult result = this.checkParams(file);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return result;
        }

        /**数据处理**/
        int count = 0;
        List<KwfTruckExcelImportDto> truckExcels = (List) result.getData();
        for (KwfTruckExcelImportDto kwfTruckExcel : truckExcels) {
            //车辆信息
            KwfTruck truck = new KwfTruck();
            truck.setTruckNo(kwfTruckExcel.getTruckNo());
            truck.setActualWeight(new BigDecimal(kwfTruckExcel.getActualWeight()));
            truck.setAuthStatus(Global.NUMERICAL_TWO);
            result = truckEdit(truck);
            if (result.getCode() == HttpStatus.SUCCESS_CODE) {
                count++;
            }
        }

        return HttpResult.ok("成功导入" + count + "行数据！");
    }

    /**
     * @param params 参数
     * @desc 新增车辆
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult add(KwfTruckDto params) {
        /**车辆信息**/
        KwfTruck truck = new KwfTruck();
        BeanUtils.copyProperties(params, truck);
        //证件都有数据则为已认证(前端校验认证数据必填)
        boolean bool = checkLicense(params);
        if (bool) {
            truck.setAuthStatus(Global.NUMERICAL_ONE);
        } else {
            truck.setAuthStatus(Global.NUMERICAL_TWO);
        }
        HttpResult result = truckEdit(truck);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return result;
        }
        truck = (KwfTruck) result.getData();

        /**车辆行驶证信息**/
        KwfTruckLicenseDto truckLicenseDto = params.getTruckLicense();
        if (truckLicenseDto != null) {
            truckLicenseDto.setTruckId(truck.getId());
            truckLicenseEdit(truckLicenseDto);
        }

        /**车辆道路运输许可证**/
        KwfTransportLicenseDto transportLicenseDto = params.getTransportLicense();
        if (transportLicenseDto != null) {
            transportLicenseDto.setTruckId(truck.getId());
            transportLicenseEdit(transportLicenseDto);
        }

        /**车队班组绑定**/
        truckFleetEdit(truck.getId(), params.getFleetId());

        return HttpResult.ok(result.getMsg(), truck);
    }

    /**
     * @param params 参数
     * @desc 修改车辆
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult update(KwfTruckDto params) {
        /**数据校验**/
        if (StringUtils.isBlank(params.getId())) {
            return HttpResult.error(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, "车辆信息ID不能为空！");
        }
        KwfTruck truck = truckDao.selectById(params.getId());
        if (truck == null) {
            return HttpResult.error("车辆信息不存在！");
        }

        /**车辆信息**/
        BeanUtils.copyProperties(params, truck);
        //证件都有数据则为已认证(前端校验认证数据必填)
        boolean bool = checkLicense(params);
        if (bool) {
            truck.setAuthStatus(Global.NUMERICAL_ONE);
        }
        HttpResult result = truckEdit(truck);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return result;
        }

        /**车辆行驶证信息**/
        KwfTruckLicenseDto truckLicenseDto = params.getTruckLicense();
        if (truckLicenseDto != null) {
            truckLicenseDto.setTruckId(truck.getId());
            truckLicenseEdit(truckLicenseDto);
        }

        /**车辆行驶证信息**/
        KwfTransportLicenseDto transportLicenseDto = params.getTransportLicense();
        if (transportLicenseDto != null) {
            transportLicenseDto.setTruckId(truck.getId());
            transportLicenseEdit(transportLicenseDto);
        }

        /**车队班组绑定**/
        truckFleetEdit(truck.getId(), params.getFleetId());
        return HttpResult.ok("车辆信息修改成功！");
    }

    /**
     * @param {ids：主键ID（多个以逗号隔开）}
     * @description 删除
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult del(String ids) {
        /**数据校验**/
        if (StringUtils.isBlank(ids)) {
            return HttpResult.error("请选择要删除的数据！");
        }

        /**数据组装**/
        String[] idArray = ids.split(",");
        KwfTruckEnt truckEntQuery = new KwfTruckEnt();
        truckEntQuery.setEntId(LoginUserHolder.getEntId());
        for (String id : idArray) {
            truckEntQuery.setTruckId(Long.parseLong(id));
            KwfTruckEnt truckEnt = truckEntDao.findByTruckEnt(truckEntQuery);
            if (truckEnt != null) {
                truckEnt.setDelFlag(Global.YES);
                if (truckEntDao.updateById(truckEnt) <= 0) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
                }
            } else {
                return HttpResult.error("选择删除的数据已不存在！");
            }
        }
        return HttpResult.ok("删除成功！");
    }

    /**
     * @param params 参数
     * @desc 更新车辆信息
     * @author zk
     * @date 2023/7/7
     **/
    public HttpResult truckEdit(KwfTruck params) {
        if (StringUtils.isBlank(params.getId())) {
            /**唯一性交易**/
            List<KwfTruck> trucks = truckDao.findTruck(new HashMap() {{
                put("truckNo", params.getTruckNo());
            }});
            if (CollectionUtils.isEmpty(trucks)) {
                /**新增**/
//                params.setEntId(LoginUserHolder.getEntId());
//                params.setEntId(params.getEntId() == null ? 1 : params.getEntId());// 暂时处理---------------zk
                params.setBusinessStatus(Global.NO);
                params.setStatus(Global.NO);
                int count = truckDao.insert(params);

                /**车辆信息与企业关联信息**/
                truckEntEdit(params);
                return count > 0 ? HttpResult.ok(params) : HttpResult.error("车辆信息新增失败！");
            } else {
                KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
                BeanUtils.copyPropertiesValue(params, truck);
                int count = truckDao.updateById(truck);

                /**车辆信息与企业关联信息**/
                KwfTruck truckEnt = new KwfTruck();
//                truckEnt.setEntId(LoginUserHolder.getEntId());
                truckEnt.setId(truck.getId());
                truckEntEdit(truckEnt);
                return count > 0 ? HttpResult.ok("车辆信息修改成功！", truck) : HttpResult.error("车辆信息修改失败！");
            }
        } else {
            /**唯一性交易**/
            List<KwfTruck> trucks = truckDao.findTruck(new HashMap() {{
                put("truckNo", params.getTruckNo());
            }});
            //校验list中对象key值是否存在与value不一致的情况
            boolean bool = listByKeyValue(trucks, params.getId());
            if (bool) {
                return HttpResult.error("车牌号已存在！");
            }

            /**更新**/
            int count = truckDao.updateById(params);
            return count > 0 ? HttpResult.ok("车辆信息修改成功！", params) : HttpResult.error("车辆信息修改失败！");
        }
    }

    /**
     * @param params 参数
     * @desc 更新车辆行驶证信息
     * @author zk
     * @date 2023/7/7
     **/
    public HttpResult truckLicenseEdit(KwfTruckLicenseDto params) {
        /**数据copy**/
        KwfTruckLicense truckLicense = new KwfTruckLicense();
        BeanUtils.copyProperties(params, truckLicense);
        truckLicense.setStatus(Global.YES);
        String certificateMain = truckLicense.getCertificateMain();
        String certificateRevolt = truckLicense.getCertificateRevolt();
        if (StringUtils.isBlank(certificateMain) && StringUtils.isBlank(certificateRevolt)) {
            truckLicense.setStatus(Global.NO);
            truckLicense.setCertificateMain(Global.EMPTY_STRING);
            truckLicense.setCertificateRevolt(Global.EMPTY_STRING);
        }
        truckLicense.setCertificateMain(StringUtils.isBlank(certificateMain)
                ? Global.EMPTY_STRING : truckLicense.getCertificateMain());
        truckLicense.setCertificateRevolt(StringUtils.isBlank(certificateRevolt)
                ? Global.EMPTY_STRING : truckLicense.getCertificateRevolt());

        /**数据更新**/
        int count = 0;
        KwfTruckLicense license = truckLicenseDao.findByTruckId(params.getTruckId());
        if (license == null) {
            count = truckLicenseDao.insert(truckLicense);
        } else {
            truckLicense.setId(license.getId());
            count = truckLicenseDao.updateById(truckLicense);
        }

        /**校验车辆是否有证书并更新状态**/
        checkLicense(truckLicense.getId());
        return count > 0 ? HttpResult.ok("车辆行驶证信息修改成功！") : HttpResult.error("车辆行驶证信息修改失败！");
    }

    /**
     * @param key 参数
     * @desc 查询车辆行驶证信息
     * @author zk
     * @date 2023/7/7
     **/
    public KwfTruckLicense findTruckLicenseByKey(Long key) {
        return truckLicenseDao.findByTruckId(key);
    }

    /**
     * @param params 参数
     * @desc 更新车辆道路运输许可证
     * @author zk
     * @date 2023/7/7
     **/
    public HttpResult transportLicenseEdit(KwfTransportLicenseDto params) {
        /**数据copy**/
        KwfTransportLicense transportLicense = new KwfTransportLicense();
        BeanUtils.copyProperties(params, transportLicense);
        transportLicense.setStatus(Global.YES);
        String certificateMain = transportLicense.getCertificateMain();
        String certificateRevolt = transportLicense.getCertificateRevolt();
        if (StringUtils.isBlank(certificateMain) && StringUtils.isBlank(certificateRevolt)) {
            transportLicense.setStatus(Global.NO);
            transportLicense.setCertificateMain(Global.EMPTY_STRING);
            transportLicense.setCertificateRevolt(Global.EMPTY_STRING);
        }
        transportLicense.setCertificateMain(StringUtils.isBlank(certificateMain)
                ? Global.EMPTY_STRING : transportLicense.getCertificateMain());
        transportLicense.setCertificateRevolt(StringUtils.isBlank(certificateRevolt)
                ? Global.EMPTY_STRING : transportLicense.getCertificateRevolt());

        /**数据更新**/
        int count = 0;
        KwfTransportLicense license = transportLicenseDao.findByTruckId(params.getTruckId());
        if (license == null) {
            count = transportLicenseDao.insert(transportLicense);
            return count > 0 ? HttpResult.ok("车辆驾驶证信息更新成功！") : HttpResult.error("车辆驾驶证信息更新失败！");
        } else {
            transportLicense.setId(license.getId());
            count = transportLicenseDao.updateById(transportLicense);
        }

        /**校验车辆是否有证书并更新状态**/
        checkLicense(transportLicense.getTruckId());
        return count > 0 ? HttpResult.ok("车辆驾驶证信息修改成功！") : HttpResult.error("车辆驾驶证信息修改失败！");
    }

    /**
     * @param key 参数
     * @desc 查询车辆道路运输许可证
     * @author zk
     * @date 2023/7/7
     **/
    public KwfTransportLicense findTransportLicenseByKey(Long key) {
        return transportLicenseDao.findByTruckId(key);
    }

    /**
     * @param params 参数
     * @desc 新增车辆信息与企业关联信息
     * @author zk
     * @date 2023/7/7
     **/
    public int truckEntEdit(KwfTruck params) {
        KwfTruckEnt truckEnt = new KwfTruckEnt();
        truckEnt.setTruckId(params.getId());
        truckEnt.setEntId(LoginUserHolder.getEntId());
        KwfTruckEnt ent = truckEntDao.findByTruckEnt(truckEnt);
        if (ent == null) {
            int count = truckEntDao.insert(truckEnt);
            return count;
        }
        return Global.MINUS_ONE;
    }
    public int truckEntEdit1(KwfTruck params, Long entId) {
        KwfTruckEnt truckEnt = new KwfTruckEnt();
        truckEnt.setTruckId(params.getId());
        truckEnt.setEntId(entId);
        KwfTruckEnt ent = truckEntDao.findByTruckEnt(truckEnt);
        if (ent == null) {
            int count = truckEntDao.insert(truckEnt);
            return count;
        }
        return Global.MINUS_ONE;
    }


    /**
     * @param truckId 车辆档案主键id fleetId 车队班组主键id
     * @desc 车队班组绑定
     * @author zk
     * @date 2023/7/7
     **/
    public HttpResult truckFleetEdit(Long truckId, Long fleetId) {
        /**数据校验**/
        if (fleetId == null) {
            return HttpResult.ok("未选择车队班组！");
        }
        KwfFleetTruck queryFleetTruck = new KwfFleetTruck();
        queryFleetTruck.setEntId(LoginUserHolder.getEntId());
        queryFleetTruck.setTruckId(truckId);
        KwfFleetTruck fleetTruck = fleetTruckDao.findByTruckFleet(queryFleetTruck);

        /**数据更新**/
        queryFleetTruck.setFleetId(fleetId);
        if (fleetTruck == null) {
            int count = fleetTruckDao.insert(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        } else {
            queryFleetTruck.setId(fleetTruck.getId());
            int count = fleetTruckDao.updateById(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        }
    }

    public HttpResult truckFleetEdit1(Long truckId, Long fleetId) {
        /**数据校验**/
        if (fleetId == null) {
            return HttpResult.ok("未选择车队班组！");
        }
        KwfFleetTruck queryFleetTruck = new KwfFleetTruck();
        queryFleetTruck.setEntId(LoginUserHolder.getEntId());
        queryFleetTruck.setTruckId(truckId);
        KwfFleetTruck fleetTruck = fleetTruckDao.findByTruckFleet(queryFleetTruck);

        /**数据更新**/
        queryFleetTruck.setFleetId(fleetId);
        if (fleetTruck == null) {
            int count = fleetTruckDao.insert(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        } else {
            queryFleetTruck.setId(fleetTruck.getId());
            int count = fleetTruckDao.updateById(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        }
    }
    public HttpResult truckFleetEdit1(Long truckId, Long fleetId, Long entId) {
        /**数据校验**/
        if (fleetId == null) {
            return HttpResult.ok("未选择车队班组！");
        }
        KwfFleetTruck queryFleetTruck = new KwfFleetTruck();
        queryFleetTruck.setEntId(entId);
        queryFleetTruck.setTruckId(truckId);
        KwfFleetTruck fleetTruck = fleetTruckDao.findByTruckFleet(queryFleetTruck);

        /**数据更新**/
        queryFleetTruck.setFleetId(fleetId);
        if (fleetTruck == null) {
            int count = fleetTruckDao.insert(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        } else {
            queryFleetTruck.setId(fleetTruck.getId());
            int count = fleetTruckDao.updateById(queryFleetTruck);
            return count > 0 ? HttpResult.ok("车队班组绑定成功！") : HttpResult.error("车队班组绑定失败！");
        }
    }
    /**
     * @param truckId 车辆id
     * @param entId   企业id
     * @desc 查询车队班组
     * @author zk
     * @date 2023/7/20
     **/
    public KwfFleet findByFleetTruck(Long truckId, Long entId) {
        return fleetTruckDao.findByFleetTruck(truckId, entId);
    }

    /**
     * @param file 上传文件
     * @desc 上传文件持久化
     * @author zk
     * @date 2023/7/6
     **/
    public void importFileSave(MultipartFile file) {
        FileInfo fileInfo = FileUtils.getFileDataList(file);
        fileInfo.setType(FileEnum.FILE_STORE_TYPE_OSS.getFileType());
        FileInfo returnFileInfo = FileUtils.uploadFileInfo(file, fileInfo, FileEnum.FILE_STORE_TYPE_OSS);

        KwfTruckImport truckImport = new KwfTruckImport();
        truckImport.setEntId(LoginUserHolder.getEntId());
        truckImport.setUrl(returnFileInfo.getFilePath());
        truckImport.setRemark(JSON.toJSONString(returnFileInfo));
        kwfTruckImportDao.insert(truckImport);

//        try {
//            //remoteFileService.fileInfoInsert(fileInfo);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * @desc 企业车辆统计
     * @author zk
     * @date 2023/9/18
     **/
    public Map<String, Object> truckStatistics() {
        return truckDao.truckStatistics(LoginUserHolder.getEntId());
    }


    /**
     * 通过企业id查询车辆ids
     * @param entId
     * @return
     */
    public List<Long> findTruckIdListByEntIds(Long entId) {
        //先查询车辆企业关联关系
        List<KwfTruckEnt> truckEntByEntIds = truckEntRepository.findTruckEntByEntIds(entId);
        if(CollectionUtils.isEmpty(truckEntByEntIds)){
            return new ArrayList<>();
        }
        return truckEntByEntIds.stream().map(KwfTruckEnt::getTruckId).collect(Collectors.toList());
    }

    /**
     * 通过企业id查询车辆信息
     * @param entId
     * @return
     */
    public List<KwfTruck> findTruckByEntIds(Long entId) {
        //先查询车辆企业关联关系
        List<KwfTruckEnt> truckEntByEntIds = truckEntRepository.findTruckEntByEntIds(entId);
        if(CollectionUtils.isEmpty(truckEntByEntIds)){
            return new ArrayList<>();
        }
        List<Long> truckIds = truckEntByEntIds.stream().map(KwfTruckEnt::getTruckId).collect(Collectors.toList());
        //通过车牌id查询车辆
        List<KwfTruck> truckList = kwfTruckRepository.findTruckByTruckIds(truckIds);
        if(CollectionUtils.isEmpty(truckList)){
            return new ArrayList<>();
        }
        return truckList;
    }

    /**
     * 统计车辆业务状态数量（全部、空闲、任务中）
     * @return 统计结果
     * @author system
     * @date 2025/12/08
     */
    public TruckBusinessStatusStatisticsVo truckBusinessStatusStatistics() {
        log.info("统计车辆业务状态数量（全部、空闲、任务中）");
        Long entId = LoginUserHolder.getEntId();
        // 统计全部车辆数量
        List<KwfTruck> trucks = findTruckByEntIds(entId);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty( trucks)){
            return TruckBusinessStatusStatisticsVo.of(0L, 0L, 0L);
        }
        // 统计空闲车辆数量（business_status = 0）
        Long idleCount = trucks.stream()
                .filter(x -> x.getBusinessStatus() == 0)
                .collect(Collectors.counting());
        // 统计任务中车辆数量（business_status = 1）
        Long busyCount = trucks.stream()
                .filter(x -> x.getBusinessStatus() == 1)
                .collect(Collectors.counting());
        return TruckBusinessStatusStatisticsVo.of(Long.parseLong(String.valueOf(trucks.size())), idleCount, busyCount);
    }

    /**
     * @param params {truckNo 車牌號}
     * @desc 车辆查询(业务关联 + 归属车辆)
     * @author zk
     * @date 2023/9/5
     **/
    public List<KwfTruckMonitorVo> findTruck(Map params) {
        long begTime = System.currentTimeMillis();
        /**车辆查询**/
        Map queryParams = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("truckNo", params.get("truckNo"));
        }};
        List<KwfTruckMonitorVo> truckList = findTruckMonitor(queryParams);
        if (truckList == null || truckList.size() == 0) {
            return truckList;
        }

        /**数据配置**/
        List<Long> entIds = new ArrayList<>();
        List<String> truckNos = new ArrayList<>();
        for (KwfTruckMonitorVo truck : truckList) {
            entIds.add(truck.getEntId());
            truckNos.add(truck.getTruckNo());
        }
        long begTime1 = System.currentTimeMillis();
        log.info("获取数据=" + (begTime1 - begTime));
        //企业数据集
        entIds = entIds.stream().distinct().collect(Collectors.toList());
        Map<Long, EntCacheResDto> ents = remoteSystemService.queryEntCacheMapByIds(entIds);
        //车辆定位数据集
        Map<String, KwfTruckGpsVo> truckGpsMap = findTruckLocateHandle(truckNos);
        long begTime2 = System.currentTimeMillis();
        log.info("获取GPS=" + (begTime2 - begTime1));

        /**数据组装**/
        for (KwfTruckMonitorVo truck : truckList) {
            EntCacheResDto ent = ents == null ? null : ents.get(truck.getEntId());
            KwfTruckGpsVo truckGps = truckGpsMap != null ? truckGpsMap.get(truck.getTruckNo()) : null;
            truck.setFirmName(ent != null ? ent.getFirmName() : null);
            truck.setRunStatus(truckGps != null ? truckGps.getRunStatus() : null);
        }
        long begTime3 = System.currentTimeMillis();
        log.info("数据组装=" + (begTime3 - begTime2));
        return truckList;
    }

    /**
     * @param truckNos 車牌號集
     * @description 车辆查询GPS(业务关联 + 归属车辆)
     * @author zk
     * @date 2023/9/6
     **/
    public List<KwfTruckGpsVo> findTruckGps(List<String> truckNos) {
        /**车辆查询**/
        List<KwfTruckGpsVo> truckGpsList = new ArrayList<>();
        Map<String, Object> queryParams = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("truckNos", truckNos);
        }};
        List<KwfTruckMonitorVo> truckList = findTruckMonitor(queryParams);
        if (truckList == null || truckList.size() == 0) {
            return truckGpsList;
        }

        //车辆定位数据集
        Map<String, KwfTruckGpsVo> truckGpsMap = findTruckLocateHandle(truckNos);

        /**数据组装**/
        for (KwfTruckMonitorVo truck : truckList) {
            KwfTruckGpsVo truckGps = truckGpsMap != null ? truckGpsMap.get(truck.getTruckNo()) : null;
            if (truckGps == null) {
                continue;
            }
            truckGps.setTruckNo(truck.getTruckNo());
            truckGps.setBusinessStatus(truck.getBusinessStatus());
            truckGpsList.add(truckGps);
        }

        return truckGpsList;
    }

    /**
     * @param params 参数
     * @desc 车辆查询(业务关联 + 归属车辆)
     * @author zk
     * @date 2023/9/6
     **/
    public List<KwfTruckMonitorVo> findTruckMonitor(Map params) {
        //企业PC/APP
        if (LoginUserHolder.getSystemType() == SystemTypeEnum.COMPANY.getCode()) {
            List<KwfTruckMonitorVo> trucks = new ArrayList<>();
            //企业属性
            String entTypes = LoginEntHolder.get().getEntTypes();
            //承运方
            Boolean bool = EntTypeEnum.carrier(entTypes);
            if (bool != null && bool) {
                params.put("entId", LoginUserHolder.getEntId());
                List<KwfTruckMonitorVo> carrierTrucks = truckDao.findTruckByEnt(params);
                trucks.addAll(carrierTrucks);
            }

            //托运方
            bool = EntTypeEnum.check(entTypes);
            if (bool != null && bool) {
                List<RTruckMonitorVo> checkTrucks = transportRemoteService.truckInTask(LoginUserHolder.getEntId());
                checkTrucks.forEach(order -> trucks.add(new KwfTruckMonitorVo(order.getEntId(), order.getTruckNo(), Global.NUMERICAL_ONE)));
            }

            return trucks;
        }

        //运营端+加客户经理数据过滤
        if (LoginUserHolder.getSystemType() == SystemTypeEnum.MANAGE.getCode()) {
            List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
            if (CollectionUtils.isEmpty(authEntIdList)) {
                List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
                if (CollectionUtils.isEmpty(ids)) {
                    return new ArrayList<>();
                }
                authEntIdList.addAll(ids);
            }
            return truckDao.findTruckByAll(params, authEntIdList);
        }
        return new ArrayList<>();
    }

    /**
     * @param truckNo 车牌号
     * @desc 车牌号查询车辆关联数据
     * @author zk
     * @date 2023/9/6
     **/
    public Map<String, Object> findDetailByTruckNo(String truckNo) {
        //定位信息
        KwfTruckGpsVo truckGps = findTruckLocate(truckNo);
        //运单信息
        RWaybillOrderVo waybillOrder = getWaybillOrder(truckNo, Global.NUMERICAL_THREE);
        String firmName = LoginEntHolder.getFirmName();
        if (LoginUserHolder.getSystemType() == SystemTypeEnum.MANAGE.getCode()) {
            List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("truckNo", truckNo);
            }});
            KwfTruck truck = CollectionUtils.isEmpty(trucks) ? null : trucks.get(Global.NUMERICAL_ZERO);
//            if (truck != null) {
//                //企业数据集
//                List<Long> entIds = new ArrayList<>() {{
//                    add(truck.getEntId());
//                }};
//                Map<Long, EntCacheResDto> ents = remoteSystemService.queryEntCacheMapByIds(entIds);
//                EntCacheResDto ent = ents == null ? null : ents.get(truck.getEntId());
//                firmName = ent != null ? ent.getFirmName() : null;
//            }
        }
        //详细地址
        String detailAddress = truckGps != null
                ? StringUtils.isNotBlank(truckGps.getDetailAddress())
                ? truckGps.getDetailAddress() : LocUtils.regeo(truckGps.getLng(), truckGps.getLat())
                : null;

        Map<String, Object> detail = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        detail.put("truckNo", truckNo);
        detail.put("firmName", firmName);
        detail.put("detailAddress", detailAddress);
        detail.put("speed", truckGps != null ? truckGps.getSpeed() : null);
        detail.put("gpsTime", truckGps != null ? truckGps.getGpsTime() : null);
        detail.put("driverName", waybillOrder != null ? waybillOrder.getDriverName() : null);
        detail.put("driverPhone", waybillOrder != null ? waybillOrder.getDriverPhone() : null);
        detail.put("startTime", waybillOrder != null ? DateUtils.formatV1(waybillOrder.getDepartureTime()) : null);
        detail.put("endTime", waybillOrder != null && waybillOrder.getDepartureTime() != null ? DateUtils.getCurrentTime() : null);
        detail.put("orderNo", waybillOrder != null ? waybillOrder.getWOrderNo() : null);
        return detail;
    }

    /**
     * @param type  字典类型
     * @param value 字典值
     * @desc 获取数据字典值
     * @author zk
     * @date 2023/8/30
     **/
    public String getDictValue(String type, String value) {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(value)) {
            return null;
        }
        List<String> dictKey = new ArrayList<>() {{
            add(type + Global.POUND + value);
        }};
        Map<String, SysDictResDto> dicts = remoteSystemService.queryDictMapByTypeValues(String.join(Global.COMMA, dictKey));
        SysDictResDto dict = dicts == null ? null : dicts.get(DictTypeEnum.APPROVED_DRIVING.getType() + Global.POUND + value);
        return dict != null ? dict.getLabel() : null;
    }

    /**
     * @param dictKey 字典值
     * @desc 获取数据字典
     * @author zk
     * @date 2023/9/11
     **/
    public Map<String, SysDictResDto> dict(List<String> dictKey) {
        if (CollectionUtils.isEmpty(dictKey)) {
            return Collections.emptyMap();
        }
        dictKey = dictKey.stream().distinct().collect(Collectors.toList());
        return remoteSystemService.queryDictMapByTypeValues(String.join(Global.COMMA, dictKey));
    }

    /**
     * @param params 参数
     * @desc 校验车辆是否有证书
     * @author zk
     * @date 2023/7/11
     **/
    public boolean checkLicense(KwfTruckDto params) {
        //车辆行驶证信息
        KwfTruckLicenseDto license = params.getTruckLicense();
        if (license == null || (StringUtils.isBlank(license.getCertificateMain())
                && StringUtils.isBlank(license.getCertificateRevolt()))) {
            return false;
        }
        //车辆道路运输许可证
        KwfTransportLicenseDto transportLicense = params.getTransportLicense();
        if (transportLicense == null || (StringUtils.isBlank(transportLicense.getCertificateMain())
                && StringUtils.isBlank(transportLicense.getCertificateRevolt()))) {
            return false;
        }
        return true;
    }

    /**
     * @param truckId 车辆主键id
     * @desc 校验车辆是否有证书并更新状态
     * @author zk
     * @date 2023/7/11
     **/
    public void checkLicense(Long truckId) {
        //车辆行驶证信息
        KwfTruckLicense license = this.findTruckLicenseByKey(truckId);
        if (license == null || (StringUtils.isBlank(license.getCertificateMain())
                && StringUtils.isBlank(license.getCertificateRevolt()))) {
            return;
        }
        //车辆道路运输许可证
        KwfTransportLicense transportLicense = this.findTransportLicenseByKey(truckId);
        if (transportLicense == null || (StringUtils.isBlank(transportLicense.getCertificateMain())
                && StringUtils.isBlank(transportLicense.getCertificateRevolt()))) {
            return;
        }
        //更新数据
        KwfTruck truck = new KwfTruck();
        truck.setId(truckId);
        truck.setAuthStatus(Global.NUMERICAL_ONE);
        truckDao.updateById(truck);
    }

    /**
     * @param file 上传文件
     * @desc 参数校验
     * @author zk
     * @date 2023/8/16
     **/
    public HttpResult checkParams(MultipartFile file) {
        ExcelReader excelReader = null;
        try {
            /**数据校验**/
            if (ExcelUtil.checkExcel(file)) {
                return HttpResult.error("请上传Excel格式的文件！");
            }

            ExcelImportListener importListener = new ExcelImportListener();
            InputStream inputStream = file.getInputStream();
            excelReader = EasyExcel.read(inputStream, importListener).build();

            ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(2).head(KwfTruckExcelImportDto.class).build();
            excelReader.read(readSheet);
            if (importListener.getErrorList().size() > 0) {
                return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "数据格式不正确，请确认！", importListener.getErrorList());
            }
            if (importListener.getDataList().size() == 0) {
                return HttpResult.error("导入数据不能空！");
            }

            return HttpResult.ok(importListener.getDataList());
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.error("车辆导入异常！");
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
    }

    /**
     * 校验list中对象key值是否存在与value不一致的情况
     *
     * @param list  数据集
     * @param value 匹配值
     * @return
     */
    public static boolean listByKeyValue(List<KwfTruck> list, Long value) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        for (KwfTruck truck : list) {
            if (value != null && !truck.getId().equals(value)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param truckNos 车牌号
     * @desc 查询车辆定位数据
     * @author zk
     * @date 2023/9/5
     **/
    public Map<String, KwfTruckGpsVo> findTruckLocateHandle(List<String> truckNos) {
        /**车牌号超过100则分批次请求数据**/
        int maxLimit = 500;
        List<List<String>> truckNoList = new ArrayList<List<String>>();
        List<String> findTruckSon = null;
        for (int i = 0; i < truckNos.size(); i++) {
            if (i % maxLimit == 0) {
                findTruckSon = new ArrayList<String>();
                truckNoList.add(findTruckSon);
            }
            findTruckSon.add(truckNos.get(i));
        }

        /**获取数据**/
        Map<String, KwfTruckGpsVo> truckGpsMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        for (List<String> turckNo : truckNoList) {
            Map<String, KwfTruckGpsVo> truckGps = findTruckLocate(turckNo);
            truckGpsMap.putAll(truckGps);
        }

        return truckGpsMap;
    }

    /**
     * @param truckNos 车牌号
     * @desc 查询车辆定位数据
     * @author zk
     * @date 2023/9/5
     **/
    public RWaybillOrderVo getWaybillOrder(String truckNo, int busStatus) {
        try {
            List<RWaybillOrderVo> waybillOrders = transportRemoteService.findWaybillOrder(new RWaybillOrderDto(truckNo, busStatus));
            if (CollectionUtils.isEmpty(waybillOrders)) {
                return null;
            }
            return waybillOrders.get(Global.NUMERICAL_ZERO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Value("${external.openapi.queryLocate}")
    private String queryLocate;
    @Value("${external.openapi.queryLocateTrack}")
    private String queryLocateTrack;

    /**
     * @param truckNos 车牌号
     * @desc 查询车辆定位数据
     * @author zk
     * @date 2023/9/5
     **/
    public Map<String, KwfTruckGpsVo> findTruckLocate(List<String> truckNos) {
        Map<String, KwfTruckGpsVo> truckGpsMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (truckNos == null || truckNos.size() == 0) {
            return truckGpsMap;
        }

        try {
            Map<String, Object> params = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("vehicleNoList", truckNos);
            }};

            long begTime = System.currentTimeMillis();
            String httpResult = HttpClientUtil.post(queryLocate, JSON.toJSONString(params));
            long entTime = System.currentTimeMillis();
            if (StringUtils.isNotBlank(httpResult)) {
                JSONObject result = JSONObject.parseObject(httpResult);
                if (result.getInteger("code") != null && result.getInteger("code") != 200) {
                    return truckGpsMap;
                }
                JSONArray trucks = result.getJSONArray("data");
                for (int i = 0; trucks != null && i < trucks.size(); i++) {
                    JSONObject truck = trucks.getJSONObject(i);
                    JSONObject locateInfo = truck.getJSONObject("locateInfo");
                    KwfTruckGpsVo truckGps = new KwfTruckGpsVo();
                    truckGps.setTruckNo(truck.getString("vehicleNo"));
                    truckGps.setLat(locateInfo.getString("lat"));
                    truckGps.setLng(locateInfo.getString("lng"));
                    truckGps.setSpeed(locateInfo.getDouble("speed"));
                    truckGps.setGpsTime(locateInfo.getString("createTime"));
                    truckGps.setRunStatus(runStatus(truckGps.getGpsTime(), truckGps.getSpeed()));
                    truckGpsMap.put(truckGps.getTruckNo(), truckGps);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return truckGpsMap;
    }

    /**
     * @param params {truckNos 車牌號集, startTime 開始實際, endTime 結束時間}
     * @desc 车辆查询GPS(通过车牌号查询)
     * @author zk
     * @date 2023/9/27
     **/
    public List<KwfTruckGpsVo> queryLocateTrack(GpsByTruckNoDto params) {
        List<KwfTruckGpsVo> truckGpsList = new ArrayList<>();
        long page = 1, pageSize = 1000, size = 0, pages = 0;
        Map queryParams = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("vehicleNo", params.getTruckNo());
            put("startTime", params.getStartTime());
            put("endTime", params.getEndTime());
            put("page", page);
            put("pageSize", pageSize);
        }};

        String httpResult = HttpClientUtil.post(queryLocateTrack, JSON.toJSONString(queryParams));
        if (StringUtils.isNotBlank(httpResult)) {
            JSONObject result = JSONObject.parseObject(httpResult);
            if (result.getInteger("code") != null && result.getInteger("code") != 200) {
                return truckGpsList;
            }
            JSONObject data = result.getJSONObject("data");
            if (data == null) {
                return truckGpsList;
            }
            size = data.getLong("size");
            pages = size / pageSize + (size % pageSize > 0 ? 1 : 0);
            JSONArray trucks = data.getJSONArray("list");
            for (int i = 0; trucks != null && i < trucks.size(); i++) {
                JSONObject truck = trucks.getJSONObject(i);
                KwfTruckGpsVo truckGps = new KwfTruckGpsVo();
                truckGps.setLat(truck.getString("lat"));
                truckGps.setLng(truck.getString("lng"));
                truckGps.setSpeed(speed(truck.getString("speed")));
                truckGps.setGpsTime(truck.getString("createTime"));
                truckGps.setRunStatus(runStatus(truckGps.getGpsTime(), truckGps.getSpeed()));
                truckGpsList.add(truckGps);
            }

            if (pages <= 1) {
                return truckGpsList;
            }

            for (long i = 2; i <= pages; i++) {
                queryParams.put("page", i);
                httpResult = HttpClientUtil.post(queryLocate, JSON.toJSONString(queryParams));
                if (StringUtils.isNotBlank(httpResult)) {
                    result = JSONObject.parseObject(httpResult);
                    if (result.getInteger("code") != null && result.getInteger("code") != 200) {
                        continue;
                    }
                    data = result.getJSONObject("data");
                    if (data == null) {
                        continue;
                    }
                    trucks = data.getJSONArray("list");
                    for (int j = 0; trucks != null && j < trucks.size(); j++) {
                        JSONObject truck = trucks.getJSONObject(j);
                        KwfTruckGpsVo truckGps = new KwfTruckGpsVo();
                        truckGps.setTruckNo(truck.getString("vehicleNo"));
                        truckGps.setLat(truck.getString("lat"));
                        truckGps.setLng(truck.getString("lng"));
                        truckGps.setSpeed(speed(truck.getString("speed")));
                        truckGps.setGpsTime(truck.getString("createTime"));
                        truckGps.setRunStatus(runStatus(truckGps.getGpsTime(), truckGps.getSpeed()));
                        truckGpsList.add(truckGps);
                    }
                }
            }

        }
        return truckGpsList;
    }


    /**
     * @param truckNos 车牌号
     * @desc 查询车辆定位数据-单车牌号
     * @author zk
     * @date 2023/9/5
     **/
    public KwfTruckGpsVo findTruckLocate(String truckNo) {
        if (StringUtils.isBlank(truckNo)) {
            return null;
        }

        try {
            Map<String, Object> params = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("vehicleNoList", new ArrayList<>() {{
                    add(truckNo);
                }});
            }};
            String httpResult = HttpClientUtil.post(queryLocate, JSON.toJSONString(params));
            if (StringUtils.isNotBlank(httpResult)) {
                JSONObject result = JSONObject.parseObject(httpResult);
                if (result.getInteger("code") != null && result.getInteger("code") != 200) {
                    return null;
                }
                JSONArray trucks = result.getJSONArray("data");
                if (trucks != null && trucks.size() > 0) {
                    JSONObject truck = trucks.getJSONObject(Global.NUMERICAL_ZERO);
                    JSONObject locateInfo = truck.getJSONObject("locateInfo");
                    KwfTruckGpsVo truckGps = new KwfTruckGpsVo();
                    truckGps.setTruckNo(truck.getString("vehicleNo"));
                    truckGps.setLat(locateInfo.getString("lat"));
                    truckGps.setLng(locateInfo.getString("lng"));
                    truckGps.setSpeed(speed(locateInfo.getString("speed")));
                    truckGps.setGpsTime(locateInfo.getString("createTime"));
                    truckGps.setRunStatus(runStatus(truckGps.getGpsTime(), truckGps.getSpeed()));
                    return truckGps;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param gpsTimeStr 地位时间
     * @param speed      速度
     * @desc 校验当前车辆运行状态
     * @author zk
     * @date 2023/9/5
     **/
    public int runStatus(String gpsTimeStr, Double speed) {
        if (StringUtils.isBlank(gpsTimeStr)) {
            return Global.NUMERICAL_TWO;
        }
        Date gpsTime = DateUtils.formatDate(gpsTimeStr);
        if (gpsTime == null) {
            return Global.NUMERICAL_TWO;
        }
        Date newTime = DateUtils.addDateMinutes(gpsTime, 15);
        int compareTo = DateUtils.compareTo(newTime, new Date());
        //-1 date1小于date2、0 date1等于date2、1 date1大于date2
        //运行状态(0行驶、1停止、2离线)
        return compareTo < 0 ? 2 : (speed == null || speed == 0) ? 1 : 0;
    }

    /**
     * @param obj 速度
     * @desc 速度处理
     * @author zk
     * @date 2023/9/5
     **/
    public static Double speed(String obj) {
        if (obj == null) {
            return Global.AMOUNT;
        }
        try {
            return Double.parseDouble(obj);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Global.AMOUNT;
        }
    }

    public CapacityStatusVo queryCapacityStatus(CapacityStatusReq req) {
        log.info("获取运力实况,请求参数：{}",JSON.toJSONString(req));
        //查询车队
        List<KwfFleet> kwfFleets = Lists.newArrayList();
        if (StringUtils.isNotBlank(req.getFleetName())){
            KwfFleet fleet = kwfFleetRepository.queryByEntIdAndName(req.getEntId() ,req.getFleetName());
            kwfFleets.add(fleet);
        }else {
            kwfFleets = kwfFleetRepository.findFleetByEntId(req.getEntId());
        }
        if (CollectionUtils.isEmpty(kwfFleets)){
            return new CapacityStatusVo();
        }
        //将车队列表转换成map
        Map<Long, KwfFleet> fleetMap = kwfFleets.stream()
                .collect(Collectors.toMap(BaseModel::getId, Function.identity(),(k1,k2)->k1));

        //根据车队id查询车辆-车队映射表
        List<KwfFleetTruck> kwfFleetTrucks= kwfFleetTruckRepository.queryByFleetIds(fleetMap.keySet());
        //按照车队进行分组
        Map<Long, List<KwfFleetTruck>> fleetIdAndFleetTruckListMap = kwfFleetTrucks.stream().collect(Collectors.groupingBy(KwfFleetTruck::getFleetId));
        List<CapacityStatusVo.Truck> truckList = Lists.newArrayList();
        //获取车辆id
        Set<Long> truckIds = kwfFleetTrucks.stream().map(KwfFleetTruck::getTruckId).collect(Collectors.toSet());

        //根据车辆id查询车辆信息
        List<KwfTruck> kwfTrucks = kwfTruckRepository.queryByTruckIds(truckIds);
        //获取要返回的车辆信息
        List<CapacityStatusVo.Truck> trucks = Lists.newArrayList();
        fleetIdAndFleetTruckListMap.forEach((fleetId, fleetTruckList) -> {
            buildTruck(fleetId, fleetTruckList, fleetMap,trucks,kwfTrucks);
        });

        CapacityStatusVo capacityStatusVo = new CapacityStatusVo();
        capacityStatusVo.setTruck(trucks);
        return capacityStatusVo;
    }

    private static void buildTruck(Long fleetId, List<KwfFleetTruck> fleetTruckList, Map<Long, KwfFleet> fleetMap,List<CapacityStatusVo.Truck> trucks,List<KwfTruck> kwfTrucks) {
        CapacityStatusVo.Truck truck = new CapacityStatusVo.Truck();
        truck.setFleetId(String.valueOf(fleetId));
        truck.setFleetName(fleetMap.getOrDefault(fleetId, new KwfFleet()).getName());
        //获取空闲车辆数
        truck.setIdleNum("0");
        truck.setRunningNum("0");
        if (CollectionUtils.isNotEmpty(fleetTruckList) ) {
            Set<Long> truckIds = fleetTruckList.stream()
                    .map(KwfFleetTruck::getTruckId)
                    .collect(Collectors.toSet());
            long idleNum = kwfTrucks.stream()
                    .filter(x -> truckIds.contains(x.getId()) && Objects.equals(x.getBusinessStatus(), 0))
                    .count();
            truck.setIdleNum(String.valueOf(idleNum));
            long runningNum = kwfTrucks.stream()
                    .filter(x -> truckIds.contains(x.getId()) && Objects.equals(x.getBusinessStatus(), 1))
                    .count();
            truck.setRunningNum(String.valueOf(runningNum));
        }
        truck.setAbnormalNum("0");
        trucks.add(truck);
    }


    public CapacityTotalStatusVo queryTotalCapacityStatus(CapacityStatusReq req) {
        log.info("获取运力实况总是统计");
        List<KwfFleet> kwfFleets = kwfFleetRepository.findFleetByEntId(req.getEntId());
        if (CollectionUtils.isEmpty(kwfFleets)){
            //初始化数据
            return initCapacityTotalStatusVo();
        }
        //获取车队id
        Set<Long> fleetIds = kwfFleets.stream().map(BaseModel::getId).collect(Collectors.toSet());
        //根据车队id查询车辆-车队映射表
        List<KwfFleetTruck> kwfFleetTrucks= kwfFleetTruckRepository.queryByFleetIds(fleetIds);
        //获取车辆id
        Set<Long> truckIds = kwfFleetTrucks.stream().map(KwfFleetTruck::getTruckId).collect(Collectors.toSet());
        //根据车辆id查询车辆信息
        List<KwfTruck> kwfTrucks = kwfTruckRepository.queryByTruckIds(truckIds);
        //获取返回数据
        return getCapacityTotalStatusVo(fleetIds, kwfTrucks);
    }


    private static CapacityStatusVo.Truck getTruck(KwfFleetTruck x, Map<Long, KwfFleet> fleetMap, Map<Long, List<KwfTruck>> truckIdAndTruckListMap) {
        CapacityStatusVo.Truck truck = new CapacityStatusVo.Truck();
        truck.setFleetId(String.valueOf(x.getFleetId()));
        truck.setFleetName(fleetMap.getOrDefault(x.getFleetId(), new KwfFleet()).getName());
        List<KwfTruck> fleetTrucks = truckIdAndTruckListMap.get(x.getTruckId());
        //获取空闲车辆数
        long idleNum = fleetTrucks.stream()
                .filter(ft -> Objects.equals(ft.getStatus(), 0))
                .count();
        truck.setIdleNum(String.valueOf(idleNum));
        long runningNum = fleetTrucks.stream()
                .filter(ft -> Objects.equals(ft.getStatus(), 1))
                .count();
        truck.setRunningNum(String.valueOf(runningNum));
        truck.setAbnormalNum("");
        return truck;
    }



    /**
     * 组装返回数据
     * @param fleetIds 车队id
     * @param truckIds 车辆id
     * @return
     */
    private static CapacityTotalStatusVo getCapacityTotalStatusVo(Set<Long> fleetIds, List<KwfTruck> kwfTrucks) {
        CapacityTotalStatusVo capacityTotalStatusVo = CapacityTotalStatusVo.getInstance();
        capacityTotalStatusVo.setFleetTotalNum(String.valueOf(fleetIds.size()));
        capacityTotalStatusVo.setTruckTotalNum(CollectionUtils.isEmpty(kwfTrucks) ? "0" :   String.valueOf(kwfTrucks.size()));
        capacityTotalStatusVo.setRunningTotalTruckNum(CollectionUtils.isEmpty(kwfTrucks) ? "0" :  String.valueOf(kwfTrucks.stream()
                .filter(x -> Objects.equals(x.getBusinessStatus(), 1))
                .count()));
        capacityTotalStatusVo.setIdleTotalTruckNum(CollectionUtils.isEmpty(kwfTrucks) ? "0" : String.valueOf(kwfTrucks.stream()
                .filter(x -> Objects.equals(x.getBusinessStatus(), 0))
                .count()));
        capacityTotalStatusVo.setAbnormalTotalTruckNum("0");
        return capacityTotalStatusVo;
    }

    private CapacityTotalStatusVo initCapacityTotalStatusVo() {
        CapacityTotalStatusVo capacityTotalStatusVo = CapacityTotalStatusVo.getInstance();
        capacityTotalStatusVo.setFleetTotalNum("0");
        capacityTotalStatusVo.setTruckTotalNum("0");
        capacityTotalStatusVo.setRunningTotalTruckNum("0");
        capacityTotalStatusVo.setIdleTotalTruckNum("0");
        capacityTotalStatusVo.setAbnormalTotalTruckNum("0");
        return capacityTotalStatusVo;
    }

    /**
     * 分页查询车辆信息
     * @param req 请求参数
     * @return 车辆信息
     */
    public PageDataResult<TruckInfoVo> pageTruckInfo(TruckInfoReq req) {
        log.info("分页查询车辆信息,请求参数：{}",JSON.toJSONString(req));
//        //查询车辆信息
//        Long entId = req.getEntId();
//        if (StringUtils.isNotBlank(req.getTruckNo())){
//            KwfTruck kwfTruck = kwfTruckRepository.queryByTruckNo(req.getTruckNo());
//        }
//
//        //分页查询所有企业
//        PageDataResult<KwsEnterpriseResDto> page = remoteSystemService.pageEnt(req.getPageNum(), req.getPageSize(), entId);
//        List<KwsEnterpriseResDto> enterpriseResDtoList = page.getList();
//        if (CollectionUtils.isEmpty(page.getList())){
//            return PageDataResult.empty(req.getPageNum(), req.getPageSize());
//        }
//        //获取企业id
//        List<Long> entIds = enterpriseResDtoList.stream()
//                .map(KwsEnterpriseResDto::getId)
//                .collect(Collectors.toList());
//        //获取车辆信息
//        List<KwfTruck> truckList = kwfTruckRepository.queryByEntIds(entIds, req.getTruckMark(), req.getStartTime(), req.getEndTime());
//        if (CollectionUtils.isEmpty(truckList)){
//            return PageDataResult.empty(req.getPageNum(), req.getPageSize());
//        }
//        if (Objects.nonNull(req.getEntId())){
//            truckList = truckList.stream()
//                    .filter(x->Objects.equals(x.getEntId(), req.getEntId()))
//                    .collect(Collectors.toList());
//        }
//        if (StringUtils.isNotBlank(req.getTruckNo())){
//            truckList = truckList.stream()
//                    .filter(x-> org.apache.commons.lang3.StringUtils.equals(x.getTruckNo(), req.getTruckNo()))
//                    .collect(Collectors.toList()) ;
//        }
//        //将车辆信息按照企业id进行分组
//        Map<Long, List<KwfTruck>> entIdAndTruckMap = truckList.stream()
//                .collect(Collectors.groupingBy(KwfTruck::getEntId));
//
//        //查询订单
//        List<RWaybillOrderVo> rWaybillOrderVos = transportRemoteService.queryWaybillOrderByEntId(req.getEntId());
//        Map<Long, List<RWaybillOrderVo>> truckIdAndOrderMap = Maps.newHashMap() ;
//        if (CollectionUtils.isNotEmpty(rWaybillOrderVos)){
//            truckIdAndOrderMap = rWaybillOrderVos.stream()
//                    .collect(Collectors.groupingBy(RWaybillOrderVo::getTruckId));
//        }
//
//
//        //遍历所有企业
//        Map<Long, List<RWaybillOrderVo>> finalTruckIdAndOrderMap = truckIdAndOrderMap;
//        List<TruckInfoVo> ents = enterpriseResDtoList.stream()
//                .map(e -> getTruckInfoVo(e, entIdAndTruckMap, finalTruckIdAndOrderMap))
//                .filter(x->CollectionUtils.isNotEmpty(x.getTruck()))
//                .collect(Collectors.toList());
//        return PageDataResult.success(page.getPageNum(),page.getPageSize(),page.getTotal(),ents);
        return PageDataResult.empty(req.getPageNum(), req.getPageSize());
    }


    private TruckInfoVo getTruckInfoVo(KwsEnterpriseResDto e, Map<Long, List<KwfTruck>> entIdAndTruckMap
                                        , Map<Long, List<RWaybillOrderVo>> truckIdAndOrderMap) {
        TruckInfoVo ent = new TruckInfoVo();
        ent.setEntId(String.valueOf(e.getId()));
        ent.setEntName(e.getFirmName());
        List<KwfTruck> kwfTrucks = entIdAndTruckMap.get(e.getId());
        if (CollectionUtils.isNotEmpty(kwfTrucks)) {
            List<TruckInfoVo.TruckData> truckDataList = kwfTrucks.stream()
                    .map(t -> getTruckData(t,truckIdAndOrderMap))
                    .collect(Collectors.toList());
            ent.setTruck(truckDataList);
        }
        return ent;
    }

    private TruckInfoVo.TruckData getTruckData(KwfTruck t, Map<Long, List<RWaybillOrderVo>> truckIdAndOrderMap) {
        TruckInfoVo.TruckData truck = new TruckInfoVo.TruckData();
        truck.setTruckId(String.valueOf(t.getId()));
        truck.setTruckNo(t.getTruckNo());
        truck.setBusinessStatus(String.valueOf(t.getBusinessStatus()));
        //根据车牌id查询
        VehicleReturnData vehicleReturnData = getVehicleReturnData(String.valueOf(t.getId()));
        if (Objects.nonNull(vehicleReturnData)){
            truck.setLatitude(vehicleReturnData.getLatitude());
            truck.setLongitude(vehicleReturnData.getLongitude());
        }
        truck.setTruckMark(String.valueOf(t.getTruckMark()));
        return truck;
    }

    private VehicleReturnData getVehicleReturnDataByOrderNo(String odrderNo) {
        VehicleDataDTO vehicleDataDTO = new VehicleDataDTO();
        vehicleDataDTO.setWOrderNo(odrderNo);
        
        try {
            // 使用 Feign 调用查询实时位置
            BaseIotResult<VehicleReturnData> result = vehicleTraceClient.queryRealTimeLocation(vehicleDataDTO);
            
            if (result == null || result.getCode() != "0" || result.getData() == null) {
                log.warn("查询实时轨迹返回空数据, 运单号: {}", odrderNo);
                return null;
            }
            
            return result.getData();
        } catch (Exception e) {
            log.error("查询任务轨迹异常, 运单号: {}", odrderNo, e);
            return null;
        }
    }

    public VehicleReturnData getVehicleReturnData(String truckId) {
        VehicleDataDTO vehicleDataDTO = new VehicleDataDTO();
        vehicleDataDTO.setCarNo(truckId);
        
        try {
            // 使用 Feign 调用查询实时位置
            BaseIotResult<VehicleReturnData> result = vehicleTraceClient.queryRealTimeLocation(vehicleDataDTO);
            
            if (result == null || result.getCode() != "0" || result.getData() == null) {
                log.warn("查询实时轨迹返回空数据, 车牌号: {}", truckId);
                return null;
            }
            
            return result.getData();
        } catch (Exception e) {
            log.error("查询任务轨迹异常, 车牌号: {}", truckId, e);
            return null;
        }
    }

    public PageDataResult<AppTruckInfoVo> pageAppTruckInfo(TruckInfoReq req) {
        log.info("app端分页查询车辆信息,请求参数：{}",JSON.toJSONString(req));
        //查询车辆信息
        Long entId = req.getEntId();
        List<Long> truckIdList = findTruckIdListByEntIds(entId);
        IPage<KwfTruck> page = kwfTruckRepository.queryByCondition(truckIdList,req.getTruckNo(),req.getTruckMark(),req.getStartTime(),req.getEndTime(),req.getPageNum(),req.getPageSize());
        List<KwfTruck> truckList = page.getRecords();
        if (CollectionUtils.isEmpty(truckList)){
            return PageDataResult.empty(req.getPageNum(), req.getPageSize());
        }
        //entId映射企业信息
        Map<Long, KwsEnterpriseResDto> entIdKwsEnterpriseResDtoMap = remoteSystemService.queryEnterpriseByEntIds(Lists.newArrayList(entId));
        //根据车辆车辆id，查询车队
        Set<Long> truckIds = truckList.stream().map(BaseModel::getId).collect(Collectors.toSet());
        List<KwfFleetTruck> kwfFleetTrucks = kwfFleetTruckRepository.queryByTruckIds(truckIds);
        Map<Long, List<KwfFleetTruck>> truckIdAndFleetTruckMap = new HashMap<>();
        Set<Long> feltIds = new HashSet<>();
        if (CollectionUtils.isNotEmpty(kwfFleetTrucks)){
            truckIdAndFleetTruckMap = kwfFleetTrucks.stream()
                    .collect(Collectors.groupingBy(KwfFleetTruck::getTruckId));
            feltIds = kwfFleetTrucks.stream().map(KwfFleetTruck::getFleetId).collect(Collectors.toSet());
        }

        List<KwfFleet> fleets = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(feltIds)){
            fleets = kwfFleetRepository.findByfleetIds(feltIds);
        }


        Map<Long, KwfFleet> fleetIdAndFleetMap =new HashMap<>();
        if (CollectionUtils.isNotEmpty(fleets)){
            //车队映射车队信息
            fleetIdAndFleetMap = fleets.stream().collect(Collectors.toMap(KwfFleet::getId, Function.identity(), (k1, k2) -> k1));
        }

        //根据车辆车辆id，司机信息
        List<KwfFleetDriver> kwfFleetDrivers  =new ArrayList<>();
        if (CollectionUtils.isNotEmpty(feltIds)){
            kwfFleetDrivers = kwfFleetDriverRepository.findByFleetIds(feltIds);
        }

        Set<Long> driverIds = new HashSet<>();
        Map<Long, List<KwfFleetDriver>> fleetIdAndDriverMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(kwfFleetDrivers)){
            driverIds = kwfFleetDrivers.stream().map(KwfFleetDriver::getDriverId).collect(Collectors.toSet());
            //车队id映射车队司机信息
            fleetIdAndDriverMap = kwfFleetDrivers.stream().collect(Collectors.groupingBy(KwfFleetDriver::getFleetId));
        }
        List<KwfDriver> drivers = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(driverIds)){
             drivers = kwfDriverRepository.findByDriverIds(driverIds);

        }
        //查询运单
        List<RWaybillOrderVo>  rWaybillOrderVos = transportRemoteService.queryWaybillOrderByEntId(entId);

        Map<Long, List<RWaybillOrderVo>> truckIdAndWaybillOrderMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(rWaybillOrderVos)){
             truckIdAndWaybillOrderMap = rWaybillOrderVos.stream().collect(Collectors.groupingBy(RWaybillOrderVo::getTruckId));
        }

        Map<Long, KwfDriver> driverIdAndDriverMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(drivers)){
            //司机id映射司机信息
            driverIdAndDriverMap = drivers.stream().collect(Collectors.toMap(BaseModel::getId, Function.identity(), (k1, k2) -> k1));
        }


        //遍历所有企业
        Map<Long, List<KwfFleetTruck>> finalTruckIdAndFleetTruckMap = truckIdAndFleetTruckMap;
        Map<Long, KwfFleet> finalFleetIdAndFleetMap = fleetIdAndFleetMap;
        Map<Long, KwfDriver> finalDriverIdAndDriverMap = driverIdAndDriverMap;
        Map<Long, List<KwfFleetDriver>> finalFleetIdAndDriverMap = fleetIdAndDriverMap;
        Map<Long, List<RWaybillOrderVo>> finalTruckIdAndWaybillOrderMap = truckIdAndWaybillOrderMap;
        List<AppTruckInfoVo> ents = truckList.stream()
                .map(t-> getAppTruckInfoVo(t, entId, entIdKwsEnterpriseResDtoMap, finalTruckIdAndFleetTruckMap
                        , finalFleetIdAndFleetMap, finalDriverIdAndDriverMap, finalFleetIdAndDriverMap, finalTruckIdAndWaybillOrderMap))
                .collect(Collectors.toList());

        return PageDataResult.success(Integer.parseInt(String.valueOf(page.getCurrent())),Integer.parseInt(String.valueOf(page.getSize())),page.getTotal(),ents);
    }


    private AppTruckInfoVo getAppTruckInfoVo(KwfTruck t, Long entId, Map<Long, KwsEnterpriseResDto> entIdKwsEnterpriseResDtoMap
            ,Map<Long, List<KwfFleetTruck>> truckIdAndFleetTruckMap
            ,Map<Long, KwfFleet> fleetIdAndFleetMap
            , Map<Long, KwfDriver> driverIdAndDriverMap
            ,Map<Long, List<KwfFleetDriver>> fleetIdAndDriverMap
            ,Map<Long, List<RWaybillOrderVo>> finalTruckIdAndWaybillOrderMap) {
        AppTruckInfoVo truckInfoVo = new AppTruckInfoVo();
        truckInfoVo.setEntId(String.valueOf(entId));
        KwsEnterpriseResDto enterpriseResDto = entIdKwsEnterpriseResDtoMap.getOrDefault(entId, new KwsEnterpriseResDto());
        truckInfoVo.setEntName(enterpriseResDto.getFirmName());
        truckInfoVo.setTruckId(String.valueOf(t.getId()));
        truckInfoVo.setTruckNo(t.getTruckNo());
        truckInfoVo.setTruckType(String.valueOf(t.getType()));
        List<KwfFleetTruck> kwfFleetTrucks = truckIdAndFleetTruckMap.get(t.getId());
        if (CollectionUtils.isNotEmpty(kwfFleetTrucks)){
            KwfFleetTruck kwfFleetTruck = kwfFleetTrucks.get(0);
            KwfFleet fleet = fleetIdAndFleetMap.getOrDefault(kwfFleetTruck.getFleetId(), new KwfFleet());
            truckInfoVo.setFleetId(String.valueOf(kwfFleetTruck.getFleetId()));
            truckInfoVo.setFleetName(fleet.getName());
            List<KwfFleetDriver> kwfFleetDrivers = fleetIdAndDriverMap.get(kwfFleetTruck.getFleetId());
            if (CollectionUtils.isNotEmpty(kwfFleetDrivers)){
                KwfFleetDriver kwfFleetDriver = kwfFleetDrivers.get(0);
                KwfDriver driver = driverIdAndDriverMap.getOrDefault(kwfFleetDriver.getDriverId(), new KwfDriver());
                truckInfoVo.setDriverId(String.valueOf(kwfFleetDriver.getDriverId()));
                truckInfoVo.setDriverName(driver.getName());
                truckInfoVo.setDriverPhone(driver.getPhone());
            }
        }
        //根据车牌id查询
        VehicleReturnData vehicleReturnData = getVehicleReturnData(String.valueOf(t.getId()));
        if (Objects.nonNull(vehicleReturnData)){
            truckInfoVo.setLatitude(vehicleReturnData.getLatitude());
            truckInfoVo.setLongitude(vehicleReturnData.getLongitude());
        }
        List<RWaybillOrderVo> rWaybillOrderVos = finalTruckIdAndWaybillOrderMap.get(t.getId());
        if (CollectionUtils.isNotEmpty(rWaybillOrderVos)){
            truckInfoVo.setOrderNo(rWaybillOrderVos.get(0).getWOrderNo());
            truckInfoVo.setOrderId(String.valueOf(rWaybillOrderVos.get(0).getId()));
        }
        truckInfoVo.setTruckMark(String.valueOf(t.getTruckMark()));
        truckInfoVo.setBusinessStatus(String.valueOf(t.getBusinessStatus()));
        return truckInfoVo;
    }


    /**
     * 通过企业id获取车牌信息
     * @param req
     * @return
     */
    public List<KwfTruckVo> queryTruckNo(TruckNoReq req) {
        List<Long> truckIds = findTruckIdListByEntIds(req.getEntId());
        List<KwfTruck> turkNoList = kwfTruckRepository.getTurkNoList(truckIds, req.getTruckNo());
        if (CollectionUtils.isEmpty(turkNoList)) {
            return Collections.emptyList();
        }
        List<KwfTruckVo> truckVoList = new ArrayList<>();
        for (KwfTruck truck : turkNoList) {
            KwfTruckVo truckVo = new KwfTruckVo();
            truckVo.setId(String.valueOf(truck.getId()));
            truckVo.setTruckNo(truck.getTruckNo());
            if (StringUtils.isNotBlank(truck.getCarAxis())) {
                TmsTruckAxleNum carAxisInfo = getCarAxisInfo(truck.getCarAxis());
                truckVo.setCarAxisId(truck.getCarAxis());
                truckVo.setCarAxis(carAxisInfo.getName());
                truckVo.setActualWeight(carAxisInfo.getLegalLoad() != null ? String.valueOf(carAxisInfo.getLegalLoad()) : "0.00");
            }
            truckVoList.add(truckVo);
        }
        return truckVoList;
    }


    public PageDataResult<KwfTruckDetailVo> queryPageCapacityTruck(TruckInfoReq req) {
         log.info("查询添加运力车辆请求参数：{}",JSON.toJSONString( req));
         if (Objects.isNull(req.getEntId())){
             throw new BusinessException("企业id不能为空");
         }
         Integer businessStatus = org.apache.commons.lang3.StringUtils.isBlank(req.getBusinessStatus()) ? null :
                 Integer.parseInt(req.getBusinessStatus());

        List<Long> truckIds = findTruckIdListByEntIds(req.getEntId());
        IPage<KwfTruck> kwfTruckIPage = kwfTruckRepository.queryByPage(req.getPageNum(), req.getPageSize(), truckIds, businessStatus,
                req.getTruckNo());
        List<KwfTruck> records = kwfTruckIPage.getRecords();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty( records)){
            return PageDataResult.empty(req.getPageNum(),req.getPageSize());
        }
        Set<Integer> carAxisIds = records.stream()
                .filter(x-> StringUtils.isNotBlank(x.getCarAxis()))
                .map(x->Integer.parseInt(x.getCarAxis()))
                .collect(Collectors.toSet());
        Map<Integer, TmsTruckAxleNum> truckAxleNumMap = Maps.newHashMap();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carAxisIds)){
            List<TmsTruckAxleNum> truckAxleNums = truckAxleNumRepository.queryByIds(carAxisIds);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(truckAxleNums)){
                truckAxleNumMap = truckAxleNums.stream()
                        .collect(Collectors.toMap(TmsTruckAxleNum::getId,Function.identity(),(v1, v2) -> v1));
            }
         }

        Map<Integer, TmsTruckAxleNum> finalTruckAxleNumMap = truckAxleNumMap;
        List<KwfTruckDetailVo> truckInfoVos = records.stream().map(truck -> {
            KwfTruckDetailVo truckInfoVo = new KwfTruckDetailVo();
            truckInfoVo.setId(truck.getId());
            truckInfoVo.setTruckNo(truck.getTruckNo());
            truckInfoVo.setBusinessStatus(truck.getBusinessStatus());
            Integer carAxisId = StringUtils.isNotBlank(truck.getCarAxis()) ? Integer.parseInt(truck.getCarAxis()) : null;
            TmsTruckAxleNum tmsTruckAxleNum = finalTruckAxleNumMap.getOrDefault(carAxisId, new TmsTruckAxleNum());
            truckInfoVo.setCarAxis(tmsTruckAxleNum.getName());
            return truckInfoVo;
        }).collect(Collectors.toList());
        return PageDataResult.of(kwfTruckIPage, truckInfoVos);
    }

    /**
     * 批量校验车牌号并查询车辆信息
     *
     * @param req 批量车牌号校验请求
     * @return 车牌号校验结果列表
     * @author system
     * @date 2025/06/24
     */
    public List<TruckValidateVo> batchValidateTruckNos(BatchTruckValidateReq req) {
        log.info("批量校验车牌号，请求参数：{}", JSON.toJSONString(req));
        Long entId = Objects.nonNull(req.getEntId()) ? req.getEntId() : LoginUserHolder.getEntId();
        List<TruckValidateVo> result = new ArrayList<>();
        
        if (StringUtils.isBlank(req.getTruckNos())) {
            return result;
        }

        // 使用TruckNoUtils拆分车牌号字符串（支持中文逗号、英文逗号、空格、换行符等）
        List<String> truckNoList = TruckNoUtils.splitTruckNos(req.getTruckNos());
        
        if (CollectionUtils.isEmpty(truckNoList)) {
            return result;
        }

        // 批量查询车辆信息
        Map<String, KwfTruck> truckMap = new HashMap<>();
        if (!truckNoList.isEmpty()) {
            List<KwfTruck> kwfTruckList = findTruckByEntIds(entId);
            //过滤掉已经停用的车牌号
            List<KwfTruck> trucks = kwfTruckList.stream().filter(Objects::nonNull)
                    .filter(truck -> truck.getTruckNo() != null && truckNoList.contains(truck.getTruckNo()) && Objects.equals(truck.getStatus(), 0))
                    .collect(Collectors.toList());
            truckMap = trucks.stream()
                .collect(Collectors.toMap(KwfTruck::getTruckNo, Function.identity(), (k1, k2) -> k1));
        }

        // 查询企业信息
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);

        // 处理每个车牌号
        for (String originalTruckNo : truckNoList) {
            TruckValidateVo vo = validateSingleTruckNo(originalTruckNo, truckMap, entCacheResDto);
            result.add(vo);
        }
        if (CollectionUtils.isNotEmpty( result)){
            result =  result.stream().filter(x->x.getValid()).collect(Collectors.toList());
        }
        List<TruckValidateVo> r = result.stream().filter(x -> Objects.nonNull(x.getTruckId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(r)){
            throw new BusinessException("车牌识别失败");
        }
        return r;
    }

    /**
     * 校验单个车牌号
     *
     * @param originalTruckNo 原始车牌号
     * @param truckMap 车辆信息Map
     * @param entMap 企业信息Map
     * @return 校验结果
     */
    private TruckValidateVo validateSingleTruckNo(String originalTruckNo, 
                                                  Map<String, KwfTruck> truckMap,
                                                  EntCacheResDto ent) {
        TruckValidateVo.TruckValidateVoBuilder builder = TruckValidateVo.builder()
            .originalTruckNo(originalTruckNo);

        // 格式化车牌号
        String formattedTruckNo = TruckNoUtils.formatTruckNo(originalTruckNo);
        builder.formattedTruckNo(formattedTruckNo);

        // 校验车牌号格式
        boolean isValid = TruckNoUtils.isValidTruckNo(formattedTruckNo);
        builder.valid(isValid);

        if (!isValid) {
            // 格式校验失败，返回错误信息
            String errorMsg = TruckNoUtils.getValidateErrorMsg(formattedTruckNo);
            builder.errorMsg(errorMsg)
                   .exists(false);
            return builder.build();
        }

        // 查询车辆信息
        KwfTruck truck = truckMap.get(formattedTruckNo);
        if (truck != null) {
            //查询车辆轴数
            TmsTruckAxleNum axleNum = getCarAxisInfo(truck.getCarAxis());
            // 车辆存在
            builder.exists(true)
                   .truckId(truck.getId())
                   .carAxis(axleNum.getName())
                   .entId(ent.getId())
                    .type(truck.getType())
                    .typeDesc(TruckTypeEnum.getName(truck.getType()));

            // 获取企业名称
            if (ent != null) {
                builder.entName(ent.getFirmName());
            }
        } else {
            // 车辆不存在
            builder.exists(false)
                   .errorMsg("车辆不在系统中");
        }

        return builder.build();
    }


    /**
     * 分页查询铲车订单
     * @param param
     * @return
     */
    public PageDataResult<TruckResp> pageQueryTruck(TruckQueryParam param) {
        log.info("查询司机信息列表：{}", JSON.toJSONString(param));
        List<Long> validTruckIds = new ArrayList<>();
        ///获取当前数据权限
        Set<Long> entIds = applyDataPermissionFilterToLogOrderIds(LoginUserHolder.getEntId());

        if (StringUtils.isNotBlank(param.getDriverName())) {
            //1.1 先根据司机名字模糊查询司机ID
            List<KwfDriver> drivers = kwfDriverRepository.list(Wrappers.<KwfDriver>lambdaQuery()
                            .like(KwfDriver::getName, param.getDriverName())
                            .eq(BaseModel::getDelFlag, 0)
            );

            if (CollectionUtils.isNotEmpty(drivers)) {
                List<Long> driverIds = drivers.stream().map(KwfDriver::getId).collect(Collectors.toList());
                // 1.2 拿着司机ID去关联表(kwf_truck_report)查车辆ID
                List<KwfTruckReport> reports = kwfTruckReportRepository.list(
                        Wrappers.<KwfTruckReport>lambdaQuery()
                                .in(KwfTruckReport::getDriverId, driverIds)
                                .in(KwfTruckReport::getEntId, entIds)
                                .eq(BaseModel::getDelFlag, 0)
                );
                if (CollectionUtils.isNotEmpty(reports)) {
                    //1.3 提取出车辆ID列表
                    validTruckIds = reports.stream()
                            .map(KwfTruckReport::getTruckId)
                            .distinct() // 去重
                            .collect(Collectors.toList());
                } else {
                    return PageDataResult.empty(param.getPageNum(), param.getPageSize());
                }

            } else {
                return PageDataResult.empty(param.getPageNum(), param.getPageSize());
            }
        }
        //根据企业id查询车辆信息
        List<KwfTruckEnt> truckEntByEntIds = truckEntRepository.findTruckEntByEntIds(entIds);
        Set<Long> truckIds = Optional.ofNullable(truckEntByEntIds).orElse(Collections.emptyList())
                .stream()
                .map(KwfTruckEnt::getTruckId)
                .collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(truckIds)) {
            return PageDataResult.empty(param.getPageNum(), param.getPageSize());
        }
        LambdaQueryWrapper<KwfTruck> wrapper = Wrappers.<KwfTruck>lambdaQuery()
                .in(CollectionUtils.isNotEmpty(truckIds), KwfTruck::getId, truckIds)
                .like(StringUtils.isNotBlank(param.getTruckNo()), KwfTruck::getTruckNo, param.getTruckNo())
                .eq(param.getType() != null, KwfTruck::getType, param.getType())
                .eq(param.getCarAxis() != null, KwfTruck::getCarAxis, param.getCarAxis())
                .eq(param.getEnergyType() != null, KwfTruck::getEnergyType, param.getEnergyType())
                .eq(param.getEev() != null, KwfTruck::getEev, param.getEev())
                .in(CollectionUtils.isNotEmpty(validTruckIds), KwfTruck::getId, validTruckIds);
        //黑名单
        if (param.getStatus() != null) {
            if (Objects.equals(param.getStatus(), 4)) {
                wrapper.eq(KwfTruck::getBlacklist, 1);
            } else {
                wrapper.eq(KwfTruck::getStatus, param.getStatus());
            }
        }

        wrapper.orderByDesc(KwfTruck::getCreateTime)
                .orderByDesc(KwfTruck::getId);

        //查询车辆信息数据
        Page<KwfTruck> pageByStatus = kwfTruckRepository.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        List<KwfTruck> records = pageByStatus.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            log.info("无车辆信息，param:{}", param);
            return PageDataResult.empty(param.getPageNum(), param.getPageSize());
        }
        List<TruckResp> truckPageResult = getTruckResp(records);
        return PageDataResult.success(param.getPageNum(), param.getPageSize(), pageByStatus.getTotal(), truckPageResult);
    }
    /**
     * 应用数据权限过滤，获取允许访问的企业ID集合
     * <p>
     * 该方法根据当前登录用户的数据权限配置，对传入的企业ID进行过滤。
     * 如果用户拥有全部数据权限或无需过滤，则返回包含原始企业ID的集合；
     * 否则，返回用户有权访问的企业ID与原始企业ID的并集（注：原逻辑为addAll，此处保持原意，通常权限过滤应为交集或替换，但根据原代码逻辑是保留原始并添加可见的，
     * 实际上原代码逻辑可能是想表达：基础是当前entId，如果有限制，则限制在可见范围内。但原代码使用了addAll，这可能导致权限扩大。
     * 鉴于指令是“添加详细注释以及日志”，我将忠实于原有逻辑进行注释补充，并增加关键节点的日志记录，以便排查权限问题。）
     * </p>
     *
     * @param entId 当前上下文中的基础企业ID
     * @return 经过数据权限过滤后的企业ID集合
     */
    private Set<Long> applyDataPermissionFilterToLogOrderIds(Long entId) {
        log.debug("开始应用数据权限过滤，基础企业ID: {}", entId);

        // 1. 获取当前用户的数据权限配置
        DataPermissionDTO perm = fetchDataPermissionForCurrentUser();
        
        // 初始化结果集合，默认包含传入的基础企业ID
        Set<Long> entIds = Sets.newHashSet(entId);

        // 如果未获取到权限配置对象，或者配置表明不需要进行数据过滤，则直接返回包含基础企业ID的集合
        if (perm == null || !perm.needFilter()) {
            log.debug("无需进行数据权限过滤，直接返回基础企业ID: {}", entId);
            return entIds;
        }

        // 创建用于存储过滤后结果的集合
        Set<Long> result = new HashSet<>(entIds);

        // 2. 处理企业维度数据权限
        // 判断是否对所有企业数据可见
        if (!perm.isAllVisible()) {
            log.debug("当前用户非全部数据可见，进入企业维度权限过滤逻辑");

            // 获取用户可见的企业ID列表
            Set<Long> visibleEntIds = perm.getVisibleEntIds();
            
            // 如果可见企业ID列表为空，说明该用户无权查看任何企业数据，返回空集合
            if (CollectionUtils.isEmpty(visibleEntIds)) {
                log.warn("数据权限过滤：用户无可见企业权限，返回空集合。用户ID: {}", LoginUserHolder.getUserId());
                return Sets.newHashSet();
            }

            // 原逻辑：将可见的企业ID添加到结果集中。
            // 注意：此处逻辑为 addAll，意味着结果集 = {基础entId} U {可见entIds}。
            // 如果业务意图是“仅保留基础entId且在可见范围内的”，则应使用 retainAll 或 intersection。
            // 此处保持原有代码逻辑不变，仅添加日志。
            result.addAll(visibleEntIds);
            
            log.debug("数据权限过滤完成。基础ID: {}, 可见ID数量: {}, 过滤后结果集大小: {}, 结果集内容: {}", 
                    entId, visibleEntIds.size(), result.size(), result);
        }

        return result;
    }


    private DataPermissionDTO fetchDataPermissionForCurrentUser() {
        try {
            DataPermissionFilterReqDto reqDto = new DataPermissionFilterReqDto();
            reqDto.setUserId(LoginUserHolder.getUserId());
            reqDto.setRoleId(LoginUserHolder.getCurrentRoleId());
            reqDto.setManager(LoginUserHolder.isManager());
            return dataPermissionFeignService.getDataPermissionFilter(reqDto);
        } catch (Exception e) {
            log.warn("获取数据权限失败，跳过本接口数据权限过滤: {}", e.getMessage());
            return null;
        }
    }
    /**
     *
     * @param records
     * @return
     */
    public List<TruckResp> getTruckResp(List<KwfTruck> trucks) {
        List<TruckResp> truckResps = new ArrayList<>();
        for (KwfTruck truck : trucks) {
            TruckResp truckResp = new TruckResp();
            truckResp.setId(truck.getId());
            truckResp.setTruckNo(truck.getTruckNo());
            truckResp.setType(truck.getType());
            truckResp.setTypeDesc(TruckTypeEnum.getName(truck.getType()));
            truckResp.setBrand(truck.getBrand());
            truckResp.setStatus(truck.getStatus());
            truckResp.setStatusDesc(TruckStatusEnum.getName(truck.getStatus()));
            truckResp.setCreateTime(truck.getCreateTime());
            truckResp.setBlacklist(truck.getBlacklist());
            truckResp.setRemark(truck.getRemark());
            truckResp.setAnnualInspectionTime(truck.getAnnualInspectionTime());
            //查询车辆轴数
            TmsTruckAxleNum axleNum = getCarAxisInfo(truck.getCarAxis());
            truckResp.setCarAxis(truck.getCarAxis());
            truckResp.setCarAxisName(axleNum.getName());

            //查询司机信息
            KwfDriver driver = getDriverInfo(truck.getId(), LoginUserHolder.getEntId());
            truckResp.setDriverName(driver.getName());

            truckResps.add(truckResp);
        }
        return truckResps;
    }

    /**
     * 车辆详情
     * @param param
     * @return
     */
    public TruckDetailResp truckDetail(TruckDetailParam param) {
        log.info("查询车辆详情，id：{}", JSON.toJSONString(param));
        if (param.getId() == null && (param.getTruckNo() == null || param.getTruckNo().trim().isEmpty())) {
            return new TruckDetailResp();
        }
        
        KwfTruck truck = kwfTruckRepository.getOne(Wrappers.<KwfTruck>lambdaQuery()
                .eq(param.getId() != null, KwfTruck::getId, param.getId())
                .eq(param.getTruckNo() != null && !param.getTruckNo().trim().isEmpty(), KwfTruck::getTruckNo, param.getTruckNo())
                .last("limit 1"));
        if (truck == null) {
            return new TruckDetailResp();
        }
        TruckDetailResp truckDetailResp = new TruckDetailResp();
        truckDetailResp.setId(truck.getId());
        truckDetailResp.setTruckNo(truck.getTruckNo());
        truckDetailResp.setType(truck.getType());
        truckDetailResp.setTypeDesc(TruckTypeEnum.getName(truck.getType()));

        truckDetailResp.setVin(truck.getVin());
        truckDetailResp.setBrand(truck.getBrand());
        truckDetailResp.setEnergyType(truck.getEnergyType());
        truckDetailResp.setEnergyTypeDesc(TruckEnergyTypeEnum.getName(truck.getEnergyType()));
        truckDetailResp.setEev(truck.getEev());
        truckDetailResp.setEevDesc(TruckEevEnum.getName(truck.getEev()));
        truckDetailResp.setStatus(truck.getStatus());
        truckDetailResp.setStatusDesc(TruckStatusEnum.getName(truck.getStatus()));
        truckDetailResp.setEngineNo(truck.getEngineNo());
        truckDetailResp.setAnnualInspectionTime(truck.getAnnualInspectionTime());
        truckDetailResp.setTransportValidityTime(truck.getTransportValidityTime());
        truckDetailResp.setPositionDevice(truck.getPositionDevice());
        truckDetailResp.setTruckLicense(truck.getTruckLicense());
        truckDetailResp.setTransportLicense(truck.getTransportLicense());
        truckDetailResp.setEnvironmentalList(truck.getEnvironmentalList());
        truckDetailResp.setBlacklist(truck.getBlacklist());
        truckDetailResp.setRemark(truck.getRemark());
        //轴数
        TmsTruckAxleNum axleNum = getCarAxisInfo(truck.getCarAxis());
        truckDetailResp.setCarAxis(truck.getCarAxis());
        truckDetailResp.setCarAxisName(axleNum.getName());

        //车队班组
        KwfFleet fleet = findByFleetTruck(truck.getId(), LoginUserHolder.getEntId());
        if (fleet != null) {
            truckDetailResp.setFleetId(fleet.getId());
            truckDetailResp.setFleetName(fleet.getName());
        }
        //查询司机信息
        KwfDriver driver = getDriverInfo(truck.getId(), LoginUserHolder.getEntId());
        truckDetailResp.setDriverName(driver.getName());

        return truckDetailResp;

    }

    /**
     * 保存车辆
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveTruck(TruckSaveParam param) {
        log.info("保存车辆，id：{}", JSON.toJSONString(param));
        if (Objects.equals(param.getEnergyType(), TruckEnergyTypeEnum.TRADITIONAL.getCode())) {
            if (param.getEev() == null) {
                throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "传统能源车辆的排放标准不能为空！");
            }
        }

        // 新增
        if (param.getId() == null) {
            KwfTruck kwfTruck = kwfTruckRepository.getOne(Wrappers.<KwfTruck>lambdaQuery()
                    .eq(KwfTruck::getTruckNo, param.getTruckNo()));
            if (kwfTruck == null) {
                //场景一：车辆不存在，执行新增流程
                KwfTruck truck = new KwfTruck();
                truck.setTruckNo(param.getTruckNo());
                truck.setType(param.getType());
                truck.setEnergyType(param.getEnergyType());
                truck.setEev(param.getEev());
                truck.setCarAxis(param.getCarAxis());
                truck.setBrand(param.getBrand());
                truck.setVin(param.getVin());
                truck.setEngineNo(param.getEngineNo());
                truck.setAnnualInspectionTime(param.getAnnualInspectionTime());
                truck.setTransportValidityTime(param.getTransportValidityTime());
                truck.setPositionDevice(param.getPositionDevice());
                truck.setTruckLicense(param.getTruckLicense());
                truck.setTransportLicense(param.getTransportLicense());
                truck.setEnvironmentalList(param.getEnvironmentalList());
                truck.setStatus(TruckStatusEnum.NORMAL.getCode());
                truck.setDelFlag(0);
                truck.setBlacklist(0);
                truck.setCreateTime(new Date());
                kwfTruckRepository.save(truck);

                // 车队班组绑定
                truckFleetEdit(truck.getId(), param.getFleetId());

                // 车辆信息与企业关联信息
                truckEntEdit(truck);
            } else {
                //场景二：车辆已存在，检查车辆企业关联
                List<KwfTruckEnt> truckEntList = truckEntRepository.findTruckEntByEntIdAndTruckId(LoginUserHolder.getEntId(), kwfTruck.getId());
                if (CollectionUtils.isNotEmpty(truckEntList)) {
                    throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_EXIST, "该车牌号已存在且已归属于当前企业，请勿重复添加");
                }
                // 车辆信息与企业关联信息
                truckEntEdit(kwfTruck);
            }
        } else {
            // 更新车辆
            KwfTruck truck = kwfTruckRepository.getById(param.getId());
            if (truck == null) {
                throw new BusinessPlatfromException(ErrorCodeEnum.DRIVER_NOT_FOUND, "车辆不已存在");
            }
            truck.setTruckNo(param.getTruckNo());
            truck.setType(param.getType());
            truck.setEnergyType(param.getEnergyType());
            truck.setEev(param.getEev());
            truck.setCarAxis(param.getCarAxis());
            truck.setBrand(param.getBrand());
            truck.setVin(param.getVin());
            truck.setEngineNo(param.getEngineNo());
            truck.setAnnualInspectionTime(param.getAnnualInspectionTime());
            truck.setTransportValidityTime(param.getTransportValidityTime());
            truck.setPositionDevice(param.getPositionDevice());
            truck.setTruckLicense(param.getTruckLicense());
            truck.setTransportLicense(param.getTransportLicense());
            truck.setEnvironmentalList(param.getEnvironmentalList());
            truck.setUpdateTime(new Date());
            kwfTruckRepository.updateById(truck);

            // 车队班组绑定
            truckFleetEdit(truck.getId(), param.getFleetId());
        }

    }
    /**
     * 保存车辆
     * @param param
     * @return
     */
    public void saveTruck1(TruckSaveParam param) {
        log.info("保存车辆，id：{}", JSON.toJSONString(param));
        if (Objects.equals(param.getEnergyType(), TruckEnergyTypeEnum.TRADITIONAL.getCode())) {
            if (param.getEev() == null) {
                throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "传统能源车辆的排放标准不能为空！");
            }
        }

        // 新增
        if (param.getId() == null) {
            KwfTruck kwfTruck = kwfTruckRepository.getOne(Wrappers.<KwfTruck>lambdaQuery()
                    .eq(KwfTruck::getTruckNo, param.getTruckNo()));
            KwfTruck truck = new KwfTruck();
            truck.setTruckNo(param.getTruckNo());
            truck.setType(param.getType());
            truck.setEnergyType(param.getEnergyType());
            truck.setEev(param.getEev());
            truck.setCarAxis(param.getCarAxis());
            truck.setBrand(param.getBrand());
            truck.setVin(param.getVin());
            truck.setEngineNo(param.getEngineNo());
            truck.setAnnualInspectionTime(param.getAnnualInspectionTime());
            truck.setTransportValidityTime(param.getTransportValidityTime());
            truck.setPositionDevice(param.getPositionDevice());
            truck.setTruckLicense(param.getTruckLicense());
            truck.setTransportLicense(param.getTransportLicense());
            truck.setEnvironmentalList(param.getEnvironmentalList());
            truck.setStatus(TruckStatusEnum.NORMAL.getCode());
            truck.setDelFlag(0);
            truck.setBlacklist(0);
            truck.setCreateTime(new Date());
            kwfTruckRepository.save(truck);

            // 车队班组绑定
            truckFleetEdit1(truck.getId(), param.getFleetId(),param.getEntId());

            // 车辆信息与企业关联信息
            truckEntEdit1(truck,param.getEntId());
        } else {
            // 更新车辆
            KwfTruck truck = kwfTruckRepository.getById(param.getId());
            if (truck == null) {
                throw new BusinessPlatfromException(ErrorCodeEnum.DRIVER_NOT_FOUND, "车辆不已存在");
            }
            truck.setTruckNo(param.getTruckNo());
            truck.setType(param.getType());
            truck.setEnergyType(param.getEnergyType());
            truck.setEev(param.getEev());
            truck.setCarAxis(param.getCarAxis());
            truck.setBrand(param.getBrand());
            truck.setVin(param.getVin());
            truck.setEngineNo(param.getEngineNo());
            truck.setAnnualInspectionTime(param.getAnnualInspectionTime());
            truck.setTransportValidityTime(param.getTransportValidityTime());
            truck.setPositionDevice(param.getPositionDevice());
            truck.setTruckLicense(param.getTruckLicense());
            truck.setTransportLicense(param.getTransportLicense());
            truck.setEnvironmentalList(param.getEnvironmentalList());
            truck.setUpdateTime(new Date());
            kwfTruckRepository.updateById(truck);

            // 车队班组绑定
            truckFleetEdit1(truck.getId(), param.getFleetId(),param.getEntId());
        }

    }
    /**
     * 车辆停用/启用
     * @param param
     * @return
     */
    public void batchUpdateStatus(TruckUpdateStatusParam param) {
        log.info("车辆停用/启用，param：{}", JSON.toJSONString(param));
        // 1. 校验状态合法性
        if (!param.getStatus().equals(TruckStatusEnum.NORMAL.getCode()) && !param.getStatus().equals(TruckStatusEnum.DISABLED.getCode())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "仅支持修改为正常或停用状态");
        }
        List<KwfTruck> trucks = kwfTruckRepository.findTruckByTruckIds(param.getIds());
        if (CollectionUtils.isEmpty(trucks)) {
            return;
        }

        // 2.启用:校验车辆都是停用状态
        if (param.getStatus().equals(TruckStatusEnum.NORMAL.getCode())) {
            boolean b = trucks.stream()
                    .allMatch(truck -> truck.getStatus() != null && truck.getStatus().equals(TruckStatusEnum.DISABLED.getCode()));
            if (!b) {
                throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "[启用]所选车辆不全是停用状态");
            }
        }
        // 3.停用:校验车辆都是正常状态
        if (param.getStatus().equals(TruckStatusEnum.DISABLED.getCode())) {
            boolean b = trucks.stream()
                    .allMatch(truck -> truck.getStatus() != null && truck.getStatus().equals(TruckStatusEnum.NORMAL.getCode()));
            if (!b) {
                throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "[停用]所选车辆不全是正常状态");
            }
        }
        LambdaUpdateWrapper<KwfTruck> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(KwfTruck::getId, param.getIds());
        updateWrapper.set(KwfTruck::getStatus, param.getStatus());
        kwfTruckRepository.update(updateWrapper);

    }

    /**
     * 黑名单
     * @param param
     * @return
     */
    public void toggleBlacklist(TruckBlacklistParam param) {
        log.info("黑名单业务：{}", JSON.toJSONString(param));
        // 校验
        if (param.getBlacklist() != 0 && param.getBlacklist() != 1) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "仅支持修改为正常或黑名单状态");
        }
        KwfTruck truck = kwfTruckRepository.getById(param.getId());
        if (truck == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_REVIEW_ERROR, "车辆不存在");
        }
        truck.setBlacklist(param.getBlacklist());
        kwfTruckRepository.updateById(truck);
    }

    /**
     * 车辆审核
     * @param param
     * @return
     */
    public void reviewTruck(TruckReviewParam param) {
        log.info("车辆审核：{}", JSON.toJSONString(param));
        // 校验
        if (param.getStatus() != 0 && param.getStatus() != 3) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "仅支持修改为正常或审核失败状态");
        }
        KwfTruck truck = kwfTruckRepository.getById(param.getId());
        if (truck == null || !Objects.equals(TruckStatusEnum.PENDING_REVIEW.getCode(), truck.getStatus())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_REVIEW_ERROR, "车辆审核状态异常：当前状态非待审核");
        }
        if (Objects.equals(TruckStatusEnum.REVIEW_REJECTED.getCode(), param.getStatus())
                && StringUtils.isBlank(param.getRemark())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_REVIEW_ERROR, "审核理由不能为空");
        }

        truck.setStatus(param.getStatus());
        if (Objects.equals(TruckStatusEnum.REVIEW_REJECTED.getCode(), param.getStatus())){
            truck.setRemark(param.getRemark());
        }
        kwfTruckRepository.updateById(truck);
    }


}
