traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java
@@ -34,6 +34,9 @@
import com.trafficaudit.reportexport.calc.MidCalc;
import com.trafficaudit.reportexport.calc.PaxCalc;
import com.trafficaudit.reportexport.calc.SummaryWorkbookFiller;
import com.trafficaudit.reportexport.calc.FreightReadinessCheck;
import com.trafficaudit.reportexport.calc.SummaryMissingDataCheck;
import com.trafficaudit.reportexport.layout.SummaryLayoutExpander;
import com.trafficaudit.reportexport.calc.WycSplitCalc;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
@@ -101,6 +104,12 @@
    private CityTaxiMonthlyMapper cityTaxiMapper;
    @Resource
    private SummaryWorkbookFiller summaryWorkbookFiller;
    @Resource
    private SummaryLayoutExpander summaryLayoutExpander;
    @Resource
    private FreightReadinessCheck freightReadinessCheck;
    @Resource
    private SummaryMissingDataCheck missingDataCheck;
    @Resource
    private WycSplitCalc wycSplitCalc;
    @Resource
@@ -2681,9 +2690,19 @@
     * 生成_中口径排名.xlsx:单块累计(选 1 个月=当月,选 1-6 月=累计),RANK/SUM 公式保留。
     */
    public byte[] exportPassengerMidRank(String period, String mode) throws Exception {
        return exportPassengerMidRank(period, mode, null);
    }
    /**
     * 方案 A(2026-09-21):中口径排名的累计同比基数与“中口径明细”保持同源。
     * 明细页的 2025 年列是母版静态定稿值,排名页原先查库现算,两者在 2025-03/04 网约车拆分上不同。
     * summaryWb 非空时直接复用当前正在生成的汇总工作簿;独立导出时再打开对应母版。
     */
    private byte[] exportPassengerMidRank(String period, String mode, XSSFWorkbook summaryWb) throws Exception {
        int maxMonth = monthOf(period, mode);
        int currentYear = Integer.parseInt(period.substring(0, 4));
        File template = resolvePassengerTemplate("生成_中口径排名.xlsx");
        Map<String, double[]> lastYearCumBase = loadMidRankStaticBase(period, mode, summaryWb, currentYear, maxMonth);
        try (InputStream in = new FileInputStream(template);
             XSSFWorkbook wb = new XSSFWorkbook(in)) {
            Sheet sheet = wb.getSheetAt(0);
@@ -2703,8 +2722,8 @@
                title.getCell(10).setCellValue(currentYear + "年" + maxMonth + "月全省分市州完成道路客运生产情况");
            }
            // 全省行 r3:B3/F3 为 SUM 公式保留;D3/H3 同比填值(0-based 列 3/7)
            setValOrBlank(sheet, 2, 3, midCumYoy(mid, currentYear, "湖北省", maxMonth, 0, true));
            setValOrBlank(sheet, 2, 7, midCumYoy(mid, currentYear, "湖北省", maxMonth, 0, false));
            setValOrBlank(sheet, 2, 3, midRankCumYoy(mid, currentYear, "湖北省", maxMonth, true, lastYearCumBase));
            setValOrBlank(sheet, 2, 7, midRankCumYoy(mid, currentYear, "湖北省", maxMonth, false, lastYearCumBase));
            // 右块全省行 N3/R3:当月同比(L3/P3 为 SUM 公式保留)
            setValOrBlank(sheet, 2, 13, midMonthYoy(mid, currentYear, maxMonth, "湖北省", 0, true));
            setValOrBlank(sheet, 2, 17, midMonthYoy(mid, currentYear, maxMonth, "湖北省", 0, false));
@@ -2715,17 +2734,13 @@
                int r0 = 3 + i;
                double pass = midCumClass(mid, currentYear, city, maxMonth, 0, true);
                double turn = midCumClass(mid, currentYear, city, maxMonth, 0, false);
                double lastPass = midCumClass(mid, currentYear - 1, city, maxMonth, 0, true);
                double lastTurn = midCumClass(mid, currentYear - 1, city, maxMonth, 0, false);
                setValOrBlank(sheet, r0, 1, pass == 0 ? null : pass);
                setValOrBlank(sheet, r0, 3, midCumYoy(mid, currentYear, city, maxMonth, 0, true));
                setValOrBlank(sheet, r0, 3, midRankCumYoy(mid, currentYear, city, maxMonth, true, lastYearCumBase));
                setValOrBlank(sheet, r0, 5, turn == 0 ? null : turn);
                setValOrBlank(sheet, r0, 7, midCumYoy(mid, currentYear, city, maxMonth, 0, false));
                setValOrBlank(sheet, r0, 7, midRankCumYoy(mid, currentYear, city, maxMonth, false, lastYearCumBase));
                // 右块当月:L/P 值、N/R 当月同比(M/O/Q/S 排名公式保留)
                double mPass = midClassVal(mid, currentYear, maxMonth, city, 0, true);
                double mTurn = midClassVal(mid, currentYear, maxMonth, city, 0, false);
                double mLastPass = midClassVal(mid, currentYear - 1, maxMonth, city, 0, true);
                double mLastTurn = midClassVal(mid, currentYear - 1, maxMonth, city, 0, false);
                setValOrBlank(sheet, r0, 11, mPass == 0 ? null : mPass);
                setValOrBlank(sheet, r0, 13, mPass == 0 ? null : midMonthYoy(mid, currentYear, maxMonth, city, 0, true));
                setValOrBlank(sheet, r0, 15, mTurn == 0 ? null : mTurn);
@@ -2734,6 +2749,112 @@
            recalc(wb);
            return toBytes(wb);
        }
    }
    /** 读取母版《中口径明细》的 2025 年逐月静态值,汇总成排名页所需的去年同期累计基数。 */
    private Map<String, double[]> readMidDetailLastYearCumulative(XSSFWorkbook sourceWb, int currentYear, int maxMonth) {
        Map<String, double[]> out = new LinkedHashMap<>();
        if (sourceWb == null || maxMonth <= 0) return out;
        Sheet sheet = sourceWb.getSheet("中口径明细");
        if (sheet == null) return out;
        Map<Integer, Integer> monthCols = new LinkedHashMap<>();
        java.util.regex.Pattern monthHeader = java.util.regex.Pattern.compile("^(\\d{4})年(\\d{1,2})月$");
        int headerEnd = Math.min(sheet.getLastRowNum(), sheet.getFirstRowNum() + 5);
        for (int r = sheet.getFirstRowNum(); r <= headerEnd; r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            for (int c = row.getFirstCellNum(); c >= 0 && c < row.getLastCellNum(); c++) {
                String text = cellText(row.getCell(c));
                if (text == null) continue;
                java.util.regex.Matcher matcher = monthHeader.matcher(text.trim());
                if (!matcher.matches()) continue;
                int y = Integer.parseInt(matcher.group(1));
                int m = Integer.parseInt(matcher.group(2));
                if (y == currentYear - 1 && m >= 1 && m <= maxMonth) monthCols.putIfAbsent(m, c);
            }
        }
        if (monthCols.size() < maxMonth) return out;
        for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            String city = RegionUtil.normalizeCityName(cellText(row.getCell(0)));
            if (city == null || !RegionUtil.CITY_LIST.contains(city)) continue;
            String metric = cellText(row.getCell(1));
            if (metric == null) continue;
            int idx = metric.contains("总旅客周转量") ? 1 : (metric.contains("总客运量") ? 0 : -1);
            if (idx < 0) continue;
            double sum = 0.0;
            boolean complete = true;
            for (int m = 1; m <= maxMonth; m++) {
                Cell c = row.getCell(monthCols.get(m));
                if (c == null) { complete = false; break; }
                if (c.getCellType() == CellType.NUMERIC) {
                    sum += c.getNumericCellValue();
                } else if (c.getCellType() == CellType.FORMULA && c.getCachedFormulaResultType() == CellType.NUMERIC) {
                    sum += c.getNumericCellValue();
                } else {
                    complete = false;
                    break;
                }
            }
            double[] values = out.computeIfAbsent(city, k -> new double[]{Double.NaN, Double.NaN});
            values[idx] = complete ? sum : Double.NaN;
        }
        double[] province = new double[2];
        for (String city : RegionUtil.CITY_LIST) {
            double[] values = out.get(city);
            if (values == null || Double.isNaN(values[0]) || Double.isNaN(values[1])) return new LinkedHashMap<>();
            province[0] += values[0];
            province[1] += values[1];
        }
        out.put("湖北省", province);
        return out;
    }
    /** 独立导出时从对应汇总母版读取静态基数;汇总导出时直接复用内存中的工作簿,避免重复 I/O。 */
    private Map<String, double[]> loadMidRankStaticBase(String period, String mode, XSSFWorkbook summaryWb,
                                                       int currentYear, int maxMonth) {
        if (summaryWb != null) {
            Map<String, double[]> base = readMidDetailLastYearCumulative(summaryWb, currentYear, maxMonth);
            if (!base.isEmpty()) return base;
            log.warn("中口径排名:当前汇总工作簿的中口径明细未读到完整 2025 静态累计基数,回退库内现算");
            return null;
        }
        double savedZipRatio = ZipSecureFile.getMinInflateRatio();
        ZipSecureFile.setMinInflateRatio(0.0001);
        try {
            File mother = resolveSummaryMother(period, mode);
            if (mother == null || !mother.isFile()) {
                log.warn("中口径排名:未找到 {} 的汇总母版,2025 累计基数回退库内现算", period);
                return null;
            }
            try (InputStream in = new FileInputStream(mother); XSSFWorkbook wb = new XSSFWorkbook(in)) {
                Map<String, double[]> base = readMidDetailLastYearCumulative(wb, currentYear, maxMonth);
                if (base.isEmpty()) {
                    log.warn("中口径排名:母版 {} 的中口径明细未读到完整 2025 静态累计基数,回退库内现算", mother.getName());
                    return null;
                }
                log.info("中口径排名:2025 累计基数改用母版静态列({})", mother.getName());
                return base;
            }
        } catch (Exception e) {
            log.warn("中口径排名:读取母版 2025 静态累计基数失败,回退库内现算:{}", e.getMessage());
            return null;
        } finally {
            ZipSecureFile.setMinInflateRatio(savedZipRatio);
        }
    }
    /** 中口径排名累计同比:方案 A 有静态基数时与其对齐,否则保留原库内现算逻辑。 */
    private Double midRankCumYoy(Map<Integer, Map<String, double[][]>> mid, int year, String area,
                                 int monthCount, boolean volume, Map<String, double[]> staticBase) {
        if (staticBase == null) return midCumYoy(mid, year, area, monthCount, 0, volume);
        double[] values = staticBase.get(area);
        if (values == null) return null;
        double current = midCumClass(mid, year, area, monthCount, 0, volume);
        if (current == 0.0) return null;
        double base = volume ? values[0] : values[1];
        return base == 0.0 ? null : yoyOf(current, base);
    }
    /** 写数值或清空(公式单元格保留不动) */
