ruoyi-inhospvisit/src/main/java/com/ruoyi/inhospvisit/service/InhospTaskOrchestrator.java
@@ -21,12 +21,26 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
 * 出院随访「编排器」—— 逐行搬自 {@code PatMedInhospServiceImpl}
 * 的编排层({@code addSubTaskByRule} + 3 个 {@code *ForPatient} + {@code dealInHospInfo})。
 *
 * <h3>⚠️ 生成口径(2026-11 更新)</h3>
 * <ul>
 *   <li><b>未配置规则({@code rule == null})</b>:按任务配置<b>全量生成</b> ——
 *       科室、病区、疾病三个维度都尝试,每个维度内命中的长期任务各生成一条;</li>
 *   <li><b>配置了规则</b>:按 {@code service_task_rule} 的首要/次要顺序执行所有配置维度,
 *       每个维度内命中的长期任务各生成一条,不再首个成功即停止;配置维度都没生成时,
 *       再走科室/病区通用兜底。</li>
 * </ul>
 * 无论哪种口径,标志位都会统一回写,保证 {@code deptcheck_flag} 不再停在 0(防重复扫描);
 * 并在写库前按 {@code patid+inhospid+taskid} 判重(见 {@code VisitTaskCreateApi#existsSubtask})。
 *
 * <h3>来源对照(@ b25c3b51)</h3>
 * <table border="1">
@@ -74,19 +88,29 @@
@Service
public class InhospTaskOrchestrator {
    /** 出院随访的服务类型 */
    /**
     * 出院随访的服务类型
     */
    private static final String SERVICE_TYPE_DISCHARGE = "2";
    /** 维度:科室 */
    /**
     * 维度:科室
     */
    private static final String DEPT_TYPE_DEPT = "1";
    /** 维度:病区 */
    /**
     * 维度:病区
     */
    private static final String DEPT_TYPE_WARD = "2";
    /** 站点:新华(跳过病区+疾病维度) */
    /**
     * 站点:新华(跳过病区+疾病维度)
     */
    private static final String SITE_XH = "xh";
    /** 站点:南华附一(疾病维度用诊断名) */
    /**
     * 站点:南华附一(疾病维度用诊断名)
     */
    private static final String SITE_NHFY = "nhfy";
    @Value("${spring.profiles.active}")
@@ -121,166 +145,258 @@
    // ==========================================================================
    /**
     * 按 {@code service_task_rule} 的「首要(1)/次要(2)」规则编排科室/病区/疾病三个维度。
     * <p>
     * 逐行对应原 {@code addSubTaskByRule(String config, List<PatMedInhosp> patMedInhosps)}。
     * <p>
     * ⚠️ 规则查询 {@code serviceTaskRuleMapper.selectServiceTaskRuleByDeptOrWard} 仍在 smartor,
     * 所以本方法接收<b>已查好的规则</b>(由调用方 {@code InhospVisitTaskService} 通过
     * {@code PublicityDataPort} 取——该端口已含"按科室/病区查规则"的能力,见下)。
     * 这样做是为了避免为"规则表"再加一个 Mapper 或端口。
     * 编排科室/病区/疾病三个维度。
     *
     * @param inhosp 待处理的出院患者
     * <h3>⚠️ 两种口径</h3>
     * <ul>
     *   <li><b>未配置规则</b>({@code rule == null}):按任务配置<b>全量生成</b>。
     *       科室、病区、疾病三个维度依次执行,每个维度内命中的长期任务各生成一条,
     *       不做“首个维度成功即停止”的截断。</li>
     *   <li><b>配置了规则</b>:按 {@code service_task_rule} 的「首要(1)/次要(2)」顺序
     *       执行所有配置维度,每个维度内命中的长期任务各生成一条,<b>不再首个成功即停止</b>。
     *       配置维度都未生成时,再走科室/病区通用兜底。</li>
     * </ul>
     * 另有一道兜底在 {@code InhospSubtaskWriter#writeInSubTask}:落库前按
     * {@code patid + inhospid + taskid} 判重,见 {@link VisitTaskCreateApi#existsSubtask}。
     *
     * <h3>站点差异(保留)</h3>
     * {@code xh} 只做科室维度 —— {@link #addDimension} 里统一挡掉病区/疾病。
     *
     * @param inhosp  待处理的出院患者
     * @param archive 患者档案
     * @param rule 已查好的规则;{@code null} = 未配置规则(全部生成)
     * @param config {@code sys_config: visit.early.day}
     * @param rule    已查好的规则;{@code null} = 该科室/病区未配置规则(按任务全量生成)
     * @param config  {@code sys_config: visit.early.day}
     */
    public void addSubTaskByRule(VisitInhospRow inhosp, VisitArchiveRow archive,
                                 VisitTaskRule rule, String config) {
    public void addSubTaskByRule(VisitInhospRow inhosp, VisitArchiveRow archive, VisitTaskRule rule, String config) {
        try {
            if (rule == null) {
                // 原 L1709-1716:规则为空,全部生成
                log.info("【基于规则】患者{}未配置规则,执行全部生成逻辑", inhosp.getInhospid());
                addDeptSubTaskForPatient(inhosp, archive, config);
                if (!SITE_XH.equals(active)) {
                    addWardSubTaskForPatient(inhosp, archive, config);
                    addIcd10SubTaskForPatient(inhosp, archive, config);
                }
                return;
            }
            // 原 L1717-1726:有规则,按规则执行
            log.info("【基于规则】患者{}查询到规则:deptRule={}, wradRule={}, diagRule={}",
                    inhosp.getInhospid(), rule.getDeptRule(), rule.getWradRule(), rule.getDiagRule());
            boolean deptIsPrimary = "1".equals(rule.getDeptRule());
            boolean wardIsPrimary = "1".equals(rule.getWradRule());
            boolean diagIsPrimary = "1".equals(rule.getDiagRule());
            boolean deptIsSecondary = "2".equals(rule.getDeptRule());
            boolean wardIsSecondary = "2".equals(rule.getWradRule());
            boolean diagIsSecondary = "2".equals(rule.getDiagRule());
            boolean hasPrimaryRule = deptIsPrimary || wardIsPrimary || diagIsPrimary;
            if (!hasPrimaryRule) {
                // 原 L1829-1837:没有首要规则,全部生成
                log.info("【基于规则】无首要规则,执行全部生成逻辑");
                addDeptSubTaskForPatient(inhosp, archive, config);
                if (!SITE_XH.equals(active)) {
                    addWardSubTaskForPatient(inhosp, archive, config);
                    addIcd10SubTaskForPatient(inhosp, archive, config);
                }
                log.info("【无规则】患者{}未配置任务规则,按任务配置全量生成", inhosp.getInhospid());
                addAllSubTasksByTaskConfig(inhosp, archive, config);
                return;
            }
            // 原 L1730-1754:先执行所有规则=1 的方法
            int deptGenCount = 0;
            int wardGenCount = 0;
            int diagGenCount = 0;
            List<Integer> order = resolveDimensionOrder(rule);
            log.info("【基于规则】患者{}规则:deptRule={}, wradRule={}, diagRule={};维度尝试顺序={}", inhosp.getInhospid(), rule.getDeptRule(), rule.getWradRule(), rule.getDiagRule(), order);
            if (deptIsPrimary) {
                log.info("【基于规则】执行科室首要规则");
                deptGenCount = addDeptSubTaskForPatient(inhosp, archive, config);
            }
            if (!SITE_XH.equals(active)) {
                if (wardIsPrimary) {
                    log.info("【基于规则】执行病区首要规则");
                    wardGenCount = addWardSubTaskForPatient(inhosp, archive, config);
                }
                if (diagIsPrimary) {
                    log.info("【基于规则】执行疾病首要规则");
                    diagGenCount = addIcd10SubTaskForPatient(inhosp, archive, config);
            Set<Integer> hitTypes = new LinkedHashSet<>();
            for (Integer type : order) {
                log.info("【基于规则】患者{}按首要/次要顺序尝试维度{}({}),全量生成", inhosp.getInhospid(), type, dimensionName(type));
                if (generateAllForDimension(inhosp, archive, type, config)) {
                    hitTypes.add(type);
                }
            }
            int primaryGeneratedCount = deptGenCount + wardGenCount + diagGenCount;
            log.info("【基于规则】首要规则执行结果: deptGen={}, wardGen={}, diagGen={}, total={}",
                    deptGenCount, wardGenCount, diagGenCount, primaryGeneratedCount);
            String remark = inhosp.getRemark();
            if (primaryGeneratedCount > 0) {
                // 原 L1758-1796:至少一个首要规则成功
                log.info("【基于规则】首要规则有成功(count={}),将次要规则对应flag设为2", primaryGeneratedCount);
                if (deptIsSecondary) {
                    updateCheckFlag(inhosp, 1, "2", StringUtils.isNotEmpty(remark)
                            ? remark + ";首要规则已生成,次要规则跳过" : "首要规则已生成,次要规则跳过");
                }
                if (!SITE_XH.equals(active)) {
                    if (wardIsSecondary) {
                        updateCheckFlag(inhosp, 2, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";首要规则已生成,次要规则跳过" : "首要规则已生成,次要规则跳过");
                    }
                    if (diagIsSecondary) {
                        updateCheckFlag(inhosp, 3, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";首要规则已生成,次要规则跳过" : "首要规则已生成,次要规则跳过");
                    }
                }
                if (deptIsPrimary && deptGenCount > 0) {
                    updateCheckFlag(inhosp, 1, "1", StringUtils.isNotEmpty(remark)
                            ? remark + ";科室首要规则生成成功" : "科室首要规则生成成功");
                }
                if (!SITE_XH.equals(active)) {
                    if (wardIsPrimary && wardGenCount > 0) {
                        updateCheckFlag(inhosp, 2, "1", StringUtils.isNotEmpty(remark)
                                ? remark + ";病区首要规则生成成功" : "病区首要规则生成成功");
                    }
                    if (diagIsPrimary && diagGenCount > 0) {
                        updateCheckFlag(inhosp, 3, "1", StringUtils.isNotEmpty(remark)
                                ? remark + ";疾病首要规则生成成功" : "疾病首要规则生成成功");
                    }
                }
                if (deptIsPrimary && deptGenCount == 0) {
                    updateCheckFlag(inhosp, 1, "2", StringUtils.isNotEmpty(remark)
                            ? remark + ";科室首要规则生成失败" : "科室首要规则生成失败");
                }
                if (!SITE_XH.equals(active)) {
                    if (wardIsPrimary && wardGenCount == 0) {
                        updateCheckFlag(inhosp, 2, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";病区首要规则生成失败" : "病区首要规则生成失败");
                    }
                    if (diagIsPrimary && diagGenCount == 0) {
                        updateCheckFlag(inhosp, 3, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";疾病首要规则生成失败" : "疾病首要规则生成失败");
                    }
                }
            } else {
                // 原 L1797-1828:所有首要规则全部失败 → 把 =1 的置 2,然后执行次要规则
                log.info("【基于规则】首要规则全部失败,将=1的flag设为2,开始执行次要规则");
                if (deptIsPrimary) {
                    updateCheckFlag(inhosp, 1, "2", StringUtils.isNotEmpty(remark)
                            ? remark + ";科室首要规则全部失败" : "科室首要规则全部失败");
                }
                if (!SITE_XH.equals(active)) {
                    if (wardIsPrimary) {
                        updateCheckFlag(inhosp, 2, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";病区首要规则全部失败" : "病区首要规则全部失败");
                    }
                    if (diagIsPrimary) {
                        updateCheckFlag(inhosp, 3, "2", StringUtils.isNotEmpty(remark)
                                ? remark + ";疾病首要规则全部失败" : "疾病首要规则全部失败");
                    }
                }
                if (deptIsSecondary) {
                    log.info("【基于规则】执行科室次要规则");
                    addDeptSubTaskForPatient(inhosp, archive, config);
                }
                if (!SITE_XH.equals(active)) {
                    if (wardIsSecondary) {
                        log.info("【基于规则】执行病区次要规则");
                        addWardSubTaskForPatient(inhosp, archive, config);
                    }
                    if (diagIsSecondary) {
                        log.info("【基于规则】执行疾病次要规则");
                        addIcd10SubTaskForPatient(inhosp, archive, config);
            // 规则配置的维度都没有生成时,才走科室/病区通用兜底;
            // 有任何一个配置维度生成成功,就不再额外生成未配置的兜底任务。
            if (hitTypes.isEmpty()) {
                for (Integer type : resolveFallbackDimensions(order)) {
                    log.info("【基于规则】患者{}配置维度均未生成,尝试通用兜底维度{}({}),全量生成", inhosp.getInhospid(), type, dimensionName(type));
                    if (generateAllForDimension(inhosp, archive, type, config)) {
                        hitTypes.add(type);
                    }
                }
            }
            log.info("【基于规则】患者{}全量生成完成,命中维度={}", inhosp.getInhospid(), hitTypes);
            writeFlagsAfterRun(inhosp, hitTypes);
        } catch (Exception e) {
            // 原 L1839-1845
            e.printStackTrace();
            log.error("【基于规则】患者{}处理异常:{}", inhosp.getInhospid(), e.getMessage());
            updateCheckFlag(inhosp, 1, "2", "基于规则处理异常");
        }
    }
    /**
     * 无规则口径:按任务配置全量生成。
     * <p>
     * 科室、病区、疾病三个维度都尝试,每个维度内由对应的 {@code *ForPatient}
     * 把所有命中的长期任务各写一条。{@code xh} 站点仍只做科室维度。
     * <p>
     * 各维度是否命中分别回写标志位({@code 1}=有生成,{@code 2}=无生成),
     * 且 {@code deptcheck_flag} 一定非 0,防止下一轮扫描重复处理。
     */
    private void addAllSubTasksByTaskConfig(VisitInhospRow inhosp, VisitArchiveRow archive, String config) {
        boolean xhSite = SITE_XH.equals(active);
        Set<Integer> hitTypes = new LinkedHashSet<>();
        if (generateAllForDimension(inhosp, archive, 1, config)) {
            hitTypes.add(1);
        }
        if (!xhSite) {
            if (generateAllForDimension(inhosp, archive, 2, config)) {
                hitTypes.add(2);
            }
            if (generateAllForDimension(inhosp, archive, 3, config)) {
                hitTypes.add(3);
            }
        }
        log.info("【无规则】患者{}按任务配置全量生成完成,命中维度={}", inhosp.getInhospid(), hitTypes);
        writeFlagsAfterRun(inhosp, hitTypes);
    }
    /**
     * 有规则时的<b>配置维度</b>顺序:{@code [首要维度…, 次要维度…]}。
     * <p>
     * 首要在前、次要其后;每个维度都会执行,且每个维度内所有命中任务都会生成,
     * 不再因为前一个维度成功就跳过后续维度。
     * <p>
     * ⚠️ {@code rule == null} 的“按任务全量生成”口径由
     * {@link #addAllSubTasksByTaskConfig} 处理,不再走本方法。
     */
    private List<Integer> resolveDimensionOrder(VisitTaskRule rule) {
        boolean xhSite = SITE_XH.equals(active);
        List<Integer> order = new ArrayList<>(4);
        boolean deptIsPrimary = "1".equals(rule.getDeptRule());
        boolean wardIsPrimary = "1".equals(rule.getWradRule());
        boolean diagIsPrimary = "1".equals(rule.getDiagRule());
        boolean deptIsSecondary = "2".equals(rule.getDeptRule());
        boolean wardIsSecondary = "2".equals(rule.getWradRule());
        boolean diagIsSecondary = "2".equals(rule.getDiagRule());
        // 同优先级内固定顺序:科室 → 病区 → 疾病
        if (deptIsPrimary) {
            addDimension(order, 1, xhSite);
        }
        if (wardIsPrimary) {
            addDimension(order, 2, xhSite);
        }
        if (diagIsPrimary) {
            addDimension(order, 3, xhSite);
        }
        if (deptIsSecondary) {
            addDimension(order, 1, xhSite);
        }
        if (wardIsSecondary) {
            addDimension(order, 2, xhSite);
        }
        if (diagIsSecondary) {
            addDimension(order, 3, xhSite);
        }
        return order;
    }
    /**
     * 规则配置的维度全部未生成时的通用兜底顺序:科室 → 病区。
     * <p>
     * 兜底只在配置维度一个都没生成时执行,避免又生成规则未配置的额外任务;
     * 已经在 {@code attempted} 里出现过的维度不重复尝试。
     */
    private List<Integer> resolveFallbackDimensions(List<Integer> attempted) {
        boolean xhSite = SITE_XH.equals(active);
        List<Integer> fallback = new ArrayList<>(2);
        if (attempted == null || !attempted.contains(1)) {
            addDimension(fallback, 1, xhSite);
        }
        if (attempted == null || !attempted.contains(2)) {
            addDimension(fallback, 2, xhSite);
        }
        return fallback;
    }
    /**
     * 追加一个候选维度;{@code xh} 站点只允许科室维度(原 {@code !active.equals("xh")} 的等价写法)
     */
    private void addDimension(List<Integer> order, int type, boolean xhSite) {
        if (xhSite && type != 1) {
            return;
        }
        if (!order.contains(type)) {
            order.add(type);
        }
    }
    private String dimensionName(int type) {
        switch (type) {
            case 1:
                return "科室";
            case 2:
                return "病区";
            case 3:
                return "疾病";
            default:
                return "未知(" + type + ")";
        }
    }
    /**
     * 尝试一个维度,生成该维度下所有命中的长期任务。
     * <p>
     * 无规则分支和配置了规则的分支都走这里。
     *
     * @return 是否至少生成(或已存在)一条子任务
     */
    private boolean generateAllForDimension(VisitInhospRow inhosp, VisitArchiveRow archive, int type, String config) {
        log.info("【全量生成】患者{}尝试维度{}({}),按任务配置全量生成", inhosp.getInhospid(), type, dimensionName(type));
        switch (type) {
            case 1:
                return addDeptSubTaskForPatient(inhosp, archive, config, true) > 0;
            case 2:
                return addWardSubTaskForPatient(inhosp, archive, config, true) > 0;
            case 3:
                return addIcd10SubTaskForPatient(inhosp, archive, config, true) > 0;
            default:
                return false;
        }
    }
    /**
     * 一轮生成结束后的标志位回写。
     * <p>
     * ⚠️ 关键点:扫描键是 {@code pat_med_inhosp.deptcheck_flag = '0'},
     * 所以<b>不论命中哪个维度,deptcheck_flag 都必须被写成 1 或 2</b>,
     * 否则下一轮扫描会把这个患者再处理一遍。
     * <p>
     * 可能有多个维度同时命中:所有命中维度写 {@code 1},其余维度写 {@code 2};
     * 只要有一个维度命中,{@code deptcheck_flag} 就一定是非 0。
     * <p>
     * 没有任何维度命中时,各维度方法已经把更具体的原因写进 {@code long_task_reason},
     * 这里只补扫描键,避免覆盖成泛泛的"未生成随访任务"。
     */
    private void writeFlagsAfterRun(VisitInhospRow inhosp, Set<Integer> hitTypes) {
        boolean xhSite = SITE_XH.equals(active);
        if (hitTypes == null || hitTypes.isEmpty()) {
            markNoTaskGenerated(inhosp);
            return;
        }
        StringBuilder hitDimensionNames = new StringBuilder();
        for (Integer type : hitTypes) {
            if (hitDimensionNames.length() > 0) {
                hitDimensionNames.append("、");
            }
            hitDimensionNames.append(dimensionName(type));
        }
        for (int type = 1; type <= 3; type++) {
            if (xhSite && type != 1) {
                continue;
            }
            if (hitTypes.contains(type)) {
                updateCheckFlag(inhosp, type, "1", composeRemark(inhosp, "按任务配置生成随访任务(维度=" + dimensionName(type) + ")"));
            } else {
                updateCheckFlag(inhosp, type, "2", composeRemark(inhosp, "本维度无任务或未生成,跳过(已生成维度=" + hitDimensionNames + ")"));
            }
        }
    }
    /**
     * 没有生成任何子任务时,只补扫描键,避免覆盖各维度方法已经写入的具体原因。
     */
    private void markNoTaskGenerated(VisitInhospRow inhosp) {
        VisitInhospRow fresh = inhospMapper.selectByInhospid(inhosp.getInhospid());
        String current = fresh == null ? null : fresh.getDeptcheckFlag();
        if (current == null || "0".equals(current)) {
            updateCheckFlag(inhosp, 1, "2", composeRemark(inhosp, "未生成随访任务(无可用长期任务)"));
        }
    }
    /**
     * 拼 reason:沿用原实现的 {@code remark + ";xxx"} 形式
     */
    private String composeRemark(VisitInhospRow inhosp, String text) {
        String remark = inhosp.getRemark();
        return StringUtils.isNotEmpty(remark) ? remark + ";" + text : text;
    }
    /**
@@ -295,11 +411,22 @@
    // ==========================================================================
    /**
     * 为单个患者生成科室维度的子任务。
     *
     * @return 生成的子任务数量
     * 兼容入口:为单个患者生成科室维度的子任务,最多生成第一条。
     * <p>
     * 当前主流程改为全量生成,调用的是带 {@code allTasks=true} 的内部重载。
     */
    public int addDeptSubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config) {
        return addDeptSubTaskForPatient(inhosp, archive, config, false);
    }
    /**
     * 为单个患者生成科室维度的子任务。
     *
     * @param allTasks {@code true}=生成所有命中的长期任务(当前主流程);
     *                 {@code false}=只生成第一条真正落库的任务(兼容入口)
     * @return 生成的子任务数量
     */
    private int addDeptSubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config, boolean allTasks) {
        int generatedCount = 0;
        try {
            // 原 L1857-1864:按患者所在科室查该科室的长期任务(dept_type=1 + service_type=2)
@@ -320,13 +447,18 @@
                u.setWardcheckFlag(fresh == null ? null : fresh.getWardcheckFlag());
                u.setDiagcheckFlag(fresh == null ? null : fresh.getDiagcheckFlag());
                // 原实现不判 null(fresh.getLongTaskReason() + "..."),原样保留
                u.setLongTaskReason((fresh == null ? null : fresh.getLongTaskReason())
                        + "该患者所在科室未配置离院长期任务;");
                u.setLongTaskReason((fresh == null ? null : fresh.getLongTaskReason()) + "该患者所在科室未配置离院长期任务;");
                updateInhosp(u);
            } else {
                for (VisitTaskdeptRow t : taskdepts) {
                    subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 1, config);
                    generatedCount++;
                    if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 1, config)) {
                        generatedCount++;
                        if (!allTasks) {
                            return generatedCount;
                        }
                    } else {
                        log.info("【科室任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                    }
                }
            }
        } catch (Exception e) {
@@ -338,6 +470,7 @@
            u.setDeptcheckFlag("2");
            u.setLongTaskReason("科室任务处理异常");
            updateInhosp(u);
            return 0;
        }
        return generatedCount;
    }
@@ -347,11 +480,22 @@
    // ==========================================================================
    /**
     * 为单个患者生成病区维度的子任务。
     *
     * @return 生成的子任务数量
     * 兼容入口:为单个患者生成病区维度的子任务,最多生成第一条。
     * <p>
     * 当前主流程改为全量生成,调用的是带 {@code allTasks=true} 的内部重载。
     */
    public int addWardSubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config) {
        return addWardSubTaskForPatient(inhosp, archive, config, false);
    }
    /**
     * 为单个患者生成病区维度的子任务。
     *
     * @param allTasks {@code true}=生成所有命中的长期任务(当前主流程);
     *                 {@code false}=只生成第一条真正落库的任务(兼容入口)
     * @return 生成的子任务数量
     */
    private int addWardSubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config, boolean allTasks) {
        int generatedCount = 0;
        try {
            String errorreason = null;
@@ -381,13 +525,18 @@
                u.setDeptcheckFlag(fresh == null ? null : fresh.getDeptcheckFlag());
                u.setDiagcheckFlag(fresh == null ? null : fresh.getDiagcheckFlag());
                // 原有判空(与科室维度那处不同),原样保留
                u.setLongTaskReason(StringUtils.isNotEmpty(fresh == null ? null : fresh.getLongTaskReason())
                        ? fresh.getLongTaskReason() + errorreason : errorreason);
                u.setLongTaskReason(StringUtils.isNotEmpty(fresh == null ? null : fresh.getLongTaskReason()) ? fresh.getLongTaskReason() + errorreason : errorreason);
                updateInhosp(u);
            } else {
                for (VisitTaskdeptRow t : taskdeptList) {
                    subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 2, config);
                    generatedCount++;
                    if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 2, config)) {
                        generatedCount++;
                        if (!allTasks) {
                            return generatedCount;
                        }
                    } else {
                        log.info("【病区任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                    }
                }
            }
        } catch (Exception e) {
@@ -399,6 +548,7 @@
            u.setWardcheckFlag("2");
            u.setLongTaskReason("病区任务处理异常");
            updateInhosp(u);
            return 0;
        }
        return generatedCount;
    }
@@ -408,11 +558,22 @@
    // ==========================================================================
    /**
     * 为单个患者生成疾病维度的子任务。
     *
     * @return 生成的子任务数量
     * 兼容入口:为单个患者生成疾病维度的子任务,最多生成第一条。
     * <p>
     * 当前主流程改为全量生成,调用的是带 {@code allTasks=true} 的内部重载。
     */
    public int addIcd10SubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config) {
        return addIcd10SubTaskForPatient(inhosp, archive, config, false);
    }
    /**
     * 为单个患者生成疾病维度的子任务。
     *
     * @param allTasks {@code true}=生成所有命中的长期任务(当前主流程);
     *                 {@code false}=只生成第一条真正落库的任务(兼容入口)
     * @return 生成的子任务数量
     */
    private int addIcd10SubTaskForPatient(VisitInhospRow inhosp, VisitArchiveRow archive, String config, boolean allTasks) {
        int generatedCount = 0;
        try {
            // 原 L1945-1947
@@ -452,16 +613,26 @@
                int flag = 0;
                for (VisitTaskdiagRow t : taskdiags) {
                    // 原 L1975-1983:必须科室或病区能匹配上才建
                    if (StringUtils.isNotEmpty(t.getDeptCode())
                            && t.getDeptCode().equals(inhosp.getLeaveldeptcode())) {
                        subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 3, config);
                        generatedCount++;
                    if (StringUtils.isNotEmpty(t.getDeptCode()) && t.getDeptCode().equals(inhosp.getLeaveldeptcode())) {
                        flag = 1;
                    } else if (StringUtils.isNotEmpty(t.getWardCode())
                            && t.getWardCode().equals(inhosp.getLeavehospitaldistrictcode())) {
                        subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 3, config);
                        generatedCount++;
                        if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 3, config)) {
                            generatedCount++;
                            if (!allTasks) {
                                return generatedCount;
                            }
                        } else {
                            log.info("【疾病任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                        }
                    } else if (StringUtils.isNotEmpty(t.getWardCode()) && t.getWardCode().equals(inhosp.getLeavehospitaldistrictcode())) {
                        flag = 1;
                        if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 3, config)) {
                            generatedCount++;
                            if (!allTasks) {
                                return generatedCount;
                            }
                        } else {
                            log.info("【疾病任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                        }
                    }
                }
                if (flag == 0) {
@@ -483,6 +654,7 @@
            u.setDiagcheckFlag("2");
            u.setLongTaskReason("疾病任务处理异常");
            updateInhosp(u);
            return 0;
        }
        return generatedCount;
    }
