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.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.common.enums.enums.FileEnum;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.EntTypeEnum;
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.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.easyexcel.ExcelImportListener;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.fleet.dao.KwfDriverMapper;
import com.sckw.fleet.dao.KwfTruckMapper;
import com.sckw.fleet.dao.KwfTruckReportImportMapper;
import com.sckw.fleet.dao.KwfTruckReportMapper;
import com.sckw.fleet.model.KwfDriver;
import com.sckw.fleet.model.KwfTruck;
import com.sckw.fleet.model.KwfTruckReport;
import com.sckw.fleet.model.KwfTruckReportImport;
import com.sckw.fleet.model.dto.KwfChangeFleetDto;
import com.sckw.fleet.model.dto.KwfTruckReportDto;
import com.sckw.fleet.model.dto.KwfTruckReportExcelImportDto;
import com.sckw.fleet.model.vo.KwfTableTopCount;
import com.sckw.fleet.model.vo.KwfTruckReportVo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zk
 * @desc 车辆上报
 * @date 2023/7/15 0006
 */
@Service
public class KwfTruckReportService {

    @Autowired
    KwfTruckMapper truckDao;
    @Autowired
    KwfDriverMapper driverDao;
    @Autowired
    KwfTruckReportMapper truckReportDao;
    @Autowired
    KwfTruckReportImportMapper kwfTruckReportImportDao;
    @Autowired
    KwfDriverService driverService;
    @Autowired
    KwfTruckService truckService;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    @DubboReference(version = "1.0.0", group = "design", check = false,timeout = 8000)
    private RemoteUserService remoteUserService;


