#
Junjie
1 天以前 e4271d60003223566b67d141e4d330b8bb4d7162
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
package com.zy.core.trace;
 
import com.alibaba.fastjson.JSON;
import com.zy.asrs.domain.vo.StationTaskTraceEventVo;
import com.zy.asrs.domain.vo.StationTaskTraceSegmentVo;
import com.zy.asrs.domain.vo.StationTaskTraceVo;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.service.WrkMastService;
import com.zy.common.utils.RedisUtil;
import com.zy.core.enums.WrkStsType;
import com.zy.core.model.command.StationCommand;
import com.zy.core.enums.RedisKeyType;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
 
@Component
public class StationTaskTraceRegistry {
 
    private static final int MAX_EVENT_COUNT = 200;
    private static final long TERMINAL_KEEP_MS = 30L * 60L * 1000L;
    private static final String TRACE_CACHE_KEY = RedisKeyType.STATION_TASK_TRACE_REGISTRY.key;
 
    public static final String STATUS_WAITING = "WAITING";
    public static final String STATUS_RUNNING = "RUNNING";
    public static final String STATUS_BLOCKED = "BLOCKED";
    public static final String STATUS_CANCELLED = "CANCELLED";
    public static final String STATUS_TIMEOUT = "TIMEOUT";
    public static final String STATUS_FINISHED = "FINISHED";
    public static final String STATUS_REROUTED = "REROUTED";
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Autowired
    private WrkMastService wrkMastService;
 
    private final Map<Integer, TraceTaskState> taskStateMap = new ConcurrentHashMap<>();
    private volatile boolean loadedFromRedis = false;
 
    public TraceRegistration registerPlan(Integer taskNo,
                                          String threadImpl,
                                          Integer startStationId,
                                          Integer currentStationId,
                                          Integer finalTargetStationId,
                                          List<Integer> localPathStationIds,
                                          List<StationTaskTraceSegmentVo> localSegmentList) {
        if (taskNo == null || taskNo <= 0) {
            return new TraceRegistration();
        }
 
        ensureCacheLoaded();
        cleanupExpired();
        TraceTaskState taskState = taskStateMap.computeIfAbsent(taskNo, TraceTaskState::new);
        TraceRegistration registration = taskState.registerPlan(threadImpl, startStationId, currentStationId, finalTargetStationId,
                copyIntegerList(localPathStationIds), copySegmentList(localSegmentList));
        persistState(taskState);
        return registration;
    }
 
    public void markSegmentIssued(Integer taskNo,
                                  Integer traceVersion,
                                  StationCommand command,
                                  String eventType,
                                  String message,
                                  Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.markSegmentIssued(traceVersion, command, eventType, message, details);
        persistState(state);
    }
 
    public void updateProgress(Integer taskNo,
                               Integer traceVersion,
                               Integer currentStationId,
                               String eventType,
                               String message,
                               Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.updateProgress(traceVersion, currentStationId, eventType, message, details);
        persistState(state);
    }
 
    public void markBlocked(Integer taskNo,
                            Integer traceVersion,
                            Integer currentStationId,
                            Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.markTerminal(traceVersion, STATUS_BLOCKED, currentStationId, currentStationId,
                "BLOCKED", "输送任务运行堵塞", details);
        persistState(state);
    }
 
    public void markCancelled(Integer taskNo,
                              Integer traceVersion,
                              Integer currentStationId,
                              Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.markTerminal(traceVersion, STATUS_CANCELLED, currentStationId, null,
                "CANCELLED", "输送任务收到取消信号", details);
        persistState(state);
    }
 
    public void markTimeout(Integer taskNo,
                            Integer traceVersion,
                            Integer currentStationId,
                            Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.markTerminal(traceVersion, STATUS_TIMEOUT, currentStationId, null,
                "TIMEOUT", "输送任务长时间无法定位当前位置", details);
        persistState(state);
    }
 
    public void markFinished(Integer taskNo,
                             Integer traceVersion,
                             Integer currentStationId,
                             Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.markTerminal(traceVersion, STATUS_FINISHED, currentStationId, null,
                "FINISHED", "输送任务轨迹完成", details);
        persistState(state);
    }
 
    public void updateLoopHint(Integer taskNo,
                               Boolean loopAlertActive,
                               String loopAlertType,
                               String loopAlertText,
                               Integer loopAlertCount,
                               Map<String, Object> details) {
        ensureCacheLoaded();
        TraceTaskState state = taskStateMap.get(taskNo);
        if (state == null) {
            return;
        }
        state.updateLoopHint(loopAlertActive, loopAlertType, loopAlertText, loopAlertCount, details);
        persistState(state);
    }
 