@@ -510,13 +682,11 @@
        try {
            VisitTaskCreateApi api = taskApi();
            if (api == null) {
                log.warn("【出入院随访】VisitTaskCreateApi 不可用,跳过再入院处理。inhospid={}",
                        newInHosp.getInhospid());
                log.warn("【出入院随访】VisitTaskCreateApi 不可用,跳过再入院处理。inhospid={}", newInHosp.getInhospid());
                return;
            }
            // 原 L1324-1328:patid + sendstate=2(不设 taskid)
            List<VisitPendingSubtaskDto> pendingList =
                    api.findPendingSubtasks(newInHosp.getPatid(), null);
            List<VisitPendingSubtaskDto> pendingList = api.findPendingSubtasks(newInHosp.getPatid(), null);
            if (CollectionUtils.isEmpty(pendingList)) {
                return;
            }
@@ -531,8 +701,7 @@
                    continue;
                }
                // 原 L1342-1350:旧子任务的出院时间在新入院时间之前 → 停掉
                if (pending.getEndtime() != null && newInHosp.getStarttime() != null
                        && pending.getEndtime().before(newInHosp.getStarttime())) {
                if (pending.getEndtime() != null && newInHosp.getStarttime() != null && pending.getEndtime().before(newInHosp.getStarttime())) {
                    pending.setSendstate(4L);
                    pending.setIsVisitAgain(2);
                    pending.setRemark("患者再入院");
@@ -546,7 +715,9 @@
        }
    }
    /** 景宁机构ID(原 L1338;与 InhospSubtaskWriter 里那份是同一常量,已逐字核对) */
    /**
     * 景宁机构ID(原 L1338;与 InhospSubtaskWriter 里那份是同一常量,已逐字核对)
     */
    private static final String ORG_JINGNING = "47255004333112711A1001";
    // ==========================================================================