@@ -3507,7 +3628,87 @@
     * 保留全部页签/版式/公式/2025 年缓存值,仅把表头年份动态化为目标年;数据填充按 P2 起逐步接入。
     */
    public byte[] exportSummaryWorkbook(String period, String mode) throws Exception {
        return exportSummaryWorkbook(period, mode, null);
        return exportSummaryWorkbook(period, mode, null, null);
    }
    /**
     * 汇总大表「按月扩列」(2026-10-09 Step 1):把 period 当月母版扩列成下一月版式。
     * 只做版式——当月数据列留空;不落盘,由调用方决定是否确认后另存为下期母版。
     */
    public byte[] expandSummaryWorkbook(String period) throws Exception {
        if (period == null || !period.contains("-")) {
            throw new RuntimeException("扩列仅支持按月,请指定 period=YYYY-MM");
        }
        int year = Integer.parseInt(period.split("-")[0]);
        int month = monthOf(period, "month");
        if (month >= 12) {
            throw new RuntimeException("扩列:12 月之后需新开一本,跨年规则另行处理");
        }
        // 2026-10-12:扩列以「当期产物」为底(产物含当期列的值与公式;母版的当期列是空的,
        // 直接拿母版扩列会把当期数据丢成空洞,导致累计漏月)。产物取自导出落盘缓存;缺产物时回退母版并告警。
        File source = resolveLatestProduct(period);
        boolean fromProduct = source != null;
        if (source == null) {
            source = resolveSummaryMother(period, "month");
            if (source != null) {
                log.warn("汇总大表扩列:未找到 {} 的产物缓存,回退用母版扩列——历史列里缺少当期数据,累计可能漏月", period);
            }
        }
        if (source == null) {
            throw new RuntimeException("未找到汇总表母版或产物(docs/生成汇总大表):" + year + "年" + month + "月道路运输量汇总表.xlsx");
        }
        try (InputStream in = new FileInputStream(source)) {
            byte[] out = summaryLayoutExpander.expand(org.apache.poi.util.IOUtils.toByteArray(in), year, month + 1);
            log.info("汇总大表扩列完成:{}{} -> {}年{}月版式(只做版式、当期列留空)",
                    fromProduct ? "产物" : "母版", source.getName(), year, month + 1);
            return out;
        }
    }
    /** 取该期「最新产物」:导出落盘缓存 _cache/summaryWorkbook_<period>_month_v*.xlsx(按修改时间取最新) */
    private File resolveLatestProduct(String period) {
        try {
            String rel = summaryTemplateDir;
            while (rel != null && rel.startsWith("./")) rel = rel.substring(2);
            String[] roots = {
                summaryTemplateDir,
                System.getProperty("user.dir") + "/" + rel,
                System.getProperty("user.dir") + "/../" + rel
            };
            String prefix = "summaryWorkbook_" + period + "_month_";
            for (String root : roots) {
                if (root == null || root.trim().isEmpty()) continue;
                File dir = new File(root, "_cache");
                if (!dir.isDirectory()) continue;
                File[] files = dir.listFiles((d, name) -> name.startsWith(prefix) && name.endsWith(".xlsx"));
                if (files == null || files.length == 0) continue;
                File latest = files[0];
                for (File f : files) {
                    if (f.lastModified() > latest.lastModified()) latest = f;
                }
                return latest;
            }
            return null;
        } catch (Exception e) {
            log.warn("汇总大表扩列:查找产物缓存失败(忽略):{}", e.getMessage());
            return null;
        }
    }
    /** 只修正当期母版里 7 个标题页的标题文字(按母版期次重写,用于修复滞后标题)。 */
    public byte[] fixSummaryTitles(String period) throws Exception {
        if (period == null || !period.contains("-")) {
            throw new RuntimeException("标题修正仅支持按月,请指定 period=YYYY-MM");
        }
        int year = Integer.parseInt(period.split("-")[0]);
        int month = monthOf(period, "month");
        File mother = resolveSummaryMother(period, "month");
        if (mother == null) {
            throw new RuntimeException("未找到汇总表母版(docs/生成汇总大表):" + year + "年" + month + "月道路运输量汇总表.xlsx");
        }
        try (InputStream in = new FileInputStream(mother)) {
            return summaryLayoutExpander.fixTitles(org.apache.poi.util.IOUtils.toByteArray(in), year, month);
        }
    }
    /** 生成_道路运输量汇总表.xlsx(P0-P1 骨架,支持 toMonth 裁剪):
@@ -3515,6 +3716,13 @@
     *  toMonth 非空且小于 M 时,把 8 个台账/合成页裁到 toMonth 月(toMonth+1..M 的当月值/同比列清空、保留表头,
     *  累计与累计同比公式改为按 toMonth 月重算),用于“先生成 1-6 月、1-7 月扩列”验证。 */
    public byte[] exportSummaryWorkbook(String period, String mode, Integer toMonth) throws Exception {
        return exportSummaryWorkbook(period, mode, toMonth, null);
    }
    /** 同上,额外通过 progress 回调报告进度(异步导出任务用:步骤百分比 + 步骤文案) */
    public byte[] exportSummaryWorkbook(String period, String mode, Integer toMonth,
                                        java.util.function.BiConsumer<Integer, String> progress) throws Exception {
        reportProgress(progress, 2, "校验报表期与母版");
        int year = Integer.parseInt(period.contains("-") ? period.split("-")[0] : period);
        int month = period.contains("-") ? monthOf(period, mode) : 12;
        File template = resolveSummaryMother(period, mode);
@@ -3522,9 +3730,11 @@
            throw new RuntimeException("未找到汇总表母版《" + year + "年" + month + "月道路运输量汇总表.xlsx》(docs/生成汇总大表)");
        }
        double savedZipRatio = ZipSecureFile.getMinInflateRatio();
        reportProgress(progress, 6, "读取母版工作簿");
        ZipSecureFile.setMinInflateRatio(0.0001); // 新版母版 styles.xml 由 openpyxl 高压缩(0.0099<0.01)触发 POI Zip-bomb 误报,读取后还原
        try (InputStream in = new FileInputStream(template);
             XSSFWorkbook wb = new XSSFWorkbook(in)) {
            reportProgress(progress, 12, "还原同期月度块");
            File donor = resolveSummaryDonor(year, month);
            if (donor != null) {
                try (InputStream din = new FileInputStream(donor); XSSFWorkbook dwb = new XSSFWorkbook(din)) {
@@ -3543,11 +3753,15 @@
            int effMonth = (toMonth != null && toMonth > 0 && toMonth < month) ? toMonth : month;
            List<String> dbProblems = new ArrayList<>();
            String effPeriod = String.format("%04d-%02d", year, effMonth);
            dbProblems.addAll(freightReadinessCheck.check(effPeriod));   // B4:货运口径导出前体检(6 条规则)
            dbProblems.addAll(missingDataCheck.check(effPeriod));        // 缺数清单(该有的数没有)
            reportProgress(progress, 22, "回填当月数据");
            int dbFilled = summaryWorkbookFiller.fillMonthlyLedger(wb, effPeriod, year, effMonth, dbProblems);
            int yoyFilled = summaryWorkbookFiller.ensureMonthYoyFormulas(wb, year, effMonth);
            int monthFormulaFilled = summaryWorkbookFiller.ensureMonthFormulas(wb, year, effMonth);
            // 累计同比分母修正:母版把「去年各月」与「去年1-M月累计」辅助列同时计入(重复计/漏当月)
            int cumYoyFixed = summaryWorkbookFiller.repairCumulativeYoyFormulas(wb, year, effMonth);
            reportProgress(progress, 45, "刷新排名页与跨页合成页");
            int rankRefreshed = refreshSummaryRankSheets(wb, effPeriod, "month");
            int cumulativeRefreshed = refreshSummaryCumulativeSheets(wb, year, effMonth); // 四张跨页合成页随报表期刷新
            int widthApplied = applySummaryReferenceLayout(wb);
@@ -3558,13 +3772,25 @@
            applyTwoDecimalFormat(wb); // 数值显示两位小数(保留全精度);% / 日期等既有样式不改变
            int inlineFixed = normalizeStaleInlineStrings(wb); // 清掉「非 inlineStr 却残留 <is>」的非法格,否则 Excel 拒绝打开
            if (inlineFixed > 0) log.warn("汇总工作簿清掉残留 inlineStr 非法格 {} 个(母版由 openpyxl 写出时的典型问题)", inlineFixed);
            reportProgress(progress, 70, "重算整本公式(约 4 万格)");
            int[] recalc = recalcWorkbookFormulas(wb); // 公式重算并写回缓存值:全省行(Σ市州)/累计列/排名 SUM 才能被预览与二次处理读到
            log.info("汇总工作簿公式重算完成:成功 {} 格,失败 {} 格(失败格保留母版旧缓存值,打开时按 fullCalcOnLoad 重算)", recalc[0], recalc[1]);
            if (!wb.getCTWorkbook().isSetCalcPr()) wb.getCTWorkbook().addNewCalcPr();
            wb.getCTWorkbook().getCalcPr().setFullCalcOnLoad(true); // 还原/改写公式后打开即重算
            reportProgress(progress, 95, "写出文件");
            return toBytes(wb);
        } finally {
            ZipSecureFile.setMinInflateRatio(savedZipRatio);
        }
    }
    /** 导出进度回调(异步导出任务用):回调自身异常不影响导出 */
    private static void reportProgress(java.util.function.BiConsumer<Integer, String> progress, int percent, String step) {
        if (progress == null) return;
        try {
            progress.accept(percent, step);
        } catch (Exception ignore) {
            // 进度回调失败不影响导出
        }
    }
@@ -3731,7 +3957,7 @@
        int n = 0;
        n += copyRankValues(wb, "货运量排名", exportFreightRank(period, mode), new int[][]{{0, 0}, {22, 0}});
        n += copyRankValues(wb, "货运周转量排名", exportTurnoverRank(period, mode), new int[][]{{0, 0}, {22, 0}});
        n += copyRankValues(wb, "中口径排名", exportPassengerMidRank(period, mode), new int[][]{{0, 0}, {0, 10}});
        n += copyRankValues(wb, "中口径排名", exportPassengerMidRank(period, mode, wb), new int[][]{{0, 0}, {0, 10}});
        return n;
    }
