huang
2025-11-20 366ba040d2447bacd3455299425e3166f1f992bb
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
package com.mes.device.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.device.entity.DeviceGroupConfig;
import com.mes.device.entity.DeviceGroupRelation;
import com.mes.device.mapper.DeviceGroupConfigMapper;
import com.mes.device.mapper.DeviceGroupRelationMapper;
import com.mes.device.service.DeviceGroupConfigService;
import com.mes.device.vo.DeviceGroupConfigVO;
import com.mes.device.vo.DeviceGroupVO;
import com.mes.device.vo.StatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 设备组配置服务实现类
 */
@Slf4j
@Service
public class DeviceGroupConfigServiceImpl extends ServiceImpl<DeviceGroupConfigMapper, DeviceGroupConfig> implements DeviceGroupConfigService {
 
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final DeviceGroupRelationMapper deviceGroupRelationMapper;
    private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<Map<String, Object>>() {};
 
    public DeviceGroupConfigServiceImpl(DeviceGroupRelationMapper deviceGroupRelationMapper) {
        this.deviceGroupRelationMapper = deviceGroupRelationMapper;
    }
 
    @Override
    public boolean createDeviceGroup(DeviceGroupConfig groupConfig) {
        try {
            // 检查设备组编号是否已存在
            if (isGroupCodeExists(groupConfig.getGroupCode(), null)) {
                log.warn("设备组编号已存在: {}", groupConfig.getGroupCode());
                return false;
            }
            
            // 初始化设备组状态为停用
            if (groupConfig.getStatus() == null) {
                groupConfig.setStatus(DeviceGroupConfig.Status.DISABLED);
            }
            
            // 设置默认配置
            if (groupConfig.getMaxConcurrentDevices() == null) {
                groupConfig.setMaxConcurrentDevices(3);
            }
            
            if (groupConfig.getHeartbeatInterval() == null) {
                groupConfig.setHeartbeatInterval(30);
            }
            
            if (groupConfig.getCommunicationTimeout() == null) {
                groupConfig.setCommunicationTimeout(5000);
            }
            
            boolean result = save(groupConfig);
            if (result) {
                log.info("创建设备组配置成功: {}", groupConfig.getGroupCode());
            }
            return result;
        } catch (Exception e) {
            log.error("创建设备组配置失败", e);
            return false;
        }
    }
 
    @Override
    public boolean updateDeviceGroup(DeviceGroupConfig groupConfig) {
        try {
            // 检查设备组编号是否已存在(排除当前设备组)
            if (isGroupCodeExists(groupConfig.getGroupCode(), groupConfig.getId())) {
                log.warn("设备组编号已存在: {}", groupConfig.getGroupCode());
                return false;
            }
            
            boolean result = updateById(groupConfig);
            if (result) {
                log.info("更新设备组配置成功: {}", groupConfig.getGroupCode());
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备组配置失败", e);
            return false;
        }
    }
 
    @Override
    public boolean deleteDeviceGroup(Long id) {
        try {
            // 先检查该设备组下是否有设备
            int deviceCount = getDeviceCountByGroupId(id);
            if (deviceCount > 0) {
                log.warn("设备组下还有设备,无法删除: {}", id);
                return false;
            }
            
            boolean result = removeById(id);
            if (result) {
                log.info("删除设备组配置成功: {}", id);
            }
            return result;
        } catch (Exception e) {
            log.error("删除设备组配置失败", e);
            return false;
        }
    }
 
    @Override
    public DeviceGroupConfig getDeviceGroupById(Long id) {
        return getById(id);
    }
 
    @Override
    public DeviceGroupConfig getDeviceGroupByCode(String groupCode) {
        LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceGroupConfig::getGroupCode, groupCode);
        wrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
        return getOne(wrapper);
    }
 
