自动化立体仓库 - WMS系统
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
package com.zy.integration.iot.biz.impl;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.core.common.Cools;
import com.core.common.R;
import com.zy.asrs.entity.LocMast;
import com.zy.asrs.entity.WrkDetl;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.entity.param.MesToCombParam;
import com.zy.asrs.entity.param.OutTaskParam;
import com.zy.asrs.service.ExternalTaskFacadeService;
import com.zy.asrs.service.LocMastService;
import com.zy.asrs.service.WrkDetlService;
import com.zy.integration.iot.biz.IotInstructionService;
import com.zy.iot.config.IotProperties;
import com.zy.iot.constant.IotConstants;
import com.zy.iot.entity.IotFeedbackMessage;
import com.zy.iot.entity.IotInstructionMessage;
import com.zy.iot.entity.IotPublishRecord;
import com.zy.iot.service.IotDbConfigService;
import com.zy.iot.service.IotPublishRecordService;
import com.zy.iot.util.IotInstructionIdGenerator;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
 
/**
 * IoT 指令核心编排服务。
 * 负责把 XBPS 下发的 MQTT 指令转换成现有 ASRS 入库/出库流程,并在本地记录幂等、乱序和回执状态。
 */
@Slf4j
@Service
public class IotInstructionServiceImpl implements IotInstructionService {
 
    /**
     * MQTT 组托入口写入 WaitPakin.boxType1=aws。
     * 真实入库任务生成时该字段会同步到 WrkDetl.boxType1,可作为入库任务来源的本地兜底标识。
     */
    private static final String MQTT_SOURCE_BOX_TYPE = "aws";
 
    private static final List<Integer> STOW_WORK_IO_TYPES = Arrays.asList(1, 8, 11, 53, 54, 57);
    private static final List<Integer> PICK_WORK_IO_TYPES = Arrays.asList(101, 108);
 
    @Autowired
    private IotPublishRecordService iotPublishRecordService;
    @Autowired
    private IotProperties iotProperties;
    @Autowired
    private IotDbConfigService iotDbConfigService;
    @Autowired
    private ExternalTaskFacadeService externalTaskFacadeService;
    @Autowired
    private LocMastService locMastService;
    @Autowired
    private WrkDetlService wrkDetlService;
 
