陈昶聿
2 天以前 67d0eef6ef56713345e03afdfd7e5badf4d4ad3d
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
package com.smartor.service.mch;
 
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.task.domain.ServiceSubtask;
import com.ruoyi.task.domain.ServiceTask;
import com.ruoyi.task.mapper.ServiceTaskMapper;
import com.smartor.common.MchFollowupConstants;
import com.smartor.common.SpecificArchiveConstants;
import com.smartor.domain.MchFollowupArchiveCandidate;
import com.smartor.domain.MchFollowupArchiveCursor;
import com.smartor.domain.MchFollowupNode;
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.domain.PatMaternityArchiveDetail;
import com.smartor.mapper.MchFollowupSubtaskMapper;
import com.smartor.mapper.PatChildArchiveDetailMapper;
import com.smartor.mapper.PatMaternityArchiveDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
 
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
/**
 * 妇幼随访任务生成/发送实现。
 *
 * <p>节点来源:档案详情的 plannedFollowTime + followupPeriod;
 * 落库:service_subtask(service_type=21),由 sfHandlle 的妇幼分支发送。</p>
 */
@Slf4j
@Service
public class MchFollowupSubtaskServiceImpl implements IMchFollowupSubtaskService {
 
    private static final String TASK_TYPE_FOLLOWUP = "1";
 
    private static final String PREACHFORM_SMS = "4";
 
    private static final String PREACHFORM_WECHAT = "5";
 
    private static final long FAR_FUTURE_MILLIS =
            java.sql.Timestamp.valueOf("9999-12-31 23:59:59").getTime();
 
    @Autowired
    private MchFollowupSubtaskMapper subtaskMapper;
 
    @Autowired
    private MchFollowupPeriodParser periodParser;
 
    @Autowired
    private MchFollowupTimeResolver timeResolver;
 
    @Autowired
    private MchFollowupMessageSender messageSender;
 
    @Autowired
    private PatMaternityArchiveDetailMapper maternityDetailMapper;
 
    @Autowired
    private PatChildArchiveDetailMapper childDetailMapper;
 
    @Autowired
    private ServiceTaskMapper serviceTaskMapper;
 
    @Autowired
    private ISysConfigService configService;
 