    public List<StationTaskTraceVo> listLatestTraces() {
        ensureCacheLoaded();
        cleanupExpired();
        reconcileInactiveBusinessTasks();
        List<StationTaskTraceVo> result = new ArrayList<>();
        for (TraceTaskState state : taskStateMap.values()) {
            if (state != null) {
                result.add(state.toVo());
            }
        }
        result.sort(new Comparator<StationTaskTraceVo>() {
            @Override
            public int compare(StationTaskTraceVo a, StationTaskTraceVo b) {
                long av = a.getUpdatedAt() == null ? 0L : a.getUpdatedAt();
                long bv = b.getUpdatedAt() == null ? 0L : b.getUpdatedAt();
                return Long.compare(bv, av);
            }
        });
        return result;
    }
 
    public List<StationTaskTraceVo> listActiveTraces() {
        List<StationTaskTraceVo> latestTraces = listLatestTraces();
        List<StationTaskTraceVo> result = new ArrayList<>();
        for (StationTaskTraceVo traceVo : latestTraces) {
            if (traceVo == null) {
                continue;
            }
            String status = traceVo.getStatus();
            if (STATUS_WAITING.equals(status)
                    || STATUS_RUNNING.equals(status)
                    || STATUS_REROUTED.equals(status)) {
                result.add(traceVo);
            }
        }
        return result;
    }
 
    private void cleanupExpired() {
        long now = System.currentTimeMillis();
        for (Map.Entry<Integer, TraceTaskState> entry : taskStateMap.entrySet()) {
            TraceTaskState state = entry.getValue();
            if (state != null && state.shouldRemove(now)) {
                taskStateMap.remove(entry.getKey(), state);
                removePersistedState(entry.getKey());
            }
        }
    }
 
    private void reconcileInactiveBusinessTasks() {
        if (wrkMastService == null) {
            return;
        }
        for (TraceTaskState state : taskStateMap.values()) {
            if (state == null || state.isTerminal()) {
                continue;
            }
            WrkMast wrkMast;
            try {
                wrkMast = wrkMastService.selectByWorkNo(state.taskNo);
            } catch (Exception ignore) {
                continue;
            }
            if (wrkMast == null) {
                Integer currentStationId = state.currentStationId != null ? state.currentStationId : state.finalTargetStationId;
                Map<String, Object> details = new LinkedHashMap<>();
                details.put("reason", "wrk_missing");
                state.markTerminal(state.traceVersion, STATUS_FINISHED, currentStationId, null,
                        "AUTO_FINISHED", "输送任务档已不存在,轨迹自动结束", details);
                persistState(state);
                continue;
            }
            if (isStationTraceActiveWrkStatus(wrkMast.getWrkSts())) {
                continue;
            }
            Integer currentStationId = state.currentStationId != null ? state.currentStationId : state.finalTargetStationId;
            Map<String, Object> details = new LinkedHashMap<>();
            details.put("reason", "wrk_status_transition");
            details.put("wrkSts", wrkMast.getWrkSts());
            details.put("wrkStsDesc", wrkMast.getWrkSts$());
            if (isManualWrkStatus(wrkMast.getWrkSts())) {
                state.markTerminal(state.traceVersion, STATUS_CANCELLED, currentStationId, null,
                        "AUTO_CANCELLED", "输送任务已退出运行,轨迹自动结束", details);
            } else {
                state.markTerminal(state.traceVersion, STATUS_FINISHED, currentStationId, null,
                        "AUTO_FINISHED", "输送任务已结束,轨迹自动结束", details);
            }
            persistState(state);
        }
    }
 
    private boolean isStationTraceActiveWrkStatus(Long wrkSts) {
        return Objects.equals(wrkSts, WrkStsType.INBOUND_DEVICE_RUN.sts)
                || Objects.equals(wrkSts, WrkStsType.STATION_RUN.sts);
    }
 
    private boolean isManualWrkStatus(Long wrkSts) {
        return Objects.equals(wrkSts, WrkStsType.INBOUND_MANUAL.sts)
                || Objects.equals(wrkSts, WrkStsType.OUTBOUND_MANUAL.sts)
                || Objects.equals(wrkSts, WrkStsType.LOC_MOVE_MANUAL.sts);
    }
 
