zxl
2025-04-10 1f11310ba04770a4efe4657d39872590575828f1
ycl-server/src/main/java/com/ycl/platform/service/impl/TMonitorServiceImpl.java
@@ -7,9 +7,7 @@
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.ycl.platform.domain.entity.TMonitor;
import com.ycl.platform.domain.excel.TMonitorExp;
import com.ycl.platform.domain.excel.VideoDailyExp;
import com.ycl.platform.domain.excel.VideoTotalExp;
import com.ycl.platform.domain.excel.*;
import com.ycl.platform.domain.form.VideoExportForm;
import com.ycl.platform.domain.query.DashboardQuery;
import com.ycl.platform.domain.query.DataCenterQuery;
@@ -32,10 +30,10 @@
import com.ycl.platform.mapper.DynamicColumnMapper;
import com.ycl.platform.mapper.TMonitorMapper;
import com.ycl.platform.mapper.WorkOrderMapper;
import com.ycl.platform.mapper.YwPointMapper;
import com.ycl.platform.service.ITMonitorService;
import com.ycl.system.Result;
import com.ycl.system.entity.SysDictData;
import com.ycl.system.mapper.SysConfigMapper;
import com.ycl.system.mapper.SysDictDataMapper;
import com.ycl.system.page.PageUtil;
import com.ycl.system.service.ISysConfigService;
@@ -43,18 +41,19 @@
import com.ycl.utils.StringUtils;
import com.ycl.utils.poi.ExcelUtil;
import constant.ApiConstants;
import constant.CheckConstants;
import enumeration.general.AreaDeptEnum;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.Validate;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import pojo.ExcelExp;
import utils.poi.ExcelUtilManySheet;
@@ -63,15 +62,15 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -81,9 +80,12 @@
 * @date 2024-03-04
 */
