traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java
@@ -5165,13 +5165,288 @@
        return null;
    }
    /** 汇总表母版定位:仅精确匹配 {year}年{month}月…(P0-P1 骨架期不允许跨月/跨年静默回退,
     *  目标期无对应母版时明确报错,月份扩展规则待 P0 母版定稿后再放开) */
    /**
     * 汇总表母版定位:先精确匹配 {year}年{month}月道路运输量汇总表.xlsx;
     * 不存在时(2026-10-16 起)**自动用上一期产物扩列生成当期母版并落盘**(扩列后做表头完整性自检+就地补齐),
     * 自动扩列失败则保持原有「明确报错」的行为。跨年(1 月)不自动扩列,仍需人工新开一本。
     */
    private File resolveSummaryMother(String period, String mode) throws Exception {
        String year = period != null && period.contains("-") ? period.split("-")[0] : (period == null ? "" : period);
        int month = period != null && period.contains("-") ? monthOf(period, mode) : 12;
        String name = year + "年" + month + "月道路运输量汇总表.xlsx";
        try {
        return resolveAnyTemplate(summaryTemplateDir, name);
        } catch (RuntimeException notFound) {
            File made = autoExpandMother(period, year, month);
            if (made != null) return made;
            throw notFound;
        }
    }
    /**
     * 缺当期母版时自动扩列(2026-10-16):以上一期「产物缓存」为底(取不到则回退上一期母版并告警),
     * 只做版式(当期列留空),扩列后做「表头完整性自检 + 就地补齐」,落盘为 {年}年{月}月道路运输量汇总表.xlsx。
     * 幂等:目标文件已存在则直接返回、绝不覆盖;任何一步失败都放弃(保持原有报错行为)。
     */
    private File autoExpandMother(String period, String year, int month) {
        try {
            if (month <= 1) {
                log.warn("汇总大表自动扩列:{} 为 1 月(跨年),需人工新开一本,已放弃自动扩列", period);
                return null;
            }
            File dir = existingSummaryDir();
            if (dir == null) { log.warn("汇总大表自动扩列:找不到母版目录,放弃"); return null; }
            String targetName = year + "年" + month + "月道路运输量汇总表.xlsx";
            File target = new File(dir, targetName);
            if (target.isFile()) return target;
            String prevPeriod = String.format("%04d-%02d", Integer.parseInt(year), month - 1);
            File src = resolveLatestProduct(prevPeriod);
            String srcTag = "产物";
            if (src == null) {
                try {
                    src = resolveAnyTemplate(summaryTemplateDir, year + "年" + (month - 1) + "月道路运输量汇总表.xlsx");
                } catch (Exception ignore) { src = null; }
                srcTag = "上一期母版";
                log.warn("汇总大表自动扩列:未找到 {} 的产物缓存,改以{}为底(历史列可能缺该期数据)", prevPeriod, srcTag);
            }
            if (src == null) { log.warn("汇总大表自动扩列:{} 的产物与母版都没有,放弃", prevPeriod); return null; }
            byte[] srcBytes;
            try (java.io.FileInputStream in = new java.io.FileInputStream(src)) {
                srcBytes = org.apache.poi.util.IOUtils.toByteArray(in);
            }
            double savedRatio = ZipSecureFile.getMinInflateRatio();
            ZipSecureFile.setMinInflateRatio(0.0001);
            byte[] expanded;
            try {
                expanded = summaryLayoutExpander.expand(srcBytes, Integer.parseInt(year), month);
            } finally {
                ZipSecureFile.setMinInflateRatio(savedRatio);
            }
            Object[] fixed = checkAndFixSummaryHeaderGaps(expanded, src);
            byte[] bytes = (byte[]) fixed[0];
            String note = (String) fixed[1];
            File tmp = new File(dir, targetName + ".tmp");
            try (java.io.FileOutputStream out = new java.io.FileOutputStream(tmp)) { out.write(bytes); }
            if (!tmp.renameTo(target)) {
                try (java.io.FileOutputStream out = new java.io.FileOutputStream(target)) { out.write(bytes); }
                tmp.delete();
            }
            log.warn("汇总大表自动扩列:已生成当期母版 {}(底={} {};表头自检:{})。请核对版式后再批量出表。",
                    targetName, srcTag, src.getName(), note);
            return target;
        } catch (Exception e) {
            log.warn("汇总大表自动扩列失败(保持原有报错行为):{}", e.toString());
            return null;
        }
    }
    /** 母版目录:取三个候选根里第一个存在的目录 */
    private File existingSummaryDir() {
        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 };
        for (String root : roots) {
            if (root == null || root.trim().isEmpty()) continue;
            File d = new File(root);
            if (d.isDirectory()) return d;
        }
        return null;
    }
    /**
     * 表头完整性自检 + 就地补齐(2026-10-16):同一页内以「月份表头最多的那一行」为参考行(big 行),
     * 其它行若也含大量月份表头(≥参考行的 60%,避免把数据行误判成表头行)却缺了其中某些月份:
     *   ① 先从**底稿(扩列源文件)同 sheet/行/列**取回(扩列把某格清空时最准);
     *   ② 取不到再找**同块参考行**——要求两者在共有列上的月份键完全一致(≥80%),避免把《轨道、轮渡》两块
     *      (2026 年月 / 2025 年月同列)互相串写;找不到同块行就只报告、不改;
     *   ③ 已有月份表头的格子**绝不覆盖**。
     * 返回 {补齐后的字节, 说明文字}。
     */
    private Object[] checkAndFixSummaryHeaderGaps(byte[] xlsx, File baseSrc) {
        XSSFWorkbook base = null;
        double savedRatio2 = ZipSecureFile.getMinInflateRatio();
        try {
            if (baseSrc != null && baseSrc.isFile()) {
                ZipSecureFile.setMinInflateRatio(0.0001); // 产物缓存由 POI 写出,styles 高压缩会触发 Zip-bomb 误报
                base = new XSSFWorkbook(new java.io.FileInputStream(baseSrc));
            }
        } catch (Exception be) {
            base = null;
            log.warn("汇总大表自动扩列:读取底稿失败(表头恢复将退化为仅同块行):{}", be.toString());
        } finally {
            ZipSecureFile.setMinInflateRatio(savedRatio2);
        }
        try (XSSFWorkbook wb = new XSSFWorkbook(new java.io.ByteArrayInputStream(xlsx))) {
            int fromBase = 0, fromSibling = 0;
            List<String> stillMissing = new ArrayList<>();
            for (int si = 0; si < wb.getNumberOfSheets(); si++) {
                Sheet sh = wb.getSheetAt(si);
                Map<Integer, Map<Integer, String>> hdrRows = new LinkedHashMap<>();
                for (int r = sh.getFirstRowNum(); r <= sh.getLastRowNum(); r++) {
                    Map<Integer, String> m = new HashMap<>();
                    Row row = sh.getRow(r);
                    if (row != null) {
                        for (int c = row.getFirstCellNum(); c >= 0 && c < row.getLastCellNum(); c++) {
                            String k = monthHeaderKey(row.getCell(c));
                            if (k != null) m.put(c, k);
                        }
                    }
                    if (m.size() >= 4) hdrRows.put(r, m);
                }
                if (hdrRows.isEmpty()) continue;
                int bestRow = -1, bestCnt = 0;
                for (Map.Entry<Integer, Map<Integer, String>> en : hdrRows.entrySet()) {
                    if (en.getValue().size() > bestCnt) { bestCnt = en.getValue().size(); bestRow = en.getKey(); }
                }
                Map<Integer, String> bestMap = hdrRows.get(bestRow);
                Sheet baseSheet = base == null ? null : base.getSheet(sh.getSheetName());
                // 2026-10-16:底稿里已是月份表头的格子,扩列后若被写成「别的年份的月份」(双块页如《轨道、轮渡》
                // 两块同列不同年时会串写),按底稿恢复——正确扩列不应改变既有月份表头;跨年不适用(年内不可能变年)。
                if (baseSheet != null) {
                    for (int r = baseSheet.getFirstRowNum(); r <= baseSheet.getLastRowNum(); r++) {
                        Row brow = baseSheet.getRow(r);
                        if (brow == null) continue;
                        Row orow = sh.getRow(r);
                        if (orow == null) continue;
                        for (int c = brow.getFirstCellNum(); c >= 0 && c < brow.getLastCellNum(); c++) {
                            String bk = monthHeaderKey(brow.getCell(c));
                            if (bk == null) bk = numericSerialKey(brow.getCell(c));   // 底稿日期序列丢格式时兜底
                            if (bk == null) continue;
                            Cell oc = orow.getCell(c);
                            String ok = monthHeaderKey(oc);
                            if (ok == null || ok.equals(bk)) continue;
                            if (bk.substring(0, 4).equals(ok.substring(0, 4))) continue;   // 同年不动(可能是列位移)
                            copyCellValueAndStyle(brow.getCell(c), oc);
                            fromBase++;
                        }
                    }
                }
                for (Map.Entry<Integer, Map<Integer, String>> en : hdrRows.entrySet()) {
                    int r = en.getKey();
                    if (r == bestRow) continue;
                    Map<Integer, String> mine = en.getValue();
                    if (mine.size() < Math.max(4, (bestCnt * 6) / 10)) continue;
                    // 找同块参考行:共有列月份键一致的列数最多、且占比 ≥80%
                    int sibRow = -1, sibScore = 0;
                    for (Map.Entry<Integer, Map<Integer, String>> en2 : hdrRows.entrySet()) {
                        int o = en2.getKey();
                        if (o == r) continue;
                        Map<Integer, String> other = en2.getValue();
                        int same = 0;
                        for (Map.Entry<Integer, String> e3 : mine.entrySet()) {
                            String k2 = other.get(e3.getKey());
                            if (k2 != null && k2.equals(e3.getValue())) same++;
                        }
                        if (same * 5 >= mine.size() * 4 && same > sibScore) { sibScore = same; sibRow = o; }
                    }
                    List<String> fixedCols = new ArrayList<>();
                    for (Map.Entry<Integer, String> e3 : bestMap.entrySet()) {
                        int col = e3.getKey();
                        Cell cur = sh.getRow(r) == null ? null : sh.getRow(r).getCell(col);
                        if (cur != null && monthHeaderKey(cur) != null) continue;      // 已有月份表头,绝不覆盖
                        boolean done = false;
                        // ① 底稿同位置
                        if (baseSheet != null) {
                            Row br = baseSheet.getRow(r);
                            Cell bc = br == null ? null : br.getCell(col);
                            if (bc != null && monthHeaderKey(bc) != null) {
                                Cell dst = cur != null ? cur : sh.getRow(r).createCell(col);
                                copyCellValueAndStyle(bc, dst);
                                fromBase++; fixedCols.add(e3.getValue()); done = true;
                            }
                        }
                        // ② 同块参考行
                        if (!done && sibRow >= 0) {
                            Row sr = sh.getRow(sibRow);
                            Cell sc = sr == null ? null : sr.getCell(col);
                            if (sc != null && monthHeaderKey(sc) != null) {
                                Cell dst = cur != null ? cur : sh.getRow(r).createCell(col);
                                copyCellValueAndStyle(sc, dst);
                                fromSibling++; fixedCols.add(e3.getValue()); done = true;
                            }
                        }
                        if (!done) { /* 无法安全补齐 */ }
                    }
                    if (!fixedCols.isEmpty()) {
                        for (String k : fixedCols) {
                            for (Map.Entry<Integer, String> e3 : bestMap.entrySet()) {
                                if (!k.equals(e3.getValue())) continue;
                                Cell c2 = sh.getRow(r).getCell(e3.getKey());
                                Cell c3 = sh.getRow(r).getCell(e3.getKey() + 1);
                                if (c3 != null && c3.getCellType() == CellType.BLANK && bestMap.containsKey(e3.getKey())) {
                                    Row br2 = bestRow >= 0 ? sh.getRow(bestRow) : null;
                                    Cell r2 = br2 == null ? null : br2.getCell(e3.getKey() + 1);
                                    if (r2 != null && r2.getCellType() != CellType.BLANK) copyCellValueAndStyle(r2, c3);
                                }
                            }
                        }
                    }
                }
            }
            baseSafeClose(base);
            int fixed = fromBase + fromSibling;
            if (fixed == 0) return new Object[]{xlsx, stillMissing.isEmpty() ? "无缺失" : "仍缺:" + String.join(";", stillMissing)};
            ByteArrayOutputStream bos = new ByteArrayOutputStream(xlsx.length);
            wb.write(bos);
            String note = "补齐 " + fixed + " 处表头(底稿 " + fromBase + " / 同块行 " + fromSibling + ")"
                    + (stillMissing.isEmpty() ? "" : ";仍有无法安全补齐的缺格(见日志)");
            return new Object[]{bos.toByteArray(), note};
        } catch (Exception e) {
            baseSafeClose(base);
            return new Object[]{xlsx, "自检失败(忽略):" + e};
        }
    }
    private void baseSafeClose(XSSFWorkbook b) {
        try { if (b != null) b.close(); } catch (Exception ignore) { }
    }
    /** 数值型 Excel 日期序列(20000~60000,即 1954~2064 年)→ "YYYY-MM";非该区间返回 null。
     *  仅用于「底稿无日期格式但其实是月份表头」的兜底比对。 */
    private String numericSerialKey(Cell c) {
        if (c == null || c.getCellType() != CellType.NUMERIC) return null;
        double v = c.getNumericCellValue();
        if (v < 20000 || v > 60000) return null;
        java.util.Date d = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(d);
        return String.format("%04d-%02d", cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH) + 1);
    }
    /** 月份表头识别:日期单元格(含日期序列)或 "YYYY年M月" 文本 → 归一化键,否则 null */
    private String monthHeaderKey(Cell c) {
        if (c == null) return null;
        CellType t = c.getCellType();
        if (t == CellType.NUMERIC && org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(c)) {
            java.util.Date d = c.getDateCellValue();
            if (d == null) return null;
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(d);
            return String.format("%04d-%02d", cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH) + 1);
        }
        if (t == CellType.STRING) {
            String v = c.getStringCellValue();
            if (v == null) return null;
            String s = v.replace(" ", "");
            if (s.endsWith("月") && s.contains("年") && s.length() <= 12) return s;
        }
        return null;
    }
    /** 克隆单元格的值与样式(表头补齐用) */
    private void copyCellValueAndStyle(Cell src, Cell dst) {
        if (src == null || dst == null) return;
        switch (src.getCellType()) {
            case STRING: dst.setCellValue(src.getStringCellValue()); break;
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(src)) dst.setCellValue(src.getDateCellValue());
                else dst.setCellValue(src.getNumericCellValue());
                break;
            case FORMULA: dst.setCellFormula(src.getCellFormula()); break;
            default: dst.setBlank();
        }
        dst.setCellStyle(src.getCellStyle());
    }
    // ==================== 网约车客运量拆分表(月度) ====================