    @Override
    public List<DeviceGroupConfig> getDeviceGroupList(Long projectId, Integer groupType, Integer status) {
        LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
        
        // 过滤未删除的设备组
        wrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
        
        if (groupType != null) {
            wrapper.eq(DeviceGroupConfig::getGroupType, groupType);
        }
        
        if (status != null) {
            wrapper.eq(DeviceGroupConfig::getStatus, status);
        }
        
        wrapper.orderByAsc(DeviceGroupConfig::getId);
        
        return list(wrapper);
    }
 
    @Override
    public Page<DeviceGroupVO.GroupInfo> getDeviceGroupList(Long projectId, String groupType, String groupStatus, String keyword, Integer page, Integer size) {
        try {
            // 创建分页对象
            Page<DeviceGroupConfig> pageEntity = new Page<>(page, size);
            
            LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
            
            // 过滤未删除的设备组
            wrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
            
            // 项目ID过滤
            if (projectId != null) {
                wrapper.eq(DeviceGroupConfig::getProjectId, projectId);
            }
            
            // 设备组类型过滤(字符串转换为枚举值)
            if (groupType != null && !groupType.trim().isEmpty()) {
                Integer typeEnum = convertGroupTypeFromString(groupType);
                if (typeEnum != null) {
                    wrapper.eq(DeviceGroupConfig::getGroupType, typeEnum);
                }
            }
            
            // 设备组状态过滤(字符串转换为枚举值)
            if (groupStatus != null && !groupStatus.trim().isEmpty()) {
                Integer statusEnum = convertStatusFromString(groupStatus);
                if (statusEnum != null) {
                    wrapper.eq(DeviceGroupConfig::getStatus, statusEnum);
                }
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                wrapper.and(w -> w
                    .like(DeviceGroupConfig::getGroupName, keyword)
                    .or().like(DeviceGroupConfig::getGroupCode, keyword)
                    .or().like(DeviceGroupConfig::getDescription, keyword));
            }
            
            wrapper.orderByDesc(DeviceGroupConfig::getUpdatedTime);
            
            // 执行分页查询
            pageEntity = page(pageEntity, wrapper);
            
            // 转换为VO对象
            List<DeviceGroupVO.GroupInfo> voList = pageEntity.getRecords().stream().map(group -> {
                DeviceGroupVO.GroupInfo vo = new DeviceGroupVO.GroupInfo();
                vo.setId(group.getId());
                vo.setGroupCode(group.getGroupCode());
                vo.setGroupName(group.getGroupName());
                vo.setGroupType(getGroupTypeName(group.getGroupType()));
                vo.setStatus(getStatusName(group.getStatus()));
                vo.setDeviceCount(getDeviceCountByGroupId(group.getId()));
                vo.setOnlineDeviceCount(getOnlineDeviceCountByGroupId(group.getId()));
                vo.setCreateTime(group.getCreatedTime());
                vo.setProjectId(group.getProjectId());
                return vo;
            }).collect(Collectors.toList());
            
            // 创建分页结果
            Page<DeviceGroupVO.GroupInfo> result = new Page<>(pageEntity.getCurrent(), pageEntity.getSize(), pageEntity.getTotal());
            result.setRecords(voList);
            
            return result;
        } catch (Exception e) {
            log.error("分页查询设备组配置列表失败", e);
            throw new RuntimeException("分页查询设备组配置列表失败: " + e.getMessage(), e);
        }
    }
 
    @Override
    public List<DeviceGroupConfigVO.GroupInfo> getDeviceGroupVOList(Long projectId, Integer groupType, Integer status) {
        List<DeviceGroupConfig> groupList = getDeviceGroupList(projectId, groupType, status);
        
        return groupList.stream().map(group -> {
            DeviceGroupConfigVO.GroupInfo vo = new DeviceGroupConfigVO.GroupInfo();
            vo.setId(group.getId());
            vo.setGroupName(group.getGroupName());
            vo.setGroupCode(group.getGroupCode());
            vo.setGroupType(getGroupTypeName(group.getGroupType()));
            vo.setDescription(group.getDescription());
            vo.setStatus(getStatusName(group.getStatus()));
            vo.setDeviceCount(getDeviceCountByGroupId(group.getId()));
            vo.setIsEnabled(group.getStatus() != null && group.getStatus() == DeviceGroupConfig.Status.ENABLED);
            vo.setLocation(extractLocationFromExtraConfig(group));
            vo.setSupervisor(extractSupervisorFromExtraConfig(group));
            vo.setCreatedTime(new Date());
            vo.setUpdatedTime(new Date());
            vo.setProjectId(group.getProjectId());
            return vo;
        }).collect(Collectors.toList());
    }
 