@Service
@Slf4j
public class TMonitorServiceImpl extends ServiceImpl<TMonitorMapper, TMonitor> implements ITMonitorService {
    @Autowired
    private TMonitorMapper tMonitorMapper;
    @Autowired
    private YwPointMapper pointMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
@@ -94,6 +96,8 @@
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private DynamicColumnMapper dynamicColumnMapper;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     * 查询设备资产
@@ -352,17 +356,30 @@
        return tMonitorMapper.recoveryException(monitor);
    }
    /**
     * 查mongo查某个月设备总数
     * 查看工单数量查看异常的数
     *
     * @param monitorQuery 查询条件
     * @return
     */
    @Override
    public Map<String, Object> home(HomeQuery monitorQuery) {
        System.out.println(monitorQuery + "~~~~~~~~~~~~~打印");
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> monthMap1 = new HashMap<>();
        Map<String, Object> monthMap2 = new HashMap<>();
        List<Map<String, Object>> home = baseMapper.home(monitorQuery);
        if (ObjectUtils.isNotEmpty(home)) {
            //拿到数据库 循环查询
            System.out.println(home + "~~~~~~~~~~~~~打印");
            for (Map<String, Object> map : home) {
                //得到map的 months键的值  num1键的值 组装为新对象
                monthMap1.put(map.get("months").toString(), map.get("num1"));
                //得到map的 months键的值  num2键的值 组装为新对象
                monthMap2.put(map.get("months").toString(), map.get("num2"));
            }
            //home 的下标0的 map的 name键的值
            dataMap.put("name", home.get(0).get("name"));
            dataMap.put("state", monthMap1);
            dataMap.put("state2", monthMap2);
@@ -425,75 +442,110 @@
            }
            exportForm.setDeptIds(deptIds);
        }
        List<ExcelExp> mysheet = new ArrayList<>();
        exportForm.setCameraFunType(Integer.valueOf(CheckConstants.Rule_Category_Video + ""));
        List<ExcelExp> sheet = new ArrayList<>();
        //通过Collections静态方法,把list转为线程安全的list
        List mysheet = Collections.synchronizedList(sheet);
        VideoExportForm.convertTags(exportForm);
        List<TMonitorResult> tMonitorResults = tMonitorMapper.selectMonitorResult(exportForm);
        List<String> deviceIds = tMonitorResults.stream().map(BaseResult::getNo).collect(Collectors.toList());
        Query query = getQuery(deviceIds, exportForm.getMonth());
        Query query = getQuery(exportForm);
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
        Map<String, TMonitorResult> uniqueResultsMap = onlineResult.stream()
                .collect(Collectors.toMap(
                        TMonitorResult::getNo, // keyMapper,这里假设 getNo() 返回 No 字段
                        Function.identity(),  // valueMapper,直接使用对象本身
                        (existing, replacement) -> existing // mergeFunction,如果有重复,保留第一个
                ));
        // 将 Map 转换为 List
        List<TMonitorResult> tMonitorResults = new ArrayList<>(uniqueResultsMap.values());
        List<String> deviceIds = tMonitorResults.stream().map(BaseResult::getNo).collect(Collectors.toList());
        // 将年月字符串解析为YearMonth对象
        YearMonth yearMonth = YearMonth.parse(exportForm.getMonth());
        // 获取当月的第一天
        LocalDate start = yearMonth.atDay(1);
        // 获取下个月的第一天(通过加上1个月并设置日为1)
        YearMonth nextMonth = yearMonth.plusMonths(1);
        LocalDate end = nextMonth.atDay(1);
        //获取这个月份的部门数据,录像由于是前一天的所以不用createTime字段
        Query videoQuery = new Query(Criteria.where("statTime").gte(start).lt(end));
        videoQuery.addCriteria(Criteria.where("no").in(deviceIds));
        //月份每日录像数据
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(query, RecordMetaDSumResult.class);
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(videoQuery, RecordMetaDSumResult.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String[] weeks = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        // 创建一个Map来存储每天的累加数据
        Map<String, VideoTotalExp> totalMap = new HashMap<>();
        Map<String, VideoTotalExp> totalMap = new ConcurrentHashMap<>();
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        //一个部门一个sheet
        for (Integer deptId : exportForm.getDeptIds()) {
            //从数据库集合筛选部门数据
            List<String> ids = tMonitorResults.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).map(BaseResult::getNo).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(ids)) continue;
            //筛选部门数据
            List<TMonitorResult> onlineList = onlineResult.stream().filter(tMonitorResult -> ids.contains(tMonitorResult.getNo())).collect(Collectors.toList());
            List<RecordMetaDSumResult> recordList = recordResult.stream().filter(result -> ids.contains(result.getNo())).collect(Collectors.toList());
            List<VideoTotalExp> videoTotalExps = new ArrayList<>();
            for (int i = 0; i < 31; i++) {
                String date = exportForm.getMonth();
                date += "-" + (i < 9 ? "0" + (i + 1) : (i + 1));
                //总量
                VideoTotalExp totalExp = totalMap.computeIfAbsent(date, k -> new VideoTotalExp());
                LocalDate parseTime = LocalDate.parse(date, formatter);
                //获取星期几
                String week = weeks[parseTime.getDayOfWeek().getValue() - 1];
                VideoTotalExp videoExp = new VideoTotalExp();
                videoExp.setDate(date);
                videoExp.setWeek(week);
                //设置点位在线总量
                List<TMonitorResult> onlines = onlineList.stream().filter(tMonitorResult -> tMonitorResult.getMongoCreateTime().minusDays(1).equals(parseTime)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(onlines)) {
                    videoExp.setTotal(onlines.size());
                    long count = onlines.stream()
                            .filter(item -> ApiConstants.UY_OnlineSite_Online.equals(item.getOnline()))
                            .count();
                    videoExp.setOnline(Integer.valueOf(count + ""));
                    videoExp.setOffline(videoExp.getTotal() - videoExp.getOnline());
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //筛选部门数据
                Set<String> ids = onlineResult.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).map(BaseResult::getNo).collect(Collectors.toSet());
                if (CollectionUtils.isEmpty(ids)) return;
                //筛选部门数据
                List<TMonitorResult> onlineList = onlineResult.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).collect(Collectors.toList());
                Map<LocalDate, List<TMonitorResult>> onlineMap = onlineList.stream()
                        .collect(Collectors.groupingBy(TMonitorResult::getMongoCreateTime));
                List<RecordMetaDSumResult> recordList = recordResult.stream().filter(result -> ids.contains(result.getNo())).collect(Collectors.toList());
                Map<Date, List<RecordMetaDSumResult>> recordMap = recordList.stream().collect(Collectors.groupingBy(RecordMetaDSumResult::getStatTime));
                List<VideoTotalExp> videoTotalExps = new ArrayList<>();
                for (int i = 0; i < 31; i++) {
                    String date = exportForm.getMonth();
                    date += "-" + (i < 9 ? "0" + (i + 1) : (i + 1));
                    //总量
                    VideoTotalExp totalExp = totalMap.computeIfAbsent(date, k -> new VideoTotalExp());
                    LocalDate parseTime = LocalDate.parse(date, formatter);
                    try {
                        Date parseDate = simpleDateFormat.parse(date);
                        //获取星期几
                        String week = weeks[parseTime.getDayOfWeek().getValue() - 1];
                        VideoTotalExp videoExp = new VideoTotalExp();
                        videoExp.setDate(date);
                        videoExp.setWeek(week);
                        //设置点位在线总量
                        List<TMonitorResult> onlines = onlineMap.get(parseTime);
                        if (!CollectionUtils.isEmpty(onlines)) {
                            videoExp.setTotal(onlines.size());
                            long count = onlines.stream()
                                    .filter(item -> ApiConstants.UY_OnlineSite_Online.equals(item.getOnline()))
                                    .count();
                            videoExp.setOnline(Integer.valueOf(count + ""));
                            videoExp.setOffline(videoExp.getTotal() - videoExp.getOnline());
                        }
                        //设置存储情况
                        List<RecordMetaDSumResult> records = recordMap.get(parseDate);
                        if (!CollectionUtils.isEmpty(records)) {
                            videoExp.setNoStore(Integer.valueOf(records.stream()
                                    .filter(record -> ApiConstants.UY_RecordStatus_Abnormal.equals(record.getRecordStatus()))
                                    .count() + ""));
                            videoExp.setPartStore(Integer.valueOf(records.stream()
                                    .filter(record -> ApiConstants.UY_RecordStatus_Interval.equals(record.getRecordStatus()))
                                    .count() + ""));
                        }
                        videoTotalExps.add(videoExp);
                        //累加作为全量表
                        totalExp.setDate(date);
                        totalExp.setWeek(week);
                        totalExp.setTotal((totalExp.getTotal() == null ? 0 : totalExp.getTotal()) + (videoExp.getTotal() == null ? 0 : videoExp.getTotal()));
                        totalExp.setOnline((totalExp.getOnline() == null ? 0 : totalExp.getOnline()) + (videoExp.getOnline() == null ? 0 : videoExp.getOnline()));
                        totalExp.setOffline((totalExp.getOffline() == null ? 0 : totalExp.getOffline()) + (videoExp.getOffline() == null ? 0 : videoExp.getOffline()));
                        totalExp.setNoStore((totalExp.getNoStore() == null ? 0 : totalExp.getNoStore()) + (videoExp.getNoStore() == null ? 0 : videoExp.getNoStore()));
                        totalExp.setPartStore((totalExp.getPartStore() == null ? 0 : totalExp.getPartStore()) + (videoExp.getPartStore() == null ? 0 : videoExp.getPartStore()));
                        totalMap.put(date, totalExp);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //设置存储情况
                List<RecordMetaDSumResult> records = recordList.stream().filter(record -> record.getMongoCreateTime().minusDays(1).equals(parseTime)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(records)) {
                    videoExp.setNoStore(Integer.valueOf(records.stream()
                            .filter(record -> ApiConstants.UY_RecordStatus_Abnormal.equals(record.getRecordStatus()))
                            .count() + ""));
                    videoExp.setPartStore(Integer.valueOf(records.stream()
                            .filter(record -> ApiConstants.UY_RecordStatus_Interval.equals(record.getRecordStatus()))
                            .count() + ""));
                }
                videoTotalExps.add(videoExp);
                //累加作为全量表
                totalExp.setDate(date);
                totalExp.setWeek(week);
                totalExp.setTotal((totalExp.getTotal() == null ? 0 : totalExp.getTotal()) + (videoExp.getTotal() == null ? 0 : videoExp.getTotal()));
                totalExp.setOnline((totalExp.getOnline() == null ? 0 : totalExp.getOnline()) + (videoExp.getOnline() == null ? 0 : videoExp.getOnline()));
                totalExp.setOffline((totalExp.getOffline() == null ? 0 : totalExp.getOffline()) + (videoExp.getOffline() == null ? 0 : videoExp.getOffline()));
                totalExp.setNoStore((totalExp.getNoStore() == null ? 0 : totalExp.getNoStore()) + (videoExp.getNoStore() == null ? 0 : videoExp.getNoStore()));
                totalExp.setPartStore((totalExp.getPartStore() == null ? 0 : totalExp.getPartStore()) + (videoExp.getPartStore() == null ? 0 : videoExp.getPartStore()));
                totalMap.put(date, totalExp);
            }
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            ExcelExp excelExp = new ExcelExp(areaDeptEnum == null ? "未知" : areaDeptEnum.getName(), videoTotalExps, VideoTotalExp.class);
            mysheet.add(excelExp);
                AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
                ExcelExp excelExp = new ExcelExp(areaDeptEnum == null ? "未知" : areaDeptEnum.getName(), videoTotalExps, VideoTotalExp.class);
                mysheet.add(excelExp);
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        allFutures.join(); // 这将阻塞直到所有任务完成
        //添加全量表
        List<VideoTotalExp> totalExps = new ArrayList<>(totalMap.values());
        totalExps = totalExps.stream().sorted(Comparator.comparing(VideoTotalExp::getDate)).collect(Collectors.toList());
@@ -510,6 +562,8 @@
     */
    @Override
    public void exportVideoOnline(HttpServletResponse response, VideoExportForm exportForm) throws IOException, NoSuchFieldException, IllegalAccessException {
        log.error("开始导出数据");
        log.error("传入的月份:{}",exportForm.getMonth());
        //默认查所有部门
        if (CollectionUtils.isEmpty(exportForm.getDeptIds())) {
            List<Integer> deptIds = new ArrayList<>();
@@ -518,10 +572,24 @@
            }
            exportForm.setDeptIds(deptIds);
        }
        List<ExcelExp> mysheet = new ArrayList<>();
        exportForm.setCameraFunType(Integer.valueOf(CheckConstants.Rule_Category_Video + ""));
        List<ExcelExp> sheet = new ArrayList<>();
        //通过Collections静态方法,把list转为线程安全的list
        List mysheet = Collections.synchronizedList(sheet);
        VideoExportForm.convertTags(exportForm);
        List<TMonitorResult> tMonitorResults = tMonitorMapper.selectMonitorResult(exportForm);
        Query query = getQuery(exportForm);
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        log.error("月份在线数据:{}条数",onlineResult.size());
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
        Map<String, TMonitorResult> uniqueResultsMap = onlineResult.stream()
                .collect(Collectors.toMap(
                        TMonitorResult::getNo, // keyMapper,这里假设 getNo() 返回 No 字段
                        Function.identity(),  // valueMapper,直接使用对象本身
                        (existing, replacement) -> existing // mergeFunction,如果有重复,保留第一个
                ));
        // 将 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);
@@ -533,51 +601,329 @@
                tMonitorResult.setDynamicColumnList(map.get(pointId));
            }
        }
        List<String> deviceIds = tMonitorResults.stream().map(BaseResult::getNo).collect(Collectors.toList());
        Query query = getQuery(deviceIds, exportForm.getMonth());
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        //全量表
        List<VideoDailyExp> totalExps = new ArrayList<>();
        //存放区域 与 设备列表 map key为 区域
        Map<Integer, List<VideoDailyExp>> map = new HashMap<>();
        List<CompletableFuture<List<VideoDailyExp>>> futures = new ArrayList<>();
        for (Integer deptId : exportForm.getDeptIds()) {
            List<VideoDailyExp> videoDailyExps = new ArrayList<>();
            //从数据库集合筛选部门数据
            List<TMonitorResult> monitors = tMonitorResults.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(monitors)) continue;
            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());
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            for (TMonitorResult result : monitors) {
                VideoDailyExp videoDailyExp = new VideoDailyExp();
                videoDailyExp.setSerialNumber(result.getNo());
                videoDailyExp.setDeviceName(result.getName());
                videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                StringBuilder tag = new StringBuilder("" + (result.getProvinceTag() ? "省厅、" : "") + (result.getImportantTag() ? "重点点位、" : "") + (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (result.getDeptTag() ? "部级、" : ""));
                //动态列处理加在标签里
                if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                    List<DynamicColumnVO> dynamicColumnList = result.getDynamicColumnList();
                    for (DynamicColumnVO dynamicColumnVO : dynamicColumnList) {
                        tag.append(dynamicColumnVO.getColumnValue()).append("、");
            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;
                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());
                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(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                    StringBuilder tag = new StringBuilder("" +
                            (result.getProvinceTag() ? "省厅、" : "") +
                            (result.getImportantTag() ? "重点点位、" : "") +
                            (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") +
                            (result.getDeptTag() ? "部级、" : ""));
                    //动态列处理加在标签里
                    if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                        for (DynamicColumnVO dynamicColumnVO : result.getDynamicColumnList()) {
                            tag.append(dynamicColumnVO.getColumnValue()).append("、");
                        }
                    }
                    // 删除字符串末尾的"、"
                    if (tag.toString().endsWith("、")) {
                        tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                    }
                    videoDailyExp.setTag(tag.toString());
                    try {
                        setOnlineDaily(videoDailyExp, result, onlines);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    videoDailyExps.add(videoDailyExp);
                }
                // 删除字符串末尾的“、”
                if (tag.toString().endsWith("、")) {
                    tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                }
                videoDailyExp.setTag(tag.toString());
                setOnlineDaily(videoDailyExp, result, onlines);
                videoDailyExps.add(videoDailyExp);
                //全量表
                totalExps.add(videoDailyExp);
            }
            ExcelExp excelExp = new ExcelExp(areaDeptEnum == null ? "未知" : areaDeptEnum.getName(), videoDailyExps, VideoDailyExp.class);
            mysheet.add(excelExp);
                ExcelExp excelExp = new ExcelExp(
                        areaDeptEnum == null ? "未知" : areaDeptEnum.getName(),
                        videoDailyExps,
                        VideoDailyExp.class
                );
                mysheet.add(excelExp);
                return videoDailyExps;
            }, threadPoolTaskExecutor);
            futures.add(future);
            map.put(deptId,future.join());
        }
        // 获取全量数据
        List<VideoDailyExp> totalExps = futures.stream()
                .map(CompletableFuture::join)
                .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<>();
        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);
        }
        videoTypeOffOnlineExps.addAll(allVideoTypeOffOnlineExps);
        videoOnlineRateExps.addAll(allVideoOnlineRateExps);
        log.error("打印计算离线的信息:{}" ,videoTypeOffOnlineExps );
        log.error("打印计在线的信息:{}" ,videoOnlineRateExps );
        //添加合计数据
        ExcelExp excelTypeOffLineExp = new ExcelExp("离线数统计", videoTypeOffOnlineExps, VideoTypeOffOnlineExp.class);
        mysheet.add(excelTypeOffLineExp);
        //添加在线率表
        ExcelExp excelOnlineRateExp = new ExcelExp("在线率统计",videoOnlineRateExps, VideoOnlineRateExp.class);
        mysheet.add(excelOnlineRateExp);
        ExcelUtilManySheet<List<ExcelExp>> util = new ExcelUtilManySheet<>(mysheet);
        util.exportExcelManySheet(response, mysheet);
        log.error("导出结束");
    }
    /**
     * 计算离线设备excel对象信息
     * @param videoDailyExps 传入的设备集合信息
     * @param type 设备类型 1人脸 2车辆 3视频
     * @param areaDeptEnum 区域
     * @return
     */
    public VideoTypeOffOnlineExp getListOfflineCountInfo(List<VideoDailyExp> videoDailyExps,
                                                         String type,
                                                         AreaDeptEnum areaDeptEnum,
                                                         boolean isTotal){
        VideoTypeOffOnlineExp videoTypeOffOnlineExp = new VideoTypeOffOnlineExp();
        List<VideoDailyExp> list = videoDailyExps.stream()
                .filter(device ->device.getType() != null && device.getType().contains(type)).collect(Collectors.toList());
        log.error("筛选完设备类型 :{} 后集合的大小:{}",type,list.size());
        //离线数量
        try {
            //设置离线数量 以及每日离线数量
            setVideoTypeOffOnlineExpCountAndDays(list,videoTypeOffOnlineExp,isTotal);
        } 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("视频");
            }
        }
        //修改区域
        videoTypeOffOnlineExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
        return videoTypeOffOnlineExp;
    }
    private void setVideoTypeOffOnlineExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoTypeOffOnlineExp videoTypeOffOnlineExp,boolean isTotal)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;
                String fieldName = "day" + i;
                for (VideoDailyExp videoDailyExp : videoDailyExps) {
                    // 构造字段名
                    Field field = videoDailyExp.getClass().getDeclaredField(fieldName);
                    // 确保字段是私有的可以访问
                    field.setAccessible(true);
                    // 获取字段值
                    String value = (String) field.get(videoDailyExp);
                    if ("离线".equals(value)) {
                        count++;
                    }
                }
                //反射添加到对象属性中
                Field field = videoTypeOffOnlineExp.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                String rateStr = count + "";
                if (!"0".equals(rateStr)) {
                    field.set(videoTypeOffOnlineExp, rateStr);
                }
            }
