Junjie
2026-04-16 424002744fa37f4483fef3e36633bd193481781a
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
package com.zy.asrs.controller;
 
import com.alibaba.fastjson.JSON;
import com.core.annotations.ManagerAuth;
import com.core.common.Cools;
import com.core.common.R;
import com.zy.asrs.entity.BasDevp;
import com.zy.asrs.entity.DeviceDataLog;
import com.zy.asrs.service.BasDevpService;
import com.zy.common.web.BaseController;
import com.zy.core.enums.SlaveType;
import com.zy.core.model.StationObjModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
@Slf4j
@RestController
public class DeviceLogController extends BaseController {
 
    private static final List<String> DEVICE_TYPE_ORDER = Arrays.asList("Crn", "DualCrn", "Rgv", "Devp");
    private static final Map<String, String> DEVICE_TYPE_LABELS = new LinkedHashMap<>();
 
    static {
        DEVICE_TYPE_LABELS.put("Crn", "堆垛机");
        DEVICE_TYPE_LABELS.put("DualCrn", "双工位堆垛机");
        DEVICE_TYPE_LABELS.put("Rgv", "RGV");
        DEVICE_TYPE_LABELS.put("Devp", "输送设备");
    }
 
    @Autowired
    private BasDevpService basDevpService;
 
    @Value("${deviceLogStorage.loggingPath}")
    private String loggingPath;
 
    @Value("${logging.file.path:./stock/out/@pom.build.finalName@/logs}")
    private String systemLoggingPath;
 
    private static final DateTimeFormatter SYSTEM_LOG_DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter SYSTEM_LOG_DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter SYSTEM_LOG_EXPORT_TIME = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
    private static final Pattern SYSTEM_LOG_TIMESTAMP = Pattern.compile("^(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})");
    private static final Pattern SYSTEM_LOG_ROLLED_FILE = Pattern.compile("^(info|error)_(\\d{4}-\\d{2}-\\d{2})\\.(\\d+)\\.log$");
 
    private static class ProgressInfo {
        long totalRaw;
        long processedRaw;
        int totalCount;
        int processedCount;
        boolean finished;
    }
 
    private static class FileNameInfo {
        String type;
        String deviceNo;
        String stationId;
        String day;
        int index;
    }
 
    private static class FileTimeRange {
        Long startTime;
        Long endTime;
    }
 
    private static class DeviceAggregate {
        String type;
        String typeLabel;
        String deviceNo;
        String stationId;
        List<String> stationIds;
        int fileCount;
        Long firstTime;
        Long lastTime;
        Integer firstIndex;
        Integer lastIndex;
        Path firstFile;
        Path lastFile;
    }
 
    private static class SystemLogFileInfo {
        String logType;
        LocalDate day;
        Integer index;
        boolean active;
        Path path;
    }
 
    private static class SystemLogDownloadRequest {
        String logType;
        LocalDateTime startTime;
        LocalDateTime endTime;
        List<Path> files;
    }
 
    private static final Map<String, ProgressInfo> DOWNLOAD_PROGRESS = new ConcurrentHashMap<>();
    private static final int SYSTEM_LOG_MAX_RANGE_DAYS = 10;
    private static final int SYSTEM_LOG_MATCH_BUFFER_LINES = 200000;
    private static final String SYSTEM_LOG_ENTRY_NAME = "system.log";
 
    private static final Map<String, SystemLogDownloadRequest> SYSTEM_LOG_DOWNLOAD_REQUESTS = new ConcurrentHashMap<>();
 