    private void ensureCacheLoaded() {
        if (loadedFromRedis) {
            return;
        }
        synchronized (this) {
            if (loadedFromRedis) {
                return;
            }
            Map<Object, Object> cacheMap = redisUtil == null ? null : redisUtil.hmget(TRACE_CACHE_KEY);
            if (cacheMap != null && !cacheMap.isEmpty()) {
                long now = System.currentTimeMillis();
                for (Map.Entry<Object, Object> entry : cacheMap.entrySet()) {
                    Integer taskNo = parseTaskNo(entry.getKey());
                    TraceSnapshot snapshot = parseSnapshot(entry.getValue(), taskNo);
                    if (snapshot == null || snapshot.getTaskNo() == null) {
                        if (taskNo != null) {
                            removePersistedState(taskNo);
                        }
                        continue;
                    }
                    if (snapshot.isExpired(now)) {
                        removePersistedState(snapshot.getTaskNo());
                        continue;
                    }
                    taskStateMap.put(snapshot.getTaskNo(), TraceTaskState.fromSnapshot(snapshot));
                }
            }
            loadedFromRedis = true;
        }
    }
 
    private void persistState(TraceTaskState state) {
        if (state == null || state.taskNo == null || redisUtil == null) {
            return;
        }
        redisUtil.hset(TRACE_CACHE_KEY, String.valueOf(state.taskNo), JSON.toJSONString(state.toSnapshot()));
    }
 
    private void removePersistedState(Integer taskNo) {
        if (taskNo == null || redisUtil == null) {
            return;
        }
        redisUtil.hdel(TRACE_CACHE_KEY, String.valueOf(taskNo));
    }
 
    private Integer parseTaskNo(Object value) {
        if (value == null) {
            return null;
        }
        try {
            return Integer.parseInt(String.valueOf(value));
        } catch (Exception e) {
            return null;
        }
    }
 
    private TraceSnapshot parseSnapshot(Object cacheValue, Integer fallbackTaskNo) {
        if (cacheValue == null) {
            return null;
        }
        try {
            TraceSnapshot snapshot = JSON.parseObject(String.valueOf(cacheValue), TraceSnapshot.class);
            if (snapshot != null && snapshot.getTaskNo() == null) {
                snapshot.setTaskNo(fallbackTaskNo);
            }
            return snapshot;
        } catch (Exception e) {
            return null;
        }
    }
 
    private static List<Integer> copyIntegerList(List<Integer> source) {
        List<Integer> result = new ArrayList<>();
        if (source == null) {
            return result;
        }
        for (Integer item : source) {
            if (item != null) {
                result.add(item);
            }
        }
        return result;
    }
 
    private static List<StationTaskTraceSegmentVo> copySegmentList(List<StationTaskTraceSegmentVo> source) {
        List<StationTaskTraceSegmentVo> result = new ArrayList<>();
        if (source == null) {
            return result;
        }
        for (StationTaskTraceSegmentVo item : source) {
            if (item == null) {
                continue;
            }
            StationTaskTraceSegmentVo copy = new StationTaskTraceSegmentVo();
            copy.setSegmentNo(item.getSegmentNo());
            copy.setSegmentCount(item.getSegmentCount());
            copy.setStationId(item.getStationId());
            copy.setTargetStationId(item.getTargetStationId());
            copy.setSegmentStartIndex(item.getSegmentStartIndex());
            copy.setSegmentEndIndex(item.getSegmentEndIndex());
            copy.setSegmentPath(copyIntegerList(item.getSegmentPath()));
            copy.setIssued(Boolean.TRUE.equals(item.getIssued()));
            result.add(copy);
        }
        return result;
    }
 