//        }
        videoTypeOffOnlineExp.setOfflineCount(String.valueOf(AllOffLineCount));
    }
    /**
     * 计算在线设备excel对象信息
     * @param videoDailyExps 传入的设备集合信息
     * @param type 设备类型 1人脸 2车辆 3视频
     * @param areaDeptEnum 区域
     * @return
     */
    public VideoOnlineRateExp getListOnLineCountInfo(List<VideoDailyExp> videoDailyExps,
                                                         String type,
                                                         AreaDeptEnum areaDeptEnum,
                                                         boolean isTotal){
        VideoOnlineRateExp videoOnlineRateExp = new VideoOnlineRateExp();
        List<VideoDailyExp> list = videoDailyExps.stream()
                .filter(device ->device.getType() != null && device.getType().contains(type)).collect(Collectors.toList());
        log.error("筛选完设备类型 :{} 后集合的大小:{}",type,list.size());
        //离线数量
        try {
            //设置离线数量 以及每日离线数量
            setVideoOnlineRateExpCountAndDays(list,videoOnlineRateExp,isTotal);
        } 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("视频");
            }
        }
        //修改区域
        videoOnlineRateExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
        return videoOnlineRateExp;
    }
    private void setVideoOnlineRateExpCountAndDays(List<VideoDailyExp> videoDailyExps,VideoOnlineRateExp videoOnlineRateExp,boolean isTotal)throws NoSuchFieldException, IllegalAccessException {
        //循环一个月
        for (int i = 1;i <= 31 ;i++){
            //在线率计算
            long count = 0;
            String fieldName = "day" + i;
            for(VideoDailyExp videoDailyExp: videoDailyExps){
                // 构造字段名
                Field field = videoDailyExp.getClass().getDeclaredField(fieldName);
                // 确保字段是私有的可以访问
                field.setAccessible(true);
                // 获取字段值
                String value = (String) field.get(videoDailyExp);
                if ("在线".equals(value)) {
                    count ++;
                }
            }
            //每日在线率
            double rate = (double) count / videoDailyExps.size();
            //反射添加到对象属性中
            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);
            }
        }
    }