    @RequestMapping(value = "/deviceLog/dates/auth")
    @ManagerAuth
    public R dates() {
        try {
            Path baseDir = Paths.get(loggingPath);
            if (!Files.exists(baseDir)) {
                return R.ok(new ArrayList<>());
            }
            List<String> days = Files.list(baseDir)
                    .filter(Files::isDirectory)
                    .map(p -> p.getFileName().toString())
                    .filter(name -> name.length() == 8 && name.chars().allMatch(Character::isDigit))
                    .sorted()
                    .collect(Collectors.toList());
            Map<String, Map<String, List<String>>> grouped = new LinkedHashMap<>();
            for (String day : days) {
                String year = day.substring(0, 4);
                String month = day.substring(4, 6);
                grouped.computeIfAbsent(year, k -> new LinkedHashMap<>())
                        .computeIfAbsent(month, k -> new ArrayList<>())
                        .add(day);
            }
            List<Map<String, Object>> tree = new ArrayList<>();
            for (Map.Entry<String, Map<String, List<String>>> yEntry : grouped.entrySet()) {
                Map<String, Object> yNode = new HashMap<>();
                yNode.put("title", yEntry.getKey());
                yNode.put("id", yEntry.getKey());
                List<Map<String, Object>> mChildren = new ArrayList<>();
                for (Map.Entry<String, List<String>> mEntry : yEntry.getValue().entrySet()) {
                    Map<String, Object> mNode = new HashMap<>();
                    mNode.put("title", mEntry.getKey());
                    mNode.put("id", yEntry.getKey() + "-" + mEntry.getKey());
                    List<Map<String, Object>> dChildren = new ArrayList<>();
                    for (String d : mEntry.getValue()) {
                        Map<String, Object> dNode = new HashMap<>();
                        dNode.put("title", d.substring(6, 8));
                        dNode.put("id", d);
                        dNode.put("day", d);
                        dChildren.add(dNode);
                    }
                    mNode.put("children", dChildren);
                    mChildren.add(mNode);
                }
                yNode.put("children", mChildren);
                tree.add(yNode);
            }
            return R.ok(tree);
        } catch (Exception e) {
            return R.error("读取日期失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/devices/auth")
    @ManagerAuth
    public R devices(@PathVariable("day") String day) {
        try {
            if (day == null || day.length() != 8 || !day.chars().allMatch(Character::isDigit)) {
                return R.error("日期格式错误");
            }
            Path dayDir = Paths.get(loggingPath, day);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.ok(new ArrayList<>());
            }
            List<Path> files = listDayLogFiles(dayDir);
            Map<String, Map<String, Object>> deviceMap = new HashMap<>();
            for (Path p : files) {
                FileNameInfo info = parseFileName(p.getFileName().toString());
                if (info == null || !day.equals(info.day)) {
                    continue;
                }
                String deviceKey = buildDeviceKey(info.type, info.deviceNo, info.stationId);
                Map<String, Object> infoMap = deviceMap.computeIfAbsent(deviceKey, k -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("deviceNo", info.deviceNo);
                    map.put("stationId", info.stationId);
                    map.put("types", new HashSet<String>());
                    map.put("fileCount", 0);
                    return map;
                });
                ((Set<String>) infoMap.get("types")).add(info.type);
                infoMap.put("fileCount", ((Integer) infoMap.get("fileCount")) + 1);
            }
            List<Map<String, Object>> res = deviceMap.values().stream().map(m -> {
                Map<String, Object> x = new HashMap<>();
                x.put("deviceNo", m.get("deviceNo"));
                x.put("stationId", m.get("stationId"));
                x.put("types", ((Set<String>) m.get("types")).stream().collect(Collectors.toList()));
                x.put("fileCount", m.get("fileCount"));
                return x;
            }).collect(Collectors.toList());
            return R.ok(res);
        } catch (Exception e) {
            return R.error("读取设备列表失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/summary/auth")
    @ManagerAuth
    public R summary(@PathVariable("day") String day) {
        try {
            String dayClean = normalizeDay(day);
            if (dayClean == null) {
                return R.error("日期格式错误");
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.ok(buildEmptySummary());
            }
 
            Map<String, DeviceAggregate> aggregateMap = new LinkedHashMap<>();
            List<Path> files = listDayLogFiles(dayDir);
            for (Path file : files) {
                FileNameInfo info = parseFileName(file.getFileName().toString());
                if (info == null || !dayClean.equals(info.day) || !DEVICE_TYPE_LABELS.containsKey(info.type)) {
                    continue;
                }
                String key = buildDeviceKey(info.type, info.deviceNo, info.stationId);
                DeviceAggregate aggregate = aggregateMap.computeIfAbsent(key, k -> {
                    DeviceAggregate x = new DeviceAggregate();
                    x.type = info.type;
                    x.typeLabel = DEVICE_TYPE_LABELS.get(info.type);
                    x.deviceNo = info.deviceNo;
                    x.stationId = info.stationId;
                    return x;
                });
                aggregate.fileCount += 1;
                if (aggregate.firstIndex == null || info.index < aggregate.firstIndex) {
                    aggregate.firstIndex = info.index;
                    aggregate.firstFile = file;
                }
                if (aggregate.lastIndex == null || info.index > aggregate.lastIndex) {
                    aggregate.lastIndex = info.index;
                    aggregate.lastFile = file;
                }
            }
            for (DeviceAggregate aggregate : aggregateMap.values()) {
                if (aggregate.firstFile != null) {
                    FileTimeRange firstRange = readFileTimeRange(aggregate.firstFile, aggregate.stationId);
                    aggregate.firstTime = firstRange.startTime != null ? firstRange.startTime : firstRange.endTime;
                }
                if (aggregate.lastFile != null) {
                    FileTimeRange lastRange = readFileTimeRange(aggregate.lastFile, aggregate.stationId);
                    aggregate.lastTime = lastRange.endTime != null ? lastRange.endTime : lastRange.startTime;
                }
            }
            enrichDevpStationIds(aggregateMap.values());
            return R.ok(buildSummaryResponse(aggregateMap.values()));
        } catch (Exception e) {
            log.error("读取设备日志摘要失败", e);
            return R.error("读取设备日志摘要失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/timeline/auth")
    @ManagerAuth
    public R timeline(@PathVariable("day") String day,
                      @RequestParam("type") String type,
                      @RequestParam("deviceNo") String deviceNo,
                      @RequestParam(value = "stationId", required = false) String stationId) {
        try {
            String dayClean = normalizeDay(day);
            if (dayClean == null) {
                return R.error("日期格式错误");
            }
            if (type == null || SlaveType.findInstance(type) == null) {
                return R.error("设备类型错误");
            }
            if (deviceNo == null || !deviceNo.chars().allMatch(Character::isDigit)) {
                return R.error("设备编号错误");
            }
            if (isDevpType(type) && (stationId == null || !stationId.chars().allMatch(Character::isDigit))) {
                return R.error("站点编号错误");
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.error("未找到日志文件");
            }
            List<Path> files = findDeviceFiles(dayDir, dayClean, type, deviceNo, stationId);
            if (files.isEmpty()) {
                return R.error("未找到日志文件");
            }
 
            List<Map<String, Object>> segments = new ArrayList<>();
            Long startTime = null;
            for (int i = 0; i < files.size(); i++) {
                Long segmentStart = getFileStartTime(files.get(i), stationId);
                if (segmentStart != null && (startTime == null || segmentStart < startTime)) {
                    startTime = segmentStart;
                }
                Map<String, Object> segment = new LinkedHashMap<>();
                segment.put("offset", i);
                segment.put("startTime", segmentStart);
                segment.put("endTime", null);
                segments.add(segment);
            }
            Long endTime = getFileEndTime(files.get(files.size() - 1), stationId);
            if (endTime == null) {
                for (int i = segments.size() - 1; i >= 0; i--) {
                    Long segmentStart = (Long) segments.get(i).get("startTime");
                    if (segmentStart != null) {
                        endTime = segmentStart;
                        break;
                    }
                }
            }
            for (int i = 0; i < segments.size(); i++) {
                Long segmentEnd = null;
                if (i < segments.size() - 1) {
                    segmentEnd = (Long) segments.get(i + 1).get("startTime");
                }
                if (segmentEnd == null && i == segments.size() - 1) {
                    segmentEnd = endTime;
                }
                if (segmentEnd == null) {
                    segmentEnd = (Long) segments.get(i).get("startTime");
                }
                segments.get(i).put("endTime", segmentEnd);
            }
 
            Map<String, Object> result = new HashMap<>();
            result.put("type", type);
            result.put("typeLabel", DEVICE_TYPE_LABELS.getOrDefault(type, type));
            result.put("deviceNo", deviceNo);
            result.put("stationId", stationId);
            result.put("startTime", startTime);
            result.put("endTime", endTime);
            result.put("totalFiles", files.size());
            result.put("segments", segments);
            return R.ok(result);
        } catch (Exception e) {
            log.error("读取设备日志时间轴失败", e);
            return R.error("读取设备日志时间轴失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/preview/auth")
    @ManagerAuth
    public R preview(@PathVariable("day") String day,
                     @RequestParam("type") String type,
                     @RequestParam("deviceNo") String deviceNo,
                     @RequestParam(value = "stationId", required = false) String stationId,
                     @RequestParam(value = "offset", required = false) Integer offset,
                     @RequestParam(value = "limit", required = false) Integer limit) {
        try {
            String dayClean = day == null ? null : day.replaceAll("\\D", "");
            if (dayClean == null || dayClean.length() != 8 || !dayClean.chars().allMatch(Character::isDigit)) {
                return R.error("日期格式错误");
            }
            if (type == null || SlaveType.findInstance(type) == null) {
                return R.error("设备类型错误");
            }
            if (deviceNo == null || !deviceNo.chars().allMatch(Character::isDigit)) {
                return R.error("设备编号错误");
            }
            if (isDevpType(type) && (stationId == null || !stationId.chars().allMatch(Character::isDigit))) {
                return R.error("站点编号错误");
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.ok(new ArrayList<>());
            }
            List<Path> files = findDeviceFiles(dayDir, dayClean, type, deviceNo, stationId);
 
            int from = offset == null || offset < 0 ? 0 : offset;
            int max = limit == null || limit <= 0 ? 5 : limit;
            if (max > 10) max = 10;
            int to = Math.min(files.size(), from + max);
 
            if (from >= files.size()) {
                return R.ok(new ArrayList<>());
            }
 
            List<Path> targetFiles = files.subList(from, to);
            List<DeviceDataLog> resultLogs = new ArrayList<>();
 
            for (Path f : targetFiles) {
                try (Stream<String> lines = Files.lines(f, StandardCharsets.UTF_8)) {
                    lines.forEach(line -> {
                        if (line != null && !line.trim().isEmpty()) {
                            try {
                                DeviceDataLog logItem = JSON.parseObject(line, DeviceDataLog.class);
                                if (matchesRequestedStation(logItem, stationId)) {
                                    resultLogs.add(logItem);
                                }
                            } catch (Exception e) {
                            }
                        }
                    });
                } catch (Exception e) {
                    log.error("读取日志文件失败: " + f, e);
                }
            }
            resultLogs.sort(Comparator.comparing(DeviceDataLog::getCreateTime, Comparator.nullsLast(Date::compareTo)));
 
            return R.ok(resultLogs);
        } catch (Exception e) {
            log.error("预览日志失败", e);
            return R.error("预览日志失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/seek/auth")
    @ManagerAuth
    public R seek(@PathVariable("day") String day,
                  @RequestParam("type") String type,
                  @RequestParam("deviceNo") String deviceNo,
                  @RequestParam(value = "stationId", required = false) String stationId,
                  @RequestParam("timestamp") Long timestamp) {
        try {
            String dayClean = day == null ? null : day.replaceAll("\\D", "");
            if (dayClean == null || dayClean.length() != 8 || !dayClean.chars().allMatch(Character::isDigit)) {
                return R.error("日期格式错误");
            }
            if (type == null || SlaveType.findInstance(type) == null) {
                return R.error("设备类型错误");
            }
            if (deviceNo == null || !deviceNo.chars().allMatch(Character::isDigit)) {
                return R.error("设备编号错误");
            }
            if (isDevpType(type) && (stationId == null || !stationId.chars().allMatch(Character::isDigit))) {
                return R.error("站点编号错误");
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.error("未找到日志文件");
            }
 
            List<Path> files = findDeviceFiles(dayDir, dayClean, type, deviceNo, stationId);
 
            if (files.isEmpty()) {
                return R.error("未找到日志文件");
            }
 
            int low = 0;
            int high = files.size() - 1;
            int foundIndex = -1;
 
            while (low <= high) {
                int mid = (low + high) >>> 1;
                Path midFile = files.get(mid);
                Long midStart = getFileStartTime(midFile, stationId);
                if (midStart == null) {
                    low = mid + 1;
                    continue;
                }
 
                if (midStart <= timestamp) {
                    foundIndex = mid;
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
 
            if (foundIndex == -1) {
                foundIndex = 0;
            }
 
            Map<String, Object> result = new HashMap<>();
            result.put("offset", foundIndex);
            return R.ok(result);
 
        } catch (Exception e) {
            log.error("寻址失败", e);
            return R.error("寻址失败");
        }
    }
    
    private Long getFileStartTime(Path file, String stationId) {
        try {
            String firstLine = readFirstMatchingLine(file, stationId);
            if (firstLine == null) return null;
            DeviceDataLog firstLog = JSON.parseObject(firstLine, DeviceDataLog.class);
            return firstLog.getCreateTime().getTime();
        } catch (Exception e) {
            return null;
        }
    }
 
    private Long getFileEndTime(Path file, String stationId) {
        try {
            String lastLine = readLastMatchingLine(file, stationId);
            if (lastLine == null) return null;
            DeviceDataLog lastLog = JSON.parseObject(lastLine, DeviceDataLog.class);
            return lastLog.getCreateTime().getTime();
        } catch (Exception e) {
            return null;
        }
    }
 
    @RequestMapping(value = "/deviceLog/day/{day}/download/auth")
    @ManagerAuth
    public void download(@PathVariable("day") String day,
                         @RequestParam("type") String type,
                         @RequestParam("deviceNo") String deviceNo,
                         @RequestParam(value = "offset", required = false) Integer offset,
                         @RequestParam(value = "limit", required = false) Integer limit,
                         @RequestParam(value = "progressId", required = false) String progressId,
                         HttpServletResponse response) {
        try {
            String dayClean = day == null ? null : day.replaceAll("\\D", "");
            if (dayClean == null || dayClean.length() != 8 || !dayClean.chars().allMatch(Character::isDigit)) {
                response.setStatus(400);
                return;
            }
            if (type == null || SlaveType.findInstance(type) == null) {
                response.setStatus(400);
                return;
            }
            if (deviceNo == null || !deviceNo.chars().allMatch(Character::isDigit)) {
                response.setStatus(400);
                return;
            }
            String stationId = request.getParameter("stationId");
            if (isDevpType(type) && (stationId == null || !stationId.chars().allMatch(Character::isDigit))) {
                response.setStatus(400);
                return;
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                response.setStatus(404);
                return;
            }
            List<Path> files = findDeviceFiles(dayDir, dayClean, type, deviceNo, stationId);
            files = sliceDownloadFiles(files, offset, limit);
            if (files.isEmpty()) {
                response.setStatus(404);
                return;
            }
            ProgressInfo info;
            String id = progressId;
            if (Cools.isEmpty(id)) {
                id = UUID.randomUUID().toString();
            }
            List<Path> finalFiles = files;
            info = DOWNLOAD_PROGRESS.computeIfAbsent(id, k -> {
                ProgressInfo x = new ProgressInfo();
                x.totalCount = finalFiles.size();
                long sum = 0L;
                for (Path f : finalFiles) {
                    try { sum += Files.size(f); } catch (Exception ignored) {}
                }
                x.totalRaw = sum;
                x.processedRaw = 0L;
                x.processedCount = 0;
                x.finished = false;
                return x;
            });
            response.reset();
            response.setContentType("application/zip");
            String filename = type + "_" + deviceNo + "_" + dayClean + ".zip";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            long totalRawSize = 0L;
            for (Path f : files) {
                try { totalRawSize += Files.size(f); } catch (Exception ignored) {}
            }
            response.setHeader("X-Total-Size", String.valueOf(totalRawSize));
            response.setHeader("X-File-Count", String.valueOf(files.size()));
            response.setHeader("X-Progress-Id", id);
            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                for (Path f : files) {
                    ZipEntry entry = new ZipEntry(f.getFileName().toString());
                    zos.putNextEntry(entry);
                    Files.copy(f, zos);
                    zos.closeEntry();
                    try {
                        info.processedRaw += Files.size(f);
                    } catch (Exception ignored) {}
                    info.processedCount += 1;
                }
                zos.finish();
                info.finished = true;
            }
        } catch (Exception e) {
            try { response.setStatus(500); } catch (Exception ignore) {}
        }
    }
 
    @RequestMapping(value = "/deviceLog/download/init/auth")
    @ManagerAuth
    public R init(@org.springframework.web.bind.annotation.RequestBody com.alibaba.fastjson.JSONObject param) {
        try {
            String day = param.getString("day");
            String type = param.getString("type");
            String deviceNo = param.getString("deviceNo");
            Integer offset = param.getInteger("offset");
            Integer limit = param.getInteger("limit");
            String dayClean = Cools.isEmpty(day) ? null : day.replaceAll("\\D", "");
            if (Cools.isEmpty(dayClean) || dayClean.length() != 8 || !dayClean.chars().allMatch(Character::isDigit)) {
                return R.error("日期格式错误");
            }
            if (Cools.isEmpty(type) || SlaveType.findInstance(type) == null) {
                return R.error("设备类型错误");
            }
            if (Cools.isEmpty(deviceNo) || !deviceNo.chars().allMatch(Character::isDigit)) {
                return R.error("设备编号错误");
            }
            String stationId = param.getString("stationId");
            if (isDevpType(type) && (Cools.isEmpty(stationId) || !stationId.chars().allMatch(Character::isDigit))) {
                return R.error("站点编号错误");
            }
            Path dayDir = Paths.get(loggingPath, dayClean);
            if (!Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
                return R.error("当日目录不存在");
            }
            List<Path> files = findDeviceFiles(dayDir, dayClean, type, deviceNo, stationId);
            if ((offset != null && offset >= files.size())) {
                return R.error("起始序号超出范围");
            }
            files = sliceDownloadFiles(files, offset, limit);
            if (files.isEmpty()) {
                return R.error("未找到日志文件");
            }
            String id = UUID.randomUUID().toString();
            ProgressInfo info = new ProgressInfo();
            info.totalCount = files.size();
            long sum = 0L;
            for (Path f : files) {
                try { sum += Files.size(f); } catch (Exception ignored) {}
            }
            info.totalRaw = sum;
            info.processedRaw = 0L;
            info.processedCount = 0;
            info.finished = false;
            DOWNLOAD_PROGRESS.put(id, info);
            Map<String, Object> res = new HashMap<>();
            res.put("progressId", id);
            res.put("totalSize", info.totalRaw);
            res.put("fileCount", info.totalCount);
            return R.ok(res);
        } catch (Exception e) {
            return R.error("初始化失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/download/progress/auth")
    @ManagerAuth
    public R progress(String id) {
        ProgressInfo info = DOWNLOAD_PROGRESS.get(id);
        if (info == null) {
            return R.error("无效进度");
        }
        long total = info.totalRaw;
        long done = info.processedRaw;
        int percent;
        if (info.finished) {
            percent = 100;
        } else if (total > 0) {
            percent = (int) Math.min(99, (done * 100L) / total);
        } else if (info.totalCount > 0) {
            percent = (int) Math.min(99, (info.processedCount * 100L) / info.totalCount);
        } else {
            percent = 0;
        }
        Map<String, Object> res = new HashMap<>();
        res.put("percent", percent);
        res.put("processedSize", done);
        res.put("totalSize", total);
        res.put("processedCount", info.processedCount);
        res.put("totalCount", info.totalCount);
        res.put("finished", info.finished);
        return R.ok(res);
    }
 
    @RequestMapping(value = "/deviceLog/system/download/init/auth")
    @ManagerAuth
    public R initSystemDownload(@org.springframework.web.bind.annotation.RequestBody com.alibaba.fastjson.JSONObject param) {
        try {
            String logType = normalizeSystemLogType(param.getString("logType"));
            if (logType == null) {
                return R.error("日志类型错误");
            }
            LocalDateTime startTime = parseSystemLogDateTime(param.getString("startTime"));
            LocalDateTime endTime = parseSystemLogDateTime(param.getString("endTime"));
            if (startTime == null || endTime == null) {
                return R.error("时间格式错误");
            }
            if (startTime.isAfter(endTime)) {
                return R.error("开始时间不能晚于结束时间");
            }
            long daySpan = java.time.temporal.ChronoUnit.DAYS.between(startTime.toLocalDate(), endTime.toLocalDate());
            if (daySpan > SYSTEM_LOG_MAX_RANGE_DAYS) {
                return R.error("时间范围不能超过" + SYSTEM_LOG_MAX_RANGE_DAYS + "天");
            }
            List<Path> files = findSystemLogFiles(logType, startTime, endTime);
            if (files.isEmpty()) {
                return R.error("未找到日志文件");
            }
            String id = UUID.randomUUID().toString();
            ProgressInfo info = new ProgressInfo();
            info.totalCount = files.size();
            long sum = 0L;
            for (Path f : files) {
                try { sum += Files.size(f); } catch (Exception ignored) {}
            }
            info.totalRaw = sum;
            info.processedRaw = 0L;
            info.processedCount = 0;
            info.finished = false;
            DOWNLOAD_PROGRESS.put(id, info);
            SystemLogDownloadRequest request = new SystemLogDownloadRequest();
            request.logType = logType;
            request.startTime = startTime;
            request.endTime = endTime;
            request.files = files;
            SYSTEM_LOG_DOWNLOAD_REQUESTS.put(id, request);
            Map<String, Object> res = new HashMap<>();
            res.put("progressId", id);
            res.put("totalSize", info.totalRaw);
            res.put("fileCount", info.totalCount);
            return R.ok(res);
        } catch (Exception e) {
            log.error("初始化系统日志下载失败", e);
            return R.error("初始化失败");
        }
    }
 
    @RequestMapping(value = "/deviceLog/system/download/auth")
    @ManagerAuth
    public void downloadSystemLog(@RequestParam("logType") String logTypeParam,
                                  @RequestParam("startTime") String startTimeParam,
                                  @RequestParam("endTime") String endTimeParam,
                                  @RequestParam(value = "progressId", required = false) String progressId,
                                  HttpServletResponse response) {
        String progressKey = null;
        try {
            String logType = normalizeSystemLogType(logTypeParam);
            LocalDateTime startTime = parseSystemLogDateTime(startTimeParam);
            LocalDateTime endTime = parseSystemLogDateTime(endTimeParam);
            if (logType == null || startTime == null || endTime == null || startTime.isAfter(endTime)) {
                response.setStatus(400);
                return;
            }
            SystemLogDownloadRequest requestInfo = null;
            if (!Cools.isEmpty(progressId)) {
                requestInfo = SYSTEM_LOG_DOWNLOAD_REQUESTS.get(progressId);
                progressKey = progressId;
            }
            List<Path> files;
            if (requestInfo != null
                    && Objects.equals(requestInfo.logType, logType)
                    && Objects.equals(requestInfo.startTime, startTime)
                    && Objects.equals(requestInfo.endTime, endTime)) {
                files = requestInfo.files == null ? Collections.emptyList() : requestInfo.files;
            } else {
                files = findSystemLogFiles(logType, startTime, endTime);
            }
            if (files.isEmpty()) {
                response.setStatus(404);
                return;
            }
            if (Cools.isEmpty(progressKey)) {
                progressKey = UUID.randomUUID().toString();
            }
            ProgressInfo info = prepareProgress(progressKey, files);
            response.reset();
            response.setContentType("application/zip");
            String filename = logType + "_" + formatSystemExportTime(startTime) + "_" + formatSystemExportTime(endTime) + ".zip";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.setHeader("X-Progress-Id", progressKey);
            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                zos.putNextEntry(new ZipEntry(SYSTEM_LOG_ENTRY_NAME));
                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos, StandardCharsets.UTF_8))) {
                    boolean written = writeSystemLogContent(files, logType, startTime, endTime, writer, info);
                    writer.flush();
                    if (!written) {
                        response.reset();
                        response.setStatus(404);
                        return;
                    }
                }
                zos.closeEntry();
                zos.finish();
                info.finished = true;
            }
        } catch (Exception e) {
            log.error("下载系统日志失败", e);
            try {
                response.reset();
                response.setStatus(500);
            } catch (Exception ignore) {
            }
        } finally {
            if (!Cools.isEmpty(progressId)) {
                SYSTEM_LOG_DOWNLOAD_REQUESTS.remove(progressId);
            }
        }
    }
 
    @RequestMapping(value = "/deviceLog/enums/auth")
    @ManagerAuth
    public R getEnums() {
        Map<String, Map<String, String>> enums = new HashMap<>();
 
        enums.put("CrnModeType", Arrays.stream(com.zy.core.enums.CrnModeType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("CrnStatusType", Arrays.stream(com.zy.core.enums.CrnStatusType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("CrnForkPosType", Arrays.stream(com.zy.core.enums.CrnForkPosType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("CrnLiftPosType", Arrays.stream(com.zy.core.enums.CrnLiftPosType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("DualCrnForkPosType", Arrays.stream(com.zy.core.enums.DualCrnForkPosType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("DualCrnLiftPosType", Arrays.stream(com.zy.core.enums.DualCrnLiftPosType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("RgvModeType", Arrays.stream(com.zy.core.enums.RgvModeType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        enums.put("RgvStatusType", Arrays.stream(com.zy.core.enums.RgvStatusType.values())
                .collect(Collectors.toMap(e -> String.valueOf(e.id), e -> e.desc)));
 
        return R.ok(enums);
    }
 
    private ProgressInfo prepareProgress(String progressId, List<Path> files) {
        return DOWNLOAD_PROGRESS.compute(progressId, (key, existing) -> {
            ProgressInfo next = existing == null ? new ProgressInfo() : existing;
            next.totalCount = files == null ? 0 : files.size();
            long total = 0L;
            if (files != null) {
                for (Path f : files) {
                    try { total += Files.size(f); } catch (Exception ignored) {}
                }
            }
            next.totalRaw = total;
            next.processedRaw = 0L;
            next.processedCount = 0;
            next.finished = false;
            return next;
        });
    }
 
    private boolean writeSystemLogContent(List<Path> files,
                                          String logType,
                                          LocalDateTime startTime,
                                          LocalDateTime endTime,
                                          BufferedWriter writer,
                                          ProgressInfo progressInfo) throws Exception {
        boolean wroteAny = false;
        for (Path file : files) {
            SystemLogFileInfo fileInfo = parseSystemLogFile(file);
            if (fileInfo == null) {
                updateProgress(progressInfo, file);
                continue;
            }
            LocalDate baseDate = fileInfo.day != null ? fileInfo.day : startTime.toLocalDate();
            try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) {
                List<String> pending = new ArrayList<>();
                boolean pendingMatched = false;
                for (Iterator<String> iterator = lines.iterator(); iterator.hasNext(); ) {
                    String line = iterator.next();
                    Matcher matcher = SYSTEM_LOG_TIMESTAMP.matcher(line == null ? "" : line);
                    if (matcher.find()) {
                        if (pendingMatched && !pending.isEmpty()) {
                            for (String pendingLine : pending) {
                                writer.write(pendingLine == null ? "" : pendingLine);
                                writer.newLine();
                            }
                            wroteAny = true;
                        }
                        pending.clear();
                        pendingMatched = isSystemLogLineInRange(baseDate, matcher.group(1), startTime, endTime);
                    }
                    if (pendingMatched) {
                        pending.add(line);
                        if (pending.size() > SYSTEM_LOG_MATCH_BUFFER_LINES) {
                            for (String pendingLine : pending) {
                                writer.write(pendingLine == null ? "" : pendingLine);
                                writer.newLine();
                            }
                            wroteAny = true;
                            pending.clear();
                        }
                    } else if (!pending.isEmpty()) {
                        pending.clear();
                    }
                }
                if (pendingMatched && !pending.isEmpty()) {
                    for (String pendingLine : pending) {
                        writer.write(pendingLine == null ? "" : pendingLine);
                        writer.newLine();
                    }
                    wroteAny = true;
                }
            }
            updateProgress(progressInfo, file);
        }
        if (progressInfo != null) {
            progressInfo.finished = true;
        }
        return wroteAny;
    }
 
    private void updateProgress(ProgressInfo progressInfo, Path file) {
        if (progressInfo == null) {
            return;
        }
        try {
            progressInfo.processedRaw += Files.size(file);
        } catch (Exception ignored) {
        }
        progressInfo.processedCount += 1;
    }
 
    private List<Path> findSystemLogFiles(String logType, LocalDateTime startTime, LocalDateTime endTime) throws Exception {
        Path baseDir = Paths.get(systemLoggingPath);
        if (!Files.exists(baseDir) || !Files.isDirectory(baseDir)) {
            return Collections.emptyList();
        }
        LocalDate startDate = startTime.toLocalDate();
        LocalDate endDate = endTime.toLocalDate();
        List<SystemLogFileInfo> matched = new ArrayList<>();
        try (Stream<Path> stream = Files.list(baseDir)) {
            stream.filter(path -> !Files.isDirectory(path)).forEach(path -> {
                SystemLogFileInfo info = parseSystemLogFile(path);
                if (info == null || !Objects.equals(info.logType, logType)) {
                    return;
                }
                if (info.active || info.day == null || (!info.day.isBefore(startDate) && !info.day.isAfter(endDate))) {
                    matched.add(info);
                }
            });
        }
        matched.sort((left, right) -> {
            LocalDate leftDay = left.day == null ? LocalDate.MAX : left.day;
            LocalDate rightDay = right.day == null ? LocalDate.MAX : right.day;
            int cmp = leftDay.compareTo(rightDay);
            if (cmp != 0) {
                return cmp;
            }
            int leftIndex = left.index == null ? Integer.MAX_VALUE : left.index;
            int rightIndex = right.index == null ? Integer.MAX_VALUE : right.index;
            if (left.active != right.active) {
                return left.active ? 1 : -1;
            }
            return Integer.compare(leftIndex, rightIndex);
        });
        return matched.stream().map(item -> item.path).collect(Collectors.toList());
    }
 
    private SystemLogFileInfo parseSystemLogFile(Path path) {
        if (path == null) {
            return null;
        }
        String name = path.getFileName().toString();
        if ("info.log".equals(name) || "error.log".equals(name)) {
            SystemLogFileInfo info = new SystemLogFileInfo();
            info.logType = name.startsWith("info") ? "info" : "error";
            info.active = true;
            info.path = path;
            return info;
        }
        Matcher matcher = SYSTEM_LOG_ROLLED_FILE.matcher(name);
        if (!matcher.matches()) {
            return null;
        }
        try {
            SystemLogFileInfo info = new SystemLogFileInfo();
            info.logType = matcher.group(1);
            info.day = LocalDate.parse(matcher.group(2), SYSTEM_LOG_DATE);
            info.index = Integer.parseInt(matcher.group(3));
            info.active = false;
            info.path = path;
            return info;
        } catch (Exception e) {
            return null;
        }
    }
 
    private String normalizeSystemLogType(String logType) {
        if (Cools.isEmpty(logType)) {
            return null;
        }
        String value = logType.trim().toLowerCase(Locale.ROOT);
        if ("info".equals(value) || "error".equals(value)) {
            return value;
        }
        return null;
    }
 
    private LocalDateTime parseSystemLogDateTime(String value) {
        if (Cools.isEmpty(value)) {
            return null;
        }
        try {
            return LocalDateTime.parse(value.trim(), SYSTEM_LOG_DATE_TIME);
        } catch (DateTimeParseException e) {
            return null;
        }
    }
 
    private boolean isSystemLogLineInRange(LocalDate baseDate,
                                           String timePart,
                                           LocalDateTime startTime,
                                           LocalDateTime endTime) {
        if (baseDate == null || Cools.isEmpty(timePart) || startTime == null || endTime == null) {
            return false;
        }
        try {
            LocalTime time = LocalTime.parse(timePart);
            LocalDateTime timestamp = LocalDateTime.of(baseDate, time);
            return !timestamp.isBefore(startTime) && !timestamp.isAfter(endTime);
        } catch (DateTimeParseException e) {
            return false;
        }
    }
 
    private String formatSystemExportTime(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "unknown";
        }
        return SYSTEM_LOG_EXPORT_TIME.format(dateTime);
    }
 
 
    private Map<String, Object> buildEmptySummary() {
        return buildSummaryResponse(Collections.emptyList());
    }
 
    private Map<String, Object> buildSummaryResponse(Collection<DeviceAggregate> aggregates) {
        List<DeviceAggregate> aggregateList = new ArrayList<>(aggregates);
        Map<String, Object> stats = new LinkedHashMap<>();
        Map<String, Object> typeCounts = new LinkedHashMap<>();
        int totalFiles = 0;
        for (String type : DEVICE_TYPE_ORDER) {
            int count = (int) aggregateList.stream().filter(item -> type.equals(item.type)).count();
            typeCounts.put(type, count);
        }
        for (DeviceAggregate aggregate : aggregateList) {
            totalFiles += aggregate.fileCount;
        }
        stats.put("totalDevices", aggregateList.size());
        stats.put("totalFiles", totalFiles);
        stats.put("typeCounts", typeCounts);
 
        List<Map<String, Object>> groups = new ArrayList<>();
        for (String type : DEVICE_TYPE_ORDER) {
            List<DeviceAggregate> devices = aggregateList.stream()
                    .filter(item -> type.equals(item.type))
                    .sorted(Comparator.comparingInt(item -> parseDeviceNo(item.deviceNo)))
                    .collect(Collectors.toList());
            Map<String, Object> group = new LinkedHashMap<>();
            group.put("type", type);
            group.put("typeLabel", DEVICE_TYPE_LABELS.get(type));
            group.put("deviceCount", devices.size());
            group.put("totalFiles", devices.stream().mapToInt(item -> item.fileCount).sum());
            group.put("devices", devices.stream().map(item -> {
                Map<String, Object> x = new LinkedHashMap<>();
                x.put("type", item.type);
                x.put("typeLabel", item.typeLabel);
                x.put("deviceNo", item.deviceNo);
                x.put("stationId", item.stationId);
                x.put("fileCount", item.fileCount);
                x.put("firstTime", item.firstTime);
                x.put("lastTime", item.lastTime);
                x.put("stationIds", item.stationIds == null ? Collections.emptyList() : item.stationIds);
                return x;
            }).collect(Collectors.toList()));
            groups.add(group);
        }
 
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("stats", stats);
        result.put("groups", groups);
        return result;
    }
 
    private void enrichDevpStationIds(Collection<DeviceAggregate> aggregates) {
        if (aggregates == null || aggregates.isEmpty() || basDevpService == null) {
            return;
        }
        List<DeviceAggregate> devpAggregates = aggregates.stream()
                .filter(item -> item != null && isDevpType(item.type) && Cools.isEmpty(item.stationId) && !Cools.isEmpty(item.deviceNo))
                .collect(Collectors.toList());
        if (devpAggregates.isEmpty()) {
            return;
        }
        List<Integer> devpNos = devpAggregates.stream()
                .map(item -> parseInteger(item.deviceNo))
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        if (devpNos.isEmpty()) {
            return;
        }
        Map<Integer, List<String>> stationIdsByDevpNo = basDevpService.listByIds(devpNos).stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(BasDevp::getDevpNo, this::extractStationIds, (left, right) -> left));
        for (DeviceAggregate aggregate : devpAggregates) {
            Integer devpNo = parseInteger(aggregate.deviceNo);
            if (devpNo != null) {
                aggregate.stationIds = stationIdsByDevpNo.getOrDefault(devpNo, Collections.emptyList());
            }
        }
    }
 
    private List<String> extractStationIds(BasDevp basDevp) {
        if (basDevp == null) {
            return Collections.emptyList();
        }
        return basDevp.getStationList$().stream()
                .map(StationObjModel::getStationId)
                .filter(Objects::nonNull)
                .map(String::valueOf)
                .distinct()
                .sorted(Comparator.comparingInt(this::parseDeviceNo))
                .collect(Collectors.toList());
    }
 
    private Integer parseInteger(String value) {
        try {
            return Integer.parseInt(String.valueOf(value));
        } catch (Exception e) {
            return null;
        }
    }
 
    private String normalizeDay(String day) {
        String dayClean = day == null ? null : day.replaceAll("\\D", "");
        if (dayClean == null || dayClean.length() != 8 || !dayClean.chars().allMatch(Character::isDigit)) {
            return null;
        }
        return dayClean;
    }
 
    private List<Path> findDeviceFiles(Path dayDir, String dayClean, String type, String deviceNo, String stationId) throws Exception {
        FileNameInfo target = new FileNameInfo();
        target.type = type;
        target.deviceNo = deviceNo;
        target.stationId = stationId;
        target.day = dayClean;
        Path deviceDir = resolveDeviceDir(dayDir, type, deviceNo);
        if (deviceDir == null || !Files.exists(deviceDir) || !Files.isDirectory(deviceDir)) {
            return Collections.emptyList();
        }
        List<Path> files;
        try (Stream<Path> stream = Files.list(deviceDir)) {
            files = stream
                    .filter(p -> !Files.isDirectory(p) && matchesFileInfo(parseFileName(p.getFileName().toString()), target))
                    .collect(Collectors.toList());
        }
        files.sort(Comparator.comparingInt(p -> {
            FileNameInfo info = parseFileName(p.getFileName().toString());
            return info == null ? Integer.MAX_VALUE : info.index;
        }));
        return files;
    }
 
    private List<Path> listDayLogFiles(Path dayDir) throws Exception {
        if (dayDir == null || !Files.exists(dayDir) || !Files.isDirectory(dayDir)) {
            return Collections.emptyList();
        }
        List<Path> files = new ArrayList<>();
        try (Stream<Path> typeStream = Files.list(dayDir)) {
            List<Path> typeDirs = typeStream.filter(Files::isDirectory).collect(Collectors.toList());
            for (Path typeDir : typeDirs) {
                try (Stream<Path> deviceStream = Files.list(typeDir)) {
                    List<Path> deviceDirs = deviceStream.filter(Files::isDirectory).collect(Collectors.toList());
                    for (Path deviceDir : deviceDirs) {
                        try (Stream<Path> fileStream = Files.list(deviceDir)) {
                            fileStream
                                    .filter(p -> !Files.isDirectory(p) && p.getFileName().toString().endsWith(".log"))
                                    .forEach(files::add);
                        }
                    }
                }
            }
        }
        return files;
    }
 
    private Path resolveDeviceDir(Path dayDir, String type, String deviceNo) {
        if (dayDir == null || Cools.isEmpty(type) || Cools.isEmpty(deviceNo)) {
            return null;
        }
        return dayDir.resolve(type).resolve(deviceNo);
    }
 
    private List<Path> sliceDownloadFiles(List<Path> files, Integer offset, Integer limit) {
        if (files == null || files.isEmpty()) {
            return Collections.emptyList();
        }
        int from = offset == null || offset < 0 ? 0 : offset;
        if (from >= files.size()) {
            return Collections.emptyList();
        }
        if (offset == null && limit == null) {
            return new ArrayList<>(files);
        }
        int to;
        if (limit == null || limit <= 0) {
            to = files.size();
        } else {
            to = Math.min(files.size(), from + limit);
        }
        return new ArrayList<>(files.subList(from, to));
    }
 
    private FileNameInfo parseFileName(String fileName) {
        if (fileName == null || !fileName.endsWith(".log")) {
            return null;
        }
        String fileNameNoExt = fileName.substring(0, fileName.length() - 4);
        String[] parts = fileNameNoExt.split("_");
        if (parts.length < 4) {
            return null;
        }
        FileNameInfo info = new FileNameInfo();
        info.type = parts[0];
        info.deviceNo = parts[1];
        if (isDevpType(info.type)) {
            if (parts.length != 6 || !"station".equals(parts[2])) {
                return null;
            }
            info.stationId = parts[3];
            info.day = parts[4];
            try {
                info.index = Integer.parseInt(parts[5]);
            } catch (Exception e) {
                return null;
            }
            return info;
        }
        if (parts.length != 4) {
            return null;
        }
        info.day = parts[2];
        try {
            info.index = Integer.parseInt(parts[3]);
        } catch (Exception e) {
            return null;
        }
        return info;
    }
 
    private String buildDeviceKey(String type, String deviceNo, String stationId) {
        StringBuilder builder = new StringBuilder();
        builder.append(String.valueOf(type)).append(":").append(String.valueOf(deviceNo));
        if (isDevpType(type)) {
            builder.append(":").append(String.valueOf(stationId));
        }
        return builder.toString();
    }
 
    private boolean matchesFileInfo(FileNameInfo actual, FileNameInfo target) {
        if (actual == null || target == null) {
            return false;
        }
        if (!Objects.equals(actual.type, target.type)) {
            return false;
        }
        if (!Objects.equals(actual.deviceNo, target.deviceNo)) {
            return false;
        }
        if (!Objects.equals(actual.day, target.day)) {
            return false;
        }
        if (isDevpType(actual.type)) {
            return Objects.equals(actual.stationId, target.stationId);
        }
        return true;
    }
 
    private boolean isDevpType(String type) {
        return SlaveType.Devp.name().equals(type);
    }
 
    private int parseDeviceNo(String deviceNo) {
        try {
            return Integer.parseInt(String.valueOf(deviceNo));
        } catch (Exception e) {
            return Integer.MAX_VALUE;
        }
    }
 
    private FileTimeRange readFileTimeRange(Path file, String stationId) {
        FileTimeRange range = new FileTimeRange();
        try {
            String firstLine = readFirstMatchingLine(file, stationId);
            String lastLine = readLastMatchingLine(file, stationId);
            range.startTime = parseLogTime(firstLine, stationId);
            range.endTime = parseLogTime(lastLine, stationId);
            return range;
        } catch (Exception e) {
            return range;
        }
    }
 
    private Long parseLogTime(String line, String stationId) {
        try {
            if (line == null || line.trim().isEmpty()) {
                return null;
            }
            DeviceDataLog logItem = JSON.parseObject(line, DeviceDataLog.class);
            if (!matchesRequestedStation(logItem, stationId)) {
                return null;
            }
            return logItem != null && logItem.getCreateTime() != null ? logItem.getCreateTime().getTime() : null;
        } catch (Exception e) {
            return null;
        }
    }
 
    private boolean matchesRequestedStation(DeviceDataLog logItem, String stationId) {
        if (Cools.isEmpty(stationId)) {
            return true;
        }
        if (logItem == null || logItem.getStationId() == null) {
            return false;
        }
        return Objects.equals(String.valueOf(logItem.getStationId()), stationId);
    }
 
    private String readFirstMatchingLine(Path file, String stationId) {
        try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) {
            return lines
                    .filter(line -> line != null && !line.trim().isEmpty())
                    .filter(line -> matchesRequestedStation(parseLogLine(line), stationId))
                    .findFirst()
                    .orElse(null);
        } catch (Exception e) {
            return null;
        }
    }
 
    private String readLastMatchingLine(Path file, String stationId) {
        try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) {
            List<String> matched = lines
                    .filter(line -> line != null && !line.trim().isEmpty())
                    .filter(line -> matchesRequestedStation(parseLogLine(line), stationId))
                    .collect(Collectors.toList());
            if (matched.isEmpty()) {
                return null;
            }
            return matched.get(matched.size() - 1);
        } catch (Exception e) {
            return null;
        }
    }
 
    private DeviceDataLog parseLogLine(String line) {
        try {
            if (line == null || line.trim().isEmpty()) {
                return null;
            }
            return JSON.parseObject(line, DeviceDataLog.class);
        } catch (Exception e) {
            return null;
        }
    }
}