#
Junjie
昨天 56ace0ff2072625bfb93131d59b39cce6a5ffd1a
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
package com.zy.core.thread.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.core.common.Cools;
import com.core.common.DateUtils;
import com.core.common.SpringUtils;
import com.zy.asrs.domain.vo.StationCycleCapacityVo;
import com.zy.asrs.domain.vo.StationCycleLoopVo;
import com.zy.asrs.entity.BasDevp;
import com.zy.asrs.entity.BasStationOpt;
import com.zy.asrs.entity.DeviceConfig;
import com.zy.asrs.entity.DeviceDataLog;
import com.zy.asrs.service.BasDevpService;
import com.zy.asrs.service.BasStationOptService;
import com.zy.asrs.service.StationCycleCapacityService;
import com.zy.asrs.utils.Utils;
import com.zy.common.model.NavigateNode;
import com.zy.common.utils.NavigateUtils;
import com.zy.common.utils.RedisUtil;
import com.zy.core.cache.MessageQueue;
import com.zy.core.cache.OutputQueue;
import com.zy.core.enums.RedisKeyType;
import com.zy.core.enums.SlaveType;
import com.zy.core.enums.StationCommandType;
import com.zy.core.model.CommandResponse;
import com.zy.core.model.Task;
import com.zy.core.model.command.StationCommand;
import com.zy.core.model.protocol.StationProtocol;
import com.zy.core.network.DeviceConnectPool;
import com.zy.core.network.ZyStationConnectDriver;
import com.zy.core.network.entity.ZyStationStatusEntity;
import com.zy.core.thread.impl.v5.StationV5SegmentExecutor;
import com.zy.core.utils.DeviceLogRedisKeyBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
@Data
@Slf4j
public class ZyStationV5Thread implements Runnable, com.zy.core.thread.StationThread {
 
    private static final int RUN_BLOCK_REROUTE_STATE_EXPIRE_SECONDS = 60 * 60 * 24;
    private static final int SHORT_PATH_REPEAT_AVOID_THRESHOLD = 2;
    private static final int SMALL_LOOP_REPEAT_AVOID_THRESHOLD = 2;
 
    private List<StationProtocol> statusList = new ArrayList<>();
    private DeviceConfig deviceConfig;
    private RedisUtil redisUtil;
    private ZyStationConnectDriver zyStationConnectDriver;
    private int deviceLogCollectTime = 200;
    private boolean initStatus = false;
    private long deviceDataLogTime = System.currentTimeMillis();
    private ExecutorService executor = Executors.newFixedThreadPool(9999);
    private StationV5SegmentExecutor segmentExecutor;
 
    public ZyStationV5Thread(DeviceConfig deviceConfig, RedisUtil redisUtil) {
        this.deviceConfig = deviceConfig;
        this.redisUtil = redisUtil;
        this.segmentExecutor = new StationV5SegmentExecutor(deviceConfig, redisUtil, this::sendCommand);
    }
 
    @Override
    @SuppressWarnings("InfiniteLoopStatement")
    public void run() {
        this.connect();
        deviceLogCollectTime = Utils.getDeviceLogCollectTime();
 
        Thread readThread = new Thread(() -> {
            while (true) {
                try {
                    if (initStatus) {
                        deviceLogCollectTime = Utils.getDeviceLogCollectTime();
                    }
                    readStatus();
                    Thread.sleep(100);
                } catch (Exception e) {
                    log.error("StationV5Thread Fail", e);
                }
            }
        }, "DevpRead-" + deviceConfig.getDeviceNo());
        readThread.start();
 
        Thread processThread = new Thread(() -> {
            while (true) {
                try {
                    int step = 1;
                    Task task = MessageQueue.poll(SlaveType.Devp, deviceConfig.getDeviceNo());
                    if (task != null) {
                        step = task.getStep();
                    }
                    if (step == 2) {
                        StationCommand cmd = (StationCommand) task.getData();
                        executor.submit(() -> segmentExecutor.execute(cmd));
                    }
                    Thread.sleep(100);
                } catch (Exception e) {
                    log.error("StationV5Process Fail", e);
                }
            }
        }, "DevpProcess-" + deviceConfig.getDeviceNo());
        processThread.start();
    }
 