@@ -594,10 +940,22 @@
            }
            exportForm.setDeptIds(deptIds);
        }
        List<ExcelExp> mysheet = new ArrayList<>();
        exportForm.setCameraFunType(Integer.valueOf(CheckConstants.Rule_Category_Video + ""));
        VideoExportForm.convertTags(exportForm);
        List<TMonitorResult> tMonitorResults = tMonitorMapper.selectMonitorResult(exportForm);
        Query query = getQuery(exportForm);
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
        Map<String, TMonitorResult> uniqueResultsMap = onlineResult.stream()
                .collect(Collectors.toMap(
                        TMonitorResult::getNo, // keyMapper,这里假设 getNo() 返回 No 字段
                        Function.identity(),  // valueMapper,直接使用对象本身
                        (existing, replacement) -> existing // mergeFunction,如果有重复,保留第一个
                ));
        // 将 Map 转换为 List
        List<TMonitorResult> tMonitorResults = new ArrayList<>(uniqueResultsMap.values());
        List<String> deviceIds = tMonitorResults.stream().map(BaseResult::getNo).collect(Collectors.toList());
        //获取动态列数据
        List<Integer> pointIds = tMonitorResults.stream().map(TMonitorResult::getPointId).collect(Collectors.toList());
        List<DynamicColumnVO> dynamics = dynamicColumnMapper.getDynamicsByIds("t_yw_point", pointIds);
@@ -609,7 +967,7 @@
                tMonitorResult.setDynamicColumnList(map.get(pointId));
            }
        }
        List<String> deviceIds = tMonitorResults.stream().map(BaseResult::getNo).collect(Collectors.toList());
        // 将年月字符串解析为YearMonth对象
        YearMonth yearMonth = YearMonth.parse(exportForm.getMonth());
        // 获取当月的第一天