    /**
     * @param params 参数
     * @desc 统计
     * @author zk
     * @date 2023/7/11
     **/
    public Map statistics(Map<String, Object> params) {
        /**参数处理**/
        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);
        }

        /**统计数据**/
        List<KwfTableTopCount> counts = truckReportDao.statistics(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<>(Global.NUMERICAL_SIXTEEN){{put("正常", 1); put("临时", 2); put("异常", 3);}};
        for(Map.Entry<String, Integer> entry:authStatusMap.entrySet()){
            System.out.println(entry.getKey()+"--->"+entry.getValue());
            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<String, Object> tableCount = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        tableCount.put("tableTop", countList);
        tableCount.put("tableBottom", tatol);
        return tableCount;
    }

    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/7/15
     **/
    public List<KwfTruckReportVo> findPage(Map<String, Object> params) {
        /**参数处理**/
        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);
        }

        /**查询分页数据**/
        List<KwfTruckReportVo> trucks = truckReportDao.findPage(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 (KwfTruckReportVo truck:trucks) {
            createBys.add(Long.parseLong(truck.getCreateBy()));
            entIds.add(Long.parseLong(truck.getDriverEntId()));
            entIds.add(Long.parseLong(truck.getTruckEntId()));
            dictKey.add(DictTypeEnum.COLOR_TYPE.getType() + pound + truck.getColor());
            dictKey.add(DictTypeEnum.TRUCK_TYPE.getType() + pound + truck.getTruckType());
        }
        //用户数据集
        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);
        //数据字典
        dictKey = dictKey.stream().distinct().collect(Collectors.toList());
        Map<String, SysDictResDto> dicts = remoteSystemService.queryDictMapByTypeValues(String.join(",", dictKey));

        /**数据组装**/
        for (KwfTruckReportVo truck:trucks) {
            UserCacheResDto user = users == null ? null : users.get(Long.parseLong(truck.getCreateBy()));
            EntCacheResDto ent = ents == null ? null : ents.get(Long.parseLong(truck.getDriverEntId()));
            SysDictResDto color = dicts == null ? null : dicts.get(DictTypeEnum.COLOR_TYPE.getType() + pound + truck.getColor());
            SysDictResDto type = dicts == null ? null : dicts.get(DictTypeEnum.COLOR_TYPE.getType() + pound + truck.getTruckType());
            truck.setCreateByName(user != null ? user.getName() : null);
            truck.setDriverFirmName(ent != null ? ent.getFirmName() : null);
            ent = ents == null ? null : ents.get(Long.parseLong(truck.getTruckEntId()));
            truck.setTruckFirmName(ent != null ? ent.getFirmName() : null);
            truck.setColorName(color != null ? color.getLabel() : null);
            truck.setTruckTypeName(type != null ? type.getLabel() : null);
        }
        return trucks;
    }

    /**
     * @param params {。。。}
     * @desc 查询
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult findList(Map<String, Object> params) throws SystemException {
        return HttpResult.ok(truckReportDao.findList(params));
    }

    /**
     * @param params {。。。}
     * @desc 上报车辆业务状态统计
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult busStatusStatistics(@RequestBody Map<String, Object> params) throws SystemException {
        params.put("entId", LoginUserHolder.getEntId());
        List<Map<String, Object>> trucks = truckReportDao.findList(params);
        /**全部数据-处理**/
        List<KwfTableTopCount> countList = new ArrayList();
        countList.add(new KwfTableTopCount("全部", null, trucks != null ? trucks.size() : 0));

        //状态数据计算
        int idle = 0;
        for (Map<String, Object> truck:trucks) {
            Object obj = truck.get("businessStatus");
            if (StringUtils.isNotBlank(obj) && NumberUtils.parseInt(obj) == 0) {
                idle ++;
            }
        }
        countList.add(new KwfTableTopCount("空闲", String.valueOf(0), idle));
        countList.add(new KwfTableTopCount("任务", String.valueOf(1), trucks != null ? (trucks.size() - idle) : 0));
        return HttpResult.ok(countList);
    }

    /**
     * @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;
//        }
//
//        List<KwfTruckReportExcelImportDto> truckReportExcels = (List)result.getData();
//        List<String> errorList = checkParams(truckReportExcels);
//        if (!CollectionUtils.isEmpty(errorList)) {
//            return HttpResult.error("导入数据存在已上报，请核对再上传！", errorList);
//        }
//
//        /**数据处理**/
//        int count = 0;
//        for (KwfTruckReportExcelImportDto truckReportExcel:truckReportExcels) {
//            KwfTruckReport truckReport = new KwfTruckReport();
//            truckReport.setEntId(LoginUserHolder.getEntId());
//
//            /**车辆信息**/
//            //校验车辆档案是否存在
//            List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("truckNo", truckReportExcel.getTruckNo());}});
//            if (CollectionUtils.isEmpty(trucks)) {
//                //车辆信息
//                KwfTruck truckParams = new KwfTruck();
//                truckParams.setTruckNo(truckReportExcel.getTruckNo());
//                truckParams.setActualWeight(new BigDecimal(truckReportExcel.getActualWeight()));
//                truckParams.setAuthStatus(Global.NUMERICAL_TWO);
//                result = truckService.truckEdit(truckParams);
//                if (result.getCode() != HttpStatus.SUCCESS_CODE) {
//                    continue;
//                }
//
//                KwfTruck truck = (KwfTruck) result.getData();
//                truckReport.setTruckId(truck.getId());
//            } else {
//                //校验车辆是否已上报
//                KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
//                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
//                    put("truckId", truck.getId());
//                    put("entId", LoginUserHolder.getEntId());
//                }});
//                if (CollectionUtils.isEmpty(reports)) {
//                    truckReport.setTruckId(truck.getId());
//                } else {
//                    continue;
//                }
//
//                //校验企业是否添加该车辆
//                KwfTruck truckEnt = new KwfTruck();
//                truckEnt.setId(truck.getId());
//                truckService.truckEntEdit(truckEnt);
//            }
//
//            /**档案信息**/
//            //校验司机档案是否存在
//            List<KwfDriver> drivers = driverDao.findDriver(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{put("phone", truckReportExcel.getPhone());}});
//            if (CollectionUtils.isEmpty(drivers)) {
//                KwfDriver driverParams = new KwfDriver();
//                driverParams.setName(truckReportExcel.getName());
//                driverParams.setPhone(truckReportExcel.getPhone());
//                driverParams.setIdcard(truckReportExcel.getIdcard());
//                driverParams.setAuthStatus(Global.NUMERICAL_TWO);
//                result = driverService.driverEdit(driverParams);
//                if (result.getCode() != HttpStatus.SUCCESS_CODE) {
//                    continue;
//                }
//
//                KwfDriver driver = (KwfDriver) result.getData();
//                truckReport.setDriverId(driver.getId());
//            } else {
//                //校验司机是否已上报
//                KwfDriver driver = drivers.get(0);
//                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
//                    put("driverId", driver.getId());
//                    put("entId", LoginUserHolder.getEntId());
//                }});
//                if (CollectionUtils.isEmpty(reports)) {
//                    truckReport.setDriverId(driver.getId());
//                } else {
//                    continue;
//                }
//
//                //校验企业是否添加该司机
//                KwfDriver driverEnt = new KwfDriver();
//                driverEnt.setId(driver.getId());
//                driverService.driverEntEdit(driverEnt);
//            }
//            count += truckReportDao.insert(truckReport);
//        }
//
//        return HttpResult.ok("成功导入"+count+"行数据！");
        return HttpResult.ok("成功导入！");
    }

    /**
     * @param params 参数
     * @desc 新增车辆上报
     * @author zk
     * @date 2023/7/15
     **/
    public HttpResult add(List<KwfTruckReportDto> params) {
        /**数据校验**/
        if (CollectionUtils.isEmpty(params)) {
            return HttpResult.error("请选择需要上报的数据！");
        }

//        for (KwfTruckReportDto reportDto:params){
//            boolean bool = checkReport(reportDto);
//            if (!bool) {
//                return HttpResult.error("上报数据已存在，请重新识别！");
//            }
//        }
//
//        /**数据更新**/
//        int count = 0;
//        for (KwfTruckReportDto reportDto:params){
//            KwfTruckReport truckReport = new KwfTruckReport();
//            truckReport.setEntId(LoginUserHolder.getEntId());
//
//            /**车辆信息**/
//            //校验车辆档案是否存在
//            List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("truckNo", reportDto.getTruckNo());}});
//            if (CollectionUtils.isEmpty(trucks)) {
//                //车辆信息
//                KwfTruck truckParams = new KwfTruck();
//                truckParams.setTruckNo(reportDto.getTruckNo());
//                truckParams.setActualWeight(reportDto.getActualWeight());
//                truckParams.setAuthStatus(Global.NUMERICAL_TWO);
//                HttpResult result = truckService.truckEdit(truckParams);
//                if (result.getCode() != HttpStatus.SUCCESS_CODE) {
//                    return result;
//                }
//
//                KwfTruck truck = (KwfTruck) result.getData();
//                truckReport.setTruckId(truck.getId());
//            } else {
//                //校验车辆是否已上报
//                KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
//                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
//                    put("truckId", truck.getId());
//                    put("entId", LoginUserHolder.getEntId());
//                }});
//                if (CollectionUtils.isEmpty(reports)) {
//                    truckReport.setTruckId(truck.getId());
//                } else {
//                    continue;
//                }
//
//                //校验企业是否添加该车辆
//                KwfTruck truckEnt = new KwfTruck();
//                truckEnt.setId(truck.getId());
//                truckService.truckEntEdit(truckEnt);
//            }
//
//            /**档案信息**/
//            //校验司机档案是否存在
//            List<KwfDriver> drivers = driverDao.findDriver(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{put("phone", reportDto.getPhone());}});
//            if (CollectionUtils.isEmpty(drivers)) {
//                KwfDriver driverParams = new KwfDriver();
//                driverParams.setName(reportDto.getName());
//                driverParams.setPhone(reportDto.getPhone());
//                driverParams.setIdcard(reportDto.getIdcard());
//                driverParams.setAuthStatus(Global.NUMERICAL_TWO);
//                HttpResult result = driverService.driverEdit(driverParams);
//                if (result.getCode() != HttpStatus.SUCCESS_CODE) {
//                    return result;
//                }
//
//                KwfDriver driver = (KwfDriver) result.getData();
//                truckReport.setDriverId(driver.getId());
//            } else {
//                //校验司机是否已上报
//                KwfDriver driver = drivers.get(0);
//                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
//                    put("driverId", driver.getId());
//                    put("entId", LoginUserHolder.getEntId());
//                }});
//                if (CollectionUtils.isEmpty(reports)) {
//                    truckReport.setDriverId(driver.getId());
//                } else {
//                    continue;
//                }
//
//                //校验企业是否添加该司机
//                KwfDriver driverEnt = new KwfDriver();
//                driverEnt.setId(driver.getId());
//                driverService.driverEntEdit(driverEnt);
//            }
//
//            count += truckReportDao.insert(truckReport);
//        }
//
//        return HttpResult.ok("车辆上报成功"+count+"条！");
        return HttpResult.ok("车辆上报成功！");
    }

    /**
     * @param params 参数
     * @desc 车辆上报修改
     * @author zk
     * @date 2023/7/15
     **/
    public HttpResult update(KwfTruckReport params) {
        /**数据校验**/
        if (StringUtils.isBlank(params.getId())) {
            return HttpResult.error("参数不正确！");
        }
        KwfTruckReport truckReport = truckReportDao.selectById(params.getId());
        if (truckReport == null) {
            return HttpResult.error("信息已不存在！");
        }

        /**更新**/
        List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("driverId", params.getDriverId());
            put("entId", LoginUserHolder.getEntId());
        }});
        if (!CollectionUtils.isEmpty(reports)) {
            Map<String, Object> report = reports.get(0);
            Long id = StringUtils.isBlank(report.get("id")) ? 0 : Long.parseLong(String.valueOf(report.get("id")));
            if (!id.equals(params.getId())) {
                return HttpResult.error("司机已关联车辆！");
            }
        }

        /**更新数据**/
        int count = truckReportDao.updateById(params);
        return count > 0 ? HttpResult.ok("修改成功！") : HttpResult.error("修改失败！");
    }

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

        /**数据组装**/
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            KwfTruckReport truckReport = truckReportDao.selectById(id);
            if (truckReport != null) {
                truckReport.setDelFlag(Global.YES);
                if (truckReportDao.updateById(truckReport) <= 0) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
                }
            } else {
                return HttpResult.error("选择删除的数据已不存在！");
            }
        }
        return HttpResult.ok("删除成功！");
    }

    /**
     * @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);

        KwfTruckReportImport truckReportImport = new KwfTruckReportImport();
        truckReportImport.setEntId(LoginUserHolder.getEntId());
        truckReportImport.setUrl(returnFileInfo.getFilePath());
        truckReportImport.setRemark(JSON.toJSONString(returnFileInfo));
        kwfTruckReportImportDao.insert(truckReportImport);
//
//        try {
//            //remoteFileService.fileInfoInsert(fileInfo);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * @param params
     * @desc 变更车队
     * @author zk
     * @date 2023/7/18
     **/
    public HttpResult changeFleet(KwfChangeFleetDto params) {
        KwfTruckReport truckReport = truckReportDao.selectById(params.getId());
        if (truckReport == null) {
            return HttpResult.error("信息已不存在！");
        }

        //更新司机所属车队班组
        HttpResult result = driverService.driverFleetEdit(truckReport.getDriverId(), params.getFleetId());
        if (result.getCode() == HttpStatus.SUCCESS_CODE) {
            //更新车辆所属车队班组
            result = truckService.truckFleetEdit(truckReport.getTruckId(), params.getFleetId());
        }

        return result;
    }

    /**
     * @param params 上报信息
     * @desc 校验上报
     * @author zk
     * @date 2023/7/18
     **/
    public HttpResult checkReports(List<String> params) {
        /**数据校验**/
        if (CollectionUtils.isEmpty(params)) {
            return HttpResult.error("请选择需要上报的数据！");
        }

        //有效上报信息
        List<KwfTruckReportDto> effective = new ArrayList();
        //已有运力/识别失败
        int haveCount = Global.NUMERICAL_ZERO, errorCount = Global.NUMERICAL_ZERO,
                rowIndex = Global.NUMERICAL_ZERO, repeatCount = Global.NUMERICAL_ZERO;
        List<String> errorMsg = new ArrayList<>();
        List<String> haveMsg = new ArrayList<>();
        List<String> repeatMsg = new ArrayList<>();
        List<String> valueStr = new ArrayList<>();
        for (String str:params){
            rowIndex ++;
            /**识别上报数据**/
            KwfTruckReportDto reportDto = analysis(str);
            if (reportDto == null || StringUtils.isNotBlank(reportDto.getRemark())) {
                errorCount ++;
                errorMsg.add("第" + rowIndex + "行数据有误," + reportDto.getRemark());
                continue;
            }

            /**校验车/司机是否已上报**/
            String haveMessage = chenkHave(reportDto);
            if (StringUtils.isNotBlank(haveMessage)) {
                haveCount ++;
                haveMsg.add("第" + rowIndex + "行数据," + haveMessage);
                continue;
            }

            /**校验重复数据*/
            if (valueStr.contains(reportDto.getTruckNo()+reportDto.getPhone())) {
                repeatCount ++;
                repeatMsg.add("第" + rowIndex + "行数据重复！");
                continue;
            } else {
                valueStr.add(reportDto.getTruckNo() + reportDto.getPhone());
            }
            effective.add(reportDto);
        }

        /**返回数据**/
        Map<String, Object> resultMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        resultMap.put("haveCount", haveCount);
        resultMap.put("haveMsg", haveMsg);
        resultMap.put("errorCount", errorCount);
        resultMap.put("errorMsg", errorMsg);
        resultMap.put("repeatCount", repeatCount);
        resultMap.put("repeatMsg", repeatMsg);
        resultMap.put("fail", haveCount + errorCount);
        resultMap.put("success", effective.size());
        resultMap.put("list", effective);
        return HttpResult.ok(resultMap);

    }

    /**
     * @param reportDto 上报信息
     * @desc 校验司机和车辆是否已上报
     * @author zk
     * @date 2023/7/18
     **/
    public boolean checkReport(KwfTruckReportDto reportDto) {
        /**车辆信息**/
        //校验车辆档案是否存在
        List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("truckNo", reportDto.getTruckNo());}});
        if (!CollectionUtils.isEmpty(trucks)) {
            //校验车辆是否已上报
            KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
            List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("truckId", truck.getId());
                put("entId", LoginUserHolder.getEntId());
            }});
            if (!CollectionUtils.isEmpty(reports)) {
                return false;
            }
        }

        /**档案信息**/
        //校验司机档案是否存在
        List<KwfDriver> drivers = driverDao.findDriver(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("phone", reportDto.getPhone()); }});
        if (!CollectionUtils.isEmpty(drivers)) {
            //校验司机是否已上报
            KwfDriver driver = drivers.get(Global.NUMERICAL_ZERO);
            List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("driverId", driver.getId());
                put("entId", LoginUserHolder.getEntId());
            }});
            if (!CollectionUtils.isEmpty(reports)) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param str 上报字符串
     * @desc 上报数据识别
     * @author zk
     * @date 2023/7/18
     **/
    public KwfTruckReportDto analysis(String str) {
        StringBuilder msg = new StringBuilder();
        /**识别上报数据**/
        KwfTruckReportDto reportDto = new KwfTruckReportDto();
        //非控校验
        if (StringUtils.isBlank(str) || StringUtils.isBlank(str.trim())) {
            msg.append("数据为空！");
            reportDto.setRemark(msg.toString());
            return reportDto;
        }
        //字符截取-英文逗号/中文逗号
        str = str.replaceAll(Global.COMMA1, Global.COMMA);
        String[] strArray = str.split(Global.COMMA);
        if (strArray == null || strArray.length <= 1 || strArray.length != 5 ) {
            msg.append("数据格式不正确！");
            reportDto.setRemark(msg.toString());
            return reportDto;
        }

        /**数据校验**/
        //车牌号-非空/长度为7
        String truckNo = strArray[0];
        if (StringUtils.isBlank(truckNo) || (truckNo.trim().length() != 7 && truckNo.trim().length() != 8)) {
            msg.append("车牌号格式不正确！");
        }

        //司机姓名-非空
        String name = strArray[1];
        if (StringUtils.isBlank(name) || name.trim().length() == 0 || name.trim().length() > 25) {
            msg.append("司机姓名格式不正确！");
        }

        //司机电话-非空/手机号正则校验
        String phone = strArray[2];
        if (StringUtils.isBlank(phone) || !RegularUtils.matchs(RegularUtils.PHONE_REG, phone.trim())) {
            msg.append("司机电话格式不正确！");
        }

        //身份证号-非空/身份证正则校验
        String idcard = strArray[3];
        if (StringUtils.isBlank(idcard) || !RegularUtils.matchs(RegularUtils.IDCARD, idcard.trim())) {
            msg.append("身份证号格式不正确！");
        }

        //核定载量/吨-非空/数值正则校验
        String actualWeight = strArray[4];
        actualWeight = StringUtils.isNotBlank(actualWeight) ? actualWeight.replaceAll(Global.UNIT_TON, Global.EMPTY_STRING) : actualWeight;
        if (StringUtils.isBlank(actualWeight) || !RegularUtils.matchs(RegularUtils.DECIMAL_REG, actualWeight.trim())) {
            msg.append("核定载量格式不正确！");
        }

        if (msg.length() > Global.NUMERICAL_ZERO) {
            reportDto.setRemark(msg.toString());
            return reportDto;
        }
        reportDto.setTruckNo(truckNo.trim());
        reportDto.setName(name.trim());
        reportDto.setPhone(phone.trim());
        reportDto.setIdcard(idcard.trim());
        reportDto.setActualWeight(new BigDecimal(actualWeight.trim()));
        return reportDto;
    }

    /**
     * @param reportDto 上报对象
     * @desc 校验车/司机是否已上报
     * @author zk
     * @date 2023/8/29
     **/
    public String chenkHave(KwfTruckReportDto reportDto){
        /**车辆信息**/
        //校验车辆档案是否存在
        StringBuilder haveMsg = new StringBuilder();
        List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{put("truckNo", reportDto.getTruckNo());}});
        if (!CollectionUtils.isEmpty(trucks)) {
            //校验车辆是否已上报
            KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
            List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("truckId", truck.getId());
                put("entId", LoginUserHolder.getEntId());
            }});
            if (!CollectionUtils.isEmpty(reports)) {
                haveMsg.append(truck.getTruckNo() + "已上报！");
            }
        }

        /**档案信息**/
        //校验司机档案是否存在
        List<KwfDriver> drivers = driverDao.findDriver(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("phone", reportDto.getPhone()); }});
        if (!CollectionUtils.isEmpty(drivers)) {
            //校验司机是否已上报
            KwfDriver driver = drivers.get(Global.NUMERICAL_ZERO);
            List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                put("driverId", driver.getId());
                put("entId", LoginUserHolder.getEntId());
            }});
            if (!CollectionUtils.isEmpty(reports)) {
                haveMsg.append(driver.getPhone() + "已上报！");
            }
        }

        return haveMsg.toString();
    }

    /**
     * @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(KwfTruckReportExcelImportDto.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();
            }
        }
    }

    /**
     * @param truckReportExcels 上传信息
     * @desc 校验是否已上报
     * @author zk
     * @date 2023/8/16
     **/
    public List<String> checkParams(List<KwfTruckReportExcelImportDto> truckReportExcels) {
        int rowNum = Global.NUMERICAL_TWO;
        //”第2行数据有误,电话号码格式不正确!,身份证号码格式不正确!“
        List<String> errorList = new ArrayList();
        for (KwfTruckReportExcelImportDto truckReportExcel:truckReportExcels) {
            rowNum ++;
            StringBuilder msg = new StringBuilder("第"+ rowNum +"行数据有误,");

            /**车辆信息**/
            //校验车辆档案是否存在
            List<KwfTruck> trucks = truckDao.findTruck(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("truckNo", truckReportExcel.getTruckNo());}});
            if (!CollectionUtils.isEmpty(trucks)) {
                //校验车辆是否已上报
                KwfTruck truck = trucks.get(Global.NUMERICAL_ZERO);
                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                    put("truckId", truck.getId());
                    put("entId", LoginUserHolder.getEntId());
                }});
                if (!CollectionUtils.isEmpty(reports)) {
                    msg.append("车牌号"+ truck.getTruckNo() +"已上报！");
                }
            }

            /**档案信息**/
            //校验司机档案是否存在
            List<KwfDriver> drivers = driverDao.findDriver(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{ put("phone", truckReportExcel.getPhone()); }});
            if (!CollectionUtils.isEmpty(drivers)) {
                //校验司机是否已上报
                KwfDriver driver = drivers.get(Global.NUMERICAL_ZERO);
                List<Map<String, Object>> reports = truckReportDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
                    put("driverId", driver.getId());
                    put("entId", LoginUserHolder.getEntId());
                }});
                if (!CollectionUtils.isEmpty(reports)) {
                    msg.append("司机"+ driver.getName() + driver.getPhone() +"已上报！");
                }
            }

            if (msg.length() > Global.NUMERICAL_TWELVE) {
                errorList.add(msg.toString());
            }
        }

        return errorList;
    }
}