@@ -594,13 +765,19 @@
     */
    public static class VisitTaskRule {
        /** 科室规则:"1"=首要 "2"=次要,其它=不参与 */
        /**
         * 科室规则:"1"=首要 "2"=次要,其它=不参与
         */
        private String deptRule;
        /** 病区规则(原字段名就是拼错的 {@code wradRule},保持同名以免读错) */
        /**
         * 病区规则(原字段名就是拼错的 {@code wradRule},保持同名以免读错)
         */
        private String wradRule;
        /** 疾病规则 */
        /**
         * 疾病规则
         */
        private String diagRule;
        public String getDeptRule() {
@@ -628,13 +805,16 @@
        }
    }
    /** 供测试/日志:本类是否拿到了必需的 Mapper */
    /**
     * 供测试/日志:本类是否拿到了必需的 Mapper
     */
    boolean hasMappers() {
        return inhospMapper != null && archiveMapper != null
                && taskdeptMapper != null && taskdiagMapper != null;
        return inhospMapper != null && archiveMapper != null && taskdeptMapper != null && taskdiagMapper != null;
    }
    /** 预留:供日志使用的时间戳(避免 IDE 报未使用 import Date) */
    /**
     * 预留:供日志使用的时间戳(避免 IDE 报未使用 import Date)
     */
    @SuppressWarnings("unused")
    private Date now() {
        return new Date();