liujie
2026-02-05 b5a5e43e2ea7af773dba1ee99c2194be61515df8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
package com.ruoyi.system.service.impl;
 
 
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.enums.DeviceType;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.model.*;
import com.ruoyi.system.model.Record;
import com.ruoyi.system.service.ClientService;
import com.ruoyi.system.service.ProjectCategoryCalculator;
import com.ruoyi.system.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 委托方 服务实现类
 * </p>
 *
 * @author administrator
 * @since 2026-01-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements ClientService {
 
    private final ProjectMapper projectMapper;
    private final PlanMapper planMapper;
    private final CheckMapper checkMapper;
    private final TaskMapper taskMapper;
    private final DeviceUsageMapper deviceUsageMapper;
    private final RecordMapper recordMapper;
    private final ProjectCategoryCalculator projectCategoryCalculator;
    private final ClientParamMapper clientParamMapper;
    private final DeviceMapper deviceMapper;
    private final ErrorReviewMapper errorReviewMapper;
 
    @Override
    public ClientDashboardVO getClientDashboard(ClientDashboardQuery query) {
        ClientDashboardVO vo = new ClientDashboardVO();
        vo.setProjectCategory(query.getProjectCategory());
 
        // 获取委托方ID(如果未传则需要从当前登录用户获取,这里暂时使用传入的值)
        Long clientId = query.getClientId();
 
        // 获取日期范围
        Date startDate = getStartDate(query.getStartDate());
        Date endDate = getEndDate(query.getEndDate());
 
        // 根据项目类型进行不同的统计
        if ("ongoing".equals(query.getProjectCategory())) {
            // 在建工程统计
            OngoingProjectDashboardVO ongoingVO = calculateOngoingProjectStatistics(clientId, startDate, endDate);
            vo.setOngoingProject(ongoingVO);
        } else if ("fixed".equals(query.getProjectCategory())) {
            // 固定资产统计
            FixedAssetDashboardVO fixedVO = calculateFixedAssetStatistics(clientId, startDate, endDate);
            vo.setFixedAsset(fixedVO);
        }
 
        return vo;
    }
 
    /**
     * 在建工程统计
     */
    private OngoingProjectDashboardVO calculateOngoingProjectStatistics(Long clientId, Date monthStart, Date monthEnd) {
        OngoingProjectDashboardVO vo = new OngoingProjectDashboardVO();
 
        // 查询在建工程项目(usage_type 表示项目用途类型,假设 0 表示在建工程)
        LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.eq(Project::getDeleted, false)
                .ne(Project::getType, 2) // 在建工程
                .and(wrapper -> wrapper
                    .eq(Project::getStatus, 1)  // 在建项目
                    .or(w -> w
                        .eq(Project::getStatus, 2)  // 已完成项目
                        .between(Project::getSuccessTime, monthStart,monthEnd)  // 完成时间 >= 开始日期// 完成时间 <= 结束日期
                    )
                );
        if (clientId != null) {
            projectWrapper.eq(Project::getClientId, clientId);
        }
        List<Project> projects = projectMapper.selectList(projectWrapper);
 
        // 1. 统计项目总数及分类
        vo.setProjectTotal(projects.size());
        long housingCount = projects.stream().filter(p -> p.getType() != null && p.getType() == 0).count();
        long municipalCount = projects.stream().filter(p -> p.getType() != null && p.getType() == 1).count();
        vo.setHousingProjectCount((int) housingCount);
        vo.setMunicipalProjectCount((int) municipalCount);
 
        // 计算检查覆盖率(仅当查询时间范围为当月时才计算)
        List<Integer> projectIds = projects.stream().map(Project::getId).collect(Collectors.toList());
        if (!projectIds.isEmpty() && isCurrentMonth(monthStart, monthEnd)) {
            // 1. 先查询符合条件的 Task
            LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.in(Task::getProjectId, projectIds)
                    .ge(Task::getDate, monthStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                    .le(Task::getDate, monthEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                    .eq(Task::getDeleted, false);
            List<Task> tasks = taskMapper.selectList(taskWrapper);
 
            if (!tasks.isEmpty()) {
                // 2. 获取 Task ID 列表
                List<Integer> taskIds = tasks.stream().map(Task::getId).collect(Collectors.toList());
 
                // 3. 建立 Task ID 到 Project ID 的映射
                Map<Integer, Integer> taskToProjectMap = tasks.stream()
                        .collect(Collectors.toMap(Task::getId, Task::getProjectId));
 
                // 4. 查询 record 表中 record_type='error' 且 device_id 为 null 的记录(项目检查)
                LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
                recordWrapper.eq(Record::getRecordType, "error")
                        .isNull(Record::getDeviceId)
                        .in(Record::getCheckTaskId, taskIds)
                        .eq(Record::getDeleted, false);
                List<Record> projectRecords = recordMapper.selectList(recordWrapper);
 
                // 5. 通过 Task 映射获取有检查记录的项目 ID
                List<Integer> checkedProjectIds = projectRecords.stream()
                        .map(Record::getCheckTaskId)
                        .map(taskToProjectMap::get)
                        .filter(Objects::nonNull)
                        .distinct()
                        .toList();
 
                // 查询配置的项目总数
                ClientParam clientParam = null;
                if (clientId != null) {
                    clientParam = clientParamMapper.selectOne(
                        new LambdaQueryWrapper<ClientParam>()
                            .eq(ClientParam::getClientId, clientId.intValue())
                    );
                }
 
                // 房建检查覆盖率
                List<Integer> housingProjectIds = projects.stream()
                        .filter(p -> p.getType() != null && p.getType() == 0)
                        .map(Project::getId)
                        .toList();
                long checkedHousingCount = checkedProjectIds.stream()
                        .filter(housingProjectIds::contains)
                        .count();
 
                // 使用配置的房建项目总数,如果没有配置则使用实际数量
                int configuredHousingNum = (clientParam != null && clientParam.getHousingProjectNum() != null)
                        ? clientParam.getHousingProjectNum()
                        : (int) housingCount;
                vo.setHousingInspectionCoverage(
                        configuredHousingNum > 0 ? (int) Math.round(checkedHousingCount * 100.0 / configuredHousingNum) : 0
                );
 
                // 市政检查覆盖率
                List<Integer> municipalProjectIds = projects.stream()
                        .filter(p -> p.getType() != null && p.getType() == 1)
                        .map(Project::getId)
                        .toList();
                long checkedMunicipalCount = checkedProjectIds.stream()
                        .filter(municipalProjectIds::contains)
                        .count();
 
                // 使用配置的市政项目总数,如果没有配置则使用实际数量
                int configuredMunicipalNum = (clientParam != null && clientParam.getMunicipalProjectNum() != null)
                        ? clientParam.getMunicipalProjectNum()
                        : (int) municipalCount;
                vo.setMunicipalInspectionCoverage(
                        configuredMunicipalNum > 0 ? (int) Math.round(checkedMunicipalCount * 100.0 / configuredMunicipalNum) : 0
                );
            } else {
                vo.setHousingInspectionCoverage(0);
                vo.setMunicipalInspectionCoverage(0);
            }
        } else {
            vo.setHousingInspectionCoverage(0);
            vo.setMunicipalInspectionCoverage(0);
        }
 
        // 2. 统计本月检查情况
        calculateMonthlyInspectionForOngoing(vo, projects, projectIds, monthStart, monthEnd);
 
        // 3. 统计大型机械设备数
        List<MachineryStatisticsVO> machineryStatistics = calculateMachineryStatistics(projectIds, monthStart, monthEnd);
        vo.setMachineryStatistics(machineryStatistics);
 
        // 汇总计算设备总数统计
        int machineryTotal = machineryStatistics.stream()
                .mapToInt(MachineryStatisticsVO::getTotal)
                .sum();
        int inspectedMachineryTotal = machineryStatistics.stream()
                .mapToInt(MachineryStatisticsVO::getInspectedCount)
                .sum();
        int uninspectedMachineryTotal = machineryStatistics.stream()
                .mapToInt(MachineryStatisticsVO::getUninspectedCount)
                .sum();
 
        vo.setMachineryTotal(machineryTotal);
        vo.setInspectedMachineryTotal(inspectedMachineryTotal);
        vo.setUninspectedMachineryTotal(uninspectedMachineryTotal);
 
        // 4. 统计重大隐患数
        calculateHazardStatistics(vo, projectIds);
 
        // 5. 获取地图标点数据
        vo.setProjectMapPoints(getProjectMapPoints(projects, clientId, monthStart, monthEnd));
 
        return vo;
    }
 
    /**
     * 固定资产统计
     */
    private FixedAssetDashboardVO calculateFixedAssetStatistics(Long clientId, Date monthStart, Date monthEnd) {
        FixedAssetDashboardVO vo = new FixedAssetDashboardVO();
 
        // 查询固定资产项目
        LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();
        projectWrapper.eq(Project::getDeleted, false)
                .eq(Project::getType, 2) // 在建工程
                .and(wrapper -> wrapper
                        .eq(Project::getStatus, 1)  // 在建项目
                        .or(w -> w
                                .eq(Project::getStatus, 2)  // 已完成项目
                                .between(Project::getSuccessTime, monthStart,monthEnd)  // 完成时间 >= 开始日期// 完成时间 <= 结束日期
                        )
                );
        if (clientId != null) {
            projectWrapper.eq(Project::getClientId, clientId);
        }
        List<Project> projects = projectMapper.selectList(projectWrapper);
 
        // 1. 统计项目总数
        vo.setProjectTotal(projects.size());
 
        List<Integer> projectIds = projects.stream().map(Project::getId).collect(Collectors.toList());
 
        // 2. 统计本月检查情况
        calculateMonthlyInspectionForFixed(vo, projects, projectIds, monthStart, monthEnd);
 
        // 3. 统计重大隐患数
        calculateHazardStatisticsForFixed(vo, projectIds);
 
        // 4. 获取地图标点数据
        vo.setProjectMapPoints(getProjectMapPoints(projects, clientId, monthStart, monthEnd));
 
        return vo;
    }
 
    /**
     * 统计在建工程本月检查情况
     */
    private void calculateMonthlyInspectionForOngoing(OngoingProjectDashboardVO vo, List<Project> projects,
                                                      List<Integer> projectIds, Date monthStart, Date monthEnd) {
        if (projectIds.isEmpty()) {
            vo.setInspectedCount(0);
            vo.setInspectedHousingCount(0);
            vo.setInspectedMunicipalCount(0);
            vo.setUninspectedCount(projects.size());
            vo.setUninspectedHousingCount(vo.getHousingProjectCount());
            vo.setUninspectedMunicipalCount(vo.getMunicipalProjectCount());
            return;
        }
 
        // 1. 先查询符合条件的 Task(本月的任务)
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.in(Task::getProjectId, projectIds)
                .ge(Task::getDate, monthStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .le(Task::getDate, monthEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .eq(Task::getDeleted, false);
        List<Task> monthlyTasks = taskMapper.selectList(taskWrapper);
 
        if (monthlyTasks.isEmpty()) {
            vo.setInspectedCount(0);
            vo.setInspectedHousingCount(0);
            vo.setInspectedMunicipalCount(0);
            vo.setUninspectedCount(projects.size());
            vo.setUninspectedHousingCount(vo.getHousingProjectCount());
            vo.setUninspectedMunicipalCount(vo.getMunicipalProjectCount());
            return;
        }
 
        // 2. 获取 Task ID 列表
        List<Integer> taskIds = monthlyTasks.stream().map(Task::getId).collect(Collectors.toList());
 
        // 3. 建立 Task ID 到 Project ID 的映射
        Map<Integer, Integer> taskToProjectMap = monthlyTasks.stream()
                .collect(Collectors.toMap(Task::getId, Task::getProjectId));
 
        // 4. 查询本月有检查记录的项目(查询 record 表中 record_type='error' 且 device_id 为 null 的记录)
        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getRecordType, "error")
                .isNull(Record::getDeviceId)
                .in(Record::getCheckTaskId, taskIds)
                .eq(Record::getDeleted, false);
        List<Record> monthlyRecords = recordMapper.selectList(recordWrapper);
 
        // 5. 通过 Task 映射获取有检查记录的项目 ID
        List<Integer> inspectedProjectIds = monthlyRecords.stream()
                .map(Record::getCheckTaskId)
                .map(taskToProjectMap::get)
                .filter(Objects::nonNull)
                .distinct()
                .toList();
 
        // 已检查项目统计
        List<Project> inspectedProjects = projects.stream()
                .filter(p -> inspectedProjectIds.contains(p.getId()))
                .toList();
 
        vo.setInspectedCount(inspectedProjects.size());
        vo.setInspectedHousingCount((int) inspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 0).count());
        vo.setInspectedMunicipalCount((int) inspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 1).count());
 
        // 未检查项目统计
        List<Project> uninspectedProjects = projects.stream()
                .filter(p -> !inspectedProjectIds.contains(p.getId()))
                .toList();
 
        vo.setUninspectedCount(uninspectedProjects.size());
        vo.setUninspectedHousingCount((int) uninspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 0).count());
        vo.setUninspectedMunicipalCount((int) uninspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 1).count());
    }
 
    /**
     * 统计固定资产本月检查情况
     */
    private void calculateMonthlyInspectionForFixed(FixedAssetDashboardVO vo, List<Project> projects,
                                                    List<Integer> projectIds, Date monthStart, Date monthEnd) {
        if (projectIds.isEmpty()) {
            vo.setInspectedCount(0);
            vo.setUninspectedCount(projects.size());
            return;
        }
 
        // 1. 先查询符合条件的 Task(本月的任务)
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.in(Task::getProjectId, projectIds)
                .ge(Task::getDate, monthStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .le(Task::getDate, monthEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .eq(Task::getDeleted, false);
        List<Task> monthlyTasks = taskMapper.selectList(taskWrapper);
 
        if (monthlyTasks.isEmpty()) {
            vo.setInspectedCount(0);
            vo.setUninspectedCount(projects.size());
            return;
        }
 
        // 2. 获取 Task ID 列表
        List<Integer> taskIds = monthlyTasks.stream().map(Task::getId).collect(Collectors.toList());
 
        // 3. 建立 Task ID 到 Project ID 的映射
        Map<Integer, Integer> taskToProjectMap = monthlyTasks.stream()
                .collect(Collectors.toMap(Task::getId, Task::getProjectId));
 
        // 4. 查询本月有检查记录的项目(查询 record 表中 record_type='error' 且 device_id 为 null 的记录)
        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getRecordType, "error")
                .isNull(Record::getDeviceId)
                .in(Record::getCheckTaskId, taskIds)
                .eq(Record::getDeleted, false);
        List<Record> monthlyRecords = recordMapper.selectList(recordWrapper);
 
        // 5. 通过 Task 映射获取有检查记录的项目 ID
        long inspectedCount = monthlyRecords.stream()
                .map(Record::getCheckTaskId)
                .map(taskToProjectMap::get)
                .filter(Objects::nonNull)
                .distinct()
                .count();
 
        vo.setInspectedCount((int) inspectedCount);
        vo.setUninspectedCount(projects.size() - (int) inspectedCount);
    }
 
    /**
     * 统计大型机械设备数(含已检查/未检查)
     */
    private List<MachineryStatisticsVO> calculateMachineryStatistics(List<Integer> projectIds, Date monthStart, Date monthEnd) {
        if (projectIds.isEmpty()) {
            return new ArrayList<>();
        }
 
        // 查询设备使用记录
        LambdaQueryWrapper<DeviceUsage> deviceWrapper = new LambdaQueryWrapper<>();
        deviceWrapper.eq(DeviceUsage::getDeleted, false)
                .in(DeviceUsage::getProjectId, projectIds);
        List<DeviceUsage> deviceUsages = deviceUsageMapper.selectList(deviceWrapper);
 
        // 批量查询 Device 信息
        List<Integer> deviceIds = deviceUsages.stream()
                .map(DeviceUsage::getDeviceId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
 
        Map<Integer, Device> deviceMap = new HashMap<>();
        if (!deviceIds.isEmpty()) {
            List<Device> deviceList = deviceMapper.selectBatchIds(deviceIds);
            deviceMap = deviceList.stream()
                    .collect(Collectors.toMap(Device::getId, d -> d));
            log.debug("批量查询到 {} 个设备信息", deviceMap.size());
 
            // 检查是否有设备信息查询失败
            if (deviceIds.size() != deviceMap.size()) {
                log.warn("部分设备信息查询失败,期望 {} 个,实际查询到 {} 个",
                         deviceIds.size(), deviceMap.size());
            }
        }
 
        // 按设备类型名称分组统计
        final Map<Integer, Device> finalDeviceMap = deviceMap;
        Map<String, List<DeviceUsage>> deviceGroupMap = deviceUsages.stream()
                .filter(d -> d.getDeviceId() != null)
                .filter(d -> finalDeviceMap.containsKey(d.getDeviceId()))
                .collect(Collectors.groupingBy(d -> {
                    try {
                        Device device = finalDeviceMap.get(d.getDeviceId());
                        return device.getDeviceType().getDesc();
                    } catch (Exception e) {
                        log.error("获取设备类型失败,deviceId: {}", d.getDeviceId(), e);
                        return DeviceType.OTHER.getDesc();
                    }
                }));
 
        log.debug("设备按类型分组完成,共 {} 种类型", deviceGroupMap.size());
 
        // 查询设备检查记录
        // 建立 device.id 到 device_usage.id 的映射
        Map<Integer, List<Integer>> deviceToUsageMap = deviceUsages.stream()
                .filter(d -> d.getDeviceId() != null)
                .collect(Collectors.groupingBy(
                        DeviceUsage::getDeviceId,
                        Collectors.mapping(DeviceUsage::getId, Collectors.toList())
                ));
 
        Map<Integer, Boolean> deviceInspectionMap = new HashMap<>();
        if (!deviceIds.isEmpty()) {
            LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
            recordWrapper.eq(Record::getRecordType, "error")
                    .isNotNull(Record::getDeviceId)
                    .in(Record::getDeviceId, deviceIds)
                    .eq(Record::getDeleted, false)
                    .between(Record::getCreateTime, monthStart, monthEnd);
            List<Record> records = recordMapper.selectList(recordWrapper);
 
            // 获取已检查的 device.id 集合
            Set<Integer> inspectedDeviceIds = records.stream()
                    .map(Record::getDeviceId)
                    .collect(Collectors.toSet());
 
            // 通过映射关系,将 device.id 的检查状态映射到 device_usage.id
            for (Map.Entry<Integer, List<Integer>> entry : deviceToUsageMap.entrySet()) {
                Integer deviceId = entry.getKey();
                boolean isInspected = inspectedDeviceIds.contains(deviceId);
 
                // 将该设备的检查状态应用到所有使用该设备的 device_usage 记录
                for (Integer usageId : entry.getValue()) {
                    deviceInspectionMap.put(usageId, isInspected);
                }
            }
        }
 
        // 构建统计结果
        List<MachineryStatisticsVO> result = new ArrayList<>();
        for (Map.Entry<String, List<DeviceUsage>> entry : deviceGroupMap.entrySet()) {
            MachineryStatisticsVO vo = new MachineryStatisticsVO();
            vo.setName(entry.getKey());
            vo.setTotal(entry.getValue().size());
 
            // 设置设备类型字段
            // 从当前分组的第一个设备使用记录中获取设备类型
            if (!entry.getValue().isEmpty()) {
                DeviceUsage firstUsage = entry.getValue().get(0);
                Device device = finalDeviceMap.get(firstUsage.getDeviceId());
                if (device != null && device.getType() != null) {
                    vo.setType(device.getType());
                }
            }
 
            long inspectedCount = entry.getValue().stream()
                    .filter(d -> deviceInspectionMap.getOrDefault(d.getId(), false))
                    .count();
            vo.setInspectedCount((int) inspectedCount);
            vo.setUninspectedCount(entry.getValue().size() - (int) inspectedCount);
 
            result.add(vo);
        }
 
        return result;
    }
 
    /**
     * 统计在建工程重大隐患数
     */
    private void calculateHazardStatistics(OngoingProjectDashboardVO vo, List<Integer> projectIds) {
        if (projectIds.isEmpty()) {
            vo.setMajorHazardTotal(0);
            vo.setRectifiedHazardCount(0);
            vo.setUnrectifiedHazardCount(0);
            return;
        }
 
        // 查询检查任务
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.in(Task::getProjectId, projectIds)
                .eq(Task::getDeleted, false);
        List<Task> tasks = taskMapper.selectList(taskWrapper);
        List<Integer> checkTaskIds = tasks.stream().map(Task::getId).collect(Collectors.toList());
 
        if (checkTaskIds.isEmpty()) {
            vo.setMajorHazardTotal(0);
            vo.setRectifiedHazardCount(0);
            vo.setUnrectifiedHazardCount(0);
            return;
        }
 
        // 查询重大隐患记录(level 表示隐患等级,0 表示重大隐患)
        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getDeleted, false)
                .in(Record::getCheckTaskId, checkTaskIds)
                .eq(Record::getLevel, 0); // 重大隐患等级
        List<Record> majorHazards = recordMapper.selectList(recordWrapper);
 
        vo.setMajorHazardTotal(majorHazards.size());
 
        // 统计已整改和未整改数量
        // 1. 收集所有非空的 errorReviewId
        List<Integer> errorReviewIds = majorHazards.stream()
                .map(Record::getErrorReviewId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
 
        // 2. 查询 ErrorReview 中 state=2 的记录
        long rectifiedCount = 0;
        if (!errorReviewIds.isEmpty()) {
            LambdaQueryWrapper<ErrorReview> reviewWrapper = new LambdaQueryWrapper<>();
            reviewWrapper.in(ErrorReview::getId, errorReviewIds)
                    .eq(ErrorReview::getState, 2)  // state=2 表示已整改
                    .eq(ErrorReview::getDeleted, false);
            rectifiedCount = errorReviewMapper.selectCount(reviewWrapper);
        }
 
        // 3. 未整改数量 = 总数 - 已整改数量
        long unrectifiedCount = majorHazards.size() - rectifiedCount;
 
        vo.setRectifiedHazardCount((int) rectifiedCount);
        vo.setUnrectifiedHazardCount((int) unrectifiedCount);
    }
 
    /**
     * 统计固定资产重大隐患数
     */
    private void calculateHazardStatisticsForFixed(FixedAssetDashboardVO vo, List<Integer> projectIds) {
        if (projectIds.isEmpty()) {
            vo.setMajorHazardTotal(0);
            vo.setRectifiedHazardCount(0);
            vo.setUnrectifiedHazardCount(0);
            return;
        }
 
        // 查询检查任务
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.in(Task::getProjectId, projectIds)
                .eq(Task::getDeleted, false);
        List<Task> tasks = taskMapper.selectList(taskWrapper);
        List<Integer> checkTaskIds = tasks.stream().map(Task::getId).collect(Collectors.toList());
 
        if (checkTaskIds.isEmpty()) {
            vo.setMajorHazardTotal(0);
            vo.setRectifiedHazardCount(0);
            vo.setUnrectifiedHazardCount(0);
            return;
        }
 
        // 查询重大隐患记录(level 表示隐患等级,0 表示重大隐患)
        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getDeleted, false)
                .in(Record::getCheckTaskId, checkTaskIds)
                .eq(Record::getLevel, 0); // 重大隐患等级
        List<Record> majorHazards = recordMapper.selectList(recordWrapper);
 
        vo.setMajorHazardTotal(majorHazards.size());
 
        // 统计已整改和未整改数量
        // 1. 收集所有非空的 errorReviewId
        List<Integer> errorReviewIds = majorHazards.stream()
                .map(Record::getErrorReviewId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
 
        // 2. 查询 ErrorReview 中 state=2 的记录
        long rectifiedCount = 0;
        if (!errorReviewIds.isEmpty()) {
            LambdaQueryWrapper<ErrorReview> reviewWrapper = new LambdaQueryWrapper<>();
            reviewWrapper.in(ErrorReview::getId, errorReviewIds)
                    .eq(ErrorReview::getState, 2)  // state=2 表示已整改
                    .eq(ErrorReview::getDeleted, false);
            rectifiedCount = errorReviewMapper.selectCount(reviewWrapper);
        }
 
        // 3. 未整改数量 = 总数 - 已整改数量
        long unrectifiedCount = majorHazards.size() - rectifiedCount;
 
        vo.setRectifiedHazardCount((int) rectifiedCount);
        vo.setUnrectifiedHazardCount((int) unrectifiedCount);
    }
 
    /**
     * 获取项目地图标点数据
     */
    private List<ProjectMapPointVO> getProjectMapPoints(
            List<Project> projects, Long clientId, Date startDate, Date endDate) {
 
        List<ProjectMapPointVO> result = new ArrayList<>();
 
        // 计算项目类别
        Map<Integer, String> categoryMap;
        if (!projects.isEmpty()) {
            // 判断项目类型:在建工程 or 固定资产
            Integer usageType = projects.get(0).getType();
            if (usageType != null && usageType != 2) {
                // 在建工程
                categoryMap = projectCategoryCalculator.calculateOngoingProjectCategories(
                        projects, clientId, startDate, endDate);
            } else if (usageType != null && usageType == 2) {
                // 固定资产
                categoryMap = projectCategoryCalculator.calculateFixedAssetCategories(
                        projects, clientId, startDate, endDate);
            } else {
                categoryMap = new HashMap<>();
            }
        } else {
            categoryMap = new HashMap<>();
        }
 
        // 构建地图标点数据
        for (Project p : projects) {
            if (!StringUtils.hasText(p.getAddressInfo())) {
                continue;
            }
 
            try {
                // 解析 address_info JSON 字符串
                JSONObject addressJson = JSON.parseObject(p.getAddressInfo());
                JSONArray gps = addressJson.getJSONArray("gps");
 
                if (gps != null && gps.size() >= 2) {
                    ProjectMapPointVO vo = new ProjectMapPointVO();
                    vo.setProjectId(p.getId());
                    vo.setProjectName(p.getName());
                    vo.setProjectType(p.getType());
 
                    // gps 数组格式:[经度, 纬度]
                    vo.setLongitude(gps.getString(0));
                    vo.setLatitude(gps.getString(1));
                    //位置信息
                    vo.setAddressInfo(addressJson);
                    // 设置项目类别
                    vo.setCategory(categoryMap.get(p.getId()));
 
                    result.add(vo);
                }
            } catch (Exception e) {
                // 解析失败则跳过该项目
                log.warn("解析项目地址信息失败,项目ID: {}, address_info: {}", p.getId(), p.getAddressInfo(), e);
            }
        }
 
        return result;
    }
 
    /**
     * 获取开始日期
     */
    private Date getStartDate(Date startDate) {
        if (startDate != null) {
            return DateUtil.beginOfDay(startDate);
        }
        // 默认为当前月份第一天
        Date date = new Date();
        return DateUtil.beginOfMonth(date);
 
    }
 
    /**
     * 获取结束日期
     */
    private Date getEndDate(Date endDate) {
        if (endDate != null) {
            return DateUtil.endOfDay(endDate);
        }
        // 默认为当前月份最后一天
        Date date = new Date();
        return DateUtil.endOfMonth(date);
    }
 
    /**
     * 判断给定的日期范围是否为当前月份
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 如果日期范围在当前月份内则返回 true,否则返回 false
     */
    private boolean isCurrentMonth(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return false;
        }
 
        YearMonth currentMonth = YearMonth.now();
        LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
 
        YearMonth startMonth = YearMonth.from(start);
        YearMonth endMonth = YearMonth.from(end);
 
        // 判断开始和结束日期是否都在当前月份
        return startMonth.equals(currentMonth) && endMonth.equals(currentMonth);
    }
}