zxl
2025-10-17 24cb5646d382f327b9ee42a18f3e40f5c0632dc0
ycl-server/src/main/java/com/ycl/platform/service/impl/TMonitorServiceImpl.java
@@ -71,6 +71,7 @@
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@@ -562,25 +563,26 @@
     */
    @Override
    public void exportVideoOnline(HttpServletResponse response, VideoExportForm exportForm) throws IOException, NoSuchFieldException, IllegalAccessException {
        log.error("开始导出数据");
        log.error("传入的月份:{}",exportForm.getMonth());
        //默认查所有部门
        log.info("开始导出数据");
        log.info("传入的月份:{}", exportForm.getMonth());
        // 默认查所有部门
        if (CollectionUtils.isEmpty(exportForm.getDeptIds())) {
            List<Integer> deptIds = new ArrayList<>();
            List<Integer> deptIds = new ArrayList<>(AreaDeptEnum.values().length);
            for (AreaDeptEnum value : AreaDeptEnum.values()) {
                deptIds.add(value.getDeptId());
            }
            exportForm.setDeptIds(deptIds);
        }
        List<ExcelExp> sheet = new ArrayList<>();
        //通过Collections静态方法,把list转为线程安全的list
        List mysheet = Collections.synchronizedList(sheet);
        // 使用线程安全的List,预先指定容量
        List<ExcelExp> mysheet = Collections.synchronizedList(new ArrayList<>());
        VideoExportForm.convertTags(exportForm);
        Query query = getQuery(exportForm);
        //月份每日在线数据
        // 月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        log.error("月份在线数据:{}条数",onlineResult.size());
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
        log.info("月份在线数据:{}条数", onlineResult.size());
        // 使用Collectors.toMap去重,保留每个No的第一个遇到的元素
        Map<String, TMonitorResult> uniqueResultsMap = onlineResult.stream()
                .collect(Collectors.toMap(
                        TMonitorResult::getNo, // keyMapper,这里假设 getNo() 返回 No 字段
@@ -589,178 +591,303 @@
                ));
        // 将 Map 转换为 List
        List<TMonitorResult> tMonitorResults = new ArrayList<>(uniqueResultsMap.values());
        log.error("去重后大小:{}",tMonitorResults.size());
        //获取动态列数据
        List<Integer> pointIds = tMonitorResults.stream().map(TMonitorResult::getPointId).collect(Collectors.toList());
        List<DynamicColumnVO> dynamics = dynamicColumnMapper.getDynamicsByIds("t_yw_point", pointIds);
        //补充动态列数据
        if (!CollectionUtils.isEmpty(dynamics)) {
            Map<Integer, List<DynamicColumnVO>> map = dynamics.stream().collect(Collectors.groupingBy(DynamicColumnVO::getRefId));
            for (TMonitorResult tMonitorResult : tMonitorResults) {
                Integer pointId = tMonitorResult.getPointId();
                tMonitorResult.setDynamicColumnList(map.get(pointId));
        log.info("去重后大小:{}", tMonitorResults.size());
        // 获取动态列数据并构建缓存Map
        Map<Integer, List<DynamicColumnVO>> dynamicColumnMap = new HashMap<>();
        if (!tMonitorResults.isEmpty()) {
            //获取点位集合
            List<Integer> pointIds = tMonitorResults.stream()
                    .map(TMonitorResult::getPointId)
                    .distinct() // 去重,减少数据库查询
                    .collect(Collectors.toList());
            //获取集合点位的补充列信息
            List<DynamicColumnVO> dynamics = dynamicColumnMapper.getDynamicsByIds("t_yw_point", pointIds);
            if (!CollectionUtils.isEmpty(dynamics)) {
                dynamicColumnMap = dynamics.stream()
                        .collect(Collectors.groupingBy(DynamicColumnVO::getRefId));
            }
            // 补充动态列数据
            for (TMonitorResult result : tMonitorResults) {
                result.setDynamicColumnList(dynamicColumnMap.getOrDefault(result.getPointId(), Collections.emptyList()));
            }
        }
        //存放区域 与 设备列表 map key为 区域
        Map<Integer, List<VideoDailyExp>> map = new HashMap<>();
        List<CompletableFuture<List<VideoDailyExp>>> futures = new ArrayList<>();
        // 按部门分组,减少后续循环中的过滤操作
        Map<Integer, List<TMonitorResult>> deptMonitorMap = tMonitorResults.stream()
                .collect(Collectors.groupingBy(TMonitorResult::getDeptId));
        // 按设备编号分组onlineResult,加速后续查找
        Map<String, List<TMonitorResult>> noToOnlineMap = onlineResult.stream()
                .collect(Collectors.groupingBy(TMonitorResult::getNo));
        // 并行处理各部门数据
        List<CompletableFuture<ExcelExp>> futures = new ArrayList<>(exportForm.getDeptIds().size());
        Map<Integer, List<VideoDailyExp>> deptExpMap = new ConcurrentHashMap<>();
        for (Integer deptId : exportForm.getDeptIds()) {
            CompletableFuture<List<VideoDailyExp>> future = CompletableFuture.supplyAsync(() -> {
                List<VideoDailyExp> videoDailyExps = new ArrayList<>();
                //筛选部门数据
                List<TMonitorResult> monitors = tMonitorResults.stream()
                        .filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(monitors)) return videoDailyExps;
            // 使用部门ID的最终变量
            final Integer currentDeptId = deptId;
            CompletableFuture<ExcelExp> future = CompletableFuture.supplyAsync(() -> {
                // 直接从预分组的Map中获取,避免每次过滤
                List<TMonitorResult> monitors = deptMonitorMap.getOrDefault(currentDeptId, Collections.emptyList());
                if (monitors.isEmpty()) {
                    return null;
                }
                List<String> ids = monitors.stream()
                        .map(BaseResult::getNo)
                        .collect(Collectors.toList());
                //筛选mongo区县数据
                List<TMonitorResult> onlines = onlineResult.stream()
                        .filter(result -> ids.contains(result.getNo()))
                        .collect(Collectors.toList());
                List<VideoDailyExp> videoDailyExps = new ArrayList<>(monitors.size());
                AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(currentDeptId);
                String areaName = areaDeptEnum == null ? "未知" : areaDeptEnum.getName();
                AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
                for (TMonitorResult result : monitors) {
                    VideoDailyExp videoDailyExp = new VideoDailyExp();
                    videoDailyExp.setSerialNumber(result.getNo());
                    videoDailyExp.setDeviceName(result.getName());
                    videoDailyExp.setType(result.getMonitorType());
                    videoDailyExp.setArea(areaName);
                    videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                    // 构建标签字符串
                    StringBuilder tag = new StringBuilder();
                    if (result.getProvinceTag()) tag.append("省厅、");
                    if (result.getImportantTag()) tag.append("重点点位、");
                    if (result.getImportantCommandImageTag()) tag.append("重点指挥图像、");
                    if (result.getDeptTag()) tag.append("部级、");
                    StringBuilder tag = new StringBuilder("" +
                            (result.getProvinceTag() ? "省厅、" : "") +
                            (result.getImportantTag() ? "重点点位、" : "") +
                            (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") +
                            (result.getDeptTag() ? "部级、" : ""));
                    //动态列处理加在标签里
                    if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                        for (DynamicColumnVO dynamicColumnVO : result.getDynamicColumnList()) {
                    // 处理动态列
                    List<DynamicColumnVO> dynamicColumns = result.getDynamicColumnList();
                    if (!dynamicColumns.isEmpty()) {
                        for (DynamicColumnVO dynamicColumnVO : dynamicColumns) {
                            tag.append(dynamicColumnVO.getColumnValue()).append("、");
                        }
                    }
                    // 删除字符串末尾的"、"
                    if (tag.toString().endsWith("、")) {
                        tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                    // 移除末尾的"、"
                    if (tag.length() > 0) {
                        tag.setLength(tag.length() - 1);
                    }
                    videoDailyExp.setTag(tag.toString());
                    // 设置在线数据
                    try {
                        // 从预构建的Map中获取,避免每次过滤
                        List<TMonitorResult> onlines = noToOnlineMap.getOrDefault(result.getNo(), Collections.emptyList());
                        setOnlineDaily(videoDailyExp, result, onlines);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        log.error("设置在线数据异常", e);
                    }
                    videoDailyExps.add(videoDailyExp);
                }
                ExcelExp excelExp = new ExcelExp(
                        areaDeptEnum == null ? "未知" : areaDeptEnum.getName(),
                        videoDailyExps,
                        VideoDailyExp.class
                );
                mysheet.add(excelExp);
                // 存储结果到线程安全的Map
                deptExpMap.put(currentDeptId, videoDailyExps);
                return videoDailyExps;
                return new ExcelExp(areaName, videoDailyExps, VideoDailyExp.class);
            }, threadPoolTaskExecutor);
            futures.add(future);
            map.put(deptId,future.join());
        }
        // 获取全量数据
        List<VideoDailyExp> totalExps = futures.stream()
                .map(CompletableFuture::join)
        // 等待所有并行任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        // 收集所有部门的ExcelExp结果
        for (CompletableFuture<ExcelExp> future : futures) {
            ExcelExp excelExp = future.join();
            if (excelExp != null) {
                mysheet.add(excelExp);
            }
        }
        // 获取全量数据并添加"全量"sheet
        List<VideoDailyExp> totalExps = deptExpMap.values().stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        log.error("打印全量数据:{}",totalExps);
        ExcelExp excelExp = new ExcelExp("全量", totalExps, VideoDailyExp.class);
        mysheet.add(excelExp);
        //添加新的sheet 离线数统计表
        List<VideoTypeOffOnlineExp> videoTypeOffOnlineExps = new ArrayList<>();
        //插入excel时确保数据出现在最后
        List<VideoTypeOffOnlineExp> allVideoTypeOffOnlineExps = new ArrayList<>();
        //在线率统计表
        List<VideoOnlineRateExp> videoOnlineRateExps = new ArrayList<>();
        //插入excel时确保数据出现在最后
        List<VideoOnlineRateExp> allVideoOnlineRateExps = new ArrayList<>();
        mysheet.add(new ExcelExp("全量", totalExps, VideoDailyExp.class));
        for (Integer deptId : map.keySet()){
            List<VideoDailyExp>  list = map.get(deptId);
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            // 添加离线表记录
            //设备类型 1人脸 2车辆 3视频
            //人脸
            log.error("传入部门集合大小:{} + 部门id:{}" ,list.size(),deptId);
            VideoTypeOffOnlineExp faceVideoTypeOffOnlineExp = this.getListOfflineCountInfo(list,"1",areaDeptEnum,false);
            //卡口
            VideoTypeOffOnlineExp carVideoTypeOffOnlineExp =this.getListOfflineCountInfo(list,"2",areaDeptEnum,false);
            //视频
            VideoTypeOffOnlineExp videoTypeOffOnlineExp = this.getListOfflineCountInfo(list,"3",areaDeptEnum,false);
            VideoOnlineRateExp faceVideoOnlineRateExp = this.getListOnLineCountInfo(list,"1",areaDeptEnum,false);
            //卡口
            VideoOnlineRateExp carVideoOnlineRateExp =this.getListOnLineCountInfo(list,"2",areaDeptEnum,false);
            //视频
            VideoOnlineRateExp VideoOnlineRateExp = this.getListOnLineCountInfo(list,"3",areaDeptEnum,false);
            //将该区域类三种设备类型的 信息 放入 excel对象内
            //放入当前区域的人脸设备相关详细
            videoTypeOffOnlineExps.add(faceVideoTypeOffOnlineExp);
            //放入当前区域的车辆设备相关详细
            videoTypeOffOnlineExps.add(carVideoTypeOffOnlineExp);
            //放入当前区域的视频设备相关详细
            videoTypeOffOnlineExps.add(videoTypeOffOnlineExp);
            videoOnlineRateExps.add(faceVideoOnlineRateExp);
            videoOnlineRateExps.add(carVideoOnlineRateExp);
            videoOnlineRateExps.add(VideoOnlineRateExp);
            VideoTypeOffOnlineExp ALLfaceVideoTypeOffOnlineExp = this.getListOfflineCountInfo(list,"1",areaDeptEnum,true);
            //卡口
            VideoTypeOffOnlineExp ALLcarVideoTypeOffOnlineExp =this.getListOfflineCountInfo(list,"2",areaDeptEnum,true);
            //视频
            VideoTypeOffOnlineExp ALLvideoTypeOffOnlineExp = this.getListOfflineCountInfo(list,"3",areaDeptEnum,true);
            VideoOnlineRateExp ALLfaceVideoOnlineRateExp = this.getListOnLineCountInfo(list,"1",areaDeptEnum,true);
            //卡口
            VideoOnlineRateExp ALLcarVideoOnlineRateExp =this.getListOnLineCountInfo(list,"2",areaDeptEnum,true);
            //视频
            VideoOnlineRateExp ALLVideoOnlineRateExp = this.getListOnLineCountInfo(list,"3",areaDeptEnum,true);
            //添加合计数据
            allVideoTypeOffOnlineExps.add(ALLfaceVideoTypeOffOnlineExp);
            //放入当前区域的车辆设备相关详细
            allVideoTypeOffOnlineExps.add(ALLcarVideoTypeOffOnlineExp);
            //放入当前区域的视频设备相关详细
            allVideoTypeOffOnlineExps.add(ALLvideoTypeOffOnlineExp);
            allVideoOnlineRateExps.add(ALLfaceVideoOnlineRateExp);
            allVideoOnlineRateExps.add(ALLcarVideoOnlineRateExp);
            allVideoOnlineRateExps.add(ALLVideoOnlineRateExp);
        // 统计各类型设备数量
        long face = 0, car = 0, video = 0;
        for (VideoDailyExp exp : totalExps) {
            String type = exp.getType();
            if (type.contains("1")) face++;
            if (type.contains("2")) car++;
            if (type.contains("3")) video++;
        }
        videoTypeOffOnlineExps.addAll(allVideoTypeOffOnlineExps);
        videoOnlineRateExps.addAll(allVideoOnlineRateExps);
        log.error("打印计算离线的信息:{}" ,videoTypeOffOnlineExps );
        log.error("打印计在线的信息:{}" ,videoOnlineRateExps );
        //添加合计数据
        ExcelExp excelTypeOffLineExp = new ExcelExp("离线数统计", videoTypeOffOnlineExps, VideoTypeOffOnlineExp.class);
        mysheet.add(excelTypeOffLineExp);
        log.info("人脸数:{}", face);
        log.info("car数:{}", car);
        log.info("video数:{}", video);
        //添加在线率表
        ExcelExp excelOnlineRateExp = new ExcelExp("在线率统计",videoOnlineRateExps, VideoOnlineRateExp.class);
        mysheet.add(excelOnlineRateExp);
        // 处理离线数统计和在线率统计
        List<VideoTypeOffOnlineExp> videoTypeOffOnlineExps = new ArrayList<>();
        List<VideoOnlineRateExp> videoOnlineRateExps = new ArrayList<>();
        for (Map.Entry<Integer, List<VideoDailyExp>> entry : deptExpMap.entrySet()) {
            Integer deptId = entry.getKey();
            List<VideoDailyExp> list = entry.getValue();
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            // 批量处理三种设备类型
            addDeviceStats(list, areaDeptEnum, "1", "人脸", videoTypeOffOnlineExps, videoOnlineRateExps);
            addDeviceStats(list, areaDeptEnum, "2", "卡口", videoTypeOffOnlineExps, videoOnlineRateExps);
            addDeviceStats(list, areaDeptEnum, "3", "视频", videoTypeOffOnlineExps, videoOnlineRateExps);
        }
        // 计算合计数据
        addTotalStats(videoTypeOffOnlineExps, videoOnlineRateExps, face, car, video);
        // 添加统计sheet
        mysheet.add(new ExcelExp("离线数统计", videoTypeOffOnlineExps, VideoTypeOffOnlineExp.class));
        mysheet.add(new ExcelExp("在线率统计", videoOnlineRateExps, VideoOnlineRateExp.class));
        // 导出Excel
        ExcelUtilManySheet<List<ExcelExp>> util = new ExcelUtilManySheet<>(mysheet);
        util.exportExcelManySheet(response, mysheet);
        log.error("导出结束");
        log.info("导出结束");
    }
    // 新增辅助方法:批量添加设备统计信息
    private void addDeviceStats(List<VideoDailyExp> list, AreaDeptEnum areaDeptEnum,
                                String typeCode, String typeName,
                                List<VideoTypeOffOnlineExp> offLineList,
                                List<VideoOnlineRateExp> onlineList) {
        offLineList.add(getListOfflineCountInfo(list, typeCode, areaDeptEnum));
        onlineList.add(getListOnLineCountInfo(list, typeCode, areaDeptEnum));
    }
    // 新增辅助方法:添加合计统计
    private void addTotalStats(List<VideoTypeOffOnlineExp> offLineList,
                               List<VideoOnlineRateExp> onlineList,
                               long face, long car, long video) throws NoSuchFieldException, IllegalAccessException {
        // 离线统计合计
        VideoTypeOffOnlineExp allFaceVideosOffline = new VideoTypeOffOnlineExp();
        setAllVideoTypeOffOnlineExpCount(offLineList, allFaceVideosOffline, "人脸");
        VideoTypeOffOnlineExp allCarVideosOffline = new VideoTypeOffOnlineExp();
        setAllVideoTypeOffOnlineExpCount(offLineList, allCarVideosOffline, "卡口");
        VideoTypeOffOnlineExp allVideosOffline = new VideoTypeOffOnlineExp();
        setAllVideoTypeOffOnlineExpCount(offLineList, allVideosOffline, "视频");
        offLineList.add(allFaceVideosOffline);
        offLineList.add(allCarVideosOffline);
        offLineList.add(allVideosOffline);
        // 在线统计合计
        VideoOnlineRateExp allFaceVideosOnline = new VideoOnlineRateExp();
        setAllVideoTypeOnlineExpCount(face, onlineList, allFaceVideosOnline, "人脸");
        VideoOnlineRateExp allCarVideosOnline = new VideoOnlineRateExp();
        setAllVideoTypeOnlineExpCount(car, onlineList, allCarVideosOnline, "卡口");
        VideoOnlineRateExp allVideosOnline = new VideoOnlineRateExp();
        setAllVideoTypeOnlineExpCount(video, onlineList, allVideosOnline, "视频");
        onlineList.add(allFaceVideosOnline);
        onlineList.add(allCarVideosOnline);
        onlineList.add(allVideosOnline);
    }
    //离线设备数据,合计对象,信息装配
    public void setAllVideoTypeOffOnlineExpCount(List<VideoTypeOffOnlineExp> videoTypeOffOnlineExps,
                                                                  VideoTypeOffOnlineExp videoTypeOffOnlineExp,
                                                                  String type) throws NoSuchFieldException, IllegalAccessException {
        List<VideoTypeOffOnlineExp> filterExps = videoTypeOffOnlineExps.stream().filter(exp -> type.equals(exp.getType())).collect(Collectors.toList());
        long allCount = 0;
        for (VideoTypeOffOnlineExp obj :filterExps){
            //obj 对象代表了该区 筛选了的指定type的设备的对象
            //计算总的设备离线总数
            long count  = Long.parseLong(obj.getOfflineCount());
            allCount += count;
            //计算每日
            for (int i =1 ;i <= 31; i++){
                String fieldName = "day" + i;
                Field dayField = obj.getClass().getDeclaredField(fieldName);
                dayField.setAccessible(true);
                Object value = dayField.get(obj); //获取字段值
                if (value != null) {
                    long newFieldValue = Long.parseLong(value.toString());
                    //获取需要填充的字段
                    Field videoTypeOffOnlineExpField = videoTypeOffOnlineExp.getClass().getDeclaredField(fieldName);
                    videoTypeOffOnlineExpField.setAccessible(true);
                    //先获取一次
                    Object oldValue = videoTypeOffOnlineExpField.get(videoTypeOffOnlineExp);
                    //为null 第一次直接诶赋值
                    if (oldValue == null){
                        videoTypeOffOnlineExpField.set(videoTypeOffOnlineExp,newFieldValue + "");
                    }else {
                        //存在旧值 相加覆盖
                        videoTypeOffOnlineExpField.set(videoTypeOffOnlineExp, (Long.parseLong(oldValue.toString()) + newFieldValue) + "");
                    }
                }
            }
        }
        videoTypeOffOnlineExp.setOfflineCount(String.valueOf(allCount));
        videoTypeOffOnlineExp.setArea("自贡市");
        videoTypeOffOnlineExp.setType(type + "合计");
    }
    //在线设备数据,合计对象,信息装配
    public void setAllVideoTypeOnlineExpCount(
            long allVideoCount,List<VideoOnlineRateExp> videoOnlineRateExps,
                                              VideoOnlineRateExp videoOnlineRateExp,
                                              String type) throws NoSuchFieldException, IllegalAccessException{
        List<VideoOnlineRateExp> filterExps = videoOnlineRateExps.stream().filter(item -> type.equals(item.getType())).collect(Collectors.toList());
        for (VideoOnlineRateExp obj :filterExps){
            for (int i = 1;i <= 31; i++){
                String countFileName = "count" +i;
                Field countField = obj.getClass().getDeclaredField(countFileName);
                countField.setAccessible(true);
                long newFieldValue = countField.getLong(obj);
                Field videoOnlineRateExpField = obj.getClass().getDeclaredField(countFileName);
                videoOnlineRateExpField.setAccessible(true);
                Object oldValue = videoOnlineRateExpField.get(videoOnlineRateExp);
                if (oldValue == null){
                    videoOnlineRateExpField.setLong(videoOnlineRateExp,newFieldValue);
                }else {
                    //存在旧值 相加覆盖
                    videoOnlineRateExpField.setLong(videoOnlineRateExp, Long.parseLong(oldValue.toString()) + newFieldValue);
                }
            }
        }
        //计算完每日在线设备数
        //循环一个月
        for (int i = 1;i <= 31 ;i++){
            //在线率计算
            String countFileName = "count" +i;
            Field countField = videoOnlineRateExp.getClass().getDeclaredField(countFileName);
            countField.setAccessible(true);
            long newFieldValue = countField.getLong(videoOnlineRateExp);
            String fieldName = "day" + i;
            //每日在线率
            double rate = (double) newFieldValue / allVideoCount;
            //反射添加到对象属性中
            Field field = videoOnlineRateExp.getClass().getDeclaredField(fieldName);
            //设置每日在线设备设备数
            field.setAccessible(true);
            String rateStr = String.format("%.2f", rate * 100) +"%";
            if (!"0.00%".equals(rateStr)){
                field.set(videoOnlineRateExp, rateStr);
            }
        }
        videoOnlineRateExp.setArea("自贡市");
        videoOnlineRateExp.setType(type + "合计");
    }
    /**
     * 计算离线设备excel对象信息
@@ -771,8 +898,8 @@
     */
    public VideoTypeOffOnlineExp getListOfflineCountInfo(List<VideoDailyExp> videoDailyExps,
                                                         String type,
                                                         AreaDeptEnum areaDeptEnum,
                                                         boolean isTotal){
                                                         AreaDeptEnum areaDeptEnum
                                                        ){
        VideoTypeOffOnlineExp videoTypeOffOnlineExp = new VideoTypeOffOnlineExp();
        List<VideoDailyExp> list = videoDailyExps.stream()
@@ -781,45 +908,36 @@
        //离线数量
        try {
            //设置离线数量 以及每日离线数量
            setVideoTypeOffOnlineExpCountAndDays(list,videoTypeOffOnlineExp,isTotal);
            setVideoTypeOffOnlineExpCountAndDays(list,videoTypeOffOnlineExp);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        //设备类型
        if(isTotal){
            if ("1".equals(type)){
                videoTypeOffOnlineExp.setType("人脸合计");
            }else if ("2".equals(type)){
                videoTypeOffOnlineExp.setType("卡口合计");
            }else if ("3".equals(type)){
                videoTypeOffOnlineExp.setType("视频合计");
            }
        }else {
            if ("1".equals(type)){
                videoTypeOffOnlineExp.setType("人脸");
            }else if ("2".equals(type)){
                videoTypeOffOnlineExp.setType("卡口");
            }else if ("3".equals(type)){
                videoTypeOffOnlineExp.setType("视频");
            }
        if ("1".equals(type)){
            videoTypeOffOnlineExp.setType("人脸");
        }else if ("2".equals(type)){
            videoTypeOffOnlineExp.setType("卡口");
        }
        else if ("3".equals(type)){
            videoTypeOffOnlineExp.setType("视频");
        }
        //修改区域
        videoTypeOffOnlineExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
        return videoTypeOffOnlineExp;
    }
    private void setVideoTypeOffOnlineExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoTypeOffOnlineExp videoTypeOffOnlineExp,boolean isTotal)throws NoSuchFieldException, IllegalAccessException {
    private void setVideoTypeOffOnlineExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoTypeOffOnlineExp videoTypeOffOnlineExp)throws NoSuchFieldException, IllegalAccessException {
        //循环一个月
        //离线总数
        long AllOffLineCount = 0;
        log.error("传入集合大小:{}", videoDailyExps.size());
        for (VideoDailyExp videoDailyExp : videoDailyExps) {
            if (videoDailyExp.isAllOfflineByMonth()) {
                AllOffLineCount++;
            }
        }
        //是合计数据不需要下方数据
//        if (!isTotal) {
            for (int i = 1; i <= 31; i++) {
                //每日离线数
                long count = 0;
@@ -857,8 +975,8 @@
     */
    public VideoOnlineRateExp getListOnLineCountInfo(List<VideoDailyExp> videoDailyExps,
                                                         String type,
                                                         AreaDeptEnum areaDeptEnum,
                                                         boolean isTotal){
                                                         AreaDeptEnum areaDeptEnum
                                                         ){
        VideoOnlineRateExp videoOnlineRateExp = new VideoOnlineRateExp();
        List<VideoDailyExp> list = videoDailyExps.stream()
@@ -866,28 +984,17 @@
        log.error("筛选完设备类型 :{} 后集合的大小:{}",type,list.size());
        //离线数量
        try {
            //设置离线数量 以及每日离线数量
            setVideoOnlineRateExpCountAndDays(list,videoOnlineRateExp,isTotal);
            setVideoOnlineRateExpCountAndDays(list,videoOnlineRateExp);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        //设备类型
        if(isTotal) {
            if ("1".equals(type)) {
                videoOnlineRateExp.setType("人脸合计");
            } else if ("2".equals(type)) {
                videoOnlineRateExp.setType("卡口合计");
            } else if ("3".equals(type)) {
                videoOnlineRateExp.setType("视频合计");
            }
        }else {
            if ("1".equals(type)) {
                videoOnlineRateExp.setType("人脸");
            } else if ("2".equals(type)) {
                videoOnlineRateExp.setType("卡口");
            } else if ("3".equals(type)) {
                videoOnlineRateExp.setType("视频");
            }
        if ("1".equals(type)) {
             videoOnlineRateExp.setType("人脸");
        } else if ("2".equals(type)) {
            videoOnlineRateExp.setType("卡口");
        } else if ("3".equals(type)) {
            videoOnlineRateExp.setType("视频");
        }
        //修改区域
        videoOnlineRateExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
@@ -895,13 +1002,13 @@
    }
    private void setVideoOnlineRateExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoOnlineRateExp videoOnlineRateExp,boolean isTotal)throws NoSuchFieldException, IllegalAccessException {
    private void setVideoOnlineRateExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoOnlineRateExp videoOnlineRateExp)throws NoSuchFieldException, IllegalAccessException {
        //循环一个月
        for (int i = 1;i <= 31 ;i++){
            //在线率计算
            long count = 0;
            String fieldName = "day" + i;
            String countName = "count" + i;
            for(VideoDailyExp videoDailyExp: videoDailyExps){
                // 构造字段名
                Field field = videoDailyExp.getClass().getDeclaredField(fieldName);
@@ -917,6 +1024,10 @@
            double rate = (double) count / videoDailyExps.size();
            //反射添加到对象属性中
            Field field = videoOnlineRateExp.getClass().getDeclaredField(fieldName);
            Field countField = videoOnlineRateExp.getClass().getDeclaredField(countName);
            countField.setAccessible(true);
            //设置每日在线设备设备数
            countField.setLong(videoOnlineRateExp, count);
            field.setAccessible(true);
            String rateStr = String.format("%.2f", rate * 100) +"%";
            if (!"0.00%".equals(rateStr)){
@@ -1065,6 +1176,8 @@
            exportForm.setDeptIds(deptIds);
        }
        Query query = getQuery(exportForm);
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
@@ -1174,6 +1287,7 @@
    @Override
    public Map<String, Object> videoHome(HomeQuery monitorQuery) throws ParseException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        List<HomeVideoVO> results = new ArrayList<>();
        String month = monitorQuery.getDate();
        if (StringUtils.isEmpty(month)) {
            //如果为空查本月的数据
@@ -1200,13 +1314,30 @@
        MongoDatabase database = mongoTemplate.getDb();
        MongoCollection<Document> collection = database.getCollection("uy_record_meta_d_sum");
        Integer examineTag = monitorQuery.getExamineTag();
        String arealayerno = monitorQuery.getArea();
        Document matchConditions = new Document("statTime", new Document("$gte", startDate).append("$lte", endDate));
        // 根据examineTag的值动态添加额外的条件
        if (examineTag != null && examineTag.equals(1)) {
            matchConditions.append("provinceTag", true);
        } else if (examineTag != null && examineTag.equals(2)) {
            matchConditions.append("deptTag", true);
        } else if(StringUtils.isNotBlank(arealayerno)){
            matchConditions.append("arealayerno",
                    new Document("$regex", "^" + arealayerno));
        }
        Document noExpr = new Document("$and", Arrays.asList(
                new Document("$gte", Arrays.asList(new Document("$strLenCP", "$no"), 3)),
                new Document("$ne", Arrays.asList(
                        new Document("$substrCP", Arrays.asList(
                                "$no",
                                new Document("$subtract", Arrays.asList(new Document("$strLenCP", "$no"), 3)),
                                1
                        )),
                        "3"
                ))
        ));
// 正确添加$expr条件(键为"$expr",值为上面定义的条件)
        matchConditions.append("$expr", noExpr);
        // 构建聚合管道
        List<Document> pipeline = Arrays.asList(
                new Document("$match", matchConditions),
@@ -1242,6 +1373,7 @@
            homeVideoVO.setIntegrityNum(doc.getInteger("normalCount"));
            homeVideoVO.setLoseNum(doc.getInteger("loseCount"));
            homeVideoVO.setErrNum(doc.getInteger("errCount"));
            results.add(homeVideoVO);
        }
@@ -1255,8 +1387,24 @@
            onlineMatch.add(new Document("provinceTag", true));
        } else if (examineTag != null && examineTag.equals(2)) {
            onlineMatch.add(new Document("deptTag", true));
        }
        } else if(StringUtils.isNotBlank(arealayerno)){
            Document noStartsWith = new Document("no", new Document("$regex", "^" + arealayerno));
            // 构建倒数第三位不是3的条件
            Document noThirdLastNot3 = new Document("$expr", new Document("$and", Arrays.asList(
                    new Document("$gte", Arrays.asList(new Document("$strLenCP", "$no"), 3)),
                    new Document("$ne", Arrays.asList(
                            new Document("$substrCP", Arrays.asList(
                                    "$no",
                                    new Document("$subtract", Arrays.asList(new Document("$strLenCP", "$no"), 3)),
                                    1
                            )),
                            "3"
                    ))
            )));
            // 将两个条件用$and组合后添加到条件列表
            onlineMatch.add(new Document("$and", Arrays.asList(noStartsWith, noThirdLastNot3)));
        }
        // 构建聚合管道
        List<Document> onlinePipeline = Arrays.asList(
                new Document("$match", new Document("$and", onlineMatch)),
@@ -1270,6 +1418,10 @@
                        ))
                )
        );
        //排除卡口集合
        // 执行聚合查询并获取结果
        AggregateIterable<Document> onlineResult = onlineCollection.aggregate(onlinePipeline);
        for (Document doc : onlineResult) {
@@ -1401,10 +1553,13 @@
        Integer examineTag = monitorQuery.getExamineTag();
        // 构建基本的$match条件
        List<Document> matchConditions = new ArrayList<>();
        String arealayerno = monitorQuery.getArea();
        matchConditions.add(new Document("mongoCreateTime", new Document("$gte", startDate).append("$lte", endDate)));
        matchConditions.add(new Document("dataType", new Document("$eq", ApiConstants.HK_DataType_CAR)));
        if (examineTag != null && examineTag.equals(1)) {
            matchConditions.add(new Document("provinceTag", true));
        }else if(StringUtils.isNotBlank(arealayerno)){
            matchConditions.add(new Document("orgCode",new Document("$eq", arealayerno)));
        }
        // 构建聚合管道
        List<Document> pipeline = Arrays.asList(
@@ -1429,6 +1584,8 @@
        onlineMatch.add(new Document("monitorType", new Document("$regex", "2")));
        if (examineTag != null && examineTag.equals(1)) {
            onlineMatch.add(new Document("provinceTag", true));
        }else if(StringUtils.isNotBlank(arealayerno)){
            onlineMatch.add(new Document("no", new Document("$regex", "^" + arealayerno)));
        }
        // 构建聚合管道
        List<Document> onlinePipeline = Arrays.asList(
@@ -1507,6 +1664,7 @@
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 获取月份最后一天的Date
        Date endDate = calendar.getTime();
        String arealayerno = monitorQuery.getArea();
        //mongo查抓拍量
        MongoDatabase database = mongoTemplate.getDb();
        MongoCollection<Document> collection = database.getCollection("hk_snapshot_data_monitor");
@@ -1517,6 +1675,8 @@
        matchConditions.add(new Document("dataType", new Document("$eq", ApiConstants.HK_DataType_FACE)));
        if (examineTag != null && examineTag.equals(1)) {
            matchConditions.add(new Document("provinceTag", true));
        }else if(StringUtils.isNotBlank(arealayerno)){
            matchConditions.add(new Document("orgCode",new Document("$eq", arealayerno)));
        }
        // 构建聚合管道
        List<Document> pipeline = Arrays.asList(
@@ -1543,6 +1703,8 @@
        onlineMatch.add(new Document("monitorType", new Document("$regex", "3")));
        if (examineTag != null && examineTag.equals(1)) {
            onlineMatch.add(new Document("provinceTag", true));
        }else if(StringUtils.isNotBlank(arealayerno)){
            onlineMatch.add(new Document("no", new Document("$regex", "^" + arealayerno)));
        }
        // 构建聚合管道
        List<Document> onlinePipeline = Arrays.asList(