    private void readStatus() {
        if (zyStationConnectDriver == null) {
            return;
        }
 
        if (statusList.isEmpty()) {
            BasDevpService basDevpService = null;
            try {
                basDevpService = SpringUtils.getBean(BasDevpService.class);
            } catch (Exception ignore) {
            }
            if (basDevpService == null) {
                return;
            }
 
            BasDevp basDevp = basDevpService
                    .getOne(new QueryWrapper<BasDevp>().eq("devp_no", deviceConfig.getDeviceNo()));
            if (basDevp == null) {
                return;
            }
 
            List<ZyStationStatusEntity> list = JSONObject.parseArray(basDevp.getStationList(), ZyStationStatusEntity.class);
            for (ZyStationStatusEntity entity : list) {
                StationProtocol stationProtocol = new StationProtocol();
                stationProtocol.setStationId(entity.getStationId());
                statusList.add(stationProtocol);
            }
            initStatus = true;
        }
 
        List<ZyStationStatusEntity> zyStationStatusEntities = zyStationConnectDriver.getStatus();
        for (ZyStationStatusEntity statusEntity : zyStationStatusEntities) {
            for (StationProtocol stationProtocol : statusList) {
                if (stationProtocol.getStationId().equals(statusEntity.getStationId())) {
                    stationProtocol.setTaskNo(statusEntity.getTaskNo());
                    stationProtocol.setTargetStaNo(statusEntity.getTargetStaNo());
                    stationProtocol.setAutoing(statusEntity.isAutoing());
                    stationProtocol.setLoading(statusEntity.isLoading());
                    stationProtocol.setInEnable(statusEntity.isInEnable());
                    stationProtocol.setOutEnable(statusEntity.isOutEnable());
                    stationProtocol.setEmptyMk(statusEntity.isEmptyMk());
                    stationProtocol.setFullPlt(statusEntity.isFullPlt());
                    stationProtocol.setPalletHeight(statusEntity.getPalletHeight());
                    stationProtocol.setError(statusEntity.getError());
                    stationProtocol.setErrorMsg(statusEntity.getErrorMsg());
                    stationProtocol.setBarcode(statusEntity.getBarcode());
                    stationProtocol.setRunBlock(statusEntity.isRunBlock());
                    stationProtocol.setEnableIn(statusEntity.isEnableIn());
                    stationProtocol.setWeight(statusEntity.getWeight());
                    stationProtocol.setTaskWriteIdx(statusEntity.getTaskWriteIdx());
                }
 
                if (!Cools.isEmpty(stationProtocol.getSystemWarning())) {
                    if (stationProtocol.isAutoing() && !stationProtocol.isLoading()) {
                        stationProtocol.setSystemWarning("");
                    }
                }
            }
        }
 
        OutputQueue.DEVP.offer(MessageFormat.format("【{0}】[id:{1}] <<<<< 实时数据更新成功",
                DateUtils.convert(new Date()), deviceConfig.getDeviceNo()));
 
        if (System.currentTimeMillis() - deviceDataLogTime > deviceLogCollectTime) {
            DeviceDataLog deviceDataLog = new DeviceDataLog();
            deviceDataLog.setOriginData(JSON.toJSONString(zyStationStatusEntities));
            deviceDataLog.setWcsData(JSON.toJSONString(statusList));
            deviceDataLog.setType(String.valueOf(SlaveType.Devp));
            deviceDataLog.setDeviceNo(deviceConfig.getDeviceNo());
            deviceDataLog.setCreateTime(new Date());
 
            redisUtil.set(DeviceLogRedisKeyBuilder.build(deviceDataLog), deviceDataLog, 60 * 60 * 24);
            deviceDataLogTime = System.currentTimeMillis();
        }
    }
 
    @Override
    public boolean connect() {
        zyStationConnectDriver = new ZyStationConnectDriver(deviceConfig, redisUtil);
        zyStationConnectDriver.start();
        DeviceConnectPool.put(SlaveType.Devp, deviceConfig.getDeviceNo(), zyStationConnectDriver);
        return true;
    }
 
    @Override
    public void close() {
        if (zyStationConnectDriver != null) {
            zyStationConnectDriver.close();
        }
        if (executor != null) {
            try {
                executor.shutdownNow();
            } catch (Exception ignore) {
            }
        }
    }
 
    @Override
    public List<StationProtocol> getStatus() {
        return statusList;
    }
 
    @Override
    public Map<Integer, StationProtocol> getStatusMap() {
        Map<Integer, StationProtocol> map = new HashMap<>();
        for (StationProtocol stationProtocol : statusList) {
            map.put(stationProtocol.getStationId(), stationProtocol);
        }
        return map;
    }
 
