From 67d0eef6ef56713345e03afdfd7e5badf4d4ad3d Mon Sep 17 00:00:00 2001
From: 陈昶聿 <chychen@nbjetron.com>
Date: 星期二, 24 十一月 2026 14:13:11 +0800
Subject: [PATCH] fix: 补提交妇幼随访 service_subtask 方案核心文件

---
 smartor/src/main/java/com/smartor/service/mch/MchFollowupSubtaskServiceImpl.java |  600 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 600 insertions(+), 0 deletions(-)

diff --git a/smartor/src/main/java/com/smartor/service/mch/MchFollowupSubtaskServiceImpl.java b/smartor/src/main/java/com/smartor/service/mch/MchFollowupSubtaskServiceImpl.java
new file mode 100644
index 0000000..cee5cb8
--- /dev/null
+++ b/smartor/src/main/java/com/smartor/service/mch/MchFollowupSubtaskServiceImpl.java
@@ -0,0 +1,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锛�
+ * 钀藉簱锛歴ervice_subtask锛坰ervice_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 寮傚父锛宎rchiveType={}锛宎rchiveId={}锛宒etailId={}",
+                    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 鐢熸垚锛宒etailId={}锛宖ollowupStatus={}",
+                    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={}锛宲eriod={}",
+                    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("銆愬骞奸殢璁裤�憇ubtask 宸插瓨鍦紝detailId={}锛宻eq={}", snapshot.archiveDetailId, node.getSeq());
+            } catch (Exception e) {
+                log.error("銆愬骞奸殢璁裤�憇ubtask 鎻掑叆澶辫触锛宒etailId={}锛宻eq={}",
+                        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 鐢熸垚瀹屾垚锛宒etailId={}锛岃妭鐐规暟={}锛屼笅娆$敓鎴愭椂闂�={}",
+                    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 澶辫触锛宎rchiveType={}锛宎rchiveId={}锛宒etailId={}",
+                        candidate.getArchiveType(), candidate.getArchiveId(),
+                        candidate.getArchiveDetailId(), e);
+            }
+        }
+        return generated;
+    }
+
+    @Override
+    public void sendSubtask(ServiceSubtask subtask) {
+        if (subtask == null || subtask.getId() == null) {
+            log.warn("銆愬骞奸殢璁裤�憇ubtask 涓虹┖锛岃烦杩囧彂閫�");
+            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("銆愬骞奸殢璁裤�憇ubtask 宸茶棰嗗彇鎴栭潪寰呭彂閫侊紝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("銆愬骞奸殢璁裤�戣妭鐐笿SON瑙f瀽澶辫触锛宻ubtaskId={}锛宩son={}", subtask.getId(), nodeJson, e);
+            finish(subtask.getId(), 5L, "error", "濡囧辜闅忚鑺傜偣JSON瑙f瀽澶辫触", 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={}锛宻endstate={}", 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;
+    }
+
+    /**
+     * 纭繚姣忕濡囧辜妗f绫诲瀷鏈変竴鏉′笓鐢� 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("濡囧辜涓撶妗f闅忚");
+        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={}锛宼askName={}", 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;
+    }
+}

--
Gitblit v1.9.3