ruoyi-inhospvisit/src/main/java/com/ruoyi/inhospvisit/service/InhospTaskOrchestrator.java
@@ -23,24 +23,24 @@
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-10 口径变更:一个患者(一次出院)只生成 <b>一条</b> 随访子任务</h3>
 * 搬迁时本类是"逐行等价"的(原实现按维度全生成:每个 {@code *ForPatient} 把命中的
 * <b>所有</b>长期任务各写一条)。业务确认改为:
 * <ol>
 *   <li>维度按 {@code service_task_rule} 优先级排序尝试:首要 → 次要 → 通用兜底(科室、病区);</li>
 *   <li>第一个真正落库成功的维度即停止 → 只留一条;</li>
 *   <li>无规则时按 {@code service_taskdept} 的科室/病区"通用模块"生成;</li>
 *   <li>标志位统一回写,保证 {@code deptcheck_flag} 不再停在 0(防重复扫描);
 *       并在写库前按 {@code patid+inhospid+taskid} 判重(见 {@code VisitTaskCreateApi#existsSubtask})。</li>
 * </ol>
 * 因此 {@code verify_inhospvisit_orchestration_semantics.py} 里 O18~O23 那 6 条
 * "搬迁等价"断言已被改为"口径变更"断言(脚本里单独分组并注明依据)。
 * <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">
@@ -145,26 +145,17 @@
    // ==========================================================================
    /**
     * 按 {@code service_task_rule} 的「首要(1)/次要(2)」规则编排科室/病区/疾病三个维度。
     * 编排科室/病区/疾病三个维度。
     *
     * <h3>⚠️ 2026-10 口径变更:一个患者(一次出院)只生成 <b>一条</b> 随访子任务</h3>
     * 原实现(以及搬迁后的等价版)是按维度"全生成":先跑所有「首要」维度的
     * {@code *ForPatient},而每个 {@code *ForPatient} 又把命中的<b>所有</b>长期任务各写一条。
     * 结果是同一患者一次出院能生成几十条(线上实测 27 条),而且因为扫描键
     * {@code deptcheck_flag} 在"只有病区/疾病维度"的规则下不会被置 1,
     * 患者每轮扫描都被重新处理 → 重复子任务持续累积。
     * <p>
     * 现口径(业务确认):
     * <ol>
     *   <li>把三个维度按规则优先级排成一个<b>尝试顺序</b>:
     *       首要(1) → 次要(2) → 通用兜底(科室、病区);同优先级内固定 科室 &gt; 病区 &gt; 疾病。
     *       {@code service_task_rule} 没有该患者科室/病区对应的规则时 → 顺序为 科室 → 病区
     *       (即"按 {@code service_taskdept} 里的通用模块生成")。</li>
     *   <li>按顺序逐个维度尝试,<b>第一个真正落库成功(或已存在)的维度即停止</b> —— 只留一条。</li>
     *   <li>最后统一回写标志位:命中维度 = {@code 1};其余维度 = {@code 2}(跳过),
     *       且<b>无论命中哪个维度,{@code deptcheck_flag} 一定会被写成非 0</b>
     *       —— 这就是"不再被下一轮扫描重复生成"的保证。</li>
     * </ol>
     * <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}。
     *
@@ -173,24 +164,41 @@
     *
     * @param inhosp  待处理的出院患者
     * @param archive 患者档案
     * @param rule    已查好的规则;{@code null} = 该科室/病区未配置规则
     * @param rule    已查好的规则;{@code null} = 该科室/病区未配置规则(按任务全量生成)
     * @param config  {@code sys_config: visit.early.day}
     */
    public void addSubTaskByRule(VisitInhospRow inhosp, VisitArchiveRow archive, VisitTaskRule rule, String config) {
        try {
            if (rule == null) {
                log.info("【无规则】患者{}未配置任务规则,按任务配置全量生成", inhosp.getInhospid());
                addAllSubTasksByTaskConfig(inhosp, archive, config);
                return;
            }
            List<Integer> order = resolveDimensionOrder(rule);
            log.info("【基于规则】患者{}规则:deptRule={}, wradRule={}, diagRule={};维度尝试顺序={}", inhosp.getInhospid(), rule == null ? null : rule.getDeptRule(), rule == null ? null : rule.getWradRule(), rule == null ? null : rule.getDiagRule(), order);
            log.info("【基于规则】患者{}规则:deptRule={}, wradRule={}, diagRule={};维度尝试顺序={}", inhosp.getInhospid(), rule.getDeptRule(), rule.getWradRule(), rule.getDiagRule(), order);
            Integer hit = null;
            Set<Integer> hitTypes = new LinkedHashSet<>();
            for (Integer type : order) {
                log.info("【基于规则】患者{}尝试维度{}({})", inhosp.getInhospid(), type, dimensionName(type));
                if (generateOneForDimension(inhosp, archive, type, config)) {
                    hit = type;
                    break;
                log.info("【基于规则】患者{}按首要/次要顺序尝试维度{}({}),全量生成", inhosp.getInhospid(), type, dimensionName(type));
                if (generateAllForDimension(inhosp, archive, type, config)) {
                    hitTypes.add(type);
                }
            }
            writeFlagsAfterRun(inhosp, hit);
            // 规则配置的维度都没有生成时,才走科室/病区通用兜底;
            // 有任何一个配置维度生成成功,就不再额外生成未配置的兜底任务。
            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();
@@ -200,22 +208,46 @@
    }
    /**
     * 维度尝试顺序(2026-10 口径)。
     * 无规则口径:按任务配置全量生成。
     * <p>
     * 规则为 {@code null} → {@code [科室, 病区]}:按 {@code service_taskdept} 里该患者的
     * 科室/病区"通用模块"生成;这是业务明确要求的兜底口径(此时<b>不进入疾病维度</b>)。
     * 科室、病区、疾病三个维度都尝试,每个维度内由对应的 {@code *ForPatient}
     * 把所有命中的长期任务各写一条。{@code xh} 站点仍只做科室维度。
     * <p>
     * 有规则 → {@code [首要维度…, 次要维度…, 科室, 病区]}:
     * 首要优先、次要其后,最后用通用兜底保证"能生成一条就生成一条"。
     * 各维度是否命中分别回写标志位({@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);
        if (rule == null) {
            addDimension(order, 1, xhSite);
            addDimension(order, 2, xhSite);
            return order;
        }
        boolean deptIsPrimary = "1".equals(rule.getDeptRule());
        boolean wardIsPrimary = "1".equals(rule.getWradRule());
        boolean diagIsPrimary = "1".equals(rule.getDiagRule());
@@ -241,10 +273,25 @@
        if (diagIsSecondary) {
            addDimension(order, 3, xhSite);
        }
        // 通用兜底:规则里配的维度全都取不到任务时,仍按 service_taskdept 的 科室/病区 生成一条
        addDimension(order, 1, xhSite);
        addDimension(order, 2, 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;
    }
    /**
@@ -273,16 +320,21 @@
    }
    /**
     * 尝试一个维度,返回"是否真的生成了(或本来就已经有)一条子任务"
     * 尝试一个维度,生成该维度下所有命中的长期任务。
     * <p>
     * 无规则分支和配置了规则的分支都走这里。
     *
     * @return 是否至少生成(或已存在)一条子任务
     */
    private boolean generateOneForDimension(VisitInhospRow inhosp, VisitArchiveRow archive, int type, String config) {
    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) > 0;
                return addDeptSubTaskForPatient(inhosp, archive, config, true) > 0;
            case 2:
                return addWardSubTaskForPatient(inhosp, archive, config) > 0;
                return addWardSubTaskForPatient(inhosp, archive, config, true) > 0;
            case 3:
                return addIcd10SubTaskForPatient(inhosp, archive, config) > 0;
                return addIcd10SubTaskForPatient(inhosp, archive, config, true) > 0;
            default:
                return false;
        }
@@ -293,34 +345,49 @@
     * <p>
     * ⚠️ 关键点:扫描键是 {@code pat_med_inhosp.deptcheck_flag = '0'},
     * 所以<b>不论命中哪个维度,deptcheck_flag 都必须被写成 1 或 2</b>,
     * 否则下一轮扫描会把这个患者再处理一遍(2026-10 重复生成的直接原因)。
     * 否则下一轮扫描会把这个患者再处理一遍。
     * <p>
     * 没生成时({@code hit == null})刻意<b>只补扫描键</b>:各维度方法已经把更具体的原因
     * ("该患者所在科室未配置离院长期任务;" / "生成子任务失败 1" …)写进
     * {@code long_task_reason} 了,这里先用一次重读判断 deptcheck 是否已经非 0,
     * 避免把它覆盖成泛泛的"未生成随访任务"。
     *
     * @param hit 命中的维度;{@code null} = 三个维度都没能生成
     * 可能有多个维度同时命中:所有命中维度写 {@code 1},其余维度写 {@code 2};
     * 只要有一个维度命中,{@code deptcheck_flag} 就一定是非 0。
     * <p>
     * 没有任何维度命中时,各维度方法已经把更具体的原因写进 {@code long_task_reason},
     * 这里只补扫描键,避免覆盖成泛泛的"未生成随访任务"。
     */
    private void writeFlagsAfterRun(VisitInhospRow inhosp, Integer hit) {
    private void writeFlagsAfterRun(VisitInhospRow inhosp, Set<Integer> hitTypes) {
        boolean xhSite = SITE_XH.equals(active);
        if (hit == null) {
            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, "未生成随访任务(无可用长期任务)"));
            }
        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 (hit == type) {
                updateCheckFlag(inhosp, type, "1", composeRemark(inhosp, "按优先级生成一条随访任务(维度=" + dimensionName(type) + ")"));
            if (hitTypes.contains(type)) {
                updateCheckFlag(inhosp, type, "1", composeRemark(inhosp, "按任务配置生成随访任务(维度=" + dimensionName(type) + ")"));
            } else {
                updateCheckFlag(inhosp, type, "2", composeRemark(inhosp, "已生成一条随访任务(维度=" + dimensionName(hit) + "),本维度跳过"));
                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, "未生成随访任务(无可用长期任务)"));
        }
    }
@@ -344,15 +411,23 @@
    // ==========================================================================
    /**
     * 为单个患者生成科室维度的子任务。
     * 兼容入口:为单个患者生成科室维度的子任务,最多生成第一条。
     * <p>
     * ⚠️ 2026-10 口径变更:命中多个长期任务时<b>只生成第一条真正落库的任务</b>
     * (原实现是 {@code for (t : taskdepts) writeInSubTask(...); generatedCount++;},
     * 一个科室配 N 个长期任务就会生成 N 条 —— 是"同一患者几十条"的主因)。
     *
     * @return 生成的子任务数量(0 或 1)
     * 当前主流程改为全量生成,调用的是带 {@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)
            VisitTaskdeptRow query = new VisitTaskdeptRow();
@@ -376,11 +451,14 @@
                updateInhosp(u);
            } else {
                for (VisitTaskdeptRow t : taskdepts) {
                    // 一个患者只留一条:第一条真正落库的即返回
                    if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 1, config)) {
                        return 1;
                        generatedCount++;
                        if (!allTasks) {
                            return generatedCount;
                    }
                    } else {
                    log.info("【科室任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                    }
                }
            }
        } catch (Exception e) {
@@ -392,8 +470,9 @@
            u.setDeptcheckFlag("2");
            u.setLongTaskReason("科室任务处理异常");
            updateInhosp(u);
        }
        return 0;
        }
        return generatedCount;
    }
    // ==========================================================================
@@ -401,13 +480,23 @@
    // ==========================================================================
    /**
     * 为单个患者生成病区维度的子任务。
     * 兼容入口:为单个患者生成病区维度的子任务,最多生成第一条。
     * <p>
     * ⚠️ 同上:命中多个长期任务时只生成第一条真正落库的(原实现是全生成)。
     *
     * @return 生成的子任务数量(0 或 1)
     * 当前主流程改为全量生成,调用的是带 {@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;
            List<VisitTaskdeptRow> taskdeptList = null;
@@ -440,11 +529,14 @@
                updateInhosp(u);
            } else {
                for (VisitTaskdeptRow t : taskdeptList) {
                    // 一个患者只留一条:第一条真正落库的即返回
                    if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 2, config)) {
                        return 1;
                        generatedCount++;
                        if (!allTasks) {
                            return generatedCount;
                    }
                    } else {
                    log.info("【病区任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                    }
                }
            }
        } catch (Exception e) {
@@ -456,8 +548,9 @@
            u.setWardcheckFlag("2");
            u.setLongTaskReason("病区任务处理异常");
            updateInhosp(u);
        }
        return 0;
        }
        return generatedCount;
    }
    // ==========================================================================
@@ -465,13 +558,23 @@
    // ==========================================================================
    /**
     * 为单个患者生成疾病维度的子任务。
     * 兼容入口:为单个患者生成疾病维度的子任务,最多生成第一条。
     * <p>
     * ⚠️ 同上:命中多个长期任务时只生成第一条真正落库的(原实现是全生成)。
     *
     * @return 生成的子任务数量(0 或 1)
     * 当前主流程改为全量生成,调用的是带 {@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
            if (StringUtils.isEmpty(inhosp.getLeaveicd10code())) {
@@ -512,17 +615,24 @@
                    // 原 L1975-1983:必须科室或病区能匹配上才建
                    if (StringUtils.isNotEmpty(t.getDeptCode()) && t.getDeptCode().equals(inhosp.getLeaveldeptcode())) {
                        flag = 1;
                        // 一个患者只留一条:第一条真正落库的即返回
                        if (subtaskWriter.writeInSubTask(t.getTaskId(), true, inhosp, archive, 3, config)) {
                            return 1;
                            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)) {
                            return 1;
                            generatedCount++;
                            if (!allTasks) {
                                return generatedCount;
                        }
                        } else {
                        log.info("【疾病任务】患者{}任务{}未生成子任务,尝试下一个候选", inhosp.getInhospid(), t.getTaskId());
                        }
                    }
                }
                if (flag == 0) {
@@ -544,9 +654,10 @@
            u.setDiagcheckFlag("2");
            u.setLongTaskReason("疾病任务处理异常");
            updateInhosp(u);
        }
        return 0;
    }
        return generatedCount;
    }
    // ==========================================================================
    // 5. 再入院处理(原 L1321-1359)