    @Override
    public StationCommand getCommand(StationCommandType commandType,
                                     Integer taskNo,
                                     Integer stationId,
                                     Integer targetStationId,
                                     Integer palletSize) {
        StationCommand stationCommand = new StationCommand();
        stationCommand.setTaskNo(taskNo);
        stationCommand.setStationId(stationId);
        stationCommand.setTargetStaNo(targetStationId);
        stationCommand.setPalletSize(palletSize);
        stationCommand.setCommandType(commandType);
 
        if (commandType == StationCommandType.MOVE && !stationId.equals(targetStationId)) {
            List<NavigateNode> nodes = calcPathNavigateNodes(taskNo, stationId, targetStationId);
            return fillMoveCommandPath(stationCommand, nodes, taskNo, stationId, targetStationId);
        }
        return stationCommand;
    }
 
    @Override
    public synchronized StationCommand getRunBlockRerouteCommand(Integer taskNo,
                                                                 Integer stationId,
                                                                 Integer targetStationId,
                                                                 Integer palletSize) {
        if (taskNo == null || taskNo <= 0 || stationId == null || targetStationId == null) {
            return null;
        }
        if (Objects.equals(stationId, targetStationId)) {
            return getCommand(StationCommandType.MOVE, taskNo, stationId, targetStationId, palletSize);
        }
 
        RunBlockRerouteState rerouteState = loadRunBlockRerouteState(taskNo, stationId);
        TaskLoopRerouteState taskLoopRerouteState = loadTaskLoopRerouteState(taskNo);
        LoopIdentity currentLoopIdentity = resolveStationLoopIdentity(stationId);
        rerouteState.setTaskNo(taskNo);
        rerouteState.setBlockStationId(stationId);
        rerouteState.setLastTargetStationId(targetStationId);
        rerouteState.setPlanCount((rerouteState.getPlanCount() == null ? 0 : rerouteState.getPlanCount()) + 1);
        rerouteState.setLastPlanTime(System.currentTimeMillis());
        taskLoopRerouteState.setTaskNo(taskNo);
 
        List<List<NavigateNode>> candidatePathList = calcCandidatePathNavigateNodes(taskNo, stationId, targetStationId);
        if (candidatePathList.isEmpty()) {
            saveRunBlockRerouteState(rerouteState);
            log.warn("输送线堵塞重规划失败,候选路径为空,taskNo={}, planCount={}, stationId={}, targetStationId={}",
                    taskNo, rerouteState.getPlanCount(), stationId, targetStationId);
            return null;
        }
 
        StationCommand rerouteCommand = selectAvailableRerouteCommand(
                rerouteState,
                taskLoopRerouteState,
                currentLoopIdentity,
                candidatePathList,
                taskNo,
                stationId,
                targetStationId,
                palletSize
        );
        if (rerouteCommand == null) {
            log.info("输送线堵塞重规划候选路线已全部试过,重置路线历史后重新开始,taskNo={}, planCount={}, stationId={}, targetStationId={}",
                    taskNo, rerouteState.getPlanCount(), stationId, targetStationId);
            rerouteState.resetIssuedRoutes();
            rerouteCommand = selectAvailableRerouteCommand(
                    rerouteState,
                    taskLoopRerouteState,
                    currentLoopIdentity,
                    candidatePathList,
                    taskNo,
                    stationId,
                    targetStationId,
                    palletSize
            );
        }
 
        if (rerouteCommand != null) {
            saveRunBlockRerouteState(rerouteState);
            touchTaskLoopRerouteState(taskLoopRerouteState, currentLoopIdentity);
            saveTaskLoopRerouteState(taskLoopRerouteState);
            log.info("输送线堵塞重规划选中候选路线,taskNo={}, planCount={}, stationId={}, targetStationId={}, route={}",
                    taskNo, rerouteState.getPlanCount(), stationId, targetStationId, JSON.toJSONString(rerouteCommand.getNavigatePath()));
            return rerouteCommand;
        }
 
        saveRunBlockRerouteState(rerouteState);
        log.warn("输送线堵塞重规划未找到可下发路线,taskNo={}, planCount={}, stationId={}, targetStationId={}, triedRoutes={}",
                taskNo,
                rerouteState.getPlanCount(),
                stationId,
                targetStationId,
                JSON.toJSONString(rerouteState.getIssuedRoutePathList()));
        return null;
    }
 