    /**
     * 处理 egress/asrs/stow 指令。
     * 只接单和预登记,不在 MQTT 回调里直接触发真实入库作业。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long handleStowInstruction(IotInstructionMessage message, String topic, String rawPayload) {
        if (message == null || Cools.isEmpty(message.getInstructionId())) {
            log.warn("ignore invalid stow message, payload={}", rawPayload);
            return null;
        }
        IotPublishRecord existing = iotPublishRecordService.findByInstructionId(message.getInstructionId());
        if (existing != null) {
            return existing.getId();
        }
 
        IotPublishRecord record = initInboundRecord(message, topic, rawPayload, IotConstants.MESSAGE_TYPE_STOW);
        iotPublishRecordService.insert(record);
        if (Cools.isEmpty(message.getContainerId())) {
            return updateAsFailure(record, null, "containerId不能为空");
        }
        if (isDelayed(message, IotConstants.MESSAGE_TYPE_STOW)) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_DELAYED, "延迟消息已忽略");
        }
 
        String preferredLocNo = resolvePreferredInboundLoc(message);
        MesToCombParam param = buildInboundParam(message, preferredLocNo);
        R result = externalTaskFacadeService.acceptInboundNotice(param);
        if (result == null || !Objects.equals(result.get("code"), 200)) {
            return updateAsFailure(record, null, resolveResultMessage(result, "接收入库指令失败"));
        }
 
        Date now = new Date();
        record.setOrderNo(param.getOrderId());
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PROCESSED);
        record.setErrorCode(null);
        record.setErrorMessage(null);
        applyFeedback(record, IotConstants.FEEDBACK_SUCCESS, null, null, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    /**
     * 处理 egress/asrs/pick 指令。
     * 远端出库口会先映射成本地站台号,再复用现有出库建单并自动确认放行。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long handlePickInstruction(IotInstructionMessage message, String topic, String rawPayload) {
        if (message == null || Cools.isEmpty(message.getInstructionId())) {
            log.warn("ignore invalid pick message, payload={}", rawPayload);
            return null;
        }
        IotPublishRecord existing = iotPublishRecordService.findByInstructionId(message.getInstructionId());
        if (existing != null) {
            return existing.getId();
        }
 
        IotPublishRecord record = initInboundRecord(message, topic, rawPayload, IotConstants.MESSAGE_TYPE_PICK);
        iotPublishRecordService.insert(record);
        if (Cools.isEmpty(message.getContainerId())) {
            return updateAsFailure(record, null, "containerId不能为空");
        }
        if (isDelayed(message, IotConstants.MESSAGE_TYPE_PICK)) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_DELAYED, "延迟消息已忽略");
        }
 
        String remoteDestination = extractFirstDestination(message.getDestinationLocationIds());
//        Integer stationId = Cools.isEmpty(remoteDestination) ? null : iotProperties.getPickStationMappings().get(remoteDestination);
        Integer stationId =602;
        if (stationId == null) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_STATION_MAPPING, "未找到目标出库口映射");
        }
 
        OutTaskParam param = new OutTaskParam();
        param.setPalletId(message.getContainerId());
        param.setOrderId(resolveReferenceId(message));
        param.setStationId(String.valueOf(stationId));
        param.setBatchSeq("amazon"+new Date().getTime());
        param.setSeq(0);
        R result = externalTaskFacadeService.createOutboundTask(param, true);
        if (result == null || !Objects.equals(result.get("code"), 200)) {
            return updateAsFailure(record, null, resolveResultMessage(result, "接收拣货指令失败"));
        }
 
        Date now = new Date();
        record.setOrderNo(param.getOrderId());
        record.setWrkNo(resolveWrkNo(result));
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PROCESSED);
        record.setErrorCode(null);
        record.setErrorMessage(null);
        applyFeedback(record, IotConstants.FEEDBACK_SUCCESS, null, null, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    /**
     * 处理 XBPS 对 ASRS 动作消息的 feedback 回执。
     * 这里只回写 IoT 发布状态,不改库存和工作档。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleFeedbackAck(IotFeedbackMessage feedbackMessage, String topic, String rawPayload) {
        if (feedbackMessage == null || Cools.isEmpty(feedbackMessage.getInstructionId())) {
            return;
        }
        IotPublishRecord record = iotPublishRecordService.findByInstructionId(feedbackMessage.getInstructionId());
        if (record == null || !IotConstants.DIRECTION_OUTBOUND.equals(record.getDirection())) {
            log.warn("ignore iot ack without outbound record, instructionId={}", feedbackMessage.getInstructionId());
            return;
        }
        Date now = new Date();
        record.setAckPayload(rawPayload);
        record.setAckTime(now);
        record.setReceiveTopic(topic);
        record.setPublishStatus(IotConstants.FEEDBACK_SUCCESS.equalsIgnoreCase(feedbackMessage.getStatus())
                ? IotConstants.PUBLISH_STATUS_ACK_SUCCESS
                : IotConstants.PUBLISH_STATUS_ACK_FAILURE);
        record.setErrorCode(feedbackMessage.getErrorCode());
        record.setErrorMessage(truncate(feedbackMessage.getMessage(), 500));
        record.setUpdateTime(now);
        iotPublishRecordService.updateById(record);
    }
 
    /**
     * 判断任务是否来自 MQTT 指令。
     *
     * 出库 MQTT 指令在 handlePickInstruction 中会先落 asr_iot_publish_record(INBOUND/PICK),
     * 再通过统一出库订单执行逻辑生成 WrkMast,因此优先用 wrk_no 精确匹配。
     *
     * 入库 MQTT 指令先落 WaitPakin,WCS 扫码后才生成 WrkMast,入站记录当时还不知道 wrk_no,
     * 所以入库侧优先看 WrkDetl.boxType1=aws,再用托盘号 + instructionId/orderNo 做兜底。
     */
    @Override
    public boolean isMqttOriginWork(WrkMast wrkMast) {
        if (wrkMast == null || wrkMast.getWrkNo() == null || wrkMast.getIoType() == null) {
            return false;
        }
        if (STOW_WORK_IO_TYPES.contains(wrkMast.getIoType())) {
            return isMqttOriginStowWork(wrkMast);
        }
        if (PICK_WORK_IO_TYPES.contains(wrkMast.getIoType())) {
            return isMqttOriginPickWork(wrkMast);
        }
        return false;
    }
 