    /**
     * 获取设备组类型名称
     */
    private String getGroupTypeName(Integer groupType) {
        switch (groupType != null ? groupType : 0) {
            case DeviceGroupConfig.GroupType.PRODUCTION_LINE:
                return "生产线";
            case DeviceGroupConfig.GroupType.TEST_LINE:
                return "测试线";
            case DeviceGroupConfig.GroupType.AUXILIARY_GROUP:
                return "辅助设备组";
            default:
                return "未知类型";
        }
    }
 
    /**
     * 字符串转换为设备组类型枚举值
     */
    private Integer convertGroupTypeFromString(String groupType) {
        if (groupType == null || groupType.trim().isEmpty()) {
            return null;
        }
        
        switch (groupType.trim()) {
            case "生产线":
            case "production_line":
            case "PRODUCTION_LINE":
                return DeviceGroupConfig.GroupType.PRODUCTION_LINE;
            case "测试线":
            case "test_line":
            case "TEST_LINE":
                return DeviceGroupConfig.GroupType.TEST_LINE;
            case "辅助设备组":
            case "auxiliary_group":
            case "AUXILIARY_GROUP":
                return DeviceGroupConfig.GroupType.AUXILIARY_GROUP;
            default:
                try {
                    // 尝试直接解析为整数
                    return Integer.parseInt(groupType.trim());
                } catch (NumberFormatException e) {
                    log.warn("无法识别的设备组类型: {}", groupType);
                    return null;
                }
        }
    }
 
    /**
     * 获取设备组状态名称
     */
    private String getStatusName(Integer status) {
        switch (status != null ? status : 0) {
            case DeviceGroupConfig.Status.ENABLED:
                return "启用";
            case DeviceGroupConfig.Status.DISABLED:
                return "停用";
            case DeviceGroupConfig.Status.MAINTENANCE:
                return "维护中";
            default:
                return "未知状态";
        }
    }
 
    /**
     * 字符串转换为设备组状态枚举值
     */
    private Integer convertStatusFromString(String status) {
        if (status == null || status.trim().isEmpty()) {
            return null;
        }
        
        switch (status.trim()) {
            case "启用":
            case "enabled":
            case "ENABLED":
                return DeviceGroupConfig.Status.ENABLED;
            case "停用":
            case "disabled":
            case "DISABLED":
                return DeviceGroupConfig.Status.DISABLED;
            case "维护中":
            case "maintenance":
            case "MAINTENANCE":
                return DeviceGroupConfig.Status.MAINTENANCE;
            default:
                try {
                    // 尝试直接解析为整数
                    return Integer.parseInt(status.trim());
                } catch (NumberFormatException e) {
                    log.warn("无法识别的设备组状态: {}", status);
                    return null;
                }
        }
    }
 
    @Override
    public boolean isGroupCodeExists(String groupCode, Long excludeId) {
        LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceGroupConfig::getGroupCode, groupCode);
        wrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
        
        if (excludeId != null) {
            wrapper.ne(DeviceGroupConfig::getId, excludeId);
        }
        