    @Override
    public CommandResponse sendCommand(StationCommand command) {
        CommandResponse commandResponse = null;
        try {
            commandResponse = zyStationConnectDriver.sendCommand(command);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BasStationOptService optService = SpringUtils.getBean(BasStationOptService.class);
            List<ZyStationStatusEntity> statusListEntity = zyStationConnectDriver.getStatus();
            ZyStationStatusEntity matched = null;
            if (statusListEntity != null) {
                for (ZyStationStatusEntity entity : statusListEntity) {
                    if (entity.getStationId() != null && entity.getStationId().equals(command.getStationId())) {
                        matched = entity;
                        break;
                    }
                }
            }
            BasStationOpt basStationOpt = new BasStationOpt(
                    command.getTaskNo(),
                    command.getStationId(),
                    new Date(),
                    String.valueOf(command.getCommandType()),
                    command.getStationId(),
                    command.getTargetStaNo(),
                    null,
                    null,
                    null,
                    JSON.toJSONString(command),
                    JSON.toJSONString(matched),
                    1,
                    JSON.toJSONString(commandResponse)
            );
            if (optService != null) {
                optService.save(basStationOpt);
            }
        }
        return commandResponse;
    }
 
    @Override
    public CommandResponse sendOriginCommand(String address, short[] data) {
        return zyStationConnectDriver.sendOriginCommand(address, data);
    }
 
    @Override
    public byte[] readOriginCommand(String address, int length) {
        return zyStationConnectDriver.readOriginCommand(address, length);
    }
 
    private List<NavigateNode> calcPathNavigateNodes(Integer taskNo, Integer startStationId, Integer targetStationId) {
        NavigateUtils navigateUtils = SpringUtils.getBean(NavigateUtils.class);
        if (navigateUtils == null) {
            return new ArrayList<>();
        }
        return navigateUtils.calcByStationId(startStationId, targetStationId, taskNo);
    }
 
    private List<List<NavigateNode>> calcCandidatePathNavigateNodes(Integer taskNo,
                                                                    Integer startStationId,
                                                                    Integer targetStationId) {
        NavigateUtils navigateUtils = SpringUtils.getBean(NavigateUtils.class);
        if (navigateUtils == null) {
            return new ArrayList<>();
        }
        return navigateUtils.calcCandidatePathByStationId(startStationId, targetStationId, taskNo);
    }
 
    private StationCommand buildMoveCommand(Integer taskNo,
                                            Integer stationId,
                                            Integer targetStationId,
                                            Integer palletSize,
                                            List<NavigateNode> nodes) {
        StationCommand stationCommand = new StationCommand();
        stationCommand.setTaskNo(taskNo);
        stationCommand.setStationId(stationId);
        stationCommand.setTargetStaNo(targetStationId);
        stationCommand.setPalletSize(palletSize);
        stationCommand.setCommandType(StationCommandType.MOVE);
        return fillMoveCommandPath(stationCommand, nodes, taskNo, stationId, targetStationId);
    }
 
    private StationCommand fillMoveCommandPath(StationCommand stationCommand,
                                               List<NavigateNode> nodes,
                                               Integer taskNo,
                                               Integer stationId,
                                               Integer targetStationId) {
        List<Integer> path = new ArrayList<>();
        List<Integer> liftTransferPath = new ArrayList<>();
        for (NavigateNode node : nodes) {
            JSONObject valueObject;
            try {
                valueObject = JSONObject.parseObject(node.getNodeValue());
            } catch (Exception ignore) {
                continue;
            }
            if (valueObject == null) {
                continue;
            }
            Integer stationNo = valueObject.getInteger("stationId");
            if (stationNo == null) {
                continue;
            }
            path.add(stationNo);
            if (Boolean.TRUE.equals(node.getIsLiftTransferPoint())) {
                liftTransferPath.add(stationNo);
            }
        }
        if (path.isEmpty()) {
            log.warn("输送线命令生成失败,路径为空,taskNo={}, stationId={}, targetStationId={}",
                    taskNo, stationId, targetStationId);
            return null;
        }
        stationCommand.setNavigatePath(path);
        stationCommand.setLiftTransferPath(liftTransferPath);
        stationCommand.setTargetStaNo(path.get(path.size() - 1));
        return stationCommand;
    }
 
