#
vincentlu
2026-04-22 cff35177242b79c916c858a75892a786cd23be8c
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
package com.zy.acs.manager.core.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zy.acs.common.hk.state.HkState;
import com.zy.acs.common.hk.state.HkStateActionState;
import com.zy.acs.common.hk.state.type.HkActionStatusType;
import com.zy.acs.common.utils.RedisSupport;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.manager.manager.entity.Action;
import com.zy.acs.manager.manager.entity.Segment;
import com.zy.acs.manager.manager.enums.ActionStsType;
import com.zy.acs.manager.manager.enums.SegmentStateType;
import com.zy.acs.manager.manager.service.ActionService;
import com.zy.acs.manager.manager.service.SegmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.Date;
import java.util.List;
 
/**
 * 海康 VDA state 闭环处理。
 * 仅复用现有结算逻辑,不改原有完成订阅逻辑。
 */
@Slf4j
@Service
public class HkOrderStateClosureService {
 
    private static final String HK_ORDER_COMPLETE_FLAG = "HK_AGV_ORDER_COMPLETE";
 
    private static final int COMPLETE_MARK_EXPIRE_SECONDS = 7 * 24 * 60 * 60;
 
    private final RedisSupport redis = RedisSupport.defaultRedisSupport;
 
    @Autowired
    private ActionService actionService;
    @Autowired
    private SegmentService segmentService;
    @Autowired
    private MainService mainService;
 
    @Transactional
    public void process(HkState state) {
        if (state == null || Cools.isEmpty(state.getOrderId())) {
            return;
        }
 
        syncFinishedActions(state);
 
        if (!isOrderCompleted(state)) {
            return;
        }
 
        settleCompletedOrder(state);
    }
 
    private void syncFinishedActions(HkState state) {
        if (Cools.isEmpty(state.getActionStates())) {
            return;
        }
 
        Date now = new Date();
        String orderId = state.getOrderId();
        for (HkStateActionState actionState : state.getActionStates()) {
            if (actionState == null || actionState.getActionStatus() != HkActionStatusType.FINISHED) {
                continue;
            }
 
            Long actionId = parseActionId(actionState.getActionId());
            if (actionId == null) {
                continue;
            }
 
            Action action = actionService.getOne(new LambdaQueryWrapper<Action>()
                    .eq(Action::getId, actionId)
                    .eq(Action::getGroupId, orderId)
                    .eq(Action::getActionSts, ActionStsType.ISSUED.val())
                    .last("limit 1"));
            if (action == null) {
                continue;
            }
 
            action.setActionSts(ActionStsType.FINISH.val());
            action.setEndTime(now);
            action.setUpdateTime(now);
            if (!actionService.updateById(action)) {
                log.error("hk state close action failed, orderId={}, actionId={}", orderId, actionId);
            } else {
                log.info("hk state close action success, orderId={}, actionId={}, hkActionId={}",
                        orderId, actionId, actionState.getActionId());
            }
        }
    }
 
    private boolean isOrderCompleted(HkState state) {
        if (!Cools.isEmpty(state.getNodeStates()) || !Cools.isEmpty(state.getEdgeStates())) {
            return false;
        }
 
        if (Cools.isEmpty(state.getActionStates())) {
            return true;
        }
 
        for (HkStateActionState actionState : state.getActionStates()) {
            if (actionState == null) {
                continue;
            }
 
            HkActionStatusType status = actionState.getActionStatus();
            if (status == null
                    || status == HkActionStatusType.WAITING
                    || status == HkActionStatusType.INITIALIZING
                    || status == HkActionStatusType.RUNNING
                    || status == HkActionStatusType.PAUSED
                    || status == HkActionStatusType.FAILED) {
                return false;
            }
        }
        return true;
    }
 
    private void settleCompletedOrder(HkState state) {
        String orderId = state.getOrderId();
        String completeKey = buildCompleteKey(state);
        if (redis.getObject(HK_ORDER_COMPLETE_FLAG, completeKey) != null) {
            return;
        }
 
        List<Segment> segmentList = segmentService.list(new LambdaQueryWrapper<Segment>()
                .eq(Segment::getGroupId, orderId)
                .orderByAsc(Segment::getSerial));
        if (Cools.isEmpty(segmentList)) {
            log.warn("hk state order completed but no segment found, agvNo={}, orderId={}, orderUpdateId={}",
                    state.getSerialNumber(), orderId, state.getOrderUpdateId());
            return;
        }
 
        if (!hasReachedOrderTail(state, segmentList)) {
//            return;
        }
 
        boolean needSettle = segmentList.stream()
                .anyMatch(segment -> !SegmentStateType.FINISH.toString().equals(segment.getState()));
        if (!needSettle) {
            redis.setObject(HK_ORDER_COMPLETE_FLAG, completeKey, Boolean.TRUE, COMPLETE_MARK_EXPIRE_SECONDS);
            return;
        }
 
        mainService.settleSegmentList(segmentList, orderId);
        redis.setObject(HK_ORDER_COMPLETE_FLAG, completeKey, Boolean.TRUE, COMPLETE_MARK_EXPIRE_SECONDS);
        log.info("hk state settle completed order, agvNo={}, orderId={}, orderUpdateId={}",
                state.getSerialNumber(), orderId, state.getOrderUpdateId());
    }
 
    private String buildCompleteKey(HkState state) {
        return state.getSerialNumber()
                + "_"
                + state.getOrderId()
                + "_"
                + (state.getOrderUpdateId() == null ? "null" : state.getOrderUpdateId());
    }
 
    private boolean hasReachedOrderTail(HkState state, List<Segment> segmentList) {
        Long lastNodeSequenceId = state.getLastNodeSequenceId();
        if (lastNodeSequenceId == null) {
            return false;
        }
 
        long expectedLastNodeSequenceId = segmentList.size() * 2L;
        return lastNodeSequenceId >= expectedLastNodeSequenceId;
    }
 
    private Long parseActionId(String hkActionId) {
        if (Cools.isEmpty(hkActionId) || hkActionId.length() < 2) {
            return null;
        }
        if (hkActionId.charAt(0) != 'A' && hkActionId.charAt(0) != 'a') {
            return null;
        }
 
        try {
            return Long.parseLong(hkActionId.substring(1));
        } catch (NumberFormatException e) {
            log.warn("parse hk action id failed, hkActionId={}", hkActionId);
            return null;
        }
    }
}