    /**
     * 在工作档真正完成后落一条待发布记录。
     * 事务内只写库,不直接发 MQTT,避免业务提交和网络发送耦合。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queueWorkCompletion(WrkMast wrkMast) {
        if (!iotDbConfigService.isMqttEnabled() || wrkMast == null || wrkMast.getWrkNo() == null) {
            return;
        }
        // MQTT 完工上报只处理 MQTT 来源的任务;ERP/open 来源的任务由 ERP 完工上报调度处理。
        // 这样同一个完工事件不会同时进入 MQTT 和 ERP 两条上报链路。
        if (!isMqttOriginWork(wrkMast)) {
            return;
        }
        int existedCount = iotPublishRecordService.selectCount(new EntityWrapper<IotPublishRecord>()
                .eq("direction", IotConstants.DIRECTION_OUTBOUND)
                .eq("wrk_no", wrkMast.getWrkNo()));
        if (existedCount > 0) {
            return;
        }
        IotPublishRecord record = buildOutboundRecord(wrkMast);
        if (record != null) {
            iotPublishRecordService.insert(record);
        }
    }
 
    private IotPublishRecord initInboundRecord(IotInstructionMessage message, String topic, String rawPayload, String messageType) {
        Date now = new Date();
        IotPublishRecord record = new IotPublishRecord();
        record.setInstructionId(message.getInstructionId());
        record.setDirection(IotConstants.DIRECTION_INBOUND);
        record.setMessageType(messageType);
        record.setReceiveTopic(topic);
        record.setContainerId(message.getContainerId());
        record.setReferenceId(message.getReferenceId());
        record.setSourceLocationId(message.getSourceLocationId());
        record.setDestinationLocationIds(normalizeDestinations(message.getDestinationLocationIds()));
        record.setMessageCreationTime(resolveCreationTime(message.getCreationTime()));
        record.setRawPayload(rawPayload);
        record.setProcessStatus(IotConstants.PROCESS_STATUS_RECEIVED);
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_NOT_REQUIRED);
        record.setCreateTime(now);
        record.setUpdateTime(now);
        return record;
    }
 
    private boolean isDelayed(IotInstructionMessage message, String messageType) {
        Long creationTime = resolveCreationTime(message.getCreationTime());
        IotPublishRecord latest = iotPublishRecordService.findLatestInboundInstruction(message.getContainerId(), messageType);
        return latest != null && latest.getMessageCreationTime() != null && latest.getMessageCreationTime() > creationTime;
    }
 
    /**
     * IoT 文档未提供物料和数量明细,这里沿用现有满托入库通知的兜底约定。
     */
    private MesToCombParam buildInboundParam(IotInstructionMessage message, String preferredLocNo) {
        MesToCombParam param = new MesToCombParam();
        param.setPalletId(message.getContainerId());
        param.setOrderId("");
        param.setBizNo(message.getInstructionId());
        param.setAnfme(1D);
        param.setFull(1);
        param.setLocId(preferredLocNo);
        param.setBoxType1(MQTT_SOURCE_BOX_TYPE);
        return param;
    }
 
    /**
     * 仅当指定库位当前仍为空位时才强制优先使用,否则回退到原有自动找位。
     */
    private String resolvePreferredInboundLoc(IotInstructionMessage message) {
        String preferredLoc = extractFirstDestination(message.getDestinationLocationIds());
        if (Cools.isEmpty(preferredLoc)) {
            return null;
        }
        LocMast locMast = locMastService.selectById(preferredLoc);
        if (locMast != null && "O".equalsIgnoreCase(locMast.getLocSts())) {
            return locMast.getLocNo();
        }
        return null;
    }
 
    private String resolveReferenceId(IotInstructionMessage message) {
        return Cools.isEmpty(message.getReferenceId()) ? message.getInstructionId() : message.getReferenceId();
    }
 