@@ -3950,9 +4176,8 @@
    private static final int SM_WYC_CX_PAX = 16, SM_WYC_CX_TURN = 17;
    private static final int SM_FREIGHT_TURN = 18;
    private static final int SM_DIM = 19;
    /** 2026 年 1 月当月值列(0 基,C 列);2025 年 1 月当月值列(0 基,V 列) */
    private static final int SM_CUR_COL0 = 2;
    private static final int SM_LAST_COL0 = 21;
    // 2026-10-09:原先写死的 SM_CUR_COL0=2(2026年1月=C)/ SM_LAST_COL0=21(2025年1月=V)已废弃,
    // 改为按表头动态定位(见 smMonthCols / smYearMonthOf),兼容「文本 / 日期序列号 / 日期格式」三种表头写法。
    /**
     * 刷新四张跨页合成页:当年累计(1..month 月)、当月(month 月)及对应同比;
@@ -3963,10 +4188,10 @@
        int[] cumMonths = new int[month];
        for (int m = 1; m <= month; m++) cumMonths[m - 1] = m;
        int[] oneMonth = new int[]{month};
        Map<String, double[]> curCum = smReadLedgerMetrics(wb, true, cumMonths);
        Map<String, double[]> lastCum = smReadLedgerMetrics(wb, false, cumMonths);
        Map<String, double[]> curMon = smReadLedgerMetrics(wb, true, oneMonth);
        Map<String, double[]> lastMon = smReadLedgerMetrics(wb, false, oneMonth);
        Map<String, double[]> curCum = smReadLedgerMetrics(wb, year, cumMonths);
        Map<String, double[]> lastCum = smReadLedgerMetrics(wb, year - 1, cumMonths);
        Map<String, double[]> curMon = smReadLedgerMetrics(wb, year, oneMonth);
        Map<String, double[]> lastMon = smReadLedgerMetrics(wb, year - 1, oneMonth);
        if (curCum.isEmpty()) {
            log.warn("汇总大表四页刷新:台账页未读到市州数据,跳过(保持母版原值)");
            return 0;
@@ -3995,22 +4220,23 @@
    }
    /** 台账页累计取数:市州规范名 -> 19 维指标 */
    private Map<String, double[]> smReadLedgerMetrics(XSSFWorkbook wb, boolean curYear, int[] months) {
    private Map<String, double[]> smReadLedgerMetrics(XSSFWorkbook wb, int blockYear, int[] months) {
        Map<String, double[]> out = new LinkedHashMap<>();
        smReadCityPaxPage(wb, "公交", curYear, months, out, SM_BUS_PAX, SM_BUS_TURN, SM_BUS_CX_PAX, SM_BUS_CX_TURN);
        smReadCityPaxPage(wb, "出租", curYear, months, out, SM_TAXI_PAX, SM_TAXI_TURN, SM_TAXI_CX_PAX, SM_TAXI_CX_TURN);
        smReadCityPaxPage(wb, "网约车", curYear, months, out, SM_WYC_PAX, SM_WYC_TURN, SM_WYC_CX_PAX, SM_WYC_CX_TURN);
        smReadRailFerry(wb, curYear, months, out);
        smReadBanxian(wb, curYear, months, out);
        smReadFreightTurnover(wb, curYear, months, out);
        smReadCityPaxPage(wb, "公交", blockYear, months, out, SM_BUS_PAX, SM_BUS_TURN, SM_BUS_CX_PAX, SM_BUS_CX_TURN);
        smReadCityPaxPage(wb, "出租", blockYear, months, out, SM_TAXI_PAX, SM_TAXI_TURN, SM_TAXI_CX_PAX, SM_TAXI_CX_TURN);
        smReadCityPaxPage(wb, "网约车", blockYear, months, out, SM_WYC_PAX, SM_WYC_TURN, SM_WYC_CX_PAX, SM_WYC_CX_TURN);
        smReadRailFerry(wb, blockYear, months, out);
        smReadBanxian(wb, blockYear, months, out);
        smReadFreightTurnover(wb, blockYear, months, out);
        return out;
    }
    /** 公交/出租/网约车页:每市州 4 行(客运量/旅客周转量/其中城市内客运量/其中城市内旅客周转量) */
    private void smReadCityPaxPage(XSSFWorkbook wb, String sheetName, boolean curYear, int[] months,
    private void smReadCityPaxPage(XSSFWorkbook wb, String sheetName, int blockYear, int[] months,
                                   Map<String, double[]> out, int paxIdx, int turnIdx, int cxPaxIdx, int cxTurnIdx) {
        Sheet sh = wb.getSheet(sheetName);
        if (sh == null) return;
        Map<Integer, Integer> monthCols = smMonthCols(sh, blockYear);
        int last = sh.getLastRowNum();
        for (int r = sh.getFirstRowNum(); r <= last; r++) {
            Row row = sh.getRow(r);
@@ -4033,10 +4259,10 @@
                    else if (paxRow < 0) paxRow = k;
                }
            }
            double totalPax = smSumMonths(sh, paxRow, curYear, months);
            double totalTurn = smSumMonths(sh, turnRow, curYear, months);
            double cityPax = smSumMonths(sh, cxPaxRow, curYear, months);
            double cityTurn = smSumMonths(sh, cxTurnRow, curYear, months);
            double totalPax = smSumMonths(sh, paxRow, monthCols, months);
            double totalTurn = smSumMonths(sh, turnRow, monthCols, months);
            double cityPax = smSumMonths(sh, cxPaxRow, monthCols, months);
            double cityTurn = smSumMonths(sh, cxTurnRow, monthCols, months);
            double[] arr = out.computeIfAbsent(city, k -> new double[SM_DIM]);
            arr[paxIdx] += cityPax;                 // 城市客运口径取“城市内”
            arr[turnIdx] += cityTurn;
@@ -4046,9 +4272,10 @@
    }
    /** 轨道、轮渡页:轨道块(武汉/黄石)+ 轮渡块(武汉) */
    private void smReadRailFerry(XSSFWorkbook wb, boolean curYear, int[] months, Map<String, double[]> out) {
    private void smReadRailFerry(XSSFWorkbook wb, int blockYear, int[] months, Map<String, double[]> out) {
        Sheet sh = wb.getSheet("轨道、轮渡");
        if (sh == null) return;
        Map<Integer, Integer> monthCols = smMonthCols(sh, blockYear);
        int last = sh.getLastRowNum();
        int ferryTitle = -1;
        for (int r = sh.getFirstRowNum(); r <= last; r++) {
@@ -4057,12 +4284,12 @@
            String a = smText(row.getCell(0));
            if (a != null && a.contains("轮渡客运量")) { ferryTitle = r; break; }
        }
        smReadRailFerryBlock(sh, curYear, months, out, sh.getFirstRowNum(),
        smReadRailFerryBlock(sh, monthCols, months, out, sh.getFirstRowNum(),
                ferryTitle < 0 ? last : ferryTitle - 1, SM_RAIL_PAX);
        if (ferryTitle >= 0) smReadRailFerryBlock(sh, curYear, months, out, ferryTitle, last, SM_FERRY_PAX);
        if (ferryTitle >= 0) smReadRailFerryBlock(sh, monthCols, months, out, ferryTitle, last, SM_FERRY_PAX);
    }
    private void smReadRailFerryBlock(Sheet sh, boolean curYear, int[] months, Map<String, double[]> out,
    private void smReadRailFerryBlock(Sheet sh, Map<Integer, Integer> monthCols, int[] months, Map<String, double[]> out,
                                      int start, int end, int baseIdx) {
        for (int r = start; r <= end; r++) {
            Row row = sh.getRow(r);
@@ -4079,15 +4306,16 @@
                else if (paxRow < 0) paxRow = k;
            }
            double[] arr = out.computeIfAbsent(city, k -> new double[SM_DIM]);
            arr[baseIdx] += smSumMonths(sh, paxRow, curYear, months);
            arr[baseIdx + 1] += smSumMonths(sh, turnRow, curYear, months);
            arr[baseIdx] += smSumMonths(sh, paxRow, monthCols, months);
            arr[baseIdx + 1] += smSumMonths(sh, turnRow, monthCols, months);
        }
    }
    /** 班线包车页:每市州 客运量 / 旅客周转量(“其中个体”行不重复计入) */
    private void smReadBanxian(XSSFWorkbook wb, boolean curYear, int[] months, Map<String, double[]> out) {
    private void smReadBanxian(XSSFWorkbook wb, int blockYear, int[] months, Map<String, double[]> out) {
        Sheet sh = wb.getSheet("班线包车");
        if (sh == null) return;
        Map<Integer, Integer> monthCols = smMonthCols(sh, blockYear);
        int last = sh.getLastRowNum();
        for (int r = sh.getFirstRowNum(); r <= last; r++) {
            Row row = sh.getRow(r);
@@ -4104,16 +4332,17 @@
                else if (b.contains("客运量") && paxRow < 0) paxRow = k;
            }
            double[] arr = out.computeIfAbsent(city, k -> new double[SM_DIM]);
            arr[SM_BX_PAX] += smSumMonths(sh, paxRow, curYear, months);
            arr[SM_BX_TURN] += smSumMonths(sh, turnRow, curYear, months);
            arr[SM_BX_PAX] += smSumMonths(sh, paxRow, monthCols, months);
            arr[SM_BX_TURN] += smSumMonths(sh, turnRow, monthCols, months);
        }
    }
    /** 货运页:每市州 规上货物周转量 + 规下货物周转量(“规上+规下”行本身是求和公式,不直接取) */
    private void smReadFreightTurnover(XSSFWorkbook wb, boolean curYear, int[] months, Map<String, double[]> out) {
    private void smReadFreightTurnover(XSSFWorkbook wb, int blockYear, int[] months, Map<String, double[]> out) {
        Sheet sh = wb.getSheet(" 货运");
        if (sh == null) sh = wb.getSheet("货运");
        if (sh == null) return;
        Map<Integer, Integer> monthCols = smMonthCols(sh, blockYear);
        int last = sh.getLastRowNum();
        for (int r = sh.getFirstRowNum(); r <= last; r++) {
            Row row = sh.getRow(r);
@@ -4130,20 +4359,74 @@
                else if (b.contains("规下货物周转量")) { if (below < 0) below = k; }
            }
            double[] arr = out.computeIfAbsent(city, k -> new double[SM_DIM]);
            arr[SM_FREIGHT_TURN] += smSumMonths(sh, above, curYear, months) + smSumMonths(sh, below, curYear, months);
            arr[SM_FREIGHT_TURN] += smSumMonths(sh, above, monthCols, months) + smSumMonths(sh, below, monthCols, months);
        }
    }
    private double smSumMonths(Sheet sh, int rowIdx, boolean curYear, int[] months) {
        if (sh == null || rowIdx < 0) return 0;
    private double smSumMonths(Sheet sh, int rowIdx, Map<Integer, Integer> monthCols, int[] months) {
        if (sh == null || rowIdx < 0 || monthCols == null) return 0;
        Row row = sh.getRow(rowIdx);
        if (row == null) return 0;
        double s = 0;
        for (int m : months) {
            int col = (curYear ? SM_CUR_COL0 : SM_LAST_COL0) + 2 * (m - 1);
            Integer col = monthCols.get(m);
            if (col == null) continue;
            s += smNum(row.getCell(col));
        }
        return s;
    }
    /** 台账页「某年 M 月」的 0 基列号:按表头动态定位(不再写死 C/V),兼容文本 / 日期序列号 / 日期格式三种写法 */
    private Map<Integer, Integer> smMonthCols(Sheet sh, int wantedYear) {
        Map<Integer, Integer> cols = new LinkedHashMap<>();
        if (sh == null) return cols;
        int lastRow = Math.min(sh.getLastRowNum(), sh.getFirstRowNum() + 4);
        for (int r = sh.getFirstRowNum(); r <= lastRow; r++) {
            Row row = sh.getRow(r);
            if (row == null) continue;
            int lastCol = row.getLastCellNum();
            for (int c = row.getFirstCellNum(); c >= 0 && c < lastCol; c++) {
                Integer ym = smYearMonthOf(row.getCell(c));
                if (ym == null || ym / 100 != wantedYear) continue;
                int mo = ym % 100;
                if (!cols.containsKey(mo)) cols.put(mo, c);
            }
        }
        if (cols.isEmpty()) {
            log.warn("汇总大表四页刷新:{} 页未识别到 {} 年的月份表头列(支持文本/序列号/日期三种形式)", sh.getSheetName(), wantedYear);
        }
        return cols;
    }
    /** 表头单元格 -> 年*100+月;只认「YYYY年M月」文本或「某月 1 号」的日期序列号,排除累计/同比/环比 */
    private Integer smYearMonthOf(Cell c) {
        if (c == null) return null;
        try {
            CellType t = c.getCellType();
            if (t == CellType.STRING) {
                String v = c.getStringCellValue();
                if (v == null) return null;
                v = v.trim();
                if (v.isEmpty() || v.contains("累计") || v.contains("同比") || v.contains("环比")) return null;
                java.util.regex.Matcher m = java.util.regex.Pattern
                        .compile("^(\\d{4})\\s*年\\s*(\\d{1,2})\\s*月$").matcher(v);
                if (!m.matches()) return null;
                int y = Integer.parseInt(m.group(1));
                int mo = Integer.parseInt(m.group(2));
                return mo >= 1 && mo <= 12 ? y * 100 + mo : null;
            }
            if (t == CellType.NUMERIC) {
                double v = c.getNumericCellValue();
                if (v < 36526 || v > 73415) return null;
                java.util.Calendar cal = java.util.Calendar.getInstance();
                cal.setTime(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v));
                if (cal.get(java.util.Calendar.DAY_OF_MONTH) != 1) return null;
                return cal.get(java.util.Calendar.YEAR) * 100 + (cal.get(java.util.Calendar.MONTH) + 1);
            }
        } catch (Exception ignore) {
            return null;
        }
        return null;
    }
    /** 台账页单元格取数(数字 / 数字文本 / 公式缓存) */
@@ -5646,6 +5929,8 @@
            String curCity = null;
            Set<Long> used = new HashSet<>();
            int filled = 0, kept = 0, dup = 0;
            List<String> skipped = new ArrayList<>();
            Map<String, Integer> skippedByCity = new LinkedHashMap<>();
            for (int r = 8; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
@@ -5657,11 +5942,16 @@
                if (!a.matches("\\d+(\\.\\d+)?")) continue;
                if (b.isEmpty() || curCity == null) continue;
                InvestmentProject p = matchInvest(projects, b, curCity, "客运站场", used);
                p = preferMonthlyCandidate(projects, p, mByProject, "客运站场", used);
                InvestmentMonthly m = p == null ? null : mByProject.get(p.getId());
                if (p == null || m == null) {
                    kept++;
                    // 有库内项目但当月无数据 → 记为待核对;无匹配项目 → 结转上月
                    if (p != null) dup++;
                    // 2026-09-22:不再静默结转上月,未覆盖的行必须留痕(行号+市州+项目名+原因)
                    skipped.add("第" + (r + 1) + "行 " + curCity + " " + b
                            + (p == null ? " → 库内无匹配项目" : " → 库内无 " + period + " 月度数据"));
                    skippedByCity.merge(curCity, 1, Integer::sum);
                    continue;
                }
                used.add(p.getId());
@@ -5691,6 +5981,7 @@
            }
            log.info("客运站投资明细表 {}:写入 {} 行,结转母版原值 {} 行(其中库内有项目但当月无数据 {} 行)",
                    period, filled, kept, dup);
            logSkippedRows("客运站投资明细表", period, skipped, skippedByCity);
            return toBytes(wb);
        }
    }
@@ -5731,6 +6022,8 @@
        Map<String, double[]> cityStats = new LinkedHashMap<>();  // 全名 -> {总数, 累计, 规划内数, 规划内累计, 规划外数, 规划外累计}
        Set<Long> used = new HashSet<>();
        int filled = 0, kept = 0;
        List<String> skipped = new ArrayList<>();
        Map<String, Integer> skippedByCity = new LinkedHashMap<>();
        for (int i = 0; i < cityRows.size(); i++) {
            int cr = cityRows.get(i);
            String cityLabel = nvl(cellText(sheet.getRow(cr).getCell(0)));
@@ -5753,8 +6046,16 @@
                if (!a.matches("\\d+(\\.\\d+)?")) continue;
                if (b.isEmpty()) continue;
                InvestmentProject p = matchInvest(projects, b, city, "物流园区", used);
                p = preferMonthlyCandidate(projects, p, mByProject, "物流园区", used);
                InvestmentMonthly m = p == null ? null : mByProject.get(p.getId());
                if (p == null || m == null) { kept++; continue; }
                if (p == null || m == null) {
                    kept++;
                    // 2026-09-22:不再静默结转上月,未覆盖的行必须留痕
                    skipped.add("第" + (r + 1) + "行 " + city + " " + b
                            + (p == null ? " → 库内无匹配项目" : " → 库内无 " + period + " 月度数据"));
                    skippedByCity.merge(city, 1, Integer::sum);
                    continue;
                }
                used.add(p.getId());
                // 口径同客运站明细表:只覆盖 H 自开始建设累计 / J 自年初累计 / K 本月完成 / M 形象进度
                if (m.getStartCum() != null) putNum(row, 7, m.getStartCum());
@@ -5885,6 +6186,7 @@
            log.warn("物流站场投资明细公式求值失败: {}", e.getMessage());
        }
        log.info("物流站场投资明细 {}:写入 {} 行,结转母版原值 {} 行", period, filled, kept);
        logSkippedRows("物流站场投资明细", period, skipped, skippedByCity);
        return toBytesHssf(wb);
    }