    @Override
    public int rebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        try {
            return doRebuildForArchive(archiveType, archiveId, archiveDetailId);
        } catch (Exception e) {
            log.error("【妇幼随访】生成 subtask 异常,archiveType={},archiveId={},detailId={}",
                    archiveType, archiveId, archiveDetailId, e);
            return 0;
        }
    }
 
    private int doRebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        if (!isEnabled()) {
            return 0;
        }
        ArchiveSnapshot snapshot = loadSnapshot(archiveType, archiveId, archiveDetailId);
        if (snapshot == null || snapshot.archiveDetailId == null) {
            return 0;
        }
        if (!SpecificArchiveConstants.LISHUI_MCH_ORG_ID.equals(snapshot.orgid)) {
            return 0;
        }
        if (!MchFollowupConstants.FOLLOWUP_STATUS_ACTIVE.equals(snapshot.followupStatus)) {
            log.debug("【妇幼随访】档案未确认随访,跳过 subtask 生成,detailId={},followupStatus={}",
                    snapshot.archiveDetailId, snapshot.followupStatus);
            return 0;
        }
        if (snapshot.plannedFollowTime == null || StringUtils.isBlank(snapshot.followupPeriod)) {
            return 0;
        }
 
        List<MchFollowupNode> nodes;
        try {
            nodes = periodParser.parse(snapshot.followupPeriod, snapshot.followupCycleTimes);
        } catch (Exception e) {
            log.error("【妇幼随访】随访周期解析失败,detailId={},period={}",
                    snapshot.archiveDetailId, snapshot.followupPeriod, e);
            return 0;
        }
        if (nodes == null || nodes.isEmpty()) {
            return 0;
        }
 
        String planHash = planHash(snapshot);
        Date now = DateUtils.getNowDate();
        long aheadMillis = generateAheadMillis();
        Date dueBefore = new Date(now.getTime() + aheadMillis);
        long notBefore = now.getTime() - MchFollowupConstants.CATCHUP_MILLIS;
 
        MchFollowupArchiveCursor cursor =
                subtaskMapper.selectMchCursor(snapshot.archiveType, snapshot.archiveDetailId);
        boolean planChanged = cursor == null || !planHash.equals(cursor.getPlanHash());
        if (planChanged) {
            subtaskMapper.cancelPendingByArchiveDetailId(snapshot.archiveDetailId, planHash, now);
        }
 
        Set<String> existingKeys = new HashSet<>();
        List<ServiceSubtask> existing = subtaskMapper.selectByArchiveDetailId(snapshot.archiveDetailId);
        if (existing != null) {
            for (ServiceSubtask subtask : existing) {
                if (subtask.getMchNodeSeq() == null || !planHash.equals(subtask.getMchPlanHash())) {
                    continue;
                }
                existingKeys.add(planHash + "#" + subtask.getMchNodeSeq());
            }
        }
 
        Long taskId = null;
        Date nextDue = null;
        boolean retryNow = false;
        int generated = 0;
        for (MchFollowupNode node : nodes) {
            if (node == null || node.getSeq() == null) {
                continue;
            }
            Date sendTime = timeResolver.resolve(snapshot.plannedFollowTime, node);
            if (sendTime == null) {
                continue;
            }
            if (sendTime.getTime() > dueBefore.getTime()) {
                // 未来节点先不生成,只记录最早的未来到期时间
                if (nextDue == null || sendTime.before(nextDue)) {
                    nextDue = sendTime;
                }
                continue;
            }
            if (sendTime.getTime() < notBefore) {
                // 超过补发窗口,不再生成,避免产生一批必然超时的任务
                continue;
            }
            String key = planHash + "#" + node.getSeq();
            if (existingKeys.contains(key)) {
                continue;
            }
            if (taskId == null) {
                taskId = ensureTask(snapshot);
                if (taskId == null) {
                    log.error("【妇幼随访】未获取到妇幼随访任务,detailId={}", snapshot.archiveDetailId);
                    retryNow = true;
                    break;
                }
            }
            ServiceSubtask subtask = buildSubtask(snapshot, node, sendTime, planHash, taskId, now);
            try {
                generated += subtaskMapper.insertMchSubtask(subtask);
                existingKeys.add(key);
            } catch (DuplicateKeyException e) {
                log.debug("【妇幼随访】subtask 已存在,detailId={},seq={}", snapshot.archiveDetailId, node.getSeq());
            } catch (Exception e) {
                log.error("【妇幼随访】subtask 插入失败,detailId={},seq={}",
                        snapshot.archiveDetailId, node.getSeq(), e);
                retryNow = true;
            }
        }
 
        Date nextDueTime;
        if (retryNow) {
            nextDueTime = now;
        } else if (nextDue != null) {
            nextDueTime = nextDue;
        } else {
            nextDueTime = new Date(FAR_FUTURE_MILLIS);
        }
        subtaskMapper.updateMchCursor(snapshot.archiveType, snapshot.archiveDetailId, planHash, nextDueTime);
        if (generated > 0) {
            log.info("【妇幼随访】到期 subtask 生成完成,detailId={},节点数={},下次生成时间={}",
                    snapshot.archiveDetailId, generated, nextDueTime);
        }
        return generated;
    }
 
    @Override
    public int rebuildAll(int limit) {
        if (!isEnabled()) {
            return 0;
        }
        int batch = limit <= 0 ? MchFollowupConstants.DEFAULT_BATCH_SIZE : limit;
        Date dueBefore = new Date(DateUtils.getNowDate().getTime() + generateAheadMillis());
        List<MchFollowupArchiveCandidate> candidates =
                subtaskMapper.selectCandidates(SpecificArchiveConstants.LISHUI_MCH_ORG_ID, dueBefore, batch);
        if (candidates == null || candidates.isEmpty()) {
            return 0;
        }
        int generated = 0;
        for (MchFollowupArchiveCandidate candidate : candidates) {
            try {
                generated += rebuildForArchive(candidate.getArchiveType(),
                        candidate.getArchiveId(), candidate.getArchiveDetailId());
            } catch (Exception e) {
                log.error("【妇幼随访】补建 subtask 失败,archiveType={},archiveId={},detailId={}",
                        candidate.getArchiveType(), candidate.getArchiveId(),
                        candidate.getArchiveDetailId(), e);
            }
        }
        return generated;
    }
 
    @Override
    public void sendSubtask(ServiceSubtask subtask) {
        if (subtask == null || subtask.getId() == null) {
            log.warn("【妇幼随访】subtask 为空,跳过发送");
            return;
        }
        if (!MchFollowupConstants.SERVICE_TYPE_MCH.equals(subtask.getServiceType())) {
            return;
        }
        Date now = DateUtils.getNowDate();
        // longTaskSend/compensateTask 按“日期”捞取,妇幼节点需要再按精确时间判断,避免提前发送
        if (subtask.getVisitTime() != null && subtask.getVisitTime().getTime() > now.getTime()) {
            return;
        }
        int claimed = subtaskMapper.claimMchSubtask(subtask.getId(), now);
        if (claimed == 0) {
            log.debug("【妇幼随访】subtask 已被领取或非待发送,subtaskId={}", subtask.getId());
            return;
        }
        try {
        // 与旧妇幼发送逻辑保持一致:只补发 1 天内到期的节点,超时节点不再发送
        if (subtask.getVisitTime() != null
                && now.getTime() - subtask.getVisitTime().getTime() > MchFollowupConstants.CATCHUP_MILLIS) {
            finish(subtask.getId(), 7L, "expired", "超过补发窗口,任务超时", null, now);
            return;
        }
 
        String nodeJson = subtask.getMchNodeJson();
        if (StringUtils.isBlank(nodeJson)) {
            nodeJson = subtaskMapper.selectNodeJsonById(subtask.getId());
        }
        if (StringUtils.isBlank(nodeJson)) {
            finish(subtask.getId(), 5L, "error", "妇幼随访节点JSON为空", null, now);
            return;
        }
 
        MchFollowupNode node;
        try {
            node = JSON.parseObject(nodeJson, MchFollowupNode.class);
        } catch (Exception e) {
            log.error("【妇幼随访】节点JSON解析失败,subtaskId={},json={}", subtask.getId(), nodeJson, e);
            finish(subtask.getId(), 5L, "error", "妇幼随访节点JSON解析失败", null, now);
            return;
        }
        if (node == null) {
            finish(subtask.getId(), 5L, "error", "妇幼随访节点JSON为空", null, now);
            return;
        }
 
        MchFollowupSendContext context = buildContext(subtask, node);
        MchFollowupSendOutcome outcome = MchFollowupConstants.SEND_TYPE_WECHAT.equals(node.getSendType())
                ? messageSender.sendWechat(context)
                : messageSender.sendSms(context);
 
        if (outcome.isOk()) {
            String remark = "妇幼随访发送成功";
            if (StringUtils.isNotBlank(outcome.getProviderMsgId())) {
                remark = remark + "," + outcome.getProviderMsgId();
            }
            finish(subtask.getId(), 6L, "success", truncate(remark), now, now);
        } else if (outcome.isSkipped()) {
            finish(subtask.getId(), 4L, "skip", truncate(outcome.getMessage()), null, now);
        } else {
            finish(subtask.getId(), 5L, "error", truncate(outcome.getMessage()), null, now);
        }
        } catch (Exception e) {
            log.error("【妇幼随访】发送异常,subtaskId={}", subtask.getId(), e);
            finish(subtask.getId(), 5L, "error", truncate("发送异常:" + e.getMessage()), null, now);
        }
    }
 
    private void finish(Long id, Long sendstate, String result, String remark, Date finishtime, Date now) {
        int updated = subtaskMapper.updateMchSendResult(id, sendstate, result, remark, finishtime, now);
        if (updated == 0) {
            log.warn("【妇幼随访】回写发送结果失败,subtaskId={},sendstate={}", id, sendstate);
        }
    }
 
    private ServiceSubtask buildSubtask(ArchiveSnapshot snapshot, MchFollowupNode node, Date sendTime,
                                        String planHash, Long taskId, Date now) {
        node.setArchiveType(snapshot.archiveType);
        node.setArchiveSubType(snapshot.archiveSubType);
        node.setPlannedFollowTime(snapshot.plannedFollowTime);
 
        ServiceSubtask subtask = new ServiceSubtask();
        subtask.setTaskid(taskId);
        subtask.setTaskName(resolveTaskName(snapshot.archiveType, snapshot.archiveSubType));
        subtask.setTaskDesc(node.getContent());
        subtask.setSendname(snapshot.patname);
        subtask.setPatid(snapshot.patid);
        subtask.setPhone(snapshot.phone);
        subtask.setSfzh(snapshot.idcardno);
        subtask.setHospno(snapshot.sourceBizNo);
        subtask.setVisitTime(sendTime);
        subtask.setSendstate(2L);
        subtask.setOrgid(snapshot.orgid);
        subtask.setCampusid(snapshot.campusid);
        subtask.setServiceType(MchFollowupConstants.SERVICE_TYPE_MCH);
        subtask.setType(TASK_TYPE_FOLLOWUP);
        subtask.setCurrentPreachform(MchFollowupConstants.SEND_TYPE_WECHAT.equals(node.getSendType())
                ? PREACHFORM_WECHAT : PREACHFORM_SMS);
        subtask.setSendType("2");
        subtask.setTemplateid(node.getTemplateId());
        subtask.setTemplatename(node.getTitleName());
        subtask.setIsVisitAgain(1);
        subtask.setCreateTime(now);
        subtask.setUpdateTime(now);
        subtask.setDelFlag("0");
        subtask.setMchArchiveDetailId(snapshot.archiveDetailId);
        subtask.setMchNodeSeq(node.getSeq());
        subtask.setMchPlanHash(planHash);
        subtask.setMchNodeJson(JSON.toJSONString(node));
        return subtask;
    }
 
    private MchFollowupSendContext buildContext(ServiceSubtask subtask, MchFollowupNode node) {
        MchFollowupSendContext context = new MchFollowupSendContext();
        context.setOrgid(subtask.getOrgid());
        context.setPatid(subtask.getPatid());
        context.setPatname(subtask.getSendname());
        context.setPhone(subtask.getPhone());
        context.setIdcardno(subtask.getSfzh());
        context.setSourceBizNo(subtask.getHospno());
        context.setArchiveType(node.getArchiveType());
        context.setPlannedFollowTime(node.getPlannedFollowTime());
        context.setSeq(node.getSeq());
        context.setSendType(node.getSendType());
        context.setContent(node.getContent());
        context.setTitleName(node.getTitleName());
        context.setTemplateId(node.getTemplateId());
        context.setUrl(node.getUrl());
        return context;
    }
 
    /**
     * 确保每种妇幼档案类型有一条专用 service_task。
     * 妇幼任务走 sfHandlle 的 service_type=21 分支,不依赖 preachform_desc。
     */
    private synchronized Long ensureTask(ArchiveSnapshot snapshot) {
        String taskName = resolveTaskName(snapshot.archiveType, snapshot.archiveSubType);
 
        ServiceTask query = new ServiceTask();
        query.setTaskName(taskName);
        query.setServiceType(MchFollowupConstants.SERVICE_TYPE_MCH);
        query.setDelFlag("0");
        List<ServiceTask> tasks = serviceTaskMapper.selectServiceTaskList(query);
        if (tasks != null) {
            for (ServiceTask task : tasks) {
                if (taskName.equals(task.getTaskName())
                        && MchFollowupConstants.SERVICE_TYPE_MCH.equals(task.getServiceType())
                        && "0".equals(task.getDelFlag())) {
                    return task.getTaskid();
                }
            }
        }
 
        Date now = DateUtils.getNowDate();
        ServiceTask task = new ServiceTask();
        task.setTaskName(taskName);
        task.setTypename("妇幼随访");
        task.setTaskDesc("妇幼专科档案随访");
        task.setServiceType(MchFollowupConstants.SERVICE_TYPE_MCH);
        task.setType(TASK_TYPE_FOLLOWUP);
        task.setPreachform(PREACHFORM_SMS);
        task.setPreachformDesc("[{\"preachform\":\"4\",\"sort\":1,\"compensateTime\":\"0\"}]");
        task.setSendType(3L);
        task.setSendState(2L);
        task.setLongTask(1);
        task.setOrgid(SpecificArchiveConstants.LISHUI_MCH_ORG_ID);
        task.setCampusid("1");
        task.setDelFlag("0");
        task.setCreateBy("system");
        task.setCreateTime(now);
        task.setUpdateTime(now);
        int inserted = serviceTaskMapper.insertServiceTask(task);
        if (inserted > 0 && task.getTaskid() != null) {
            log.info("【妇幼随访】创建专用任务,taskid={},taskName={}", task.getTaskid(), taskName);
            return task.getTaskid();
        }
        log.error("【妇幼随访】创建专用任务失败,taskName={}", taskName);
        return null;
    }
 
    private String resolveTaskName(String archiveType, String archiveSubType) {
        if (MchFollowupConstants.ARCHIVE_TYPE_MATERNITY.equals(archiveType)) {
            if ("1".equals(archiveSubType)) {
                return "早孕关爱随访";
            }
            if ("2".equals(archiveSubType)) {
                return "围绝经期MHI随访";
            }
            return "妇保随访";
        }
        if (MchFollowupConstants.ARCHIVE_TYPE_CHILD.equals(archiveType)) {
            if ("1".equals(archiveSubType)) {
                return "营养性疾病随访";
            }
            if ("2".equals(archiveSubType)) {
                return "学习困难随访";
            }
            if ("3".equals(archiveSubType)) {
                return "高危儿专案随访";
            }
            return "儿保随访";
        }
        return "妇幼随访";
    }
 
    private ArchiveSnapshot loadSnapshot(String archiveType, Long archiveId, Long archiveDetailId) {
        if (MchFollowupConstants.ARCHIVE_TYPE_MATERNITY.equals(archiveType)) {
            return loadMaternitySnapshot(archiveId, archiveDetailId);
        }
        if (MchFollowupConstants.ARCHIVE_TYPE_CHILD.equals(archiveType)) {
            return loadChildSnapshot(archiveId, archiveDetailId);
        }
        return null;
    }
 
    private ArchiveSnapshot loadMaternitySnapshot(Long archiveId, Long archiveDetailId) {
        PatMaternityArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = maternityDetailMapper.selectPatMaternityArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatMaternityArchiveDetail query = new PatMaternityArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatMaternityArchiveDetail> list =
                    maternityDetailMapper.selectPatMaternityArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_MATERNITY;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.archiveSubType = detail.getArchiveType();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = detail.getPhone();
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        snapshot.followupCycleTimes = detail.getFollowupCycleTimes();
        snapshot.followupStatus = detail.getFollowupStatus();
        return snapshot;
    }
 
    private ArchiveSnapshot loadChildSnapshot(Long archiveId, Long archiveDetailId) {
        PatChildArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = childDetailMapper.selectPatChildArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatChildArchiveDetail query = new PatChildArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatChildArchiveDetail> list =
                    childDetailMapper.selectPatChildArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_CHILD;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.archiveSubType = detail.getArchiveType();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = firstNotBlank(detail.getParentPhone(), detail.getPhone());
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        snapshot.followupStatus = detail.getFollowupStatus();
        return snapshot;
    }
 
    private String planHash(ArchiveSnapshot snapshot) {
        String raw = (snapshot.plannedFollowTime == null ? "" : snapshot.plannedFollowTime.getTime())
                + "|" + nvl(snapshot.followupPeriod)
                + "|" + nvl(snapshot.followupCycleTimes);
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] bytes = digest.digest(raw.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(bytes.length * 2);
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new BaseException("计算妇幼随访计划哈希失败:" + e.getMessage());
        }
    }
 
    private long generateAheadMillis() {
        try {
            String value = configService.selectConfigByKey(
                    MchFollowupConstants.CONFIG_GENERATE_AHEAD_MINUTES);
            if (StringUtils.isNotBlank(value)) {
                long minutes = Long.parseLong(value.trim());
                if (minutes >= 0) {
                    return minutes * 60_000L;
                }
            }
        } catch (Exception e) {
            log.warn("【妇幼随访】读取懒生成提前量配置失败,使用默认值:{}", e.getMessage());
        }
        return MchFollowupConstants.GENERATE_AHEAD_MILLIS;
    }
 
    private boolean isEnabled() {
        try {
            String value = configService.selectConfigByKey(MchFollowupConstants.CONFIG_ENABLED);
            return value == null || !"false".equalsIgnoreCase(value.trim());
        } catch (Exception e) {
            log.warn("【妇幼随访】读取启用开关失败,按启用处理:{}", e.getMessage());
            return true;
        }
    }
 
    private static String firstNotBlank(String first, String second) {
        return StringUtils.isNotBlank(first) ? first : second;
    }
 
    private static String nvl(String value) {
        return value == null ? "" : value;
    }
 
    private static String truncate(String text) {
        if (text == null) {
            return null;
        }
        return text.length() <= 500 ? text : text.substring(0, 500);
    }
 
    private static class ArchiveSnapshot {
        private String archiveType;
        private Long archiveId;
        private Long archiveDetailId;
        private String orgid;
        private String campusid;
        private String archiveSubType;
        private String sourceType;
        private String sourceBizNo;
        private Long patid;
        private String patname;
        private String phone;
        private String idcardno;
        private Date plannedFollowTime;
        private String followupPeriod;
        private String followupCycleTimes;
        private String followupStatus;
    }
}