    private StationCommand selectAvailableRerouteCommand(RunBlockRerouteState rerouteState,
                                                         TaskLoopRerouteState taskLoopRerouteState,
                                                         LoopIdentity currentLoopIdentity,
                                                         List<List<NavigateNode>> candidatePathList,
                                                         Integer taskNo,
                                                         Integer stationId,
                                                         Integer targetStationId,
                                                         Integer palletSize) {
        if (rerouteState == null || candidatePathList == null || candidatePathList.isEmpty()) {
            return null;
        }
 
        Set<String> issuedRouteSignatureSet = rerouteState.getIssuedRouteSignatureSet();
        int currentLoopIssuedCount = resolveCurrentLoopIssuedCount(taskLoopRerouteState, currentLoopIdentity);
        List<RerouteCandidateCommand> candidateCommandList = new ArrayList<>();
        for (List<NavigateNode> candidatePath : candidatePathList) {
            StationCommand rerouteCommand = buildMoveCommand(taskNo, stationId, targetStationId, palletSize, candidatePath);
            if (rerouteCommand == null || rerouteCommand.getNavigatePath() == null || rerouteCommand.getNavigatePath().isEmpty()) {
                continue;
            }
            String routeSignature = buildPathSignature(rerouteCommand.getNavigatePath());
            if (Cools.isEmpty(routeSignature)) {
                continue;
            }
            RerouteCandidateCommand candidateCommand = new RerouteCandidateCommand();
            candidateCommand.setCommand(rerouteCommand);
            candidateCommand.setRouteSignature(routeSignature);
            candidateCommand.setPathLength(rerouteCommand.getNavigatePath().size());
            candidateCommand.setIssuedCount(rerouteState.getRouteIssueCountMap().getOrDefault(routeSignature, 0));
            candidateCommand.setLoopFingerprint(currentLoopIdentity.getLoopFingerprint());
            candidateCommand.setLoopIssuedCount(currentLoopIssuedCount);
            candidateCommand.setCurrentLoopHitCount(countCurrentLoopStationHit(rerouteCommand.getNavigatePath(), currentLoopIdentity.getStationIdSet()));
            candidateCommandList.add(candidateCommand);
        }
        if (candidateCommandList.isEmpty()) {
            return null;
        }
 
        List<RerouteCandidateCommand> orderedCandidateCommandList = reorderCandidateCommandsForLoopRelease(candidateCommandList);
        for (RerouteCandidateCommand candidateCommand : orderedCandidateCommandList) {
            if (candidateCommand == null || candidateCommand.getCommand() == null) {
                continue;
            }
            if (issuedRouteSignatureSet.contains(candidateCommand.getRouteSignature())) {
                continue;
            }
 
            StationCommand rerouteCommand = candidateCommand.getCommand();
            issuedRouteSignatureSet.add(candidateCommand.getRouteSignature());
            rerouteState.getIssuedRoutePathList().add(new ArrayList<>(rerouteCommand.getNavigatePath()));
            rerouteState.setLastSelectedRoute(new ArrayList<>(rerouteCommand.getNavigatePath()));
            rerouteState.getRouteIssueCountMap().put(
                    candidateCommand.getRouteSignature(),
                    rerouteState.getRouteIssueCountMap().getOrDefault(candidateCommand.getRouteSignature(), 0) + 1
            );
            return rerouteCommand;
        }
        return null;
    }
 