    private static Map<String, Object> copyDetails(Map<String, Object> source) {
        Map<String, Object> result = new LinkedHashMap<>();
        if (source == null || source.isEmpty()) {
            return result;
        }
        for (Map.Entry<String, Object> entry : source.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List) {
                result.put(entry.getKey(), new ArrayList<>((List<?>) value));
            } else if (value instanceof Map) {
                result.put(entry.getKey(), new LinkedHashMap<>((Map<?, ?>) value));
            } else {
                result.put(entry.getKey(), value);
            }
        }
        return result;
    }
 
    private static List<StationTaskTraceEventVo> copyEventList(List<StationTaskTraceEventVo> source) {
        List<StationTaskTraceEventVo> result = new ArrayList<>();
        if (source == null) {
            return result;
        }
        for (StationTaskTraceEventVo item : source) {
            if (item == null) {
                continue;
            }
            StationTaskTraceEventVo copy = new StationTaskTraceEventVo();
            copy.setTimestamp(item.getTimestamp());
            copy.setEventType(item.getEventType());
            copy.setMessage(item.getMessage());
            copy.setStatus(item.getStatus());
            copy.setCurrentStationId(item.getCurrentStationId());
            copy.setTargetStationId(item.getTargetStationId());
            copy.setTraceVersion(item.getTraceVersion());
            copy.setDetails(copyDetails(item.getDetails()));
            result.add(copy);
        }
        return result;
    }
 
    private static boolean isTerminalStatus(String status) {
        return STATUS_BLOCKED.equals(status)
                || STATUS_CANCELLED.equals(status)
                || STATUS_TIMEOUT.equals(status)
                || STATUS_FINISHED.equals(status);
    }
 
    @Data
    public static class TraceRegistration {
        private Integer traceVersion;
        private Integer pathOffset;
        private List<Integer> fullPathStationIds = new ArrayList<>();
        private boolean rerouted;
    }
 
    @Data
    private static class TraceSnapshot {
        private Integer taskNo;
        private String threadImpl;
        private String status;
        private Integer traceVersion;
        private Integer startStationId;
        private Integer currentStationId;
        private Integer finalTargetStationId;
        private Integer blockedStationId;
        private List<Integer> fullPathStationIds = new ArrayList<>();
        private List<Integer> issuedStationIds = new ArrayList<>();
        private List<Integer> passedStationIds = new ArrayList<>();
        private List<Integer> pendingStationIds = new ArrayList<>();
        private List<Integer> latestIssuedSegmentPath = new ArrayList<>();
        private List<StationTaskTraceSegmentVo> segmentList = new ArrayList<>();
        private Integer issuedSegmentCount;
        private Integer totalSegmentCount;
        private Boolean loopAlertActive;
        private String loopAlertType;
        private String loopAlertText;
        private Integer loopAlertCount;
        private Long updatedAt;
        private Long terminalExpireAt;
        private List<StationTaskTraceEventVo> events = new ArrayList<>();
 
        private boolean isExpired(long now) {
            return terminalExpireAt != null && terminalExpireAt <= now;
        }
    }
 
    private static class TraceTaskState {
 
        private final Integer taskNo;
        private String threadImpl;
        private String status = STATUS_WAITING;
        private Integer traceVersion = 0;
        private Integer startStationId;
        private Integer currentStationId;
        private Integer finalTargetStationId;
        private Integer blockedStationId;
        private List<Integer> fullPathStationIds = new ArrayList<>();
        private List<Integer> issuedStationIds = new ArrayList<>();
        private List<Integer> passedStationIds = new ArrayList<>();
        private List<Integer> pendingStationIds = new ArrayList<>();
        private List<Integer> latestIssuedSegmentPath = new ArrayList<>();
        private List<StationTaskTraceSegmentVo> segmentList = new ArrayList<>();
        private Integer issuedSegmentCount = 0;
        private Integer totalSegmentCount = 0;
        private Boolean loopAlertActive = Boolean.FALSE;
        private String loopAlertType;
        private String loopAlertText;
        private Integer loopAlertCount;
        private final List<StationTaskTraceEventVo> events = new ArrayList<>();
        private Long updatedAt = System.currentTimeMillis();
        private Long terminalExpireAt;
 
        private TraceTaskState(Integer taskNo) {
            this.taskNo = taskNo;
        }
 
        private synchronized TraceRegistration registerPlan(String threadImpl,
                                                            Integer startStationId,
                                                            Integer currentStationId,
                                                            Integer finalTargetStationId,
                                                            List<Integer> localPathStationIds,
                                                            List<StationTaskTraceSegmentVo> localSegmentList) {
            TraceRegistration registration = new TraceRegistration();
            boolean firstPlan = this.traceVersion == null || this.traceVersion <= 0;
            boolean rerouted = !isTerminalStatus(this.status) && this.traceVersion != null && this.traceVersion > 0;
            int nextTraceVersion = rerouted ? this.traceVersion + 1 : 1;
            int pathOffset = rerouted ? this.passedStationIds.size() : 0;
            Integer planCurrentStationId = currentStationId != null ? currentStationId : startStationId;
            List<Integer> nextFullPath = buildFullPathForRegistration(rerouted, planCurrentStationId, localPathStationIds);
            List<StationTaskTraceSegmentVo> nextSegmentList = shiftSegments(copySegmentList(localSegmentList), pathOffset);
 
            this.threadImpl = threadImpl;
            this.traceVersion = nextTraceVersion;
            this.startStationId = rerouted && this.startStationId != null ? this.startStationId : startStationId;
            this.currentStationId = planCurrentStationId;
            this.finalTargetStationId = finalTargetStationId;
            this.blockedStationId = null;
            this.fullPathStationIds = nextFullPath;
            this.segmentList = nextSegmentList;
            this.issuedSegmentCount = 0;
            this.totalSegmentCount = nextSegmentList.size();
            this.issuedStationIds = new ArrayList<>();
            this.latestIssuedSegmentPath = new ArrayList<>();
            this.status = rerouted ? STATUS_REROUTED : STATUS_WAITING;
            this.terminalExpireAt = null;
            if (firstPlan) {
                clearLoopHintState();
            }
            rebuildProgress(planCurrentStationId);
            this.updatedAt = System.currentTimeMillis();
 
            Map<String, Object> details = new LinkedHashMap<>();
            details.put("traceVersion", nextTraceVersion);
            details.put("fullPathStationIds", copyIntegerList(this.fullPathStationIds));
            details.put("segmentCount", this.totalSegmentCount);
            details.put("pathOffset", pathOffset);
            details.put("currentStationId", this.currentStationId);
            appendLoopHintDetails(details);
            appendEvent(rerouted ? "REROUTED" : "PLAN_READY",
                    rerouted ? "输送任务路径已重算并续接轨迹" : "输送任务分段计划已建立",
                    details);
 
            registration.setTraceVersion(nextTraceVersion);
            registration.setPathOffset(pathOffset);
            registration.setFullPathStationIds(copyIntegerList(this.fullPathStationIds));
            registration.setRerouted(rerouted);
            return registration;
        }
 
        private synchronized void markSegmentIssued(Integer traceVersion,
                                                    StationCommand command,
                                                    String eventType,
                                                    String message,
                                                    Map<String, Object> details) {
            if (!acceptTraceVersion(traceVersion)) {
                return;
            }
            this.status = STATUS_RUNNING;
            this.blockedStationId = null;
            int currentIssued = this.issuedSegmentCount == null ? 0 : this.issuedSegmentCount;
            int nextIssued = command == null || command.getSegmentNo() == null ? currentIssued : command.getSegmentNo();
            this.issuedSegmentCount = Math.max(currentIssued, nextIssued);
            this.latestIssuedSegmentPath = copyIntegerList(command == null ? null : command.getNavigatePath());
            int segmentEndIndex = command == null || command.getSegmentEndIndex() == null ? -1 : command.getSegmentEndIndex();
            if (segmentEndIndex >= 0 && !this.fullPathStationIds.isEmpty()) {
                int end = Math.min(segmentEndIndex + 1, this.fullPathStationIds.size());
                this.issuedStationIds = copyIntegerList(this.fullPathStationIds.subList(0, end));
            }
            this.updatedAt = System.currentTimeMillis();
 
            Map<String, Object> nextDetails = copyDetails(details);
            if (command != null) {
                nextDetails.put("segmentNo", command.getSegmentNo());
                nextDetails.put("segmentCount", command.getSegmentCount());
                nextDetails.put("commandStationId", command.getStationId());
                nextDetails.put("commandTargetStationId", command.getTargetStaNo());
                nextDetails.put("segmentPath", copyIntegerList(command.getNavigatePath()));
                nextDetails.put("issuedSegmentCount", this.issuedSegmentCount);
                nextDetails.put("totalSegmentCount", this.totalSegmentCount);
            }
            appendEvent(eventType, message, nextDetails);
        }
 
        private synchronized void updateProgress(Integer traceVersion,
                                                 Integer currentStationId,
                                                 String eventType,
                                                 String message,
                                                 Map<String, Object> details) {
            if (!acceptTraceVersion(traceVersion)) {
                return;
            }
            boolean changed = !Objects.equals(this.currentStationId, currentStationId);
            rebuildProgress(currentStationId);
            if (!isTerminalStatus(this.status)) {
                this.status = STATUS_RUNNING;
                this.blockedStationId = null;
            }
            this.updatedAt = System.currentTimeMillis();
            if (changed && eventType != null) {
                Map<String, Object> nextDetails = copyDetails(details);
                nextDetails.put("currentStationId", currentStationId);
                nextDetails.put("passedStationIds", copyIntegerList(this.passedStationIds));
                nextDetails.put("pendingStationIds", copyIntegerList(this.pendingStationIds));
                appendEvent(eventType, message, nextDetails);
            }
        }
 
        private synchronized void markTerminal(Integer traceVersion,
                                               String terminalStatus,
                                               Integer currentStationId,
                                               Integer blockedStationId,
                                               String eventType,
                                               String message,
                                               Map<String, Object> details) {
            if (!acceptTraceVersion(traceVersion)) {
                return;
            }
            if (currentStationId != null) {
                rebuildProgress(currentStationId);
            }
            this.status = terminalStatus;
            this.blockedStationId = blockedStationId;
            if (shouldClearPathOnTerminal(terminalStatus)) {
                clearPathState();
            }
            this.updatedAt = System.currentTimeMillis();
            this.terminalExpireAt = this.updatedAt + TERMINAL_KEEP_MS;
 
            Map<String, Object> nextDetails = copyDetails(details);
            nextDetails.put("currentStationId", this.currentStationId);
            nextDetails.put("blockedStationId", this.blockedStationId);
            nextDetails.put("passedStationIds", copyIntegerList(this.passedStationIds));
            nextDetails.put("pendingStationIds", copyIntegerList(this.pendingStationIds));
            appendEvent(eventType, message, nextDetails);
        }
 
        private synchronized void updateLoopHint(Boolean loopAlertActive,
                                                 String loopAlertType,
                                                 String loopAlertText,
                                                 Integer loopAlertCount,
                                                 Map<String, Object> details) {
            boolean active = Boolean.TRUE.equals(loopAlertActive)
                    && loopAlertCount != null
                    && loopAlertCount > 1
                    && loopAlertText != null
                    && !loopAlertText.trim().isEmpty();
            String nextType = active ? loopAlertType : null;
            String nextText = active ? loopAlertText.trim() : null;
            Integer nextCount = active ? loopAlertCount : null;
            boolean changed = !Objects.equals(this.loopAlertActive, active)
                    || !Objects.equals(this.loopAlertType, nextType)
                    || !Objects.equals(this.loopAlertText, nextText)
                    || !Objects.equals(this.loopAlertCount, nextCount);
            if (!changed) {
                return;
            }
 
            this.loopAlertActive = active;
            this.loopAlertType = nextType;
            this.loopAlertText = nextText;
            this.loopAlertCount = nextCount;
            this.updatedAt = System.currentTimeMillis();
            if (!active) {
                return;
            }
 
            Map<String, Object> nextDetails = copyDetails(details);
            nextDetails.put("loopAlertActive", Boolean.TRUE);
            nextDetails.put("loopAlertType", this.loopAlertType);
            nextDetails.put("loopAlertText", this.loopAlertText);
            nextDetails.put("loopAlertCount", this.loopAlertCount);
            appendEvent("LOOP_REPEAT_ALERT", this.loopAlertText, nextDetails);
        }
 
        private void clearPathState() {
            this.fullPathStationIds = new ArrayList<>();
            this.issuedStationIds = new ArrayList<>();
            this.passedStationIds = new ArrayList<>();
            this.pendingStationIds = new ArrayList<>();
            this.latestIssuedSegmentPath = new ArrayList<>();
            this.segmentList = new ArrayList<>();
            this.issuedSegmentCount = 0;
            this.totalSegmentCount = 0;
        }
 
        private boolean shouldClearPathOnTerminal(String terminalStatus) {
            return STATUS_BLOCKED.equals(terminalStatus)
                    || STATUS_CANCELLED.equals(terminalStatus);
        }
 
        private synchronized boolean shouldRemove(long now) {
            return terminalExpireAt != null && terminalExpireAt <= now;
        }
 
        private synchronized boolean isTerminal() {
            return isTerminalStatus(this.status);
        }
 
        private synchronized StationTaskTraceVo toVo() {
            StationTaskTraceVo vo = new StationTaskTraceVo();
            vo.setTaskNo(taskNo);
            vo.setThreadImpl(threadImpl);
            vo.setStatus(status);
            vo.setTraceVersion(traceVersion);
            vo.setStartStationId(startStationId);
            vo.setCurrentStationId(currentStationId);
            vo.setFinalTargetStationId(finalTargetStationId);
            vo.setBlockedStationId(blockedStationId);
            vo.setFullPathStationIds(copyIntegerList(fullPathStationIds));
            vo.setIssuedStationIds(copyIntegerList(issuedStationIds));
            vo.setPassedStationIds(copyIntegerList(passedStationIds));
            vo.setPendingStationIds(copyIntegerList(pendingStationIds));
            vo.setLatestIssuedSegmentPath(copyIntegerList(latestIssuedSegmentPath));
            vo.setSegmentList(copySegmentListWithIssued(segmentList, issuedSegmentCount));
            vo.setIssuedSegmentCount(issuedSegmentCount);
            vo.setTotalSegmentCount(totalSegmentCount);
            vo.setLoopAlertActive(loopAlertActive);
            vo.setLoopAlertType(loopAlertType);
            vo.setLoopAlertText(loopAlertText);
            vo.setLoopAlertCount(loopAlertCount);
            vo.setUpdatedAt(updatedAt);
            vo.setEvents(copyEventList(events));
            return vo;
        }
 
        private synchronized TraceSnapshot toSnapshot() {
            TraceSnapshot snapshot = new TraceSnapshot();
            snapshot.setTaskNo(taskNo);
            snapshot.setThreadImpl(threadImpl);
            snapshot.setStatus(status);
            snapshot.setTraceVersion(traceVersion);
            snapshot.setStartStationId(startStationId);
            snapshot.setCurrentStationId(currentStationId);
            snapshot.setFinalTargetStationId(finalTargetStationId);
            snapshot.setBlockedStationId(blockedStationId);
            snapshot.setFullPathStationIds(copyIntegerList(fullPathStationIds));
            snapshot.setIssuedStationIds(copyIntegerList(issuedStationIds));
            snapshot.setPassedStationIds(copyIntegerList(passedStationIds));
            snapshot.setPendingStationIds(copyIntegerList(pendingStationIds));
            snapshot.setLatestIssuedSegmentPath(copyIntegerList(latestIssuedSegmentPath));
            snapshot.setSegmentList(copySegmentList(segmentList));
            snapshot.setIssuedSegmentCount(issuedSegmentCount);
            snapshot.setTotalSegmentCount(totalSegmentCount);
            snapshot.setLoopAlertActive(loopAlertActive);
            snapshot.setLoopAlertType(loopAlertType);
            snapshot.setLoopAlertText(loopAlertText);
            snapshot.setLoopAlertCount(loopAlertCount);
            snapshot.setUpdatedAt(updatedAt);
            snapshot.setTerminalExpireAt(terminalExpireAt);
            snapshot.setEvents(copyEventList(events));
            return snapshot;
        }
 
        private static TraceTaskState fromSnapshot(TraceSnapshot snapshot) {
            TraceTaskState state = new TraceTaskState(snapshot.getTaskNo());
            state.threadImpl = snapshot.getThreadImpl();
            state.status = snapshot.getStatus() == null ? STATUS_WAITING : snapshot.getStatus();
            state.traceVersion = snapshot.getTraceVersion() == null ? 0 : snapshot.getTraceVersion();
            state.startStationId = snapshot.getStartStationId();
            state.currentStationId = snapshot.getCurrentStationId();
            state.finalTargetStationId = snapshot.getFinalTargetStationId();
            state.blockedStationId = snapshot.getBlockedStationId();
            state.fullPathStationIds = copyIntegerList(snapshot.getFullPathStationIds());
            state.issuedStationIds = copyIntegerList(snapshot.getIssuedStationIds());
            state.passedStationIds = copyIntegerList(snapshot.getPassedStationIds());
            state.pendingStationIds = copyIntegerList(snapshot.getPendingStationIds());
            state.latestIssuedSegmentPath = copyIntegerList(snapshot.getLatestIssuedSegmentPath());
            state.segmentList = copySegmentList(snapshot.getSegmentList());
            state.issuedSegmentCount = snapshot.getIssuedSegmentCount() == null ? 0 : snapshot.getIssuedSegmentCount();
            state.totalSegmentCount = snapshot.getTotalSegmentCount() == null ? state.segmentList.size() : snapshot.getTotalSegmentCount();
            state.loopAlertActive = Boolean.TRUE.equals(snapshot.getLoopAlertActive());
            state.loopAlertType = snapshot.getLoopAlertType();
            state.loopAlertText = snapshot.getLoopAlertText();
            state.loopAlertCount = snapshot.getLoopAlertCount();
            state.updatedAt = snapshot.getUpdatedAt() == null ? System.currentTimeMillis() : snapshot.getUpdatedAt();
            state.terminalExpireAt = snapshot.getTerminalExpireAt();
            state.events.clear();
            state.events.addAll(copyEventList(snapshot.getEvents()));
            return state;
        }
 
        private List<Integer> buildFullPathForRegistration(boolean rerouted,
                                                           Integer planCurrentStationId,
                                                           List<Integer> localPathStationIds) {
            List<Integer> localPath = copyIntegerList(localPathStationIds);
            if (!rerouted) {
                if (localPath.isEmpty() && planCurrentStationId != null) {
                    localPath.add(planCurrentStationId);
                }
                return localPath;
            }
 
            List<Integer> result = new ArrayList<>(copyIntegerList(this.passedStationIds));
            if (planCurrentStationId != null) {
                result.add(planCurrentStationId);
            }
            if (!localPath.isEmpty()) {
                int startIdx = 0;
                if (planCurrentStationId != null && Objects.equals(localPath.get(0), planCurrentStationId)) {
                    startIdx = 1;
                }
                for (int i = startIdx; i < localPath.size(); i++) {
                    Integer stationId = localPath.get(i);
                    if (stationId != null) {
                        result.add(stationId);
                    }
                }
            }
            return result;
        }
 
        private void rebuildProgress(Integer nextCurrentStationId) {
            this.currentStationId = nextCurrentStationId;
            List<Integer> fullPath = copyIntegerList(this.fullPathStationIds);
            this.passedStationIds = new ArrayList<>();
            this.pendingStationIds = copyIntegerList(fullPath);
            int currentIndex = nextCurrentStationId == null ? -1 : fullPath.indexOf(nextCurrentStationId);
            if (currentIndex < 0) {
                return;
            }
            this.passedStationIds = copyIntegerList(fullPath.subList(0, currentIndex));
            this.pendingStationIds = copyIntegerList(fullPath.subList(currentIndex + 1, fullPath.size()));
        }
 
        private void clearLoopHintState() {
            this.loopAlertActive = Boolean.FALSE;
            this.loopAlertType = null;
            this.loopAlertText = null;
            this.loopAlertCount = null;
        }
 
        private void appendLoopHintDetails(Map<String, Object> details) {
            if (details == null || !Boolean.TRUE.equals(this.loopAlertActive) || this.loopAlertCount == null || this.loopAlertCount <= 1) {
                return;
            }
            details.put("loopAlertActive", Boolean.TRUE);
            details.put("loopAlertType", this.loopAlertType);
            details.put("loopAlertText", this.loopAlertText);
            details.put("loopAlertCount", this.loopAlertCount);
        }
 
        private boolean acceptTraceVersion(Integer incomingTraceVersion) {
            return incomingTraceVersion != null
                    && this.traceVersion != null
                    && incomingTraceVersion.intValue() == this.traceVersion.intValue();
        }
 
        private void appendEvent(String eventType, String message, Map<String, Object> details) {
            if (eventType == null) {
                return;
            }
            StationTaskTraceEventVo event = new StationTaskTraceEventVo();
            event.setTimestamp(System.currentTimeMillis());
            event.setEventType(eventType);
            event.setMessage(message);
            event.setStatus(this.status);
            event.setCurrentStationId(this.currentStationId);
            event.setTargetStationId(this.finalTargetStationId);
            event.setTraceVersion(this.traceVersion);
            event.setDetails(copyDetails(details));
            this.events.add(event);
            if (this.events.size() > MAX_EVENT_COUNT) {
                this.events.remove(0);
            }
        }
 
        private List<StationTaskTraceSegmentVo> shiftSegments(List<StationTaskTraceSegmentVo> source, int pathOffset) {
            List<StationTaskTraceSegmentVo> result = new ArrayList<>();
            for (StationTaskTraceSegmentVo item : source) {
                if (item == null) {
                    continue;
                }
                StationTaskTraceSegmentVo copy = new StationTaskTraceSegmentVo();
                copy.setSegmentNo(item.getSegmentNo());
                copy.setSegmentCount(item.getSegmentCount());
                copy.setStationId(item.getStationId());
                copy.setTargetStationId(item.getTargetStationId());
                copy.setSegmentStartIndex(item.getSegmentStartIndex() == null ? null : item.getSegmentStartIndex() + pathOffset);
                copy.setSegmentEndIndex(item.getSegmentEndIndex() == null ? null : item.getSegmentEndIndex() + pathOffset);
                copy.setSegmentPath(copyIntegerList(item.getSegmentPath()));
                copy.setIssued(Boolean.FALSE);
                result.add(copy);
            }
            return result;
        }
 
        private List<StationTaskTraceSegmentVo> copySegmentListWithIssued(List<StationTaskTraceSegmentVo> source, Integer issuedSegmentCount) {
            List<StationTaskTraceSegmentVo> result = new ArrayList<>();
            int issuedCount = issuedSegmentCount == null ? 0 : issuedSegmentCount;
            for (StationTaskTraceSegmentVo item : source) {
                if (item == null) {
                    continue;
                }
                StationTaskTraceSegmentVo copy = new StationTaskTraceSegmentVo();
                copy.setSegmentNo(item.getSegmentNo());
                copy.setSegmentCount(item.getSegmentCount());
                copy.setStationId(item.getStationId());
                copy.setTargetStationId(item.getTargetStationId());
                copy.setSegmentStartIndex(item.getSegmentStartIndex());
                copy.setSegmentEndIndex(item.getSegmentEndIndex());
                copy.setSegmentPath(copyIntegerList(item.getSegmentPath()));
                copy.setIssued(item.getSegmentNo() != null && item.getSegmentNo() <= issuedCount);
                result.add(copy);
            }
            return result;
        }
    }
}