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;
/**
* 妇幼随访任务生成/发送实现。
*
*
节点来源:档案详情的 plannedFollowTime + followupPeriod;
* 落库:service_subtask(service_type=21),由 sfHandlle 的妇幼分支发送。
*/
@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 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 existingKeys = new HashSet<>();
List 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 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 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 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 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;
}
}