@@ -618,48 +976,75 @@
        YearMonth nextMonth = yearMonth.plusMonths(1);
        LocalDate end = nextMonth.atDay(1);
        //获取这个月份的部门数据,录像由于是前一天的所以不用createTime字段
        Query query = new Query(Criteria.where("statTime").gte(start).lt(end));
        query.addCriteria(Criteria.where("no").in(deviceIds));
        Query videoQuery = new Query(Criteria.where("statTime").gte(start).lt(end));
        videoQuery.addCriteria(Criteria.where("no").in(deviceIds));
        //月份每日录像线数据
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(query, RecordMetaDSumResult.class);
        //全量表
        List<VideoDailyExp> totalExps = new ArrayList<>();
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(videoQuery, RecordMetaDSumResult.class);
        // 预先按部门ID分组
        Map<Integer, List<TMonitorResult>> monitorsByDept = tMonitorResults.stream()
                .collect(Collectors.groupingBy(TMonitorResult::getDeptId));
        // 预先构建映射
        Map<String, List<RecordMetaDSumResult>> recordMap = recordResult.stream()
                .collect(Collectors.groupingBy(RecordMetaDSumResult::getNo));
        List<CompletableFuture<List<VideoDailyExp>>> futures = new ArrayList<>();
        for (Integer deptId : exportForm.getDeptIds()) {
            List<VideoDailyExp> videoDailyExps = new ArrayList<>();
            //从数据库集合筛选部门数据
            List<TMonitorResult> monitors = tMonitorResults.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(monitors)) continue;
            List<String> ids = monitors.stream().map(BaseResult::getNo).collect(Collectors.toList());
            //筛选mongo区县数据
            List<RecordMetaDSumResult> records = recordResult.stream().filter(result -> ids.contains(result.getNo())).collect(Collectors.toList());
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            for (TMonitorResult result : monitors) {
                VideoDailyExp videoDailyExp = new VideoDailyExp();
                videoDailyExp.setSerialNumber(result.getNo());
                videoDailyExp.setDeviceName(result.getName());
                videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                StringBuilder tag = new StringBuilder("" + (result.getProvinceTag() ? "省厅、" : "") + (result.getImportantTag() ? "重点点位、" : "") + (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (result.getDeptTag() ? "部级、" : ""));
                //动态列处理加在标签里
                if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                    List<DynamicColumnVO> dynamicColumnList = result.getDynamicColumnList();
                    for (DynamicColumnVO dynamicColumnVO : dynamicColumnList) {
                        tag.append(dynamicColumnVO.getColumnValue()).append("、");
            CompletableFuture<List<VideoDailyExp>> future = CompletableFuture.supplyAsync(() -> {
                List<VideoDailyExp> videoDailyExps = new ArrayList<>();
                // 获取当前部门的数据
                List<TMonitorResult> monitors = monitorsByDept.getOrDefault(deptId, Collections.emptyList());
                if (CollectionUtils.isEmpty(monitors)) return videoDailyExps;
                AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
                for (TMonitorResult result : monitors) {
                    VideoDailyExp videoDailyExp = new VideoDailyExp();
                    videoDailyExp.setSerialNumber(result.getNo());
                    videoDailyExp.setDeviceName(result.getName());
                    videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                    StringBuilder tag = new StringBuilder("" + (result.getProvinceTag() ? "省厅、" : "") + (result.getImportantTag() ? "重点点位、" : "") + (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (result.getDeptTag() ? "部级、" : ""));
                    //动态列处理加在标签里
                    if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                        List<DynamicColumnVO> dynamicColumnList = result.getDynamicColumnList();
                        for (DynamicColumnVO dynamicColumnVO : dynamicColumnList) {
                            tag.append(dynamicColumnVO.getColumnValue()).append("、");
                        }
                    }
                    // 删除字符串末尾的“、”
                    if (tag.toString().endsWith("、")) {
                        tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                    }
                    videoDailyExp.setTag(tag.toString());
                    // 使用Map直接获取记录,避免filter操作
                    List<RecordMetaDSumResult> recordsResult = recordMap.get(result.getNo());
                    try {
                        if (!CollectionUtils.isEmpty(recordsResult))
                            setRecordDaily(videoDailyExp, result, recordsResult);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    //区县表
                    videoDailyExps.add(videoDailyExp);
                }
                // 删除字符串末尾的“、”
                if (tag.toString().endsWith("、")) {
                    tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                }
                videoDailyExp.setTag(tag.toString());
                setRecordDaily(videoDailyExp, result, records);
                //区县表
                videoDailyExps.add(videoDailyExp);
                //全量表
                totalExps.add(videoDailyExp);
            }
            ExcelExp excelExp = new ExcelExp(areaDeptEnum == null ? "未知" : areaDeptEnum.getName(), videoDailyExps, VideoDailyExp.class);
            mysheet.add(excelExp);
                return videoDailyExps;
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        // 每个部门的数据单独保存
        List<List<VideoDailyExp>> results = futures.stream()
                .map(CompletableFuture::join)  // 获取每个Future的结果
                .collect(Collectors.toList());
        List<VideoDailyExp> totalExps = new ArrayList<>();
        List<ExcelExp> mysheet = new ArrayList<>();
        for (List<VideoDailyExp> result : results) {
            ExcelExp excelExp = new ExcelExp(
                    result.get(0).getArea() == null ? "未知" : result.get(0).getArea(),
                    result,
                    VideoDailyExp.class);
            mysheet.add(excelExp);
            totalExps.addAll(result);
        }
        ExcelExp excelExp = new ExcelExp("全量", totalExps, VideoDailyExp.class);
        mysheet.add(excelExp);
        ExcelUtilManySheet<List<ExcelExp>> util = new ExcelUtilManySheet<>(mysheet);
@@ -679,10 +1064,19 @@
            }
            exportForm.setDeptIds(deptIds);
        }
        List<ExcelExp> mysheet = new ArrayList<>();
        exportForm.setCameraFunType(Integer.valueOf(CheckConstants.Rule_Category_Video + ""));
        VideoExportForm.convertTags(exportForm);
        List<TMonitorResult> tMonitorResults = tMonitorMapper.selectMonitorResult(exportForm);
        Query query = getQuery(exportForm);
        //月份每日在线数据
        List<TMonitorResult> onlineResult = mongoTemplate.find(query, TMonitorResult.class);
        // 使用 Collectors.toMap 去重,保留每个 No 的第一个遇到的元素
        Map<String, TMonitorResult> uniqueResultsMap = onlineResult.stream()
                .collect(Collectors.toMap(
                        TMonitorResult::getNo, // keyMapper,这里假设 getNo() 返回 No 字段
                        Function.identity(),  // valueMapper,直接使用对象本身
                        (existing, replacement) -> existing // mergeFunction,如果有重复,保留第一个
                ));
        // 将 Map 转换为 List
        List<TMonitorResult> tMonitorResults = new ArrayList<>(uniqueResultsMap.values());
        //获取动态列数据
        List<Integer> pointIds = tMonitorResults.stream().map(TMonitorResult::getPointId).collect(Collectors.toList());
        List<DynamicColumnVO> dynamics = dynamicColumnMapper.getDynamicsByIds("t_yw_point", pointIds);
@@ -703,46 +1097,72 @@
        YearMonth nextMonth = yearMonth.plusMonths(1);
        LocalDate end = nextMonth.atDay(1);
        //获取这个月份的部门数据,录像由于是前一天的所以不用createTime字段
        Query query = new Query(Criteria.where("statTime").gte(start).lt(end));
        query.addCriteria(Criteria.where("no").in(deviceIds));
        Query videoQuery = new Query(Criteria.where("statTime").gte(start).lt(end));
        videoQuery.addCriteria(Criteria.where("no").in(deviceIds));
        //月份每日录像线数据
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(query, RecordMetaDSumResult.class);
        //全量表
        List<VideoDailyExp> totalExps = new ArrayList<>();
        List<RecordMetaDSumResult> recordResult = mongoTemplate.find(videoQuery, RecordMetaDSumResult.class);
        // 预先按部门ID分组
        Map<Integer, List<TMonitorResult>> monitorsByDept = tMonitorResults.stream()
                .collect(Collectors.groupingBy(TMonitorResult::getDeptId));
        // 预先构建映射
        Map<String, List<RecordMetaDSumResult>> recordMap = recordResult.stream()
                .collect(Collectors.groupingBy(RecordMetaDSumResult::getNo));
        List<CompletableFuture<List<VideoDailyExp>>> futures = new ArrayList<>();
        for (Integer deptId : exportForm.getDeptIds()) {
            List<VideoDailyExp> videoDailyExps = new ArrayList<>();
            //从数据库集合筛选部门数据
            List<TMonitorResult> monitors = tMonitorResults.stream().filter(tMonitorResult -> deptId.equals(tMonitorResult.getDeptId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(monitors)) continue;
            List<String> ids = monitors.stream().map(BaseResult::getNo).collect(Collectors.toList());
            //筛选mongo区县数据
            List<RecordMetaDSumResult> records = recordResult.stream().filter(result -> ids.contains(result.getNo())).collect(Collectors.toList());
            AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
            for (TMonitorResult result : monitors) {
                VideoDailyExp videoDailyExp = new VideoDailyExp();
                videoDailyExp.setSerialNumber(result.getNo());
                videoDailyExp.setDeviceName(result.getName());
                videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                StringBuilder tag = new StringBuilder("" + (result.getProvinceTag() ? "省厅、" : "") + (result.getImportantTag() ? "重点点位、" : "") + (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (result.getDeptTag() ? "部级、" : ""));
                //动态列处理加在标签里
                if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                    List<DynamicColumnVO> dynamicColumnList = result.getDynamicColumnList();
                    for (DynamicColumnVO dynamicColumnVO : dynamicColumnList) {
                        tag.append(dynamicColumnVO.getColumnValue()).append("、");
            CompletableFuture<List<VideoDailyExp>> future = CompletableFuture.supplyAsync(() -> {
                List<VideoDailyExp> videoDailyExps = new ArrayList<>();
                // 获取当前部门的数据
                List<TMonitorResult> monitors = monitorsByDept.getOrDefault(deptId, Collections.emptyList());
                if (CollectionUtils.isEmpty(monitors)) return videoDailyExps;
                AreaDeptEnum areaDeptEnum = AreaDeptEnum.fromDept(deptId);
                for (TMonitorResult result : monitors) {
                    VideoDailyExp videoDailyExp = new VideoDailyExp();
                    videoDailyExp.setSerialNumber(result.getNo());
                    videoDailyExp.setDeviceName(result.getName());
                    videoDailyExp.setArea(areaDeptEnum == null ? "未知" : areaDeptEnum.getName());
                    StringBuilder tag = new StringBuilder("" + (result.getProvinceTag() ? "省厅、" : "") + (result.getImportantTag() ? "重点点位、" : "") + (result.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (result.getDeptTag() ? "部级、" : ""));
                    //动态列处理加在标签里
                    if (!CollectionUtils.isEmpty(result.getDynamicColumnList())) {
                        List<DynamicColumnVO> dynamicColumnList = result.getDynamicColumnList();
                        for (DynamicColumnVO dynamicColumnVO : dynamicColumnList) {
                            tag.append(dynamicColumnVO.getColumnValue()).append("、");
                        }
                    }
                    // 删除字符串末尾的“、”
                    if (tag.toString().endsWith("、")) {
                        tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                    }
                    videoDailyExp.setTag(tag.toString());
                    // 使用Map直接获取记录,避免filter操作
                    List<RecordMetaDSumResult> recordsResult = recordMap.get(result.getNo());
                    try {
                        if (!CollectionUtils.isEmpty(recordsResult)) setLoseDaily(videoDailyExp, recordsResult);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    videoDailyExps.add(videoDailyExp);
                }
                // 删除字符串末尾的“、”
                if (tag.toString().endsWith("、")) {
                    tag = new StringBuilder(tag.substring(0, tag.length() - 1));
                }
                videoDailyExp.setTag(tag.toString());
                setLoseDaily(videoDailyExp, result, records);
                videoDailyExps.add(videoDailyExp);
                //全量表
                totalExps.add(videoDailyExp);
            }
            ExcelExp excelExp = new ExcelExp(areaDeptEnum == null ? "未知" : areaDeptEnum.getName(), videoDailyExps, VideoDailyExp.class);
                return videoDailyExps;
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        // 每个部门的数据单独保存
        List<List<VideoDailyExp>> results = futures.stream()
                .map(CompletableFuture::join)  // 获取每个Future的结果
                .collect(Collectors.toList());
        List<VideoDailyExp> totalExps = new ArrayList<>();
        List<ExcelExp> mysheet = new ArrayList<>();
        for (List<VideoDailyExp> result : results) {
            ExcelExp excelExp = new ExcelExp(
                    result.get(0).getArea() == null ? "未知" : result.get(0).getArea(),
                    result,
                    VideoDailyExp.class);
            mysheet.add(excelExp);
            totalExps.addAll(result);
        }
        ExcelExp excelExp = new ExcelExp("全量", totalExps, VideoDailyExp.class);
        mysheet.add(excelExp);
@@ -800,6 +1220,13 @@
                        ))
                        .append("loseCount", new Document("$sum",
                                new Document("$cond", Arrays.asList(
                                        new Document("$eq", Arrays.asList("$recordStatus", 0)),
                                        1,
                                        0
                                ))
                        ))
                        .append("errCount", new Document("$sum",
                                new Document("$cond", Arrays.asList(
                                        new Document("$eq", Arrays.asList("$recordStatus", -1)),
                                        1,
                                        0
@@ -814,6 +1241,7 @@
            homeVideoVO.setCreateDate(doc.getDate("_id"));
            homeVideoVO.setIntegrityNum(doc.getInteger("normalCount"));
            homeVideoVO.setLoseNum(doc.getInteger("loseCount"));
            homeVideoVO.setErrNum(doc.getInteger("errCount"));
            results.add(homeVideoVO);
        }
@@ -897,7 +1325,7 @@
                String type = car.replaceAll("3", "人脸");
                monitor.setCameraFunType(type);
            }
            StringBuilder tag = new StringBuilder("" + (monitor.getProvinceTagVideo() ? "省厅视频、" : "") + (monitor.getProvinceTagCar() ? "省厅车辆、" : "")+ (monitor.getProvinceTagFace() ? "省厅人脸、" : "")+ (monitor.getImportantTag() ? "重点点位、" : "") + (monitor.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (monitor.getDeptTag() ? "部级、" : ""));
            StringBuilder tag = new StringBuilder("" + (monitor.getProvinceTagVideo() ? "省厅视频、" : "") + (monitor.getProvinceTagCar() ? "省厅车辆、" : "") + (monitor.getProvinceTagFace() ? "省厅人脸、" : "") + (monitor.getImportantTag() ? "重点点位、" : "") + (monitor.getImportantCommandImageTag() ? "重点指挥图像、" : "") + (monitor.getDeptTag() ? "部级、" : ""));
            //动态列处理加在标签里
            if (!CollectionUtils.isEmpty(monitor.getDynamicColumnList())) {
                List<DynamicColumnVO> dynamicColumnList = monitor.getDynamicColumnList();
@@ -913,14 +1341,32 @@
        });
        ExcelUtil<TMonitorExp> util = new ExcelUtil<>(TMonitorExp.class);
        String sheetName = "";
        if("1".equals(tMonitor.getCameraFunType())){
        if ("1".equals(tMonitor.getCameraFunType())) {
            sheetName = "视频";
        }else if("2".equals(tMonitor.getCameraFunType())){
        } else if ("2".equals(tMonitor.getCameraFunType())) {
            sheetName = "车辆";
        }else if("3".equals(tMonitor.getCameraFunType())){
        } else if ("3".equals(tMonitor.getCameraFunType())) {
            sheetName = "人脸";
        }
        util.exportExcel(response, monitors,sheetName);
        util.exportExcel(response, monitors, sheetName);
    }
    /**
     * 清理一机一档
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result clearMonitor() {
      tMonitorMapper.clearMonitor();
      pointMapper.clearMonitor();
      return Result.ok();
    }
    @Override
    public Result assetManagementCount(DataCenterQuery query) {
        Map<String, String> map =tMonitorMapper.assetManagementCount();
        return Result.ok().data(map);
    }
@@ -1006,30 +1452,33 @@
        Map<String, Object> resultMap = new HashMap<>();
        //按时间排序
        results = results.stream().sorted(Comparator.comparing(BaseHomeVO::getCreateDate)).collect(Collectors.toList());
        int snapCount = 0;
        for (HomeCarVO vo : results) {
            if (vo.getSnapCount() != null) {
                snapCount += vo.getSnapCount();
        //如果是默认或累和则进行累和以及获取基准线
        if (monitorQuery.getCategory() == null || monitorQuery.getCategory().equals(1)) {
            int snapCount = 0;
            for (HomeCarVO vo : results) {
                if (vo.getSnapCount() != null) {
                    snapCount += vo.getSnapCount();
                }
                vo.setSnapCount(snapCount);
            }
            vo.setSnapCount(snapCount);
            //从字典获取基准线
            List<SysDictData> baseLines = dictDataMapper.selectDictDataByType("home_baseLine");
            String condition;
            if (examineTag != null && examineTag == 1) {
                condition = "car_province_baseLine";
            } else if (examineTag != null && examineTag == 2) {
                condition = "car_dept_baseLine";
            } else {
                condition = "car_all_baseLine";
            }
            Optional<SysDictData> first = baseLines.stream().filter(sysDictData -> condition.equals(sysDictData.getDictLabel())).findFirst();
            if (first.isPresent()) {
                SysDictData sysDictData = first.get();
                resultMap.put("baseLine", Integer.valueOf(sysDictData.getDictValue()));
            }
        }
        resultMap.put("list", results);
        //从字典获取基准线
        List<SysDictData> baseLines = dictDataMapper.selectDictDataByType("home_baseLine");
        String condition;
        if (examineTag != null && examineTag == 1) {
            condition = "car_province_baseLine";
        } else if (examineTag != null && examineTag == 2) {
            condition = "car_dept_baseLine";
        } else {
            condition = "car_all_baseLine";
        }
        Optional<SysDictData> first = baseLines.stream().filter(sysDictData -> condition.equals(sysDictData.getDictLabel())).findFirst();
        if (first.isPresent()) {
            SysDictData sysDictData = first.get();
            resultMap.put("baseLine", Integer.valueOf(sysDictData.getDictValue()));
        }
        return resultMap;
    }
@@ -1114,32 +1563,35 @@
            HomeFaceVO vo = findOrCreateVO(doc, results, HomeFaceVO.class);
            vo.setOnline(doc.getInteger("onlineCount"));
        }
        Map<String, Object> resultMap = new HashMap<>();
        //按时间排序
        results = results.stream().sorted(Comparator.comparing(BaseHomeVO::getCreateDate)).collect(Collectors.toList());
        int snapCount = 0;
        for (HomeFaceVO vo : results) {
            if (vo.getSnapCount() != null) {
                snapCount += vo.getSnapCount();
        //如果是默认或累和则进行累和以及获取基准线
        if (monitorQuery.getCategory() == null || monitorQuery.getCategory().equals(1)) {
            int snapCount = 0;
            for (HomeFaceVO vo : results) {
                if (vo.getSnapCount() != null) {
                    snapCount += vo.getSnapCount();
                }
                vo.setSnapCount(snapCount);
            }
            vo.setSnapCount(snapCount);
            //从字典获取基准线
            List<SysDictData> baseLines = dictDataMapper.selectDictDataByType("home_baseLine");
            String condition;
            if (examineTag != null && examineTag == 1) {
                condition = "face_province_baseLine";
            } else if (examineTag != null && examineTag == 2) {
                condition = "face_dept_baseLine";
            } else {
                condition = "face_all_baseLine";
            }
            Optional<SysDictData> first = baseLines.stream().filter(sysDictData -> condition.equals(sysDictData.getDictLabel())).findFirst();
            if (first.isPresent()) {
                SysDictData sysDictData = first.get();
                resultMap.put("baseLine", Integer.valueOf(sysDictData.getDictValue()));
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", results);
        //从字典获取基准线
        List<SysDictData> baseLines = dictDataMapper.selectDictDataByType("home_baseLine");
        String condition;
        if (examineTag != null && examineTag == 1) {
            condition = "face_province_baseLine";
        } else if (examineTag != null && examineTag == 2) {
            condition = "face_dept_baseLine";
        } else {
            condition = "face_all_baseLine";
        }
        Optional<SysDictData> first = baseLines.stream().filter(sysDictData -> condition.equals(sysDictData.getDictLabel())).findFirst();
        if (first.isPresent()) {
            SysDictData sysDictData = first.get();
            resultMap.put("baseLine", Integer.valueOf(sysDictData.getDictValue()));
        }
        return resultMap;
    }
@@ -1157,7 +1609,8 @@
        return vo;
    }
    private Query getQuery(List<String> deviceIds, String month) {
    private Query getQuery(VideoExportForm exportForm) {
        String month = exportForm.getMonth();
        // 将年月字符串解析为YearMonth对象
        YearMonth yearMonth = YearMonth.parse(month);
        // 获取当月的第一天
@@ -1167,7 +1620,15 @@
        LocalDate end = nextMonth.atDay(1);
        //获取这个月份的部门数据
        Query query = new Query(Criteria.where("mongoCreateTime").gte(start).lt(end));
        query.addCriteria(Criteria.where("no").in(deviceIds));
        if (!CollectionUtils.isEmpty(exportForm.getDeptIds()))
            query.addCriteria(Criteria.where("deptId").in(exportForm.getDeptIds()));
        if (exportForm.getDeptTag() != null) query.addCriteria(Criteria.where("deptTag").is(exportForm.getDeptTag()));
        if (exportForm.getProvinceTag() != null)
            query.addCriteria(Criteria.where("provinceTag").is(exportForm.getProvinceTag()));
        if (exportForm.getImportantTag() != null)
            query.addCriteria(Criteria.where("importantTag").is(exportForm.getImportantTag()));
        if (exportForm.getImportantCommandImageTag() != null)
            query.addCriteria(Criteria.where("importantCommandImageTag").is(exportForm.getImportantCommandImageTag()));
        return query;
    }
@@ -1175,6 +1636,7 @@
    private void setOnlineDaily(VideoDailyExp videoDailyExp, TMonitorResult result, List<TMonitorResult> onlines) throws NoSuchFieldException, IllegalAccessException {
        //一个设备当月在线情况
        List<TMonitorResult> onlineResult = onlines.stream().filter(online -> online.getNo().equals(result.getNo())).collect(Collectors.toList());
        videoDailyExp.setOnlineStateList(onlineResult);
        for (TMonitorResult monitorResult : onlineResult) {
            int dayOfMonth = monitorResult.getMongoCreateTime().getDayOfMonth();
            String online = "";
@@ -1190,12 +1652,12 @@
            field.setAccessible(true);
            field.set(videoDailyExp, online);
        }
    }
    //设置每日录像数据
    private void setRecordDaily(VideoDailyExp videoDailyExp, TMonitorResult result, List<RecordMetaDSumResult> records) throws NoSuchFieldException, IllegalAccessException {
        //一个设备当月在线情况
        List<RecordMetaDSumResult> recordResults = records.stream().filter(online -> online.getNo().equals(result.getNo())).collect(Collectors.toList());
    private void setRecordDaily(VideoDailyExp videoDailyExp, TMonitorResult result, List<RecordMetaDSumResult> recordResults) throws NoSuchFieldException, IllegalAccessException {
        for (RecordMetaDSumResult recordResult : recordResults) {
            int dayOfMonth = DateUtils.getDayOfMonth(recordResult.getStatTime());
            Integer status = recordResult.getRecordStatus();
@@ -1215,17 +1677,16 @@
    }
    //设置每日录像缺失时长数据
    private void setLoseDaily(VideoDailyExp videoDailyExp, TMonitorResult result, List<RecordMetaDSumResult> records) throws NoSuchFieldException, IllegalAccessException {
    private void setLoseDaily(VideoDailyExp videoDailyExp, List<RecordMetaDSumResult> recordResults) throws NoSuchFieldException, IllegalAccessException {
        //一个设备当月在线情况
        List<RecordMetaDSumResult> recordResults = records.stream().filter(online -> online.getNo().equals(result.getNo())).collect(Collectors.toList());
        for (RecordMetaDSumResult recordResult : recordResults) {
            int dayOfMonth = DateUtils.getDayOfMonth(recordResult.getStatTime());
            int dayOfMonth = DateUtils.getDayOfMonth(recordResult.getStatTime());  //获取启动日期是当月第几天
            //反射赋值,字段统一定义为day+1,2,3...
            Field field = videoDailyExp.getClass().getDeclaredField("day" + dayOfMonth);
            field.setAccessible(true);
            //防止转换为科学计数法
            BigDecimal bigDecimal = BigDecimal.valueOf(recordResult.getMissDuration() == null ? 0 : recordResult.getMissDuration());
            field.set(videoDailyExp, bigDecimal.toString());
            BigDecimal bigDecimal = BigDecimal.valueOf(recordResult.getMissDuration() == null ? 0 : (recordResult.getMissDuration()) * 60);
            field.set(videoDailyExp, bigDecimal.setScale(2, RoundingMode.HALF_UP).toString());
        }
    }
}