    private Long updateAsFailure(IotPublishRecord record, String errorCode, String errorMessage) {
        Date now = new Date();
        record.setProcessStatus(IotConstants.PROCESS_STATUS_FAILED);
        record.setOrderNo(Cools.isEmpty(record.getOrderNo()) ? record.getReferenceId() : record.getOrderNo());
        record.setErrorCode(errorCode);
        record.setErrorMessage(truncate(errorMessage, 500));
        applyFeedback(record, IotConstants.FEEDBACK_FAILURE, errorCode, errorMessage, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    private boolean isMqttOriginStowWork(WrkMast wrkMast) {
        List<WrkDetl> wrkDetls = loadWrkDetls(wrkMast);
        if (hasMqttSourceBoxType(wrkDetls)) {
            return true;
        }
        if (hasProcessedInboundByWrkNo(wrkMast.getWrkNo(), IotConstants.MESSAGE_TYPE_STOW)) {
            return true;
        }
 
        String containerId = resolveContainerId(wrkMast, wrkDetls);
        if (Cools.isEmpty(containerId)) {
            return false;
        }
        String bizNo = firstNonEmpty(wrkMast.getUserNo(), resolveOrderNo(wrkDetls));
        return hasProcessedInboundByBusinessKey(IotConstants.MESSAGE_TYPE_STOW, containerId, bizNo);
    }
 
    private boolean isMqttOriginPickWork(WrkMast wrkMast) {
        if (hasProcessedInboundByWrkNo(wrkMast.getWrkNo(), IotConstants.MESSAGE_TYPE_PICK)) {
            return true;
        }
        List<WrkDetl> wrkDetls = loadWrkDetls(wrkMast);
        String containerId = resolveContainerId(wrkMast, wrkDetls);
        if (Cools.isEmpty(containerId)) {
            return false;
        }
        String orderNo = firstNonEmpty(wrkMast.getUserNo(), resolveOrderNo(wrkDetls));
        return hasProcessedInboundByBusinessKey(IotConstants.MESSAGE_TYPE_PICK, containerId, orderNo);
    }
 
    private List<WrkDetl> loadWrkDetls(WrkMast wrkMast) {
        if (wrkMast == null || wrkMast.getWrkNo() == null) {
            return Collections.emptyList();
        }
        List<WrkDetl> wrkDetls = wrkDetlService.selectList(new EntityWrapper<WrkDetl>().eq("wrk_no", wrkMast.getWrkNo()));
        return wrkDetls == null ? Collections.<WrkDetl>emptyList() : wrkDetls;
    }
 
    private boolean hasMqttSourceBoxType(List<WrkDetl> wrkDetls) {
        if (Cools.isEmpty(wrkDetls)) {
            return false;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (wrkDetl != null && MQTT_SOURCE_BOX_TYPE.equalsIgnoreCase(wrkDetl.getBoxType1())) {
                return true;
            }
        }
        return false;
    }
 
    private boolean hasProcessedInboundByWrkNo(Integer wrkNo, String messageType) {
        if (wrkNo == null || Cools.isEmpty(messageType)) {
            return false;
        }
        return iotPublishRecordService.selectCount(new EntityWrapper<IotPublishRecord>()
                .eq("direction", IotConstants.DIRECTION_INBOUND)
                .eq("message_type", messageType)
                .eq("process_status", IotConstants.PROCESS_STATUS_PROCESSED)
                .eq("wrk_no", wrkNo)) > 0;
    }
 
    private boolean hasProcessedInboundByBusinessKey(String messageType, String containerId, String bizNo) {
        if (Cools.isEmpty(messageType) || Cools.isEmpty(containerId) || Cools.isEmpty(bizNo)) {
            return false;
        }
        // 出库:order_no/reference_id 通常是订单号;入库:instruction_id 通常会同步到 WrkMast.userNo。
        // 三个字段分别查询,避免 MyBatis-Plus 旧版本复杂 OR 条件在不同数据库方言下生成异常 SQL。
        return hasProcessedInbound(messageType, containerId, "order_no", bizNo)
                || hasProcessedInbound(messageType, containerId, "reference_id", bizNo)
                || hasProcessedInbound(messageType, containerId, "instruction_id", bizNo);
    }
 
    private boolean hasProcessedInbound(String messageType, String containerId, String column, String value) {
        return iotPublishRecordService.selectCount(new EntityWrapper<IotPublishRecord>()
                .eq("direction", IotConstants.DIRECTION_INBOUND)
                .eq("message_type", messageType)
                .eq("process_status", IotConstants.PROCESS_STATUS_PROCESSED)
                .eq("container_id", containerId)
                .eq(column, value)) > 0;
    }
 
    private String resolveContainerId(WrkMast wrkMast, List<WrkDetl> wrkDetls) {
        if (wrkMast != null && !Cools.isEmpty(wrkMast.getBarcode())) {
            return wrkMast.getBarcode();
        }
        if (Cools.isEmpty(wrkDetls)) {
            return null;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (wrkDetl != null && !Cools.isEmpty(wrkDetl.getZpallet())) {
                return wrkDetl.getZpallet();
            }
        }
        return null;
    }
 
    private String resolveOrderNo(List<WrkDetl> wrkDetls) {
        if (Cools.isEmpty(wrkDetls)) {
            return null;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (wrkDetl != null && !Cools.isEmpty(wrkDetl.getOrderNo())) {
                return wrkDetl.getOrderNo();
            }
        }
        return null;
    }
 
    private String firstNonEmpty(String first, String second) {
        return Cools.isEmpty(first) ? second : first;
    }
 
    private void applyFeedback(IotPublishRecord record, String status, String errorCode, String errorMessage, Date now) {
        IotFeedbackMessage feedbackMessage = new IotFeedbackMessage();
        feedbackMessage.setInstructionId(record.getInstructionId());
        feedbackMessage.setStatus(status);
        feedbackMessage.setErrorCode(errorCode);
        feedbackMessage.setMessage(errorMessage);
        feedbackMessage.setCreationTime(System.currentTimeMillis());
 
        record.setFeedbackStatus(status);
        record.setPublishTopic(iotDbConfigService.getEffectiveTopics().getIngressFeedback());
        record.setPublishPayload(JSON.toJSONString(feedbackMessage));
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_PENDING);
        record.setUpdateTime(now);
    }
 
    private String resolveResultMessage(R result, String defaultMessage) {
        if (result == null) {
            return defaultMessage;
        }
        Object msg = result.get("msg");
        return msg == null ? defaultMessage : String.valueOf(msg);
    }
 
    private Integer resolveWrkNo(R result) {
        if (result == null) {
            return null;
        }
        Object wrkNo = result.get("wrkNo");
        if (wrkNo instanceof Number) {
            return ((Number) wrkNo).intValue();
        }
        if (wrkNo instanceof String && !Cools.isEmpty(String.valueOf(wrkNo))) {
            return Integer.valueOf(String.valueOf(wrkNo));
        }
        return null;
    }
 
    private IotPublishRecord buildOutboundRecord(WrkMast wrkMast) {
        Integer ioType = wrkMast.getIoType();
        if (ioType == null) {
            return null;
        }
        String containerId = resolveContainerId(wrkMast);
        if (Cools.isEmpty(containerId)) {
            return null;
        }
        if (Arrays.asList(1, 8, 11, 53, 54, 57).contains(ioType)) {
            return buildStowOutboundRecord(wrkMast, containerId);
        }
        if (Arrays.asList(101, 108).contains(ioType)) {
            return buildPickOutboundRecord(wrkMast, containerId);
        }
        return null;
    }
 
    private IotPublishRecord buildStowOutboundRecord(WrkMast wrkMast, String containerId) {
        List<String> destinationLocationIds = wrkMast.getLocNo() == null
                ? Collections.<String>emptyList()
                : Collections.singletonList(wrkMast.getLocNo());
        if (destinationLocationIds.isEmpty()) {
            return null;
        }
        IotInstructionMessage payload = new IotInstructionMessage();
        payload.setInstructionId(IotInstructionIdGenerator.generate(String.valueOf(wrkMast.getWrkNo())));
        payload.setContainerId(containerId);
        if (Objects.equals(wrkMast.getIoType(), 11)) {
            payload.setSourceLocationId(wrkMast.getSourceLocNo());
        }
        payload.setDestinationLocationIds(destinationLocationIds);
        if (!Cools.isEmpty(wrkMast.getUserNo())) {
            payload.setReferenceId(wrkMast.getUserNo());
        }
        payload.setCreationTime(System.currentTimeMillis());
        return initOutboundRecord(wrkMast, IotConstants.MESSAGE_TYPE_STOW, iotDbConfigService.getEffectiveTopics().getIngressStow(), payload);
    }
 
    private IotPublishRecord buildPickOutboundRecord(WrkMast wrkMast, String containerId) {
        IotInstructionMessage payload = new IotInstructionMessage();
        payload.setInstructionId(IotInstructionIdGenerator.generate(String.valueOf(wrkMast.getWrkNo())));
        payload.setContainerId(containerId);
        payload.setSourceLocationId(wrkMast.getSourceLocNo());
        payload.setDestinationLocationIds(Collections.singletonList(resolveRemoteStationId(wrkMast.getStaNo())));
        if (!Cools.isEmpty(wrkMast.getUserNo())) {
            payload.setReferenceId(wrkMast.getUserNo());
        }
        payload.setCreationTime(System.currentTimeMillis());
        return initOutboundRecord(wrkMast, IotConstants.MESSAGE_TYPE_PICK, iotDbConfigService.getEffectiveTopics().getIngressPick(), payload);
    }
 
    private IotPublishRecord initOutboundRecord(WrkMast wrkMast, String messageType, String publishTopic, IotInstructionMessage payload) {
        Date now = new Date();
        IotPublishRecord record = new IotPublishRecord();
        record.setInstructionId(payload.getInstructionId());
        record.setDirection(IotConstants.DIRECTION_OUTBOUND);
        record.setMessageType(messageType);
        record.setPublishTopic(publishTopic);
        record.setContainerId(payload.getContainerId());
        record.setReferenceId(payload.getReferenceId());
        record.setSourceLocationId(payload.getSourceLocationId());
        record.setDestinationLocationIds(normalizeDestinations(payload.getDestinationLocationIds()));
        record.setMessageCreationTime(payload.getCreationTime());
        record.setPublishPayload(JSON.toJSONString(payload));
        record.setRawPayload(record.getPublishPayload());
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PENDING);
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_PENDING);
        record.setWrkNo(wrkMast.getWrkNo());
        record.setOrderNo(wrkMast.getUserNo());
        record.setCreateTime(now);
        record.setUpdateTime(now);
        return record;
    }
 
    private String resolveContainerId(WrkMast wrkMast) {
        if (!Cools.isEmpty(wrkMast.getBarcode())) {
            return wrkMast.getBarcode();
        }
        List<WrkDetl> wrkDetls = wrkDetlService.selectList(new EntityWrapper<WrkDetl>().eq("wrk_no", wrkMast.getWrkNo()));
        if (Cools.isEmpty(wrkDetls)) {
            return null;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (!Cools.isEmpty(wrkDetl.getZpallet())) {
                return wrkDetl.getZpallet();
            }
        }
        return null;
    }
 
    private String resolveRemoteStationId(Integer staNo) {
        if (staNo == null) {
            return null;
        }
        for (Map.Entry<String, Integer> entry : iotProperties.getPickStationMappings().entrySet()) {
            if (Objects.equals(entry.getValue(), staNo)) {
                return entry.getKey();
            }
        }
        return String.valueOf(staNo);
    }
 
    private String extractFirstDestination(List<String> destinationLocationIds) {
        if (Cools.isEmpty(destinationLocationIds)) {
            return null;
        }
        for (String destinationLocationId : destinationLocationIds) {
            if (!Cools.isEmpty(destinationLocationId)) {
                return destinationLocationId;
            }
        }
        return null;
    }
 
    private Long resolveCreationTime(Long creationTime) {
        return creationTime == null ? System.currentTimeMillis() : creationTime;
    }
 
    private String normalizeDestinations(List<String> destinationLocationIds) {
        if (Cools.isEmpty(destinationLocationIds)) {
            return null;
        }
        return JSON.toJSONString(new ArrayList<String>(destinationLocationIds));
    }
 
    private String truncate(String message, int maxLength) {
        if (message == null || message.length() <= maxLength) {
            return message;
        }
        return message.substring(0, maxLength);
    }
}