        return count(wrapper) > 0;
    }
 
    @Override
    public boolean updateDeviceGroupStatus(Long id, Integer status) {
        try {
            DeviceGroupConfig group = getById(id);
            if (group == null) {
                log.warn("设备组不存在: {}", id);
                return false;
            }
            
            group.setStatus(status);
            boolean result = updateById(group);
            if (result) {
                log.info("更新设备组状态成功: {} -> {}", id, status);
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备组状态失败", e);
            return false;
        }
    }
 
    @Override
    public boolean batchUpdateDeviceGroupStatus(List<Long> ids, Integer status) {
        try {
            LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(DeviceGroupConfig::getId, ids);
            
            DeviceGroupConfig updateEntity = new DeviceGroupConfig();
            updateEntity.setStatus(status);
            
            boolean result = update(updateEntity, wrapper);
            if (result) {
                log.info("批量更新设备组状态成功: {} 个设备组 -> {}", ids.size(), status);
            }
            return result;
        } catch (Exception e) {
            log.error("批量更新设备组状态失败", e);
            return false;
        }
    }
 
    @Override
    public Map<String, Object> getExtraConfig(Long id) {
        try {
            DeviceGroupConfig group = getById(id);
            if (group == null || group.getExtraConfig() == null) {
                return new HashMap<>();
            }
            
            return objectMapper.readValue(group.getExtraConfig(), 
                new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            log.error("解析设备组扩展配置失败", e);
            return new HashMap<>();
        }
    }
 
    @Override
    public boolean updateExtraConfig(Long id, Map<String, Object> extraConfig) {
        try {
            DeviceGroupConfig group = getById(id);
            if (group == null) {
                log.warn("设备组不存在: {}", id);
                return false;
            }
            
            String extraConfigJson = objectMapper.writeValueAsString(extraConfig);
            group.setExtraConfig(extraConfigJson);
            
            boolean result = updateById(group);
            if (result) {
                log.info("更新设备组扩展配置成功: {}", id);
            }
            return result;
        } catch (IOException e) {
            log.error("序列化设备组扩展配置失败", e);
            return false;
        }
    }
 
    @Override
    public int getDeviceCountByGroupId(Long groupId) {
        if (groupId == null) {
            return 0;
        }
        try {
            LambdaQueryWrapper<DeviceGroupRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeviceGroupRelation::getGroupId, groupId)
                   .eq(DeviceGroupRelation::getIsDeleted, 0);
            return (int) deviceGroupRelationMapper.selectCount(wrapper);
        } catch (Exception e) {
            log.error("获取设备组设备数量失败, groupId={}", groupId, e);
            return 0;
        }
    }
 
    /**
     * 获取设备组下的在线设备数量
     * 
     * @param groupId 设备组ID
     * @return 在线设备数量
     */
    private int getOnlineDeviceCountByGroupId(Long groupId) {
        if (groupId == null) {
            return 0;
        }
        try {
            Integer count = deviceGroupRelationMapper.getOnlineDeviceCountByGroupId(groupId);
            return count != null ? count : 0;
        } catch (Exception e) {
            log.error("获取设备组在线设备数量失败, groupId={}", groupId, e);
            return 0;
        }
    }
 
    /**
     * 获取设备组类型统计数据
     */
    private List<StatisticsVO.GroupTypeStatistics> getDeviceGroupTypeStatistics(Long projectId) {
        try {
            List<StatisticsVO.GroupTypeStatistics> groupTypeStats = new ArrayList<>();
            
            // 获取所有设备组类型枚举值
            // 注意:需要手动列出所有可能的设备组类型,因为枚举类结构与预期不符
            List<Integer> groupTypes = Arrays.asList(DeviceGroupConfig.GroupType.PRODUCTION_LINE, DeviceGroupConfig.GroupType.TEST_LINE, DeviceGroupConfig.GroupType.AUXILIARY_GROUP);
            
            for (Integer groupType : groupTypes) {
                // 设备组总数
                LambdaQueryWrapper<DeviceGroupConfig> totalWrapper = new LambdaQueryWrapper<>();
                totalWrapper.eq(DeviceGroupConfig::getGroupType, groupType);
                totalWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
                long totalCount = count(totalWrapper);
                
                // 在线数(启用的设备组数)
                LambdaQueryWrapper<DeviceGroupConfig> onlineWrapper = new LambdaQueryWrapper<>();
                onlineWrapper.eq(DeviceGroupConfig::getGroupType, groupType);
                onlineWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.ENABLED);
                onlineWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
                long onlineCount = count(onlineWrapper);
                
                // 离线数(停用的设备组数)
                LambdaQueryWrapper<DeviceGroupConfig> offlineWrapper = new LambdaQueryWrapper<>();
                offlineWrapper.eq(DeviceGroupConfig::getGroupType, groupType);
                offlineWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.DISABLED);
                offlineWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
                long offlineCount = count(offlineWrapper);
                
                // 维护中的设备组数
                LambdaQueryWrapper<DeviceGroupConfig> maintenanceWrapper = new LambdaQueryWrapper<>();
                maintenanceWrapper.eq(DeviceGroupConfig::getGroupType, groupType);
                maintenanceWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.MAINTENANCE);
                maintenanceWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
                long maintenanceCount = count(maintenanceWrapper);
                
                // 计算可用性
                double availability = totalCount > 0 ? (onlineCount * 100.0 / totalCount) : 0.0;
                
                // 创建设备组类型统计对象
                StatisticsVO.GroupTypeStatistics groupTypeStat = new StatisticsVO.GroupTypeStatistics();
                groupTypeStat.setGroupType(getGroupTypeName(groupType));
                groupTypeStat.setTotalCount((int) totalCount);
                // 注意:StatisticsVO.GroupTypeStatistics的字段与代码期望不符,这里做适当调整
                // activeCount表示启用的设备组数
                groupTypeStat.setActiveCount((int) onlineCount);
                
                groupTypeStats.add(groupTypeStat);
            }
            
            return groupTypeStats;
        } catch (Exception e) {
            log.error("获取设备组类型统计数据失败", e);
            return new ArrayList<>();
        }
    }
 
    @Override
    public int getOnlineDeviceGroupCount(Long projectId) {
        // 简化实现,实际项目中可能需要根据项目ID过滤
        LambdaQueryWrapper<DeviceGroupConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.ENABLED);
        wrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
        
        return (int) count(wrapper);
    }
 
    @Override
    public StatisticsVO.GroupStatistics getDeviceGroupStatistics(Long projectId) {
        try {
            // 设备组总数
            LambdaQueryWrapper<DeviceGroupConfig> totalWrapper = new LambdaQueryWrapper<>();
            totalWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
            if (projectId != null) {
                totalWrapper.eq(DeviceGroupConfig::getProjectId, projectId);
            }
            long totalGroups = count(totalWrapper);
            
            // 启用的设备组数
            LambdaQueryWrapper<DeviceGroupConfig> enabledWrapper = new LambdaQueryWrapper<>();
            enabledWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.ENABLED);
            enabledWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
            if (projectId != null) {
                enabledWrapper.eq(DeviceGroupConfig::getProjectId, projectId);
            }
            long enabledGroups = count(enabledWrapper);
            
            // 停用的设备组数
            LambdaQueryWrapper<DeviceGroupConfig> disabledWrapper = new LambdaQueryWrapper<>();
            disabledWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.DISABLED);
            disabledWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
            if (projectId != null) {
                disabledWrapper.eq(DeviceGroupConfig::getProjectId, projectId);
            }
            long disabledGroups = count(disabledWrapper);
            
            // 维护中的设备组数
            LambdaQueryWrapper<DeviceGroupConfig> maintenanceWrapper = new LambdaQueryWrapper<>();
            maintenanceWrapper.eq(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.MAINTENANCE);
            maintenanceWrapper.eq(DeviceGroupConfig::getIsDeleted, 0);
            if (projectId != null) {
                maintenanceWrapper.eq(DeviceGroupConfig::getProjectId, projectId);
            }
            long maintenanceGroups = count(maintenanceWrapper);
            
            // 创建设备组统计对象
            StatisticsVO.GroupStatistics groupStats = new StatisticsVO.GroupStatistics();
            groupStats.setTotalGroups((int) totalGroups);
            groupStats.setActiveGroups((int) enabledGroups);
            groupStats.setInactiveGroups((int) disabledGroups);
            // 注意:StatisticsVO.GroupStatistics没有直接的维护中设备组字段,这里忽略或调整
            
            // 计算设备组可用性(启用设备组 / 总设备组 * 100%)
            double availability = totalGroups > 0 ? (enabledGroups * 100.0 / totalGroups) : 0.0;
            groupStats.setGroupAvailability(availability);
            
            // 获取按设备组类型的统计数据
            List<StatisticsVO.GroupTypeStatistics> groupTypeStats = getDeviceGroupTypeStatistics(projectId);
            groupStats.setGroupTypeStats(groupTypeStats);
            
            log.info("获取设备组统计信息成功: 总数={}, 启用={}, 停用={}, 维护中={}", 
                totalGroups, enabledGroups, disabledGroups, maintenanceGroups);
            
            return groupStats;
        } catch (Exception e) {
            log.error("获取设备组统计信息失败", e);
            // 返回默认统计对象
            return new StatisticsVO.GroupStatistics();
        }
    }
 
    @Override
    public DeviceGroupVO.PerformanceStats getGroupPerformance(Long groupId) {
        try {
            // 检查设备组是否存在
            DeviceGroupConfig group = getById(groupId);
            if (group == null) {
                log.warn("设备组不存在: {}", groupId);
                return new DeviceGroupVO.PerformanceStats();
            }
 
            // 获取设备组下的设备数量
            int totalDevices = getDeviceCountByGroupId(groupId);
            
            // 获取在线设备数量(状态为正常的设备数)
            int activeDevices = getActiveDeviceCountByGroupId(groupId);
            
            // 计算平均性能指标(模拟数据)
            double averageCpuUsage = 45.5; // CPU使用率百分比
            double averageMemoryUsage = 65.2; // 内存使用率百分比
            int totalTasksCompleted = 1000; // 总完成任务数
            double successRate = 99.2; // 任务成功率百分比
            
            // 创建设备组性能统计对象
            DeviceGroupVO.PerformanceStats performanceStats = new DeviceGroupVO.PerformanceStats();
            performanceStats.setTotalDevices(totalDevices);
            performanceStats.setActiveDevices(activeDevices);
            performanceStats.setAverageCpuUsage(averageCpuUsage);
            performanceStats.setAverageMemoryUsage(averageMemoryUsage);
            performanceStats.setTotalTasksCompleted(totalTasksCompleted);
            performanceStats.setSuccessRate(successRate);
            performanceStats.setStatsTime(new Date());
            performanceStats.setDevicePerformances(new ArrayList<>());
            
            log.info("获取设备组性能统计成功: groupId={}, totalDevices={}", 
                groupId, totalDevices);
            
            return performanceStats;
        } catch (Exception e) {
            log.error("获取设备组性能统计失败", e);
            // 返回默认性能统计对象
            return new DeviceGroupVO.PerformanceStats();
        }
    }
 
    @Override
    public DeviceGroupVO.HealthCheckResult performGroupHealthCheck(Long groupId) {
        try {
            // 检查设备组是否存在
            DeviceGroupConfig group = getById(groupId);
            if (group == null) {
                log.warn("设备组不存在: {}", groupId);
                DeviceGroupVO.HealthCheckResult errorResult = new DeviceGroupVO.HealthCheckResult();
                errorResult.setIsHealthy(false);
                errorResult.setTotalDevices(0);
                errorResult.setOnlineDevices(0);
                errorResult.setOfflineDevices(0);
                errorResult.setFailedDevices(new ArrayList<>());
                errorResult.setCheckTime(new Date());
                errorResult.setCheckSummary("设备组不存在");
                return errorResult;
            }
 
            // 获取设备组下的设备信息
            int totalDevices = getDeviceCountByGroupId(groupId);
            int onlineDevices = getActiveDeviceCountByGroupId(groupId);
            int offlineDevices = totalDevices - onlineDevices;
            
            // 计算健康状态
            boolean isHealthy = onlineDevices >= totalDevices * 0.9; // 90%以上在线则健康
            
            // 创建健康检查结果
            DeviceGroupVO.HealthCheckResult healthResult = new DeviceGroupVO.HealthCheckResult();
            healthResult.setIsHealthy(isHealthy);
            healthResult.setTotalDevices(totalDevices);
            healthResult.setOnlineDevices(onlineDevices);
            healthResult.setOfflineDevices(offlineDevices);
            healthResult.setFailedDevices(new ArrayList<>()); // 设置为空列表
            healthResult.setCheckTime(new Date());
            healthResult.setCheckSummary(isHealthy ? "设备组健康" : "设备组存在问题");
            
            log.info("设备组健康检查完成: groupId={}, isHealthy={}, totalDevices={}, onlineDevices={}", 
                groupId, isHealthy, totalDevices, onlineDevices);
            
            return healthResult;
        } catch (Exception e) {
            log.error("执行设备组健康检查失败", e);
            // 返回错误状态的结果
            DeviceGroupVO.HealthCheckResult errorResult = new DeviceGroupVO.HealthCheckResult();
            errorResult.setIsHealthy(false);
            errorResult.setTotalDevices(0);
            errorResult.setOnlineDevices(0);
            errorResult.setOfflineDevices(0);
            errorResult.setFailedDevices(new ArrayList<>());
            errorResult.setCheckTime(new Date());
            errorResult.setCheckSummary("健康检查执行失败: " + e.getMessage());
            return errorResult;
        }
    }
 
    @Override
    public boolean enableDeviceGroup(Long id) {
        try {
            // 检查设备组是否存在
            DeviceGroupConfig group = getById(id);
            if (group == null) {
                log.warn("设备组不存在: {}", id);
                return false;
            }
 
            // 更新设备组状态为启用
            group.setStatus(DeviceGroupConfig.Status.ENABLED);
            boolean result = updateById(group);
            
            if (result) {
                log.info("启用设备组成功: {}", id);
            } else {
                log.error("启用设备组失败: {}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("启用设备组异常", e);
            return false;
        }
    }
 
    @Override
    public boolean disableDeviceGroup(Long id) {
        try {
            // 检查设备组是否存在
            DeviceGroupConfig group = getById(id);
            if (group == null) {
                log.warn("设备组不存在: {}", id);
                return false;
            }
 
            // 更新设备组状态为禁用
            group.setStatus(DeviceGroupConfig.Status.DISABLED);
            boolean result = updateById(group);
            
            if (result) {
                log.info("禁用设备组成功: {}", id);
            } else {
                log.error("禁用设备组失败: {}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("禁用设备组异常", e);
            return false;
        }
    }
 
    @Override
    public boolean batchEnableDeviceGroups(java.util.List<Long> groupIds) {
        try {
            if (groupIds == null || groupIds.isEmpty()) {
                log.warn("批量启用设备组: 设备组ID列表为空");
                return false;
            }
 
            // 批量更新设备组状态
            LambdaUpdateWrapper<DeviceGroupConfig> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(DeviceGroupConfig::getId, groupIds)
                        .set(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.ENABLED);
            
            boolean result = update(updateWrapper);
            
            if (result) {
                log.info("批量启用设备组成功: {} 个设备组", groupIds.size());
            } else {
                log.error("批量启用设备组失败");
            }
            
            return result;
        } catch (Exception e) {
            log.error("批量启用设备组异常", e);
            return false;
        }
    }
 
    @Override
    public boolean batchDisableDeviceGroups(java.util.List<Long> groupIds) {
        try {
            if (groupIds == null || groupIds.isEmpty()) {
                log.warn("批量禁用设备组: 设备组ID列表为空");
                return false;
            }
 
            // 批量更新设备组状态
            LambdaUpdateWrapper<DeviceGroupConfig> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(DeviceGroupConfig::getId, groupIds)
                        .set(DeviceGroupConfig::getStatus, DeviceGroupConfig.Status.DISABLED);
            
            boolean result = update(updateWrapper);
            
            if (result) {
                log.info("批量禁用设备组成功: {} 个设备组", groupIds.size());
            } else {
                log.error("批量禁用设备组失败");
            }
            
            return result;
        } catch (Exception e) {
            log.error("批量禁用设备组异常", e);
            return false;
        }
    }
 
    @Override
    public java.util.List<String> getAllGroupTypes() {
        try {
            // 返回预定义的设备组类型列表
            java.util.List<String> groupTypes = new java.util.ArrayList<>();
            groupTypes.add("PRODUCTION");
            groupTypes.add("QUALITY_CONTROL");
            groupTypes.add("LOGISTICS");
            groupTypes.add("MAINTENANCE");
            groupTypes.add("MONITORING");
            
            log.debug("获取设备组类型列表: {} 个类型", groupTypes.size());
            return groupTypes;
        } catch (Exception e) {
            log.error("获取设备组类型列表失败", e);
            return new java.util.ArrayList<>();
        }
    }
 
    /**
     * 从扩展配置中提取位置信息
     */
    private String extractLocationFromExtraConfig(DeviceGroupConfig group) {
        if (group == null || group.getExtraConfig() == null) {
            return "默认位置";
        }
        try {
            Map<String, Object> extraConfig = objectMapper.readValue(group.getExtraConfig(), MAP_TYPE);
            Object location = extraConfig.get("location");
            return location != null ? String.valueOf(location) : "默认位置";
        } catch (Exception e) {
            log.warn("解析设备组位置信息失败, groupId={}", group.getId(), e);
            return "默认位置";
        }
    }
 
    /**
     * 从扩展配置中提取管理员信息
     */
    private String extractSupervisorFromExtraConfig(DeviceGroupConfig group) {
        if (group == null || group.getExtraConfig() == null) {
            return "默认管理员";
        }
        try {
            Map<String, Object> extraConfig = objectMapper.readValue(group.getExtraConfig(), MAP_TYPE);
            Object supervisor = extraConfig.get("supervisor");
            return supervisor != null ? String.valueOf(supervisor) : "默认管理员";
        } catch (Exception e) {
            log.warn("解析设备组管理员信息失败, groupId={}", group.getId(), e);
            return "默认管理员";
        }
    }
 
    /**
     * 获取设备组中活跃设备数量(状态为正常的设备)
     */
    private int getActiveDeviceCountByGroupId(Long groupId) {
        if (groupId == null) {
            return 0;
        }
        try {
            LambdaQueryWrapper<DeviceGroupRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeviceGroupRelation::getGroupId, groupId)
                   .eq(DeviceGroupRelation::getStatus, DeviceGroupRelation.Status.NORMAL)
                   .eq(DeviceGroupRelation::getIsDeleted, 0);
            return (int) deviceGroupRelationMapper.selectCount(wrapper);
        } catch (Exception e) {
            log.error("获取设备组活跃设备数量失败, groupId={}", groupId, e);
            return 0;
        }
    }
 
    @Override
    public java.util.List<String> getAllGroupStatuses() {
        try {
            // 返回预定义的设备组状态列表
            java.util.List<String> groupStatuses = new java.util.ArrayList<>();
            groupStatuses.add("ENABLED");
            groupStatuses.add("DISABLED");
            groupStatuses.add("MAINTENANCE");
            groupStatuses.add("OFFLINE");
            
            log.debug("获取设备组状态列表: {} 个状态", groupStatuses.size());
            return groupStatuses;
        } catch (Exception e) {
            log.error("获取设备组状态列表失败", e);
            return new java.util.ArrayList<>();
        }
    }
}