@@ -6179,6 +6481,40 @@
        return full != null && RegionUtil.cityList().contains(full);
    }
    /**
     * 同名(归一化后一致)多档时,优先选「当月有数据」的那一档。
     * 背景(2026-09-22):十堰「快递物流产业园二期」在库内有两档 id=154(竣工 2026,月度只到 7 月)与
     * id=181(竣工 2029,有 8 月),模板行名前缀与 154 一致 → 导出取到 154 的 7 月值。
     */
    private InvestmentProject preferMonthlyCandidate(List<InvestmentProject> pool, InvestmentProject p,
                                                    Map<Long, InvestmentMonthly> mByProject,
                                                    String category, Set<Long> excludeIds) {
        if (p == null || mByProject.containsKey(p.getId())) return p;
        String norm = normInvestName(p.getProjectName());
        if (norm.isEmpty()) return p;
        InvestmentProject better = null;
        for (InvestmentProject c : pool) {
            if (c == null || c.getId().equals(p.getId())) continue;
            if (excludeIds != null && excludeIds.contains(c.getId())) continue;
            if (category != null && !category.equals(c.getCategory())) continue;
            if (!mByProject.containsKey(c.getId())) continue;
            if (!norm.equals(normInvestName(c.getProjectName()))) continue;
            if (better == null || c.getId() > better.getId()) better = c;
        }
        return better != null ? better : p;
    }
    /** 未按当月数据覆盖的行必须留痕:逐行列出行号+市州+项目名,避免「静默结转上期值」再次发生 */
    private void logSkippedRows(String reportName, String period, List<String> skipped, Map<String, Integer> byCity) {
        if (skipped == null || skipped.isEmpty()) return;
        log.warn("{} {}:{} 行未按当月数据覆盖(结转母版原值),需人工核对源文件/库内数据:",
                reportName, period, skipped.size());
        int limit = Math.min(skipped.size(), 50);
        for (int i = 0; i < limit; i++) log.warn("  [未覆盖] {}", skipped.get(i));
        if (skipped.size() > limit) log.warn("  …另有 {} 行未逐行列出", skipped.size() - limit);
        if (byCity != null && !byCity.isEmpty()) log.warn("  未覆盖行按市州统计:{}", byCity);
    }
    /** 在候选项目池中按名称匹配 DB 项目(可选 市州/类别 过滤 + 县区前缀消歧),未命中返回 null */
    private InvestmentProject matchInvest(List<InvestmentProject> pool, String name, String cityFull, String category) {
        return matchInvest(pool, name, cityFull, category, null);
@@ -6227,7 +6563,8 @@
        if (name == null) return "";
        String s = name.trim();
        s = s.replaceAll("[((]", "").replaceAll("[))]", "");
        s = s.replaceAll("[·•—-_\\-]", "");
        // 2026-09-22:补充半/全角句点、顿号、分号等(库内「中国供销.公安商贸物流园」因半角句点匹配不上模板行)
        s = s.replaceAll("[·•—-_\\-..。、,,;;::]", "");
        s = s.replaceAll("[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ]", "I");
        s = s.replaceAll("^(湖北省|武汉市|黄石市|十堰市|宜昌市|襄阳市|鄂州市|荆门市|孝感市|荆州市|黄冈市|咸宁市|随州市|恩施州|仙桃市|潜江市|天门市|神农架林区)", "");
        s = s.replaceAll("^(?:[\\u4e00-\\u9fa5]{2,4}(?:县|市|区))", "");