    private List<RerouteCandidateCommand> reorderCandidateCommandsForLoopRelease(List<RerouteCandidateCommand> candidateCommandList) {
        if (candidateCommandList == null || candidateCommandList.isEmpty()) {
            return new ArrayList<>();
        }
 
        int shortestPathLength = Integer.MAX_VALUE;
        int shortestPathLoopHitCount = Integer.MAX_VALUE;
        boolean shortestPathOverused = false;
        boolean currentLoopOverused = false;
        boolean hasLongerCandidate = false;
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null || candidateCommand.getPathLength() <= 0) {
                continue;
            }
            shortestPathLength = Math.min(shortestPathLength, candidateCommand.getPathLength());
        }
        if (shortestPathLength == Integer.MAX_VALUE) {
            return candidateCommandList;
        }
 
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null || candidateCommand.getPathLength() <= 0) {
                continue;
            }
            if (candidateCommand.getPathLength() == shortestPathLength) {
                shortestPathLoopHitCount = Math.min(shortestPathLoopHitCount, safeInt(candidateCommand.getCurrentLoopHitCount()));
            }
            if (candidateCommand.getPathLength() > shortestPathLength) {
                hasLongerCandidate = true;
            }
            if (candidateCommand.getPathLength() == shortestPathLength
                    && candidateCommand.getIssuedCount() != null
                    && candidateCommand.getIssuedCount() >= SHORT_PATH_REPEAT_AVOID_THRESHOLD) {
                shortestPathOverused = true;
            }
            if (!Cools.isEmpty(candidateCommand.getLoopFingerprint())
                    && candidateCommand.getLoopIssuedCount() != null
                    && candidateCommand.getLoopIssuedCount() >= SMALL_LOOP_REPEAT_AVOID_THRESHOLD) {
                currentLoopOverused = true;
            }
        }
        if (!shortestPathOverused && !currentLoopOverused) {
            return candidateCommandList;
        }
        if (shortestPathLoopHitCount == Integer.MAX_VALUE) {
            shortestPathLoopHitCount = 0;
        }
 
        boolean hasLoopExitCandidate = false;
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null) {
                continue;
            }
            if (safeInt(candidateCommand.getCurrentLoopHitCount()) < shortestPathLoopHitCount) {
                hasLoopExitCandidate = true;
                break;
            }
        }
        if (!hasLongerCandidate && !hasLoopExitCandidate) {
            return candidateCommandList;
        }
 
        List<RerouteCandidateCommand> reorderedList = new ArrayList<>();
        if (currentLoopOverused && hasLoopExitCandidate) {
            for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
                if (candidateCommand == null) {
                    continue;
                }
                if (safeInt(candidateCommand.getCurrentLoopHitCount()) < shortestPathLoopHitCount) {
                    appendCandidateIfAbsent(reorderedList, candidateCommand);
                }
            }
        }
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand != null
                    && candidateCommand.getPathLength() != null
                    && candidateCommand.getPathLength() > shortestPathLength) {
                appendCandidateIfAbsent(reorderedList, candidateCommand);
            }
        }
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null) {
                continue;
            }
            appendCandidateIfAbsent(reorderedList, candidateCommand);
        }
        return reorderedList;
    }
 
    private void appendCandidateIfAbsent(List<RerouteCandidateCommand> reorderedList,
                                         RerouteCandidateCommand candidateCommand) {
        if (reorderedList == null || candidateCommand == null) {
            return;
        }
        if (!reorderedList.contains(candidateCommand)) {
            reorderedList.add(candidateCommand);
        }
    }
 
    private RunBlockRerouteState loadRunBlockRerouteState(Integer taskNo, Integer blockStationId) {
        if (redisUtil == null || taskNo == null || taskNo <= 0 || blockStationId == null || blockStationId <= 0) {
            return new RunBlockRerouteState();
        }
        Object stateObj = redisUtil.get(buildRunBlockRerouteStateKey(taskNo, blockStationId));
        if (stateObj == null) {
            return new RunBlockRerouteState();
        }
        try {
            RunBlockRerouteState state = JSON.parseObject(String.valueOf(stateObj), RunBlockRerouteState.class);
            return state == null ? new RunBlockRerouteState() : state.normalize();
        } catch (Exception ignore) {
            return new RunBlockRerouteState();
        }
    }
 
    private void saveRunBlockRerouteState(RunBlockRerouteState rerouteState) {
        if (redisUtil == null
                || rerouteState == null
                || rerouteState.getTaskNo() == null
                || rerouteState.getTaskNo() <= 0
                || rerouteState.getBlockStationId() == null
                || rerouteState.getBlockStationId() <= 0) {
            return;
        }
        rerouteState.normalize();
        redisUtil.set(
                buildRunBlockRerouteStateKey(rerouteState.getTaskNo(), rerouteState.getBlockStationId()),
                JSON.toJSONString(rerouteState),
                RUN_BLOCK_REROUTE_STATE_EXPIRE_SECONDS
        );
    }
 
    private TaskLoopRerouteState loadTaskLoopRerouteState(Integer taskNo) {
        if (redisUtil == null || taskNo == null || taskNo <= 0) {
            return new TaskLoopRerouteState();
        }
        Object stateObj = redisUtil.get(RedisKeyType.STATION_RUN_BLOCK_TASK_LOOP_STATE_.key + taskNo);
        if (stateObj == null) {
            return new TaskLoopRerouteState();
        }
        try {
            TaskLoopRerouteState state = JSON.parseObject(String.valueOf(stateObj), TaskLoopRerouteState.class);
            return state == null ? new TaskLoopRerouteState() : state.normalize();
        } catch (Exception ignore) {
            return new TaskLoopRerouteState();
        }
    }
 
    private void saveTaskLoopRerouteState(TaskLoopRerouteState taskLoopRerouteState) {
        if (redisUtil == null
                || taskLoopRerouteState == null
                || taskLoopRerouteState.getTaskNo() == null
                || taskLoopRerouteState.getTaskNo() <= 0) {
            return;
        }
        taskLoopRerouteState.normalize();
        redisUtil.set(
                RedisKeyType.STATION_RUN_BLOCK_TASK_LOOP_STATE_.key + taskLoopRerouteState.getTaskNo(),
                JSON.toJSONString(taskLoopRerouteState),
                RUN_BLOCK_REROUTE_STATE_EXPIRE_SECONDS
        );
    }
 
    private void touchTaskLoopRerouteState(TaskLoopRerouteState taskLoopRerouteState,
                                           LoopIdentity currentLoopIdentity) {
        if (taskLoopRerouteState == null || currentLoopIdentity == null || Cools.isEmpty(currentLoopIdentity.getLoopFingerprint())) {
            return;
        }
        taskLoopRerouteState.getLoopIssueCountMap().put(
                currentLoopIdentity.getLoopFingerprint(),
                taskLoopRerouteState.getLoopIssueCountMap().getOrDefault(currentLoopIdentity.getLoopFingerprint(), 0) + 1
        );
        taskLoopRerouteState.setLastLoopFingerprint(currentLoopIdentity.getLoopFingerprint());
        taskLoopRerouteState.setLastIssueTime(System.currentTimeMillis());
    }
 
    private int resolveCurrentLoopIssuedCount(TaskLoopRerouteState taskLoopRerouteState,
                                              LoopIdentity currentLoopIdentity) {
        if (taskLoopRerouteState == null || currentLoopIdentity == null || Cools.isEmpty(currentLoopIdentity.getLoopFingerprint())) {
            return 0;
        }
        return taskLoopRerouteState.getLoopIssueCountMap().getOrDefault(currentLoopIdentity.getLoopFingerprint(), 0);
    }
 
    private int countCurrentLoopStationHit(List<Integer> path, Set<Integer> currentLoopStationIdSet) {
        if (path == null || path.isEmpty() || currentLoopStationIdSet == null || currentLoopStationIdSet.isEmpty()) {
            return 0;
        }
        int hitCount = 0;
        for (Integer stationId : path) {
            if (stationId != null && currentLoopStationIdSet.contains(stationId)) {
                hitCount++;
            }
        }
        return hitCount;
    }
 
    private String buildPathSignature(List<Integer> path) {
        if (path == null || path.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (Integer stationNo : path) {
            if (stationNo == null) {
                continue;
            }
            if (builder.length() > 0) {
                builder.append("->");
            }
            builder.append(stationNo);
        }
        return builder.toString();
    }
 
    private String buildRunBlockRerouteStateKey(Integer taskNo, Integer blockStationId) {
        return RedisKeyType.STATION_RUN_BLOCK_REROUTE_STATE_.key + taskNo + "_" + blockStationId;
    }
 
    private LoopIdentity resolveStationLoopIdentity(Integer stationId) {
        if (stationId == null || stationId <= 0) {
            return LoopIdentity.empty();
        }
        try {
            StationCycleCapacityService stationCycleCapacityService = SpringUtils.getBean(StationCycleCapacityService.class);
            if (stationCycleCapacityService == null) {
                return LoopIdentity.empty();
            }
            StationCycleCapacityVo capacityVo = stationCycleCapacityService.getLatestSnapshot();
            if (capacityVo == null || capacityVo.getLoopList() == null || capacityVo.getLoopList().isEmpty()) {
                return LoopIdentity.empty();
            }
            for (StationCycleLoopVo loopVo : capacityVo.getLoopList()) {
                List<Integer> loopStationIdList = normalizeLoopStationIdList(loopVo == null ? null : loopVo.getStationIdList());
                if (loopStationIdList.isEmpty() || !loopStationIdList.contains(stationId)) {
                    continue;
                }
                return new LoopIdentity(buildLoopFingerprint(loopStationIdList), new HashSet<>(loopStationIdList));
            }
        } catch (Exception ignore) {
        }
        return LoopIdentity.empty();
    }
 
    private List<Integer> normalizeLoopStationIdList(List<Integer> stationIdList) {
        if (stationIdList == null || stationIdList.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> normalizedList = new ArrayList<>();
        Set<Integer> seenStationIdSet = new HashSet<>();
        for (Integer stationId : stationIdList) {
            if (stationId == null || stationId <= 0 || !seenStationIdSet.add(stationId)) {
                continue;
            }
            normalizedList.add(stationId);
        }
        Collections.sort(normalizedList);
        return normalizedList;
    }
 
    private String buildLoopFingerprint(List<Integer> stationIdList) {
        if (stationIdList == null || stationIdList.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (Integer stationId : stationIdList) {
            if (stationId == null) {
                continue;
            }
            if (builder.length() > 0) {
                builder.append("|");
            }
            builder.append(stationId);
        }
        return builder.toString();
    }
 
    private int safeInt(Integer value) {
        return value == null ? 0 : value;
    }
 
    @Data
    private static class RunBlockRerouteState {
        private Integer taskNo;
        private Integer blockStationId;
        private Integer planCount = 0;
        private Integer lastTargetStationId;
        private Long lastPlanTime;
        private List<List<Integer>> issuedRoutePathList = new ArrayList<>();
        private List<Integer> lastSelectedRoute = new ArrayList<>();
        private Set<String> issuedRouteSignatureSet = new LinkedHashSet<>();
        private Map<String, Integer> routeIssueCountMap = new HashMap<>();
 
        private RunBlockRerouteState normalize() {
            if (planCount == null || planCount < 0) {
                planCount = 0;
            }
            if (issuedRoutePathList == null) {
                issuedRoutePathList = new ArrayList<>();
            }
            if (lastSelectedRoute == null) {
                lastSelectedRoute = new ArrayList<>();
            }
            if (issuedRouteSignatureSet == null) {
                issuedRouteSignatureSet = new LinkedHashSet<>();
            }
            if (routeIssueCountMap == null) {
                routeIssueCountMap = new HashMap<>();
            }
            for (List<Integer> routePath : issuedRoutePathList) {
                if (routePath == null || routePath.isEmpty()) {
                    continue;
                }
                String pathSignature = buildPathSignatureText(routePath);
                if (!Cools.isEmpty(pathSignature)) {
                    issuedRouteSignatureSet.add(pathSignature);
                    routeIssueCountMap.putIfAbsent(pathSignature, 1);
                }
            }
            return this;
        }
 
        private void resetIssuedRoutes() {
            this.issuedRoutePathList = new ArrayList<>();
            this.lastSelectedRoute = new ArrayList<>();
            this.issuedRouteSignatureSet = new LinkedHashSet<>();
        }
 
        private static String buildPathSignatureText(List<Integer> routePath) {
            if (routePath == null || routePath.isEmpty()) {
                return "";
            }
            StringBuilder builder = new StringBuilder();
            for (Integer stationId : routePath) {
                if (stationId == null) {
                    continue;
                }
                if (builder.length() > 0) {
                    builder.append("->");
                }
                builder.append(stationId);
            }
            return builder.toString();
        }
    }
 
    @Data
    private static class RerouteCandidateCommand {
        private StationCommand command;
        private String routeSignature;
        private Integer pathLength;
        private Integer issuedCount;
        private String loopFingerprint;
        private Integer loopIssuedCount;
        private Integer currentLoopHitCount;
    }
 
    @Data
    private static class TaskLoopRerouteState {
        private Integer taskNo;
        private String lastLoopFingerprint;
        private Long lastIssueTime;
        private Map<String, Integer> loopIssueCountMap = new HashMap<>();
 
        private TaskLoopRerouteState normalize() {
            if (loopIssueCountMap == null) {
                loopIssueCountMap = new HashMap<>();
            }
            return this;
        }
    }
 
    @Data
    private static class LoopIdentity {
        private String loopFingerprint;
        private Set<Integer> stationIdSet = new HashSet<>();
 
        private LoopIdentity(String loopFingerprint, Set<Integer> stationIdSet) {
            this.loopFingerprint = loopFingerprint;
            this.stationIdSet = stationIdSet == null ? new HashSet<>() : stationIdSet;
        }
 
        private static LoopIdentity empty() {
            return new LoopIdentity("", new HashSet<>());
        }
    }
}