traffic-audit-server/src/main/java/com/trafficaudit/dataimport/service/DataImportService.java
@@ -2,7 +2,9 @@
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.trafficaudit.auditengine.entity.AuditResult;
import com.trafficaudit.auditengine.entity.AuditRun;
import com.trafficaudit.auditengine.mapper.AuditResultMapper;
import com.trafficaudit.auditengine.mapper.AuditRunMapper;
import com.trafficaudit.common.util.RegionUtil;
import com.trafficaudit.dataimport.entity.EnergyAuthVehicle;
import com.trafficaudit.dataimport.entity.EnergyVehicleQuarterly;
@@ -18,6 +20,8 @@
import com.trafficaudit.dataimport.entity.CityBusMonthly;
import com.trafficaudit.dataimport.entity.CityTaxiMonthly;
import com.trafficaudit.dataimport.entity.CityTaxiAuth;
import com.trafficaudit.dataimport.entity.WycOrderMonthly;
import com.trafficaudit.dataimport.entity.WycTotalMonthly;
import com.trafficaudit.dataimport.entity.ScaleSplitTransport;
import com.trafficaudit.dataimport.entity.TransportAuthVehicle;
import com.trafficaudit.dataimport.entity.VehicleTrackMileage;
@@ -36,6 +40,8 @@
import com.trafficaudit.dataimport.mapper.CityBusMonthlyMapper;
import com.trafficaudit.dataimport.mapper.CityTaxiMonthlyMapper;
import com.trafficaudit.dataimport.mapper.CityTaxiAuthMapper;
import com.trafficaudit.dataimport.mapper.WycOrderMonthlyMapper;
import com.trafficaudit.dataimport.mapper.WycTotalMonthlyMapper;
import com.trafficaudit.dataimport.mapper.ScaleSplitTransportMapper;
import com.trafficaudit.dataimport.mapper.TransportAuthVehicleMapper;
import com.trafficaudit.dataimport.mapper.VehicleTrackMileageMapper;
@@ -50,8 +56,13 @@
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import cn.hutool.core.io.IoUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
@@ -67,6 +78,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.trafficaudit.dataimport.dto.ImportResult;
import org.apache.poi.ss.usermodel.DateUtil;
import java.util.Comparator;
@@ -94,6 +106,9 @@
    /** H204 燃料1计量单位码 -> 中文单位 */
    private static final Map<String, String> ENERGY_FUEL_UNIT_NAMES = new HashMap<>();
    /** 能耗导入按报表期互斥,防止同报表期并发重导互相覆盖 */
    private final ConcurrentHashMap<String, Object> energyImportLocks = new ConcurrentHashMap<>();
    static {
        ENERGY_VEHICLE_TYPE_NAMES.put("01", "普通货车");
@@ -135,6 +150,8 @@
    @Resource
    private AuditResultMapper auditResultMapper;
    @Resource
    private AuditRunMapper auditRunMapper;
    @Resource
    private PassengerEnterpriseMonthlyMapper passengerMapper;
    @Resource
    private PassengerIndividualMonthlyMapper passengerIndividualMapper;
@@ -158,6 +175,10 @@
    private CityTaxiMonthlyMapper cityTaxiMapper;
    @Resource
    private CityTaxiAuthMapper cityTaxiAuthMapper;
    @Resource
    private WycTotalMonthlyMapper wycTotalMapper;
    @Resource
    private WycOrderMonthlyMapper wycOrderMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;
@@ -403,41 +424,20 @@
    /** 公路旅客个体客运量/周转量(企业线下汇报数据,按所属地区导入,供分市州表个体行填充) */
    /** 公路旅客个体客运量/周转量(导入后按市州汇总填充分市州表个体行),支持两种模板:
     *  ① 企业线下汇报明细(表头含「企业名称」):逐企业入库;
     *  ② 省厅市州汇总表《湖北省公路旅客运输个体户月度生产情况(YYYY.M)》:
     *     sheet 内为「全省N月个体客运量汇总表」标题块 + 「市州/个体车辆数/…/个体客运量/个体旅客周转量」表头,
     *     按市州逐行入库(同一市州多行如 县内班线+跨县班线 均入库,报表侧按市州自动汇总)。 */
    public ImportResult importPassengerIndividual(MultipartFile file, String period) throws Exception {
        List<PassengerIndividualMonthly> rows = new ArrayList<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            Map<String, Integer> colMap = buildHeaderMap(sheet.getRow(0));
            Integer codeCol = colMap.get("所属地区");
            Integer entCol = colMap.get("企业代码");
            Integer nameCol = colMap.get("企业名称");
            Integer passCol = null;
            Integer turnCol = null;
            for (Map.Entry<String, Integer> e : colMap.entrySet()) {
                String k = e.getKey();
                if (k != null && k.contains("个体") && k.contains("客运量")) passCol = e.getValue();
                if (k != null && k.contains("个体") && (k.contains("周转量") || k.contains("周转"))) turnCol = e.getValue();
            }
            if (passCol == null && turnCol == null) {
                throw new RuntimeException("未找到「个体客运量/个体旅客周转量」列,请检查模板(列名需包含“个体客运量”“个体周转量”)");
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String name = nameCol != null ? getString(row, nameCol) : null;
                if (name == null || name.trim().isEmpty()) continue;
                Double pass = passCol != null ? getDecimalOrNull(row, passCol) : null;
                Double turn = turnCol != null ? getDecimalOrNull(row, turnCol) : null;
                if ((pass == null || pass == 0.0) && (turn == null || turn == 0.0)) continue;
                PassengerIndividualMonthly entity = new PassengerIndividualMonthly();
                entity.setReportPeriod(period);
                entity.setRegionCode(codeCol != null ? getString(row, codeCol) : null);
                entity.setEnterpriseCode(entCol != null ? getString(row, entCol) : null);
                entity.setEnterpriseName(name.trim());
                entity.setPassengerCount(pass);
                entity.setTurnover(turn);
                rows.add(entity);
            if (colMap.containsKey("企业名称")) {
                parsePassengerIndividualEnterprise(sheet, colMap, period, rows);
            } else {
                parsePassengerIndividualCitySheet(sheet, period, rows);
            }
        } catch (Exception e) {
            log.error("Passenger individual parse error", e);
@@ -472,24 +472,125 @@
        return new ImportResult(success, failDetails.size(), failDetails);
    }
    /** 公路旅客运政车辆数(独立模板:企业代码/企业名称/车辆数/载客位数) */
    /** 旧版个体客运量模板(企业线下汇报明细:所属地区/企业代码/企业名称/…个体客运量/…个体旅客周转量) */
    private void parsePassengerIndividualEnterprise(Sheet sheet, Map<String, Integer> colMap, String period,
                                                    List<PassengerIndividualMonthly> rows) {
        Integer codeCol = colMap.get("所属地区");
        Integer entCol = colMap.get("企业代码");
        Integer nameCol = colMap.get("企业名称");
        Integer passCol = null;
        Integer turnCol = null;
        for (Map.Entry<String, Integer> e : colMap.entrySet()) {
            String k = e.getKey();
            if (k != null && k.contains("个体") && k.contains("客运量")) passCol = e.getValue();
            if (k != null && k.contains("个体") && (k.contains("周转量") || k.contains("周转"))) turnCol = e.getValue();
        }
        if (passCol == null && turnCol == null) {
            throw new RuntimeException("未找到「个体客运量/个体旅客周转量」列,请检查模板(列名需包含“个体客运量”“个体周转量”)");
        }
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            String name = nameCol != null ? getString(row, nameCol) : null;
            if (name == null || name.trim().isEmpty()) continue;
            Double pass = passCol != null ? getDecimalOrNull(row, passCol) : null;
            Double turn = turnCol != null ? getDecimalOrNull(row, turnCol) : null;
            if ((pass == null || pass == 0.0) && (turn == null || turn == 0.0)) continue;
            PassengerIndividualMonthly entity = new PassengerIndividualMonthly();
            entity.setReportPeriod(period);
            entity.setRegionCode(codeCol != null ? getString(row, codeCol) : null);
            entity.setEnterpriseCode(entCol != null ? getString(row, entCol) : null);
            entity.setEnterpriseName(name.trim());
            entity.setPassengerCount(pass);
            entity.setTurnover(turn);
            rows.add(entity);
        }
    }
    /** 新版市州汇总模板:《全省N月个体客运量汇总表》标题行 → 表头行(市州/…/个体客运量/个体旅客周转量)→ 市州数据行 */
    private void parsePassengerIndividualCitySheet(Sheet sheet, String period, List<PassengerIndividualMonthly> rows) {
        int targetMonth;
        try {
            targetMonth = Integer.parseInt(period.split("-")[1]);
        } catch (Exception e) {
            throw new RuntimeException("报表期格式应为 yyyy-MM:" + period);
        }
        int titleRow = -1;
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            String t = getString(row, 0);
            if (t == null || !t.contains("全省") || !t.contains("月")) continue;
            java.util.regex.Matcher m = java.util.regex.Pattern.compile("全省(\\d+)月").matcher(t);
            if (!m.find()) continue;
            if (Integer.parseInt(m.group(1)) == targetMonth) { titleRow = r; break; }
            if (titleRow < 0) titleRow = r; // 标题不含目标月份时暂记第一个标题块兜底
        }
        if (titleRow < 0) {
            throw new RuntimeException("未找到「全省N月个体客运量汇总表」标题块,请使用《模板_湖北省公路旅客运输个体户月度生产情况(YYYY.M)》整理后导入");
        }
        Row header = sheet.getRow(titleRow + 1);
        if (header == null) {
            throw new RuntimeException("「全省" + targetMonth + "月…汇总表」标题后缺少表头行(市州/个体客运量/个体旅客周转量)");
        }
        int cityCol = -1, passCol = -1, turnCol = -1;
        for (Cell c : header) {
            String h = FORMATTER.formatCellValue(c).trim();
            if (h.isEmpty()) continue;
            if (h.contains("市州")) cityCol = c.getColumnIndex();
            else if (h.contains("个体") && h.contains("客运量")) passCol = c.getColumnIndex();
            else if (h.contains("个体") && (h.contains("周转量") || h.contains("周转"))) turnCol = c.getColumnIndex();
        }
        if (cityCol < 0 || (passCol < 0 && turnCol < 0)) {
            throw new RuntimeException("未找到「市州 / 个体客运量 / 个体旅客周转量」列,请使用系统模板整理后导入");
        }
        int lastRow = Math.min(sheet.getLastRowNum(), titleRow + 40);
        for (int r = titleRow + 2; r <= lastRow; r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            String first = getString(row, cityCol);
            if (first == null) break;
            String t = first.trim();
            if (t.isEmpty() || t.contains("合计") || t.contains("环比") || t.contains("全省")) break;
            String city = RegionUtil.normalizeCityName(t);
            if (!RegionUtil.cityList().contains(city)) continue;
            Double pass = passCol >= 0 ? getDecimalOrNull(row, passCol) : null;
            Double turn = turnCol >= 0 ? getDecimalOrNull(row, turnCol) : null;
            if ((pass == null || pass == 0.0) && (turn == null || turn == 0.0)) continue;
            PassengerIndividualMonthly entity = new PassengerIndividualMonthly();
            entity.setReportPeriod(period);
            entity.setRegionCode(RegionUtil.codeOfCity(city));
            entity.setEnterpriseName(city);
            entity.setPassengerCount(pass);
            entity.setTurnover(turn);
            rows.add(entity);
        }
    }
    /** 公路旅客运政车辆数(兼容两种表头:① 企业代码/企业名称/车辆数/载客位数;② 运政库导出 OWNERNAME/总车辆数/客位数,无企业代码列) */
    public ImportResult importPassengerAuth(MultipartFile file, String period) throws Exception {
        List<PassengerAuthVehicle> authList = new ArrayList<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            Map<String, Integer> colMap = buildHeaderMap(sheet.getRow(0));
            requireHeaderCols(sheet, "旅客运政车辆数", "企业名称", "车辆数", "载客位数");
            Map<String, Integer> colMap = buildHeaderMapCompat(sheet.getRow(0));
            Integer nameCol = firstColIdx(colMap, "企业名称", "OWNERNAME");
            Integer vehicleCol = firstColIdx(colMap, "车辆数", "总车辆数");
            Integer seatCol = firstColIdx(colMap, "载客位数", "客位数");
            Integer codeCol = firstColIdx(colMap, "企业代码");
            if (nameCol == null || vehicleCol == null || seatCol == null) {
                throw new RuntimeException("所选数据类型【旅客运政车辆数】与文件内容不符:表头需含【企业名称/车辆数/载客位数】或【OWNERNAME/总车辆数/客位数】,请确认是否选错了数据类型或使用了旧模板");
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String name = gs(row, colMap, "企业名称");
                String name = getString(row, nameCol);
                if (name == null || name.trim().isEmpty()) continue;
                PassengerAuthVehicle auth = new PassengerAuthVehicle();
                auth.setReportPeriod(period);
                auth.setEnterpriseCode(gs(row, colMap, "企业代码"));
                auth.setEnterpriseCode(codeCol == null ? null : getString(row, codeCol));
                auth.setEnterpriseName(name.trim());
                auth.setVehicleCount(gi(row, colMap, "车辆数"));
                auth.setSeatCount(gi(row, colMap, "载客位数"));
                auth.setVehicleCount(getInt(row, vehicleCol));
                auth.setSeatCount(getInt(row, seatCol));
                authList.add(auth);
            }
        } catch (Exception e) {
@@ -527,6 +628,15 @@
    /** 能耗明细每组固定18列,车牌号起始列(0-based):3,21,39,57,75 */
    private static final int[] ENERGY_GROUP_COLS = {3, 21, 39, 57, 75};
    /** 能耗明细模板表头关键列(0-based):程序按固定列位解析,解析前校验表头,错位直接拒绝 */
    private static final int[] ENERGY_HEADER_COLS = {3, 4, 5, 21, 39, 57, 75};
    private static final String[] ENERGY_HEADER_KEYWORDS = {"车牌号", "车辆类型", "燃料类型", "车牌号", "车牌号", "车牌号", "车牌号"};
    /** 能耗导入按报表期互斥锁(H204 明细与运政信息共用,避免同报表期并发重导互相覆盖) */
    private Object energyLock(String period) {
        return energyImportLocks.computeIfAbsent(period == null ? "" : period, k -> new Object());
    }
    public ImportResult importEnergyMonthly(MultipartFile file, String period) throws Exception {
        List<EnergyRow> rows = new ArrayList<>();
        List<EnergyAuthVehicle> authList = new ArrayList<>();
@@ -534,6 +644,7 @@
            // sheet0: 第二季度货车能耗明细(每行左右各5组车辆,每组固定18列)
            Sheet sheet = wb.getSheetAt(0);
            requireHeaderKeyword(sheet, "道路货运车辆能源消耗情况", "企业名称", "车牌号");
            requireEnergyHeaderLayout(sheet);
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
@@ -541,7 +652,7 @@
                if (enterpriseName == null || enterpriseName.trim().isEmpty()) continue;
                for (int group : ENERGY_GROUP_COLS) {
                    String plate = getString(row, group);
                    if (plate == null || plate.trim().isEmpty()) continue;
                    if (plate == null || plate.trim().isEmpty() || "0".equals(plate.trim())) continue;
                    EnergyVehicleQuarterly e = new EnergyVehicleQuarterly();
                    e.setReportPeriod(period);
                    e.setRegionCode(getString(row, 0));
@@ -580,7 +691,7 @@
                    Row row = authSheet.getRow(r);
                    if (row == null) continue;
                    String plate = getString(row, 0);
                    if (plate == null || plate.trim().isEmpty()) continue;
                    if (plate == null || plate.trim().isEmpty() || "0".equals(plate.trim())) continue;
                    EnergyAuthVehicle auth = new EnergyAuthVehicle();
                    auth.setReportPeriod(period);
                    auth.setPlateNo(plate.trim());
@@ -597,54 +708,57 @@
        }
        // 幂等:同报表期重新导入,先删除旧数据(两表 + H204 规则审核结果)
        energyMapper.delete(new LambdaQueryWrapper<EnergyVehicleQuarterly>()
            .eq(EnergyVehicleQuarterly::getReportPeriod, period));
        energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
            .eq(EnergyAuthVehicle::getReportPeriod, period));
        List<Long> h204RuleIds = new ArrayList<>();
        for (com.trafficaudit.rulemanage.entity.AuditRule rule : ruleMapper.selectList(null)) {
            if ("H204".equals(rule.getReportType())) h204RuleIds.add(rule.getId());
        }
        if (!h204RuleIds.isEmpty()) {
            auditResultMapper.delete(new LambdaQueryWrapper<AuditResult>()
                .eq(AuditResult::getReportPeriod, period)
                .in(AuditResult::getRuleId, h204RuleIds));
        }
        int success = 0;
        List<String> failDetails = new ArrayList<>();
        for (EnergyRow item : rows) {
            try {
                energyMapper.insert(item.entity);
                success++;
            } catch (Exception e) {
                Throwable cause = e;
                while (cause.getCause() != null) cause = cause.getCause();
                String reason = cause.getMessage();
                if (reason == null || reason.trim().isEmpty()) reason = e.getMessage();
                failDetails.add("第 " + item.excelRow + " 行(" + item.entity.getEnterpriseName()
                    + " " + item.entity.getPlateNo() + "):" + reason);
                log.error("Energy insert error: row {}, {}", item.excelRow, item.entity.getPlateNo(), e);
        // 加锁:同报表期并发重导互斥,防止 delete/insert 交错导致数据残留或翻倍
        synchronized (energyLock(period)) {
            energyMapper.delete(new LambdaQueryWrapper<EnergyVehicleQuarterly>()
                .eq(EnergyVehicleQuarterly::getReportPeriod, period));
            energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
                .eq(EnergyAuthVehicle::getReportPeriod, period));
            List<Long> h204RuleIds = new ArrayList<>();
            for (com.trafficaudit.rulemanage.entity.AuditRule rule : ruleMapper.selectList(null)) {
                if ("H204".equals(rule.getReportType())) h204RuleIds.add(rule.getId());
            }
        }
        String errorDetail = String.join("\n", failDetails);
        if (errorDetail.length() > 4000) {
            errorDetail = errorDetail.substring(0, 4000) + "\n……";
        }
        recordBatch(file.getOriginalFilename(), "H204", period, rows.size(), success, failDetails.size(), errorDetail);
        int authSuccess = 0;
        for (EnergyAuthVehicle auth : authList) {
            try {
                energyAuthMapper.insert(auth);
                authSuccess++;
            } catch (Exception e) {
                log.error("energy auth insert error: {}", auth.getPlateNo(), e);
            if (!h204RuleIds.isEmpty()) {
                auditResultMapper.delete(new LambdaQueryWrapper<AuditResult>()
                    .eq(AuditResult::getReportPeriod, period)
                    .in(AuditResult::getRuleId, h204RuleIds));
            }
            int success = 0;
            List<String> failDetails = new ArrayList<>();
            for (EnergyRow item : rows) {
                try {
                    energyMapper.insert(item.entity);
                    success++;
                } catch (Exception e) {
                    Throwable cause = e;
                    while (cause.getCause() != null) cause = cause.getCause();
                    String reason = cause.getMessage();
                    if (reason == null || reason.trim().isEmpty()) reason = e.getMessage();
                    failDetails.add("第 " + item.excelRow + " 行(" + item.entity.getEnterpriseName()
                        + " " + item.entity.getPlateNo() + "):" + reason);
                    log.error("Energy insert error: row {}, {}", item.excelRow, item.entity.getPlateNo(), e);
                }
            }
            String errorDetail = String.join("\n", failDetails);
            if (errorDetail.length() > 4000) {
                errorDetail = errorDetail.substring(0, 4000) + "\n……";
            }
            recordBatch(file.getOriginalFilename(), "H204", period, rows.size(), success, failDetails.size(), errorDetail);
            int authSuccess = 0;
            for (EnergyAuthVehicle auth : authList) {
                try {
                    energyAuthMapper.insert(auth);
                    authSuccess++;
                } catch (Exception e) {
                    log.error("energy auth insert error: {}", auth.getPlateNo(), e);
                }
            }
            recordBatch(file.getOriginalFilename(), "ENERGY_AUTH", period, authList.size(), authSuccess, 0, null);
            log.info("Energy monthly imported: {} vehicles, auth {} rows for {}", success, authSuccess, period);
            return new ImportResult(success, failDetails.size(), failDetails);
        }
        recordBatch(file.getOriginalFilename(), "ENERGY_AUTH", period, authList.size(), authSuccess, 0, null);
        log.info("Energy monthly imported: {} vehicles, auth {} rows for {}", success, authSuccess, period);
        return new ImportResult(success, failDetails.size(), failDetails);
    }
    /** 能耗车辆运政信息(独立模板:车牌号/车辆类型/燃料类型/标记吨位/准牵引质量) */
@@ -653,11 +767,17 @@
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            requireHeaderKeyword(sheet, "能耗车辆运政信息", "车牌号");
            Row authHeader = sheet.getRow(0);
            String authH0 = authHeader == null ? null : FORMATTER.formatCellValue(authHeader.getCell(0)).trim();
            if (authH0 == null || authH0.isEmpty() || !authH0.contains("车牌号")) {
                throw new RuntimeException("能耗车辆运政信息表头与系统模板不一致:第 1 列应为「车牌号」,实际为「"
                    + (authH0 == null || authH0.isEmpty() ? "空" : authH0) + "」。请使用系统模板《模板_能耗车辆运政信息.xlsx》整理后再导入");
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String plate = getString(row, 0);
                if (plate == null || plate.trim().isEmpty()) continue;
                if (plate == null || plate.trim().isEmpty() || "0".equals(plate.trim())) continue;
                EnergyAuthVehicle auth = new EnergyAuthVehicle();
                auth.setReportPeriod(period);
                auth.setPlateNo(plate.trim());
@@ -671,30 +791,32 @@
            log.error("Energy auth parse error", e);
            throw e;
        }
        // 幂等:同报表期重新导入,先删除旧数据
        energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
            .eq(EnergyAuthVehicle::getReportPeriod, period));
        deleteRuleResults("H204", period);
        int success = 0;
        List<String> failDetails = new ArrayList<>();
        for (EnergyAuthVehicle auth : authList) {
            try {
                energyAuthMapper.insert(auth);
                success++;
            } catch (Exception e) {
                Throwable cause = e;
                while (cause.getCause() != null) cause = cause.getCause();
                String reason = cause.getMessage();
                if (reason == null || reason.trim().isEmpty()) reason = e.getMessage();
                failDetails.add("第 " + (authList.indexOf(auth) + 2) + " 行(" + auth.getPlateNo() + "):" + reason);
                log.error("Energy auth insert error: {}", auth.getPlateNo(), e);
        // 幂等:同报表期重新导入,先删除旧数据;与 H204 明细共用报表期锁,防并发互相覆盖
        synchronized (energyLock(period)) {
            energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
                .eq(EnergyAuthVehicle::getReportPeriod, period));
            deleteRuleResults("H204", period);
            int success = 0;
            List<String> failDetails = new ArrayList<>();
            for (EnergyAuthVehicle auth : authList) {
                try {
                    energyAuthMapper.insert(auth);
                    success++;
                } catch (Exception e) {
                    Throwable cause = e;
                    while (cause.getCause() != null) cause = cause.getCause();
                    String reason = cause.getMessage();
                    if (reason == null || reason.trim().isEmpty()) reason = e.getMessage();
                    failDetails.add("第 " + (authList.indexOf(auth) + 2) + " 行(" + auth.getPlateNo() + "):" + reason);
                    log.error("Energy auth insert error: {}", auth.getPlateNo(), e);
                }
            }
            String errorDetail = String.join("\n", failDetails);
            if (errorDetail.length() > 4000) errorDetail = errorDetail.substring(0, 4000) + "\n……";
            recordBatch(file.getOriginalFilename(), "ENERGY_AUTH", period, authList.size(), success, failDetails.size(), errorDetail);
            log.info("Energy auth imported: {} rows for {}", success, period);
            return new ImportResult(success, failDetails.size(), failDetails);
        }
        String errorDetail = String.join("\n", failDetails);
        if (errorDetail.length() > 4000) errorDetail = errorDetail.substring(0, 4000) + "\n……";
        recordBatch(file.getOriginalFilename(), "ENERGY_AUTH", period, authList.size(), success, failDetails.size(), errorDetail);
        log.info("Energy auth imported: {} rows for {}", success, period);
        return new ImportResult(success, failDetails.size(), failDetails);
    }
    /** H204 行记录:保留 Excel 行号用于失败定位 */
@@ -716,25 +838,27 @@
    // ========== 运政车辆 ==========
    /** 运政车辆导入:与 H203-2 月报一致,按表头名称定位列,列顺序变化也能正确导入 */
    public int importTransportAuth(MultipartFile file, String period) throws Exception {
        List<TransportAuthVehicle> list = new ArrayList<>();
        int failRows = 0;
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            requireHeaderKeyword(sheet, "运政车辆", "企业名称");
            requireHeaderCols(sheet, "运政车辆", "企业名称", "总牵引车数", "总挂车数", "其它车辆数", "挂车总吨位(吨)", "其它车辆总吨位(吨)");
            Map<String, Integer> colMap = buildHeaderMap(sheet.getRow(0));
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String name = getString(row, 0);
                String name = gs(row, colMap, "企业名称");
                if (name == null || name.trim().isEmpty()) continue;
                TransportAuthVehicle entity = new TransportAuthVehicle();
                entity.setReportPeriod(period);
                entity.setEnterpriseName(name);
                entity.setTractorCount(getInt(row, 1));
                entity.setTrailerCount(getInt(row, 2));
                entity.setOtherCount(getInt(row, 3));
                entity.setTrailerTons(getDecimal(row, 4));
                entity.setOtherTons(getDecimal(row, 5));
                entity.setTractorCount(gi(row, colMap, "总牵引车数"));
                entity.setTrailerCount(gi(row, colMap, "总挂车数"));
                entity.setOtherCount(gi(row, colMap, "其它车辆数"));
                entity.setTrailerTons(gd(row, colMap, "挂车总吨位(吨)"));
                entity.setOtherTons(gd(row, colMap, "其它车辆总吨位(吨)"));
                list.add(entity);
            }
        } catch (Exception e) {
@@ -764,21 +888,23 @@
    // ========== 轨迹里程 ==========
    /** 轨迹里程导入:与 H203-2 月报一致,按表头名称定位列,列顺序变化也能正确导入 */
    public int importTrackMileage(MultipartFile file, String period) throws Exception {
        List<VehicleTrackMileage> list = new ArrayList<>();
        int failRows = 0;
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            requireHeaderKeyword(sheet, "轨迹里程", "企业名称");
            requireHeaderCols(sheet, "轨迹里程", "企业名称", "月度总里程(公里)", "有里程的车辆数");
            Map<String, Integer> colMap = buildHeaderMap(sheet.getRow(0));
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String name = getString(row, 1);
                String name = gs(row, colMap, "企业名称");
                if (name == null || name.trim().isEmpty()) continue;
                VehicleTrackMileage entity = new VehicleTrackMileage();
                entity.setEnterpriseName(name);
                entity.setMonthlyMileage(getDecimal(row, 2));
                entity.setTrackedVehicles(getInt(row, 3));
                entity.setMonthlyMileage(gd(row, colMap, "月度总里程(公里)"));
                entity.setTrackedVehicles(gi(row, colMap, "有里程的车辆数"));
                entity.setReportPeriod(period);
                list.add(entity);
            }
@@ -813,10 +939,11 @@
        List<ScaleSplitTransport> list = new ArrayList<>();
        int failRows = 0;
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            int targetMonth = Integer.parseInt(period.split("-")[1]); // 仅导入目标期所在月的页签(1-N月文件按目标期取当月/累计)
            boolean hasPeriodSheet = false;
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                String sn = wb.getSheetAt(i).getSheetName();
                if (sn != null && (sn.contains("当月") || sn.contains("累计"))) { hasPeriodSheet = true; break; }
                if (sn != null && (sn.contains("当月") || sn.contains("月份") || sn.contains("累计"))) { hasPeriodSheet = true; break; }
            }
            if (!hasPeriodSheet) {
                throw new RuntimeException("所选数据类型【规上规下拆分】与文件内容不符:未找到含 当月/累计 的 sheet,请确认是否选错了数据类型");
@@ -825,9 +952,31 @@
                Sheet sheet = wb.getSheetAt(i);
                String sheetName = sheet.getSheetName();
                String periodType = null;
                if (sheetName.contains("当月")) periodType = "MONTH";
                else if (sheetName.contains("累计")) periodType = "CUMULATIVE";
                java.util.regex.Matcher mSheetMonth = java.util.regex.Pattern.compile("(\\d{1,2})\\u6708(\\u4efd|\\u7d2f\\u8ba1)").matcher(sheetName);
                if (mSheetMonth.find()) {
                    int sheetMonth = Integer.parseInt(mSheetMonth.group(1));
                    if (sheetMonth == targetMonth) {
                        periodType = "份".equals(mSheetMonth.group(2)) ? "MONTH" : "CUMULATIVE";
                    }
                } else {
                    if (sheetName.contains("当月")) periodType = "MONTH";
                    else if (sheetName.contains("累计")) periodType = "CUMULATIVE";
                }
                if (periodType == null) continue;
                // 校验 sheet 布局:第2行应含「市州/规上企业运输量」,第3行子表头应含「周转量」或「货运量」(扩展布局)
                Row headRow = sheet.getRow(1);
                Row subHeadRow = sheet.getRow(2);
                boolean layoutOk = headRow != null
                    && getString(headRow, 0) != null && getString(headRow, 0).contains("市州")
                    && getString(headRow, 1) != null && getString(headRow, 1).contains("规上")
                    && subHeadRow != null
                    && ("货运量".equals(getString(subHeadRow, 0))
                        || (getString(subHeadRow, 1) != null && getString(subHeadRow, 1).contains("周转量")));
                if (!layoutOk) {
                    throw new RuntimeException("所选数据类型【规上规下拆分】与文件内容不符:sheet「" + sheetName
                        + "」未找到「市州/规上企业运输量/周转量」表头,请确认是否选错了数据类型");
                }
                // 检测子表头:是否包含货运量列(扩展布局)
                Row subHeader = sheet.getRow(2);
@@ -911,6 +1060,12 @@
        int monthCount = Integer.parseInt(period.split("-")[1]);
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            Row header = sheet.getRow(0);
            String h0 = header == null ? null : getString(header, 0);
            String h1 = header == null ? null : getString(header, 1);
            if (header == null || h0 == null || !h0.contains("货运量") || h1 == null || !h1.contains("月")) {
                throw new RuntimeException("所选数据类型【货运量周转量】与文件内容不符:表头应为「货运量(万吨)/1月…12月」布局,请确认是否选错了数据类型");
            }
            boolean cityRowFound = false;
            for (int r = 1; r <= Math.min(sheet.getLastRowNum(), 30); r++) {
                Row rr = sheet.getRow(r);
@@ -1166,6 +1321,275 @@
        }
    }
    /** 支持“按类型清空”的数据类型 -> 数据表操作键(同表同类别归并,避免重复删除) */
    private static final Map<String, String> CLEAR_TYPE_TO_OP = new LinkedHashMap<>();
    /** 数据类型 -> 关联审核规则类型(同步清除审核结果与已审核标记) */
    private static final Map<String, String[]> CLEAR_TYPE_TO_AUDIT = new HashMap<>();
    /** 数据类型 -> 关联导入批次 importType(同步清除导入批次记录) */
    private static final Map<String, String[]> CLEAR_TYPE_TO_BATCH = new HashMap<>();
    static {
        CLEAR_TYPE_TO_OP.put("h2032", "H2032");
        CLEAR_TYPE_TO_OP.put("transportAuth", "TRANSPORT_AUTH");
        CLEAR_TYPE_TO_OP.put("trackMileage", "TRACK_MILEAGE");
        CLEAR_TYPE_TO_OP.put("scaleSplit", "SCALE_SPLIT");
        CLEAR_TYPE_TO_OP.put("freightTurnover", "FREIGHT_TURNOVER");
        CLEAR_TYPE_TO_OP.put("passengerMonthly", "H2031");
        CLEAR_TYPE_TO_OP.put("passengerAuth", "PASSENGER_AUTH");
        CLEAR_TYPE_TO_OP.put("passengerIndividual", "PASSENGER_INDIVIDUAL");
        CLEAR_TYPE_TO_OP.put("energyMonthly", "H204");
        CLEAR_TYPE_TO_OP.put("energyAuth", "ENERGY_AUTH");
        CLEAR_TYPE_TO_OP.put("investment", "INVEST_MONTHLY_PASSENGER");
        CLEAR_TYPE_TO_OP.put("investCityPassenger", "INVEST_MONTHLY_PASSENGER");
        CLEAR_TYPE_TO_OP.put("investmentLogistics", "INVEST_MONTHLY_LOGISTICS");
        CLEAR_TYPE_TO_OP.put("investCityLogistics", "INVEST_MONTHLY_LOGISTICS");
        CLEAR_TYPE_TO_OP.put("investmentSystem", "INVEST_SYSTEM");
        CLEAR_TYPE_TO_OP.put("cityBus", "CITY_BUS");
        CLEAR_TYPE_TO_OP.put("cityTaxi", "CITY_TAXI");
        CLEAR_TYPE_TO_OP.put("cityTaxiAuth", "CITY_TAXI_AUTH");
        CLEAR_TYPE_TO_OP.put("wycTotal", "WYC_TOTAL");
        CLEAR_TYPE_TO_OP.put("wycOrder", "WYC_ORDER");
        CLEAR_TYPE_TO_OP.put("wycOrderReport", "WYC_ORDER");
        CLEAR_TYPE_TO_AUDIT.put("h2032", new String[]{"H2032"});
        CLEAR_TYPE_TO_AUDIT.put("transportAuth", new String[]{"H2032"});
        CLEAR_TYPE_TO_AUDIT.put("trackMileage", new String[]{"H2032"});
        CLEAR_TYPE_TO_AUDIT.put("scaleSplit", new String[]{"H2032"});
        CLEAR_TYPE_TO_AUDIT.put("freightTurnover", new String[]{"H2032"});
        CLEAR_TYPE_TO_AUDIT.put("passengerMonthly", new String[]{"H2031"});
        CLEAR_TYPE_TO_AUDIT.put("passengerAuth", new String[]{"H2031"});
        CLEAR_TYPE_TO_AUDIT.put("passengerIndividual", new String[]{"H2031"});
        CLEAR_TYPE_TO_AUDIT.put("energyMonthly", new String[]{"H204"});
        CLEAR_TYPE_TO_AUDIT.put("energyAuth", new String[]{"H204"});
        CLEAR_TYPE_TO_AUDIT.put("investment", new String[]{"INVEST"});
        CLEAR_TYPE_TO_AUDIT.put("investmentLogistics", new String[]{"INVEST"});
        CLEAR_TYPE_TO_AUDIT.put("investCityPassenger", new String[]{"INVEST"});
        CLEAR_TYPE_TO_AUDIT.put("investCityLogistics", new String[]{"INVEST"});
        CLEAR_TYPE_TO_AUDIT.put("investmentSystem", new String[]{"INVEST"});
        CLEAR_TYPE_TO_AUDIT.put("cityBus", new String[]{"CITY_BUS"});
        CLEAR_TYPE_TO_AUDIT.put("cityTaxi", new String[]{"CITY_TAXI"});
        CLEAR_TYPE_TO_AUDIT.put("cityTaxiAuth", new String[]{"CITY_TAXI"});
        String[] investPassengerBatch = {"INVEST_客运站场", "INVEST_客运站场_CITY"};
        String[] investLogisticsBatch = {"INVEST_物流园区", "INVEST_物流园区_CITY"};
        CLEAR_TYPE_TO_BATCH.put("h2032", new String[]{"H2032"});
        CLEAR_TYPE_TO_BATCH.put("transportAuth", new String[]{"TRANSPORT_AUTH"});
        CLEAR_TYPE_TO_BATCH.put("trackMileage", new String[]{"TRACK_MILEAGE"});
        CLEAR_TYPE_TO_BATCH.put("scaleSplit", new String[]{"SCALE_SPLIT"});
        CLEAR_TYPE_TO_BATCH.put("freightTurnover", new String[]{"FREIGHT_TURNOVER"});
        CLEAR_TYPE_TO_BATCH.put("passengerMonthly", new String[]{"H2031"});
        CLEAR_TYPE_TO_BATCH.put("passengerAuth", new String[]{"PASSENGER_AUTH"});
        CLEAR_TYPE_TO_BATCH.put("passengerIndividual", new String[]{"PASSENGER_INDIVIDUAL"});
        CLEAR_TYPE_TO_BATCH.put("energyMonthly", new String[]{"H204"});
        CLEAR_TYPE_TO_BATCH.put("energyAuth", new String[]{"ENERGY_AUTH"});
        CLEAR_TYPE_TO_BATCH.put("investment", investPassengerBatch);
        CLEAR_TYPE_TO_BATCH.put("investCityPassenger", investPassengerBatch);
        CLEAR_TYPE_TO_BATCH.put("investmentLogistics", investLogisticsBatch);
        CLEAR_TYPE_TO_BATCH.put("investCityLogistics", investLogisticsBatch);
        CLEAR_TYPE_TO_BATCH.put("investmentSystem", new String[]{"INVEST_SYSTEM"});
        CLEAR_TYPE_TO_BATCH.put("cityBus", new String[]{"CITY_BUS"});
        CLEAR_TYPE_TO_BATCH.put("cityTaxi", new String[]{"CITY_TAXI"});
        CLEAR_TYPE_TO_BATCH.put("cityTaxiAuth", new String[]{"CITY_TAXI_AUTH"});
        CLEAR_TYPE_TO_BATCH.put("wycTotal", new String[]{"WYC_TOTAL"});
        CLEAR_TYPE_TO_BATCH.put("wycOrder", new String[]{"WYC_ORDER", "WYC_ORDER_REPORT"});
        CLEAR_TYPE_TO_BATCH.put("wycOrderReport", new String[]{"WYC_ORDER_REPORT", "WYC_ORDER"});
    }
    /**
     * 清空指定报表期已导入数据与审核结果,用于整月重导;投资项目主档保留。
     *
     * @param types 需清空的数据类型(前端类型键,如 h2032/cityBus);为空则清空该报表期全部类型
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> clearPeriod(String period, List<String> types) {
        if (period == null || !period.matches("\\d{4}-\\d{2}")) {
            throw new IllegalArgumentException("报表期格式不正确,应为 yyyy-MM");
        }
        Set<String> selected = new LinkedHashSet<>();
        if (types != null) {
            for (String t : types) {
                if (t != null && !t.trim().isEmpty()) selected.add(t.trim());
            }
        }
        boolean clearAll = selected.isEmpty();
        int dataRows = 0;
        int auditRows = 0;
        int auditRunRows = 0;
        int batchRows = 0;
        if (clearAll) {
        dataRows += h2032Mapper.delete(new LambdaQueryWrapper<H2032EnterpriseMonthly>()
            .eq(H2032EnterpriseMonthly::getReportPeriod, period));
        dataRows += transportAuthMapper.delete(new LambdaQueryWrapper<TransportAuthVehicle>()
            .eq(TransportAuthVehicle::getReportPeriod, period));
        dataRows += trackMileageMapper.delete(new LambdaQueryWrapper<VehicleTrackMileage>()
            .eq(VehicleTrackMileage::getReportPeriod, period));
        dataRows += scaleSplitMapper.delete(new LambdaQueryWrapper<ScaleSplitTransport>()
            .eq(ScaleSplitTransport::getReportPeriod, period));
        dataRows += freightTurnoverMapper.delete(new LambdaQueryWrapper<FreightTurnoverImport>()
            .eq(FreightTurnoverImport::getReportPeriod, period));
        dataRows += passengerMapper.delete(new LambdaQueryWrapper<PassengerEnterpriseMonthly>()
            .eq(PassengerEnterpriseMonthly::getReportPeriod, period));
        dataRows += passengerIndividualMapper.delete(new LambdaQueryWrapper<PassengerIndividualMonthly>()
            .eq(PassengerIndividualMonthly::getReportPeriod, period));
        dataRows += passengerAuthMapper.delete(new LambdaQueryWrapper<PassengerAuthVehicle>()
            .eq(PassengerAuthVehicle::getReportPeriod, period));
        dataRows += energyMapper.delete(new LambdaQueryWrapper<EnergyVehicleQuarterly>()
            .eq(EnergyVehicleQuarterly::getReportPeriod, period));
        dataRows += energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
            .eq(EnergyAuthVehicle::getReportPeriod, period));
        dataRows += investMonthlyMapper.delete(new LambdaQueryWrapper<InvestmentMonthly>()
            .eq(InvestmentMonthly::getReportPeriod, period));
        dataRows += investSystemMapper.delete(new LambdaQueryWrapper<InvestmentSystem>()
            .eq(InvestmentSystem::getReportPeriod, period));
        dataRows += cityBusMapper.delete(new LambdaQueryWrapper<CityBusMonthly>()
            .eq(CityBusMonthly::getReportPeriod, period));
        dataRows += cityTaxiMapper.delete(new LambdaQueryWrapper<CityTaxiMonthly>()
            .eq(CityTaxiMonthly::getReportPeriod, period));
        dataRows += cityTaxiAuthMapper.delete(new LambdaQueryWrapper<CityTaxiAuth>()
            .eq(CityTaxiAuth::getReportPeriod, period));
        dataRows += wycTotalMapper.delete(new LambdaQueryWrapper<WycTotalMonthly>()
            .eq(WycTotalMonthly::getReportPeriod, period));
        dataRows += wycOrderMapper.delete(new LambdaQueryWrapper<WycOrderMonthly>()
            .eq(WycOrderMonthly::getReportPeriod, period));
        auditRows = auditResultMapper.delete(new LambdaQueryWrapper<AuditResult>()
            .eq(AuditResult::getReportPeriod, period));
        auditRunRows = auditRunMapper.delete(new LambdaQueryWrapper<AuditRun>()
            .eq(AuditRun::getReportPeriod, period));
        batchRows = importBatchMapper.delete(new LambdaQueryWrapper<ImportBatch>()
            .eq(ImportBatch::getReportPeriod, period));
        } else {
            Set<String> ops = new LinkedHashSet<>();
            Set<String> auditTypes = new LinkedHashSet<>();
            Set<String> batchTypes = new LinkedHashSet<>();
            for (String t : selected) {
                String op = CLEAR_TYPE_TO_OP.get(t);
                if (op == null) {
                    log.warn("清空数据:未知数据类型 {},已忽略", t);
                    continue;
                }
                ops.add(op);
                String[] at = CLEAR_TYPE_TO_AUDIT.get(t);
                if (at != null) java.util.Collections.addAll(auditTypes, at);
                String[] bt = CLEAR_TYPE_TO_BATCH.get(t);
                if (bt != null) java.util.Collections.addAll(batchTypes, bt);
            }
            if (ops.isEmpty()) {
                throw new IllegalArgumentException("未指定有效的数据类型");
            }
            for (String op : ops) {
                dataRows += clearTypeData(op, period);
            }
            if (!auditTypes.isEmpty()) {
                List<Long> ruleIds = new ArrayList<>();
                for (com.trafficaudit.rulemanage.entity.AuditRule rule : ruleMapper.selectList(null)) {
                    if (rule.getReportType() != null && auditTypes.contains(rule.getReportType())) {
                        ruleIds.add(rule.getId());
                    }
                }
                if (!ruleIds.isEmpty()) {
                    auditRows = auditResultMapper.delete(new LambdaQueryWrapper<AuditResult>()
                        .eq(AuditResult::getReportPeriod, period)
                        .in(AuditResult::getRuleId, ruleIds));
                }
                for (String rt : auditTypes) {
                    auditRunRows += auditRunMapper.delete(new LambdaQueryWrapper<AuditRun>()
                        .eq(AuditRun::getReportPeriod, period)
                        .eq(AuditRun::getReportType, rt));
                }
            }
            if (!batchTypes.isEmpty()) {
                batchRows = importBatchMapper.delete(new LambdaQueryWrapper<ImportBatch>()
                    .eq(ImportBatch::getReportPeriod, period)
                    .in(ImportBatch::getImportType, batchTypes));
            }
        }
        Map<String, Object> stats = new LinkedHashMap<>();
        stats.put("period", period);
        stats.put("scope", clearAll ? "all" : "types");
        if (!clearAll) stats.put("types", new ArrayList<>(selected));
        stats.put("dataRows", dataRows);
        stats.put("auditRows", auditRows);
        stats.put("auditRunRows", auditRunRows);
        stats.put("batchRows", batchRows);
        log.info("清空报表期 {}({})完成:业务数据 {} 行、审核结果 {} 行、审核标记 {} 行、导入批次 {} 行",
            period, clearAll ? "全部类型" : String.join(",", selected), dataRows, auditRows, auditRunRows, batchRows);
        return stats;
    }
    /** 按“数据表操作键”清空对应业务表(投资月度按项目类别过滤),返回删除行数 */
    private int clearTypeData(String op, String period) {
        switch (op) {
            case "H2032":
                return h2032Mapper.delete(new LambdaQueryWrapper<H2032EnterpriseMonthly>()
                    .eq(H2032EnterpriseMonthly::getReportPeriod, period));
            case "TRANSPORT_AUTH":
                return transportAuthMapper.delete(new LambdaQueryWrapper<TransportAuthVehicle>()
                    .eq(TransportAuthVehicle::getReportPeriod, period));
            case "TRACK_MILEAGE":
                return trackMileageMapper.delete(new LambdaQueryWrapper<VehicleTrackMileage>()
                    .eq(VehicleTrackMileage::getReportPeriod, period));
            case "SCALE_SPLIT":
                return scaleSplitMapper.delete(new LambdaQueryWrapper<ScaleSplitTransport>()
                    .eq(ScaleSplitTransport::getReportPeriod, period));
            case "FREIGHT_TURNOVER":
                return freightTurnoverMapper.delete(new LambdaQueryWrapper<FreightTurnoverImport>()
                    .eq(FreightTurnoverImport::getReportPeriod, period));
            case "H2031":
                return passengerMapper.delete(new LambdaQueryWrapper<PassengerEnterpriseMonthly>()
                    .eq(PassengerEnterpriseMonthly::getReportPeriod, period));
            case "PASSENGER_AUTH":
                return passengerAuthMapper.delete(new LambdaQueryWrapper<PassengerAuthVehicle>()
                    .eq(PassengerAuthVehicle::getReportPeriod, period));
            case "PASSENGER_INDIVIDUAL":
                return passengerIndividualMapper.delete(new LambdaQueryWrapper<PassengerIndividualMonthly>()
                    .eq(PassengerIndividualMonthly::getReportPeriod, period));
            case "H204":
                return energyMapper.delete(new LambdaQueryWrapper<EnergyVehicleQuarterly>()
                    .eq(EnergyVehicleQuarterly::getReportPeriod, period));
            case "ENERGY_AUTH":
                return energyAuthMapper.delete(new LambdaQueryWrapper<EnergyAuthVehicle>()
                    .eq(EnergyAuthVehicle::getReportPeriod, period));
            case "INVEST_MONTHLY_PASSENGER":
                return deleteInvestmentMonthly(period, "客运站场");
            case "INVEST_MONTHLY_LOGISTICS":
                return deleteInvestmentMonthly(period, "物流园区");
            case "INVEST_SYSTEM":
                return investSystemMapper.delete(new LambdaQueryWrapper<InvestmentSystem>()
                    .eq(InvestmentSystem::getReportPeriod, period));
            case "CITY_BUS":
                return cityBusMapper.delete(new LambdaQueryWrapper<CityBusMonthly>()
                    .eq(CityBusMonthly::getReportPeriod, period));
            case "CITY_TAXI":
                return cityTaxiMapper.delete(new LambdaQueryWrapper<CityTaxiMonthly>()
                    .eq(CityTaxiMonthly::getReportPeriod, period));
            case "CITY_TAXI_AUTH":
                return cityTaxiAuthMapper.delete(new LambdaQueryWrapper<CityTaxiAuth>()
                    .eq(CityTaxiAuth::getReportPeriod, period));
            case "WYC_TOTAL":
                return wycTotalMapper.delete(new LambdaQueryWrapper<WycTotalMonthly>()
                    .eq(WycTotalMonthly::getReportPeriod, period));
            case "WYC_ORDER":
                return wycOrderMapper.delete(new LambdaQueryWrapper<WycOrderMonthly>()
                    .eq(WycOrderMonthly::getReportPeriod, period));
            default:
                log.warn("清空数据:未知数据表操作 {}", op);
                return 0;
        }
    }
    /** 投资月度按项目类别清除(投资项目主档保留) */
    private int deleteInvestmentMonthly(String period, String category) {
        List<Long> projectIds = new ArrayList<>();
        for (InvestmentProject p : investProjectMapper.selectList(new LambdaQueryWrapper<InvestmentProject>()
                .eq(InvestmentProject::getCategory, category))) {
            projectIds.add(p.getId());
        }
        if (projectIds.isEmpty()) return 0;
        return investMonthlyMapper.delete(new LambdaQueryWrapper<InvestmentMonthly>()
            .eq(InvestmentMonthly::getReportPeriod, period)
            .in(InvestmentMonthly::getProjectId, projectIds));
    }
    /** 数据变化后删除指定报表类型指定报表期的审核结果(需重新执行审核) */
    private void deleteRuleResults(String reportType, String period) {
        List<Long> ruleIds = new ArrayList<>();
@@ -1206,6 +1630,43 @@
        throw new RuntimeException("所选数据类型【" + typeLabel + "】与文件内容不符:表头未包含【" + String.join("】【", keywords) + "】等列,请确认是否选错了数据类型");
    }
    /** 能耗明细表头列位校验:系统模板为“前3列 + 5组×18列”,程序按固定列位解析,表头错位会导致整表错乱,错位时直接拒绝 */
    private void requireEnergyHeaderLayout(Sheet sheet) {
        Row header = sheet == null ? null : sheet.getRow(0);
        if (header == null) {
            throw new RuntimeException("能耗明细表头缺失,请使用系统模板《模板_道路货运车辆能源消耗情况(2026).xlsx》整理后再导入");
        }
        for (int i = 0; i < ENERGY_HEADER_COLS.length; i++) {
            int col = ENERGY_HEADER_COLS[i];
            String keyword = ENERGY_HEADER_KEYWORDS[i];
            Cell cell = header.getCell(col);
            String hv = cell == null ? null : FORMATTER.formatCellValue(cell).trim();
            if (hv == null || hv.isEmpty() || !hv.contains(keyword)) {
                throw new RuntimeException("表头与系统模板不一致:第 " + (col + 1) + " 列应为「" + keyword + "」,实际为「"
                    + (hv == null || hv.isEmpty() ? "空" : hv) + "」。请使用系统模板《模板_道路货运车辆能源消耗情况(2026).xlsx》整理后再导入");
            }
        }
    }
    /** 通用表头列位校验:程序按固定列位解析,表头错位会导致整表错乱,错位时直接拒绝导入 */
    private void requireHeaderLayout(Sheet sheet, String typeLabel, String templateHint,
                                     int[] cols, String[] keywords) {
        Row header = sheet == null ? null : sheet.getRow(0);
        if (header == null) {
            throw new RuntimeException("所选数据类型【" + typeLabel + "】文件表头缺失,请使用系统模板《" + templateHint + "》整理后再导入");
        }
        for (int i = 0; i < cols.length; i++) {
            int col = cols[i];
            String keyword = keywords[i];
            Cell cell = header.getCell(col);
            String hv = cell == null ? null : FORMATTER.formatCellValue(cell).trim();
            if (hv == null || hv.isEmpty() || !hv.contains(keyword)) {
                throw new RuntimeException("表头与系统模板不一致:第 " + (col + 1) + " 列应为「" + keyword + "」,实际为「"
                    + (hv == null || hv.isEmpty() ? "空" : hv) + "」。所选数据类型【" + typeLabel + "】请使用系统模板《" + templateHint + "》整理后再导入");
            }
        }
    }
    /** 按表头名称建立列号映射,兼容新旧模板列位差异 */
    private Map<String, Integer> buildHeaderMap(Row header) {
        Map<String, Integer> colMap = new HashMap<>();
@@ -1217,6 +1678,33 @@
            }
        }
        return colMap;
    }
    /** 兼容表头映射:去引号/去空白;纯英文表头统一大写(如 'OWNERNAME' → OWNERNAME),便于新旧模板混用 */
    private Map<String, Integer> buildHeaderMapCompat(Row header) {
        Map<String, Integer> colMap = new HashMap<>();
        if (header == null) return colMap;
        for (Cell cell : header) {
            if (cell == null) continue;
            String h = FORMATTER.formatCellValue(cell).replace("'", "").replace("\"", "").trim();
            if (h.isEmpty()) continue;
            boolean ascii = true;
            for (int i = 0; i < h.length(); i++) {
                if (h.charAt(i) > 127) { ascii = false; break; }
            }
            if (ascii) h = h.toUpperCase();
            if (!colMap.containsKey(h)) colMap.put(h, cell.getColumnIndex());
        }
        return colMap;
    }
    /** 按别名顺序取第一个存在的列号,全部缺失返回 null */
    private Integer firstColIdx(Map<String, Integer> colMap, String... aliases) {
        for (String a : aliases) {
            Integer idx = colMap.get(a);
            if (idx != null) return idx;
        }
        return null;
    }
    private int colIdx(Map<String, Integer> colMap, String header) {
@@ -1778,8 +2266,10 @@
        if (name == null || name.isEmpty()) return false;
        String norm = name.replace(" ", "");
        int month = Integer.parseInt(period.substring(5, 7));
        String normDash = norm.replace('.', '-'); // "2026.8"/"2026.08" -> "2026-8"/"2026-08"
        return norm.contains(month + "月") || norm.contains(String.format("%02d", month) + "月")
            || name.contains(period) || name.contains(period.replace("-0", "-"));
            || name.contains(period) || name.contains(period.replace("-0", "-"))
            || normDash.contains(period) || normDash.contains(period.replace("-0", "-"));
    }
    /** 解析单个市州报表:选 sheet(报表期名优先 + 数据行数),按列名映射提取项目行 */
@@ -1794,6 +2284,11 @@
            if (col == null) continue;
            int cnt = countInvestRows(sh, col);
            int score = cnt + (cnt > 0 && investSheetMatchesPeriod(sh, period) ? 1000000 : 0);
            if (cnt > 0 && investSheetMatchesPeriod(sh, period)) {
                // 当期真实报表 sheet 名通常带年份(如 2026.8/2026年8月),历史sheet多为纯月份名(8月):带年份的优先
                String norm = sh.getSheetName() == null ? "" : sh.getSheetName().replace(" ", "");
                if (norm.contains(period.substring(0, 4))) score += 100000;
            }
            if (score > bestScore) {
                best = sh;
                bestCol = col;
@@ -1838,10 +2333,12 @@
                if (seq == null || seq.trim().isEmpty()) {
                    // 市州小节行(如 "武汉" "天 门"),更新当前市州
                    String c = investmentCity(nt);
                    if (c != null) currentCity = c;
                    if (c != null) { currentCity = c; continue; }
                    // 序号为空的真实项目行(部分市州月报不填序号,如神农架物流园)也按项目处理
                    if (!isLikelyInvestProjectName(nt)) continue;
                } else if (!seq.trim().matches("\\d+(\\.\\d+)?")) {
                    continue;
                }
                if (!seq.trim().matches("\\d+(\\.\\d+)?")) continue;
            } else {
                // 无序号列(随州等):项目名非空即项目行,市州小节行用 investmentCity 识别
                String c = investmentCity(nt);
@@ -1966,7 +2463,11 @@
                if (nt.length() > 4) count++;
            } else {
                String seq = cellStr(row, seqCol);
                if (seq != null && seq.trim().matches("\\d+(\\.\\d+)?")) count++;
                if (seq != null && seq.trim().matches("\\d+(\\.\\d+)?")) {
                    count++;
                } else if ((seq == null || seq.trim().isEmpty()) && isLikelyInvestProjectName(nt)) {
                    count++;
                }
            }
        }
        return count;
@@ -2036,6 +2537,15 @@
            log.error("load five year project names error", e);
        }
        return names;
    }
    /** 序号为空的非市州行是否像项目行:长度>4 且非备注/说明等杂项 */
    private boolean isLikelyInvestProjectName(String nt) {
        if (nt == null || nt.length() <= 4) return false;
        if (investmentCity(nt) != null) return false;
        return !nt.startsWith("备注") && !nt.startsWith("说明") && !nt.startsWith("注:")
            && !nt.startsWith("填表") && !nt.startsWith("审核") && !nt.startsWith("统计")
            && !nt.startsWith("负责");
    }
    /** 项目名规范化:去空白/换行/括号内容/标点/「项目」后缀,用于十五五清单匹配 */
@@ -2214,12 +2724,18 @@
        }
    }
    /** 投资系统导出导入(审核比对基准),固定8列:行号/单位/时期/计划总投资/自开始累计/本年计划/自年初累计/当月完成 */
    private static final int[] INVEST_SYSTEM_HEADER_COLS = {0, 1, 2, 3, 4, 5, 6, 7};
    private static final String[] INVEST_SYSTEM_HEADER_KEYWORDS =
        {"行号", "单位", "时期", "计划总投资", "自开始建设", "本年计划投资", "自年初", "当月完成投资"};
    public int importInvestmentSystem(MultipartFile file, String period) throws Exception {
        List<InvestmentSystem> list = new ArrayList<>();
        int failRows = 0;
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            requireHeaderKeyword(sheet, "投资系统导出", "项目名称");
            requireHeaderKeyword(sheet, "投资系统导出", "项目名称", "计划总投资", "单位");
            requireHeaderLayout(sheet, "投资系统导出", "模板_查询结果(投资系统-客运+物流 2026.7).xls",
                INVEST_SYSTEM_HEADER_COLS, INVEST_SYSTEM_HEADER_KEYWORDS);
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
@@ -2257,15 +2773,18 @@
    }
    /** 城市公交月报导入(城市公共交通月度运营情况,企业级明细,取公共汽电车字段) */
    /** 城市公交(U203)模板关键列位(0-based):所属地区/企业代码/企业名称/运营车数/客运量/轨道客运量/轮渡客运量/平均运距/填表人/联系电话/报出日期 */
    private static final int[] CITY_BUS_HEADER_COLS = {0, 1, 2, 5, 8, 13, 17, 19, 24, 25, 26};
    private static final String[] CITY_BUS_HEADER_KEYWORDS =
        {"所属地区", "企业代码", "企业名称", "公共汽电车_运营车数", "公共汽电车_客运量", "轨道交通_客运量",
         "城市客运轮渡_客运量", "公共汽电车平均运距", "填表人", "联系电话", "报出日期"};
    public ImportResult importCityBus(MultipartFile file, String period) throws Exception {
        List<CityBusRow> rows = new ArrayList<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            Row header = sheet.getRow(0);
            if (header == null || getString(header, 2) == null
                    || !getString(header, 2).contains("企业名称")) {
                throw new RuntimeException("未找到表头行(需包含 企业名称 列)");
            }
            requireHeaderLayout(sheet, "城市公交", "模板_交企统U203表_城市公共交通月度运营情况(2026年7月).xls",
                CITY_BUS_HEADER_COLS, CITY_BUS_HEADER_KEYWORDS);
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
@@ -2369,15 +2888,18 @@
    }
    /** 巡游出租月报导入(市州级,17 行;含核实说明/上报说明/修改记录) */
    /** 巡游出租(U402)模板关键列位(0-based):所属地区/企业代码/企业名称/载客车次总数/客运量/旅客周转量/运营车辆数/平均运距/填表人/联系电话/报出日期 */
    private static final int[] CITY_TAXI_HEADER_COLS = {0, 1, 2, 4, 6, 8, 10, 11, 15, 16, 17};
    private static final String[] CITY_TAXI_HEADER_KEYWORDS =
        {"所属地区", "企业代码", "企业名称", "载客车次总数", "客运量", "旅客周转量", "运营车辆数",
         "巡游出租汽车平均运距", "填表人", "联系电话", "报出日期"};
    public ImportResult importCityTaxi(MultipartFile file, String period) throws Exception {
        List<TaxiRow> rows = new ArrayList<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            Row header = sheet.getRow(0);
            if (header == null || getString(header, 2) == null
                    || !getString(header, 2).contains("企业名称")) {
                throw new RuntimeException("未找到表头行(需包含 企业名称 列)");
            }
            requireHeaderLayout(sheet, "巡游出租", "模板_交行统U402表-巡游出租汽车运营服务情况月报(2026).xls",
                CITY_TAXI_HEADER_COLS, CITY_TAXI_HEADER_KEYWORDS);
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
@@ -2508,6 +3030,358 @@
        recordBatch(file.getOriginalFilename(), "CITY_TAXI_AUTH", period, list.size(), success, fail, null);
        log.info("CityTaxiAuth imported: {} rows for {}", success, period);
        return success;
    }
    // ========== 网约车月度输入导入(全省 pin / 订单) ==========
    /** 网约车总数月度输入:模板_网约车总数.xlsx(sheet1;A 列=月份日期;B=全省客运量 C=其中城市内 D=周转量 E=其中城市内周转量)。整表按报表期覆盖。 */
    public synchronized int importWycTotal(MultipartFile file, String period) throws Exception {
        Map<String, WycTotalMonthly> rows = new LinkedHashMap<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            for (int r = 2; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String rp = periodOfCell(row.getCell(0));
                if (rp == null) continue;
                double pk = dbl(row, 1), pck = dbl(row, 2), pz = dbl(row, 3), pcz = dbl(row, 4);
                if (pk <= 0 && pck <= 0 && pz <= 0 && pcz <= 0) continue;
                WycTotalMonthly item = new WycTotalMonthly();
                item.setReportPeriod(rp);
                item.setPinK(pk > 0 ? pk : null);
                item.setPinCK(pck > 0 ? pck : null);
                item.setPinZ(pz > 0 ? pz : null);
                item.setPinCZ(pcz > 0 ? pcz : null);
                rows.put(rp, item);
            }
        }
        if (rows.isEmpty()) throw new RuntimeException("未识别到有效月份行:A 列应为日期(如 2026-07),B-E 为全省客运量/城市内/周转量/城市内周转量");
        int ok = upsertWycTotal(rows);
        log.info("WycTotal imported: {} periods ok={}", rows.size(), ok);
        return ok;
    }
    /** 网约车订单及全省总量:模板_网约车订单及全省总量.xlsx 首个数据 sheet(A=月份;B-E=全省 pin;F=订单合计;G-W=17 市州订单) */
    public synchronized int importWycOrder(MultipartFile file, String period) throws Exception {
        Map<String, WycOrderMonthly> rows = new LinkedHashMap<>();
        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            int head = -1;
            for (int r = 0; r <= Math.min(sheet.getLastRowNum(), 4); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String a = getString(row, 0);
                if (a != null && a.contains("月份")) { head = r; break; }
            }
            if (head < 0) throw new RuntimeException("未找到表头:A 列需含“月份”");
            for (int r = head + 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                String rp = periodOfCell(row.getCell(0));
                if (rp == null) continue;
                double pk = dbl(row, 1), pck = dbl(row, 2), pz = dbl(row, 3), pcz = dbl(row, 4), sum = dbl(row, 5);
                double citySum = 0;
                for (int k = 0; k < 17; k++) citySum += dbl(row, 6 + k);
                if (pk <= 0 && pck <= 0 && pz <= 0 && pcz <= 0 && sum <= 0 && citySum <= 0) continue;
                WycOrderMonthly it = new WycOrderMonthly();
                it.setReportPeriod(rp);
                it.setPinK(pk > 0 ? pk : null);
                it.setPinCK(pck > 0 ? pck : null);
                it.setPinZ(pz > 0 ? pz : null);
                it.setPinCZ(pcz > 0 ? pcz : null);
                if (sum <= 0 && citySum > 0) sum = citySum;
                it.setOrderSum(sum > 0 ? sum : null);
                it.setOrderWuhan(dblN(row, 6));
                it.setOrderHuangshi(dblN(row, 7));
                it.setOrderShiyan(dblN(row, 8));
                it.setOrderYichang(dblN(row, 9));
                it.setOrderXiangyang(dblN(row, 10));
                it.setOrderEzhou(dblN(row, 11));
                it.setOrderJingmen(dblN(row, 12));
                it.setOrderXiaogan(dblN(row, 13));
                it.setOrderJingzhou(dblN(row, 14));
                it.setOrderHuanggang(dblN(row, 15));
                it.setOrderXianning(dblN(row, 16));
                it.setOrderSuizhou(dblN(row, 17));
                it.setOrderEnshi(dblN(row, 18));
                it.setOrderXiantao(dblN(row, 19));
                it.setOrderQianjiang(dblN(row, 20));
                it.setOrderTianmen(dblN(row, 21));
                it.setOrderShennong(dblN(row, 22));
                rows.put(rp, it);
            }
        }
        if (rows.isEmpty()) throw new RuntimeException("未识别到有效月份行:A 列应为 yyyy-MM,B-E 全省 pin / F 合计 / G-W 17 市州订单");
        int ok = upsertWyc(rows);
        log.info("WycOrder imported: {} periods ok={}", rows.size(), ok);
        return ok;
    }
    private int upsertWyc(Map<String, WycOrderMonthly> rows) {
        int ok = 0, fail = 0;
        for (WycOrderMonthly item : rows.values()) {
            try {
                wycOrderMapper.delete(new LambdaQueryWrapper<WycOrderMonthly>().eq(WycOrderMonthly::getReportPeriod, item.getReportPeriod()));
                wycOrderMapper.insert(item);
                recordBatch("网约车订单及全省总量", "WYC_ORDER", item.getReportPeriod(), 1, 1, 0, null);
                ok++;
            } catch (Exception e) {
                fail++;
                log.error("WycOrder insert error period={}", item.getReportPeriod(), e);
            }
        }
        return ok;
    }
    private int upsertWycTotal(Map<String, WycTotalMonthly> rows) {
        int ok = 0, fail = 0;
        for (WycTotalMonthly item : rows.values()) {
            try {
                wycTotalMapper.delete(new LambdaQueryWrapper<WycTotalMonthly>().eq(WycTotalMonthly::getReportPeriod, item.getReportPeriod()));
                wycTotalMapper.insert(item);
                recordBatch("网约车总数", "WYC_TOTAL", item.getReportPeriod(), 1, 1, 0, null);
                ok++;
            } catch (Exception e) {
                fail++;
                log.error("WycTotal insert error period={}", item.getReportPeriod(), e);
            }
        }
        return ok;
    }
    // ========== 网约车订单运行监测分析报告(docx)导入 ==========
    /** 网约车订单报告导入结果(报表期/订单合计/覆盖市州数/缺失市州) */
    public static class WycOrderReportResult {
        private final String period;
        private final double orderSum;
        private final int cityCount;
        private final List<String> missingCities;
        public WycOrderReportResult(String period, double orderSum, int cityCount, List<String> missingCities) {
            this.period = period;
            this.orderSum = orderSum;
            this.cityCount = cityCount;
            this.missingCities = missingCities;
        }
        public String getPeriod() { return period; }
        public double getOrderSum() { return orderSum; }
        public int getCityCount() { return cityCount; }
        public List<String> getMissingCities() { return missingCities; }
    }
    /**
     * 《网约车行业YYYY年M月运行监测情况分析报告》(docx)导入:
     * 解析报告附件中「地市名称 | … | 订单数总数」表的 17 市州订单数,写入 wyc_order_monthly 的
     * F 订单合计与 G-W 17 市州订单列;全省 pin(B-E)沿用该期已有行,若无该期行则从
     * wyc_total_monthly 同报表期复制。报表期优先取报告标题年月,取不到时用页面所选报表期。
     */
    public synchronized WycOrderReportResult importWycOrderReport(MultipartFile file, String period) throws Exception {
        Map<String, Double> orders = new LinkedHashMap<>();
        double[] sumHolder = new double[]{0.0};
        String docPeriod;
        try (java.io.InputStream in = file.getInputStream();
             XWPFDocument doc = new XWPFDocument(in)) {
            docPeriod = periodOfDocx(doc);
            parseWycOrderReportTables(doc, orders, sumHolder);
        } catch (Exception e) {
            throw new RuntimeException("无法读取 Word 文档,请上传 .docx 格式的《网约车行业YYYY年M月运行监测情况分析报告》;"
                    + "若上传的其实是 Excel/PDF,请改用对应模板导入。(原始错误:" + e.getMessage() + ")");
        }
        if (orders.isEmpty()) {
            throw new RuntimeException("未解析到任何市州订单数,请确认上传的是《网约车行业YYYY年M月运行监测情况分析报告》");
        }
        String rp = null;
        if (docPeriod != null && docPeriod.matches("\\d{4}-\\d{2}")) rp = docPeriod;
        else if (period != null && period.matches("\\d{4}-\\d{2}")) rp = period;
        if (rp == null) {
            throw new RuntimeException("无法确定报表期:报告标题未含「YYYY年M月」,且页面未选择报表期");
        }
        List<String> missing = new ArrayList<>();
        double citySum = 0.0;
        for (String city : RegionUtil.cityList()) {
            Double v = orders.get(city);
            if (v == null) missing.add(city);
            else citySum += v;
        }
        double sum = sumHolder[0] > 0 ? sumHolder[0] : citySum;
        WycOrderMonthly it = wycOrderMapper.selectOne(new LambdaQueryWrapper<WycOrderMonthly>()
                .eq(WycOrderMonthly::getReportPeriod, rp).last("LIMIT 1"));
        if (it == null) it = new WycOrderMonthly();
        it.setReportPeriod(rp);
        it.setOrderSum(sum > 0 ? sum : null);
        it.setOrderWuhan(orderOf(orders, "武汉市"));
        it.setOrderHuangshi(orderOf(orders, "黄石市"));
        it.setOrderShiyan(orderOf(orders, "十堰市"));
        it.setOrderYichang(orderOf(orders, "宜昌市"));
        it.setOrderXiangyang(orderOf(orders, "襄阳市"));
        it.setOrderEzhou(orderOf(orders, "鄂州市"));
        it.setOrderJingmen(orderOf(orders, "荆门市"));
        it.setOrderXiaogan(orderOf(orders, "孝感市"));
        it.setOrderJingzhou(orderOf(orders, "荆州市"));
        it.setOrderHuanggang(orderOf(orders, "黄冈市"));
        it.setOrderXianning(orderOf(orders, "咸宁市"));
        it.setOrderSuizhou(orderOf(orders, "随州市"));
        it.setOrderEnshi(orderOf(orders, "恩施州"));
        it.setOrderXiantao(orderOf(orders, "仙桃市"));
        it.setOrderQianjiang(orderOf(orders, "潜江市"));
        it.setOrderTianmen(orderOf(orders, "天门市"));
        it.setOrderShennong(orderOf(orders, "神农架林区"));
        if (it.getPinK() == null || it.getPinCK() == null || it.getPinZ() == null || it.getPinCZ() == null) {
            WycTotalMonthly tot = wycTotalMapper.selectOne(new LambdaQueryWrapper<WycTotalMonthly>()
                    .eq(WycTotalMonthly::getReportPeriod, rp).last("LIMIT 1"));
            if (tot != null) {
                if (it.getPinK() == null) it.setPinK(tot.getPinK());
                if (it.getPinCK() == null) it.setPinCK(tot.getPinCK());
                if (it.getPinZ() == null) it.setPinZ(tot.getPinZ());
                if (it.getPinCZ() == null) it.setPinCZ(tot.getPinCZ());
            }
        }
        wycOrderMapper.delete(new LambdaQueryWrapper<WycOrderMonthly>().eq(WycOrderMonthly::getReportPeriod, rp));
        wycOrderMapper.insert(it);
        recordBatch(file.getOriginalFilename(), "WYC_ORDER_REPORT", rp, 1, 1, 0, null);
        log.info("WycOrderReport imported: period={} sum={} cities={} missing={}", rp, sum, orders.size(), missing);
        return new WycOrderReportResult(rp, sum, orders.size(), missing);
    }
    /** 报告标题中的报表期:网约车行业2026年7月 -> 2026-07;取不到返回 null */
    private String periodOfDocx(XWPFDocument doc) {
        java.util.regex.Pattern titlePat = java.util.regex.Pattern.compile("网约车行业\\s*(\\d{4})\\s*年\\s*(\\d{1,2})\\s*月");
        java.util.regex.Pattern anyPat = java.util.regex.Pattern.compile("(\\d{4})\\s*年\\s*(\\d{1,2})\\s*月");
        String fallback = null;
        int scanned = 0;
        for (XWPFParagraph para : doc.getParagraphs()) {
            String text = para.getText();
            if (text == null) continue;
            String flat = text.replaceAll("\\s+", "");
            if (flat.isEmpty()) continue;
            java.util.regex.Matcher m = titlePat.matcher(flat);
            if (m.find()) return ymd(m.group(1), m.group(2));
            if (fallback == null && scanned < 10) {
                java.util.regex.Matcher m2 = anyPat.matcher(flat);
                if (m2.find()) fallback = ymd(m2.group(1), m2.group(2));
            }
            scanned++;
        }
        return fallback;
    }
    private String ymd(String y, String mo) {
        try {
            int month = Integer.parseInt(mo);
            if (month < 1 || month > 12) return null;
            return String.format("%04d-%02d", Integer.parseInt(y), month);
        } catch (NumberFormatException e) {
            return null;
        }
    }
    /** 解析报告中的「地市名称 | … | 订单数总数」表,orders=市州订单,sumHolder[0]=合计行订单数 */
    private void parseWycOrderReportTables(XWPFDocument doc, Map<String, Double> orders, double[] sumHolder) {
        for (XWPFTable table : doc.getTables()) {
            List<XWPFTableRow> rows = table.getRows();
            if (rows.size() < 3) continue;
            int headerRow = -1;
            int orderCol = -1;
            for (int r = 0; r < Math.min(rows.size(), 3); r++) {
                List<org.apache.poi.xwpf.usermodel.XWPFTableCell> cells = rows.get(r).getTableCells();
                for (int c = 0; c < cells.size(); c++) {
                    String norm = flat(cells.get(c).getText());
                    if (norm.contains("订单数总数") || "订单数".equals(norm)) {
                        headerRow = r;
                        orderCol = c;
                        break;
                    }
                }
                if (headerRow >= 0) break;
            }
            if (headerRow < 0 || orderCol < 0) continue;
            Map<String, Double> found = new LinkedHashMap<>();
            double citySum = 0.0;
            boolean hasTotal = false;
            for (int r = headerRow + 1; r < rows.size(); r++) {
                List<org.apache.poi.xwpf.usermodel.XWPFTableCell> cells = rows.get(r).getTableCells();
                if (orderCol >= cells.size()) continue;
                String name = flat(cells.get(0).getText());
                if (name.isEmpty()) continue;
                Double val = parsePlainNumber(cells.get(orderCol).getText());
                if (val == null) continue;
                String city = RegionUtil.normalizeCityName(name);
                if (city != null && RegionUtil.cityList().contains(city)) {
                    found.put(city, val);
                    citySum += val;
                } else if (name.contains("合计") || name.contains("总计") || name.contains("全省") || name.contains("湖北")) {
                    hasTotal = true;
                    sumHolder[0] = val;
                }
            }
            if (!found.isEmpty()) {
                orders.clear();
                orders.putAll(found);
                if (!hasTotal) sumHolder[0] = citySum;
                return;
            }
        }
    }
    private String flat(String s) {
        return s == null ? "" : s.replaceAll("\\s+", "").trim();
    }
    /** 「11,183,267 单」这类文本取数值 */
    private Double parsePlainNumber(String s) {
        if (s == null) return null;
        String t = s.replaceAll("[,\\s]", "").trim();
        if (t.isEmpty()) return null;
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("-?\\d+(?:\\.\\d+)?").matcher(t);
        if (!m.find()) return null;
        try {
            return Double.parseDouble(m.group());
        } catch (NumberFormatException e) {
            return null;
        }
    }
    private Double orderOf(Map<String, Double> orders, String city) {
        Double v = orders.get(city);
        return (v == null || v <= 0) ? null : v;
    }
    private String periodOfCell(Cell c) {
        if (c == null) return null;
        if (c.getCellType() == CellType.NUMERIC) {
            try {
                double v = c.getNumericCellValue();
                if (v >= 40000 && v <= 60000) {
                    java.util.Date d = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                    java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM");
                    return f.format(d);
                }
            } catch (Exception ignore) { }
        }
        String s = null;
        try { s = c.getStringCellValue(); } catch (Exception ignore) { }
        if (s != null) {
            java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d{4})[-/.年](\\d{1,2})").matcher(s.trim());
            if (m.find()) return String.format("%04d-%02d", Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)));
        }
        return null;
    }
    private double dbl(Row row, int idx) {
        Double v = getDecimal(row, idx);
        return v == null ? 0.0 : v;
    }
    private Double dblN(Row row, int idx) {
        Double v = getDecimal(row, idx);
        return (v == null || v <= 0) ? null : v;
    }
    /** 运政出租车市州提取:道路运输证字号→档案号→经营权号→业户地址,取 6 位区划代码 */
@@ -2846,6 +3720,9 @@
            case "trackMileage": return new ImportResult(importTrackMileage(file, period), 0, new ArrayList<>());
            case "freightTurnover": return new ImportResult(importFreightTurnover(file, period), 0, new ArrayList<>());
            case "scaleSplit": return new ImportResult(importScaleSplit(file, period), 0, new ArrayList<>());
            case "wycTotal": return new ImportResult(importWycTotal(file, period), 0, new ArrayList<>());
            case "wycOrder": return new ImportResult(importWycOrder(file, period), 0, new ArrayList<>());
            case "wycOrderReport": return new ImportResult(importWycOrderReport(file, period).getCityCount(), 0, new ArrayList<>());
            default: throw new RuntimeException("不支持的导入类型:" + type);
        }
    }