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
package com.mes.device.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.DeviceConfig;
import com.mes.device.mapper.DeviceConfigMapper;
import com.mes.device.service.DeviceConfigService;
import com.mes.device.vo.DeviceConfigVO;
import com.mes.device.vo.StatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 设备配置服务实现类
 * @author huang
 */
@Slf4j
@Service
public class DeviceConfigServiceImpl extends ServiceImpl<DeviceConfigMapper, DeviceConfig> implements DeviceConfigService {
 
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<Map<String, Object>>() {};
 
    @Override
    public boolean createDevice(DeviceConfig deviceConfig) {
        try {
            // 检查设备编号是否已存在
            if (isDeviceCodeExists(deviceConfig.getDeviceCode(), null)) {
                log.warn("设备编号已存在: {}", deviceConfig.getDeviceCode());
                return false;
            }
            
            // 初始化设备状态为离线
            if (deviceConfig.getStatus() == null) {
                deviceConfig.setStatus("离线");
            }
            
            boolean result = save(deviceConfig);
            if (result) {
                log.info("创建设备配置成功: {}", deviceConfig.getDeviceCode());
            }
            return result;
        } catch (Exception e) {
            log.error("创建设备配置失败", e);
            return false;
        }
    }
 
    @Override
    public boolean updateDevice(DeviceConfig deviceConfig) {
        try {
            // 检查设备编号是否已存在(排除当前设备)
            if (isDeviceCodeExists(deviceConfig.getDeviceCode(), deviceConfig.getId())) {
                log.warn("设备编号已存在: {}", deviceConfig.getDeviceCode());
                return false;
            }
            
            boolean result = updateById(deviceConfig);
            if (result) {
                log.info("更新设备配置成功: {}", deviceConfig.getDeviceCode());
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备配置失败", e);
            return false;
        }
    }
 
    @Override
    public boolean deleteDevice(Long id) {
        try {
            boolean result = removeById(id);
            if (result) {
                log.info("删除设备配置成功: {}", id);
            }
            return result;
        } catch (Exception e) {
            log.error("删除设备配置失败", e);
            return false;
        }
    }
 
    @Override
    public DeviceConfig getDeviceById(Long id) {
        return getById(id);
    }
 
    @Override
    public DeviceConfig getDeviceByCode(String deviceCode) {
        LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceConfig::getDeviceCode, deviceCode);
        wrapper.eq(DeviceConfig::getIsDeleted, 0);
        return getOne(wrapper);
    }
 
    @Override
    public List<DeviceConfig> getDeviceList(Long projectId, String deviceType, String status) {
        LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
        
        if (projectId != null) {
            wrapper.eq(DeviceConfig::getProjectId, projectId);
        }
        if (deviceType != null && !deviceType.isEmpty()) {
            wrapper.eq(DeviceConfig::getDeviceType, deviceType);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(DeviceConfig::getStatus, status);
        }
        
        wrapper.eq(DeviceConfig::getIsDeleted, 0);
        wrapper.orderByDesc(DeviceConfig::getCreatedTime);
        
        return list(wrapper);
    }
 
    @Override
    public Page<DeviceConfigVO.DeviceInfo> getDeviceList(Long projectId, String deviceType, String deviceStatus, String keyword, Integer page, Integer size) {
        // 创建分页对象
       Page<DeviceConfig> pageQuery = new Page<>(page != null ? page : 1, size != null ? size : 10);
        
        // 构建查询条件
        LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
        
        if (projectId != null) {
            wrapper.eq(DeviceConfig::getProjectId, projectId);
        }
        
        // 设备类型过滤
        if (deviceType != null && !deviceType.trim().isEmpty()) {
            String convertedDeviceType = convertDeviceTypeFromString(deviceType);
            if (convertedDeviceType != null) {
                wrapper.eq(DeviceConfig::getDeviceType, convertedDeviceType);
            }
        }
        
        // 设备状态过滤
        if (deviceStatus != null && !deviceStatus.trim().isEmpty()) {
            String convertedStatus = convertStatusFromString(deviceStatus);
            if (convertedStatus != null) {
                wrapper.eq(DeviceConfig::getStatus, convertedStatus);
            }
        }
        
        // 关键词搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(w -> w
                .like(DeviceConfig::getDeviceName, keyword)
                .or().like(DeviceConfig::getDeviceCode, keyword)
                .or().like(DeviceConfig::getDescription, keyword));
        }
        
        wrapper.eq(DeviceConfig::getIsDeleted, 0);
        wrapper.orderByDesc(DeviceConfig::getCreatedTime);
        
        // 执行分页查询
        Page<DeviceConfig> result = page(pageQuery, wrapper);
        
        // 转换为VO对象
        List<DeviceConfigVO.DeviceInfo> voList = result.getRecords().stream().map(device -> {
            DeviceConfigVO.DeviceInfo vo = new DeviceConfigVO.DeviceInfo();
            vo.setId(device.getId());
            vo.setDeviceName(device.getDeviceName());
            vo.setDeviceCode(device.getDeviceCode());
            vo.setDeviceType(getDeviceTypeName(device.getDeviceType()));
            vo.setPlcIp(device.getPlcIp());
            vo.setPlcPort(device.getPlcPort());
            vo.setPlcType(device.getPlcType());
            vo.setModuleName(device.getModuleName());
            vo.setIsPrimary(device.getIsPrimary());
            vo.setEnabled(Boolean.TRUE.equals(device.getEnabled()));
            vo.setIsEnabled(Boolean.TRUE.equals(device.getEnabled()));
            vo.setStatus(getStatusName(device.getStatus()));
            vo.setDeviceStatus(convertStatusToCode(device.getStatus()));
            vo.setLastHeartbeat(device.getUpdatedTime());
            vo.setLocation("默认位置");
            vo.setDescription(device.getDescription());
            vo.setCreatedTime(device.getCreatedTime());
            vo.setUpdatedTime(device.getUpdatedTime());
            vo.setProjectId(device.getProjectId());
            return vo;
        }).collect(Collectors.toList());
        
        // 创建返回的Page对象
        Page<DeviceConfigVO.DeviceInfo> pageResult = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        pageResult.setRecords(voList);
        
        return pageResult;
    }
 
    @Override
    public List<DeviceConfigVO.DeviceInfo> getDeviceVOList(Long projectId, String deviceType, String status) {
        List<DeviceConfig> deviceList = getDeviceList(projectId, deviceType, status);
        
        return deviceList.stream().map(device -> {
            DeviceConfigVO.DeviceInfo vo = new DeviceConfigVO.DeviceInfo();
            vo.setId(device.getId());
            vo.setDeviceName(device.getDeviceName());
            vo.setDeviceCode(device.getDeviceCode());
            vo.setDeviceType(getDeviceTypeName(device.getDeviceType()));
            vo.setPlcIp(device.getPlcIp());
            vo.setPlcPort(device.getPlcPort());
            vo.setPlcType(device.getPlcType());
            vo.setModuleName(device.getModuleName());
            vo.setIsPrimary(device.getIsPrimary());
            vo.setEnabled(Boolean.TRUE.equals(device.getEnabled()));
            vo.setIsEnabled(Boolean.TRUE.equals(device.getEnabled()));
            vo.setStatus(getStatusName(device.getStatus()));
            vo.setDeviceStatus(convertStatusToCode(device.getStatus()));
            vo.setDescription(device.getDescription());
            vo.setLocation(extractLocationFromDevice(device));
            vo.setCreatedTime(device.getCreatedTime());
            vo.setUpdatedTime(device.getUpdatedTime());
            vo.setProjectId(device.getProjectId());
            return vo;
        }).collect(Collectors.toList());
    }
 
    /**
     * 获取设备类型名称
     */
    private String getDeviceTypeName(String deviceType) {
        if (deviceType == null) return "未知设备";
        
        // 直接返回设备类型值,因为实体类中已经使用中文类型
        return deviceType;
    }
 
    /**
     * 获取设备状态名称
     */
    private String getStatusName(String status) {
        if (status == null) return "未知状态";
        
        // 直接返回状态值,因为实体类中已经使用中文状态
        return status;
    }
 
    /**
     * 将中文状态转换为前端使用的状态编码
     */
    private String convertStatusToCode(String status) {
        if (status == null) return "UNKNOWN";
        switch (status) {
            case "在线":
                return "ONLINE";
            case "离线":
                return "OFFLINE";
            case "维护中":
            case "维护":
                return "MAINTENANCE";
            case "故障":
                return "FAULT";
            default:
                return status.toUpperCase();
        }
    }
 
    /**
     * 更新单个设备启用状态
     */
    private boolean updateDeviceEnabledState(Long id, boolean enabled) {
        try {
            DeviceConfig device = getById(id);
            if (device == null) {
                log.warn("设备不存在: {}", id);
                return false;
            }
            device.setEnabled(enabled);
            device.setStatus(enabled ? DeviceConfig.Status.ONLINE : DeviceConfig.Status.OFFLINE);
            boolean result = updateById(device);
            if (result) {
                log.info("更新设备启用状态成功: {} -> {}", id, enabled);
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备启用状态失败", e);
            return false;
        }
    }
 
    /**
     * 批量更新设备启用状态
     */
    private boolean batchUpdateDeviceEnabledState(List<Long> ids, boolean enabled) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        try {
            LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(DeviceConfig::getId, ids);
 
            DeviceConfig updateEntity = new DeviceConfig();
            updateEntity.setEnabled(enabled);
            updateEntity.setStatus(enabled ? DeviceConfig.Status.ONLINE : DeviceConfig.Status.OFFLINE);
 
            boolean result = update(updateEntity, wrapper);
            if (result) {
                log.info("批量更新设备启用状态成功: {} 个设备 -> {}", ids.size(), enabled);
            }
            return result;
        } catch (Exception e) {
            log.error("批量更新设备启用状态失败", e);
            return false;
        }
    }
 
    /**
     * 字符串转换为设备类型
     */
    private String convertDeviceTypeFromString(String deviceType) {
        if (deviceType == null) return null;
        
        switch (deviceType.trim().toLowerCase()) {
            case "load_vehicle":
            case "上大车":
            case "1":
                return DeviceConfig.DeviceType.LOAD_VEHICLE;
            case "large_glass":
            case "大理片":
            case "2":
                return DeviceConfig.DeviceType.LARGE_GLASS;
            case "glass_storage":
            case "玻璃存储":
            case "3":
                return DeviceConfig.DeviceType.GLASS_STORAGE;
            default:
                return null;
        }
    }
 
    /**
     * 字符串转换为状态
     */
    private String convertStatusFromString(String deviceStatus) {
        if (deviceStatus == null) return null;
        
        switch (deviceStatus.trim().toLowerCase()) {
            case "online":
            case "在线":
            case "1":
                return "在线";
            case "offline":
            case "离线":
            case "2":
                return "离线";
            case "maintenance":
            case "维护":
            case "维护中":
            case "3":
                return "维护中";
            case "fault":
            case "故障":
            case "4":
                return "故障";
            default:
                return null;
        }
    }
 
    @Override
    public boolean isDeviceCodeExists(String deviceCode, Long excludeId) {
        LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceConfig::getDeviceCode, deviceCode);
        wrapper.eq(DeviceConfig::getIsDeleted, 0);
        
        if (excludeId != null) {
            wrapper.ne(DeviceConfig::getId, excludeId);
        }
        
        return count(wrapper) > 0;
    }
 
    @Override
    public boolean updateDeviceStatus(Long id, String status) {
        try {
            DeviceConfig device = getById(id);
            if (device == null) {
                log.warn("设备不存在: {}", id);
                return false;
            }
            
            device.setStatus(status);
            boolean result = updateById(device);
            if (result) {
                log.info("更新设备状态成功: {} -> {}", id, status);
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备状态失败", e);
            return false;
        }
    }
 
    @Override
    public boolean batchUpdateDeviceStatus(List<Long> ids, String status) {
        try {
            LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(DeviceConfig::getId, ids);
            
            DeviceConfig updateEntity = new DeviceConfig();
            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> getExtraParams(Long id) {
        try {
            DeviceConfig device = getById(id);
            if (device == null || device.getExtraParams() == null) {
                return new HashMap<>();
            }
            
            return objectMapper.readValue(device.getExtraParams(), 
                new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            log.error("解析设备扩展参数失败", e);
            return new HashMap<>();
        }
    }
 
    @Override
    public boolean updateExtraParams(Long id, Map<String, Object> extraParams) {
        try {
            DeviceConfig device = getById(id);
            if (device == null) {
                log.warn("设备不存在: {}", id);
                return false;
            }
            
            String extraParamsJson = objectMapper.writeValueAsString(extraParams);
            device.setExtraParams(extraParamsJson);
            
            boolean result = updateById(device);
            if (result) {
                log.info("更新设备扩展参数成功: {}", id);
            }
            return result;
        } catch (IOException e) {
            log.error("序列化设备扩展参数失败", e);
            return false;
        }
    }
 
    @Override
    public int getOnlineDeviceCount(Long projectId) {
        // 简化实现,实际项目中可能需要根据项目ID过滤
        LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceConfig::getStatus, "在线");
        wrapper.eq(DeviceConfig::getIsDeleted, 0);
        
        if (projectId != null) {
            wrapper.eq(DeviceConfig::getProjectId, projectId);
        }
        
        return (int) count(wrapper);
    }
 
    @Override
    public StatisticsVO.DeviceStatistics getDeviceStatistics(Long projectId) {
        try {
            // 设备总数
            LambdaQueryWrapper<DeviceConfig> totalWrapper = new LambdaQueryWrapper<>();
            totalWrapper.eq(DeviceConfig::getIsDeleted, 0);
            if (projectId != null) {
                totalWrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            int totalDevices = (int) count(totalWrapper);
            
            // 在线设备数
            LambdaQueryWrapper<DeviceConfig> onlineWrapper = new LambdaQueryWrapper<>();
            onlineWrapper.eq(DeviceConfig::getStatus, "在线");
            onlineWrapper.eq(DeviceConfig::getIsDeleted, 0);
            if (projectId != null) {
                onlineWrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            int onlineDevices = (int) count(onlineWrapper);
            
            // 离线设备数
            LambdaQueryWrapper<DeviceConfig> offlineWrapper = new LambdaQueryWrapper<>();
            offlineWrapper.eq(DeviceConfig::getStatus, "离线");
            offlineWrapper.eq(DeviceConfig::getIsDeleted, 0);
            if (projectId != null) {
                offlineWrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            int offlineDevices = (int) count(offlineWrapper);
            
            // 活跃设备数(在线设备)
            int activeDevices = onlineDevices;
            int inactiveDevices = offlineDevices;
            
            // 维护中设备数
            LambdaQueryWrapper<DeviceConfig> maintenanceWrapper = new LambdaQueryWrapper<>();
            maintenanceWrapper.eq(DeviceConfig::getStatus, "维护中");
            maintenanceWrapper.eq(DeviceConfig::getIsDeleted, 0);
            if (projectId != null) {
                maintenanceWrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            int maintenanceDevices = (int) count(maintenanceWrapper);
            
            // 故障设备数
            LambdaQueryWrapper<DeviceConfig> faultWrapper = new LambdaQueryWrapper<>();
            faultWrapper.eq(DeviceConfig::getStatus, "故障");
            faultWrapper.eq(DeviceConfig::getIsDeleted, 0);
            if (projectId != null) {
                faultWrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            int faultDevices = (int) count(faultWrapper);
            
            // 计算设备可用性
            double deviceAvailability = totalDevices > 0 ? (double) activeDevices / totalDevices * 100 : 0.0;
            
            // 计算平均正常运行时间(模拟值)
            double averageUptime = 95.5; // 默认值,实际应用中可以基于历史数据计算
            
            // 获取设备类型统计
            List<StatisticsVO.DeviceTypeStatistics> deviceTypeStats = getDeviceTypeStatistics(projectId);
            
            // 创建设备统计对象
            StatisticsVO.DeviceStatistics deviceStatistics = new StatisticsVO.DeviceStatistics(
                totalDevices,
                onlineDevices,
                offlineDevices,
                activeDevices,
                inactiveDevices,
                faultDevices,
                maintenanceDevices,
                deviceTypeStats.size(),
                deviceAvailability,
                averageUptime,
                new Date(),
                deviceTypeStats
            );
            
            log.info("获取设备统计信息成功: 总设备数={}, 在线设备数={}, 可用性={}%", 
                totalDevices, onlineDevices, String.format("%.2f", deviceAvailability));
            
            return deviceStatistics;
        } catch (Exception e) {
            log.error("获取设备统计信息失败", e);
            // 返回默认统计信息
            return new StatisticsVO.DeviceStatistics(0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, new Date(), new ArrayList<>());
        }
    }
 
    /**
     * 获取设备类型统计信息
     */
    private List<StatisticsVO.DeviceTypeStatistics> getDeviceTypeStatistics(Long projectId) {
        try {
            List<StatisticsVO.DeviceTypeStatistics> deviceTypeStats = new ArrayList<>();
            
            // 获取所有设备类型
            List<String> deviceTypeNames = getAllDeviceTypes();
            
            for (String deviceTypeName : deviceTypeNames) {
                // 总数
                LambdaQueryWrapper<DeviceConfig> totalWrapper = new LambdaQueryWrapper<>();
                totalWrapper.eq(DeviceConfig::getDeviceType, deviceTypeName);
                totalWrapper.eq(DeviceConfig::getIsDeleted, 0);
                if (projectId != null) {
                    totalWrapper.eq(DeviceConfig::getProjectId, projectId);
                }
                Integer totalCount = Math.toIntExact(count(totalWrapper));
                
                // 在线数
                LambdaQueryWrapper<DeviceConfig> onlineWrapper = new LambdaQueryWrapper<>();
                onlineWrapper.eq(DeviceConfig::getDeviceType, deviceTypeName);
                onlineWrapper.eq(DeviceConfig::getStatus, "在线");
                onlineWrapper.eq(DeviceConfig::getIsDeleted, 0);
                if (projectId != null) {
                    onlineWrapper.eq(DeviceConfig::getProjectId, projectId);
                }
                Integer onlineCount = Math.toIntExact(count(onlineWrapper));
                
                // 离线数
                LambdaQueryWrapper<DeviceConfig> offlineWrapper = new LambdaQueryWrapper<>();
                offlineWrapper.eq(DeviceConfig::getDeviceType, deviceTypeName);
                offlineWrapper.eq(DeviceConfig::getStatus, "离线");
                offlineWrapper.eq(DeviceConfig::getIsDeleted, 0);
                if (projectId != null) {
                    offlineWrapper.eq(DeviceConfig::getProjectId, projectId);
                }
                Integer offlineCount = Math.toIntExact(count(offlineWrapper));
                
                // 可用性
                double availability = totalCount > 0 ? (double) onlineCount / totalCount * 100 : 0.0;
                
                deviceTypeStats.add(new StatisticsVO.DeviceTypeStatistics(
                    deviceTypeName, totalCount, onlineCount, offlineCount, availability
                ));
            }
            
            return deviceTypeStats;
        } catch (Exception e) {
            log.error("获取设备类型统计失败", e);
            return new ArrayList<>();
        }
    }
 
    @Override
    public Long getDeviceCount(Long projectId, String deviceType, String deviceStatus, String keyword) {
        try {
            LambdaQueryWrapper<DeviceConfig> wrapper = new LambdaQueryWrapper<>();
            
            if (projectId != null) {
                wrapper.eq(DeviceConfig::getProjectId, projectId);
            }
            
            // 设备类型过滤
            if (deviceType != null && !deviceType.trim().isEmpty()) {
                String convertedDeviceType = convertDeviceTypeFromString(deviceType);
                if (convertedDeviceType != null) {
                    wrapper.eq(DeviceConfig::getDeviceType, convertedDeviceType);
                }
            }
            
            // 设备状态过滤
            if (deviceStatus != null && !deviceStatus.trim().isEmpty()) {
                String convertedStatus = convertStatusFromString(deviceStatus);
                if (convertedStatus != null) {
                    wrapper.eq(DeviceConfig::getStatus, convertedStatus);
                }
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                wrapper.and(w -> w
                    .like(DeviceConfig::getDeviceName, keyword)
                    .or().like(DeviceConfig::getDeviceCode, keyword)
                    .or().like(DeviceConfig::getDescription, keyword));
            }
            
            wrapper.eq(DeviceConfig::getIsDeleted, 0);
            return (long) count(wrapper);
        } catch (Exception e) {
            log.error("获取设备总数失败", e);
            return 0L;
        }
    }
 
    @Override
    public List<String> getAllDeviceTypes() {
        List<String> deviceTypes = new ArrayList<>();
        deviceTypes.add("PLC设备");
        deviceTypes.add("传感器设备");
        deviceTypes.add("执行器设备");
        deviceTypes.add("人机界面设备");
        return deviceTypes;
    }
 
    @Override
    public List<String> getAllDeviceStatuses() {
        List<String> deviceStatuses = new ArrayList<>();
        deviceStatuses.add("在线");
        deviceStatuses.add("离线");
        deviceStatuses.add("维护中");
        deviceStatuses.add("故障");
        return deviceStatuses;
    }
 
    @Override
    public boolean enableDevice(Long id) {
        return updateDeviceEnabledState(id, true);
    }
 
    @Override
    public boolean disableDevice(Long id) {
        return updateDeviceEnabledState(id, false);
    }
 
    @Override
    public boolean batchEnableDevices(List<Long> deviceIds) {
        return batchUpdateDeviceEnabledState(deviceIds, true);
    }
 
    @Override
    public boolean batchDisableDevices(List<Long> deviceIds) {
        return batchUpdateDeviceEnabledState(deviceIds, false);
    }
 
    @Override
    public DeviceConfigVO.HealthCheckResult performHealthCheck(Long id) {
        try {
            DeviceConfig device = getById(id);
            if (device == null) {
                log.warn("设备不存在: {}", id);
                DeviceConfigVO.HealthCheckResult result = new DeviceConfigVO.HealthCheckResult();
                result.setIsHealthy(false);
                result.setOverallStatus("设备不存在");
                result.setCheckTime(LocalDateTime.now());
                return result;
            }
            
            // 简化的健康检查逻辑
            boolean isHealthy = true;
            List<String> issues = new ArrayList<>();
            
            // 检查IP和端口配置
            if (device.getPlcIp() == null || device.getPlcIp().trim().isEmpty()) {
                isHealthy = false;
                issues.add("IP地址配置缺失");
            }
            
            if (device.getPlcPort() == null || device.getPlcPort() <= 0) {
                isHealthy = false;
                issues.add("端口配置无效");
            }
            
            // 检查设备状态
            if (device.getStatus() != null && device.getStatus().equals(DeviceConfig.Status.FAULT)) {
                isHealthy = false;
                issues.add("设备状态异常");
            }
            
            String message = isHealthy ? "设备运行正常" : String.join(";", issues);
            log.info("设备健康检查完成: {} - {}", id, message);
            
            DeviceConfigVO.HealthCheckResult result = new DeviceConfigVO.HealthCheckResult();
            result.setIsHealthy(isHealthy);
            result.setOverallStatus(message);
            result.setCheckTime(LocalDateTime.now());
            return result;
        } catch (Exception e) {
            log.error("设备健康检查失败: {}", id, e);
            DeviceConfigVO.HealthCheckResult result = new DeviceConfigVO.HealthCheckResult();
            result.setIsHealthy(false);
            result.setOverallStatus("健康检查失败: " + e.getMessage());
            result.setCheckTime(LocalDateTime.now());
            return result;
        }
    }
 
    @Override
    public List<DeviceConfigVO.DeviceTreeNode> getDeviceTree(Long projectId) {
        try {
            List<DeviceConfig> devices = getDeviceList(projectId, null, null);
            
            return devices.stream().map(device -> {
                DeviceConfigVO.DeviceTreeNode node = new DeviceConfigVO.DeviceTreeNode();
                node.setId(device.getId());
                node.setLabel(device.getDeviceName() + " (" + device.getDeviceCode() + ")");
                node.setType("device");
                node.setStatus(getStatusName(device.getStatus()));
                // 将额外信息放入data对象
                Map<String, Object> data = new HashMap<>();
                data.put("deviceId", device.getId());
                data.put("deviceCode", device.getDeviceCode());
                data.put("deviceType", getDeviceTypeName(device.getDeviceType()));
                node.setData(data);
                node.setChildren(null); // 设备节点没有子节点
                return node;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取设备树结构失败", e);
            return new ArrayList<>();
        }
    }
 
    /**
     * 从设备扩展参数中提取位置信息
     */
    private String extractLocationFromDevice(DeviceConfig device) {
        if (device == null) {
            return "默认位置";
        }
        try {
            // 优先从extraParams中获取
            if (device.getExtraParams() != null && !device.getExtraParams().trim().isEmpty()) {
                Map<String, Object> extraParams = objectMapper.readValue(device.getExtraParams(), MAP_TYPE);
                Object location = extraParams.get("location");
                if (location != null) {
                    return String.valueOf(location);
                }
            }
            // 从configJson中获取
            if (device.getConfigJson() != null && !device.getConfigJson().trim().isEmpty()) {
                Map<String, Object> configJson = objectMapper.readValue(device.getConfigJson(), MAP_TYPE);
                Object location = configJson.get("location");
                if (location != null) {
                    return String.valueOf(location);
                }
            }
        } catch (Exception e) {
            log.warn("解析设备位置信息失败, deviceId={}", device.getId(), e);
        }
        return "默认位置";
    }
}