package com.trafficaudit.freightforecast.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.trafficaudit.auditengine.service.TrackMileageSelector; import com.trafficaudit.auditengine.service.TrackMileageCitySourceRuleService; import com.trafficaudit.common.util.RegionUtil; import com.trafficaudit.dataimport.dto.ImportResult; import com.trafficaudit.dataimport.entity.H2032EnterpriseMonthly; import com.trafficaudit.dataimport.entity.ScaleSplitTransport; import com.trafficaudit.dataimport.entity.TransportAuthVehicle; import com.trafficaudit.dataimport.entity.VehicleTrackMileage; import com.trafficaudit.dataimport.mapper.H2032EnterpriseMonthlyMapper; import com.trafficaudit.dataimport.mapper.ScaleSplitTransportMapper; import com.trafficaudit.dataimport.mapper.TransportAuthVehicleMapper; import com.trafficaudit.dataimport.mapper.VehicleTrackMileageMapper; import com.trafficaudit.dataimport.service.DataImportService; import com.trafficaudit.freightforecast.dto.BelowForecastRequest; import com.trafficaudit.freightforecast.dto.FreightForecastAnalysis; import com.trafficaudit.freightforecast.dto.FreightForecastReportRow; import com.trafficaudit.freightforecast.entity.FreightForecastAboveEnterprise; import com.trafficaudit.freightforecast.entity.FreightForecastAboveHistory; import com.trafficaudit.freightforecast.entity.FreightForecastBaseMonth; import com.trafficaudit.freightforecast.entity.FreightForecastBelowResult; import com.trafficaudit.freightforecast.entity.FreightForecastReportRound; import com.trafficaudit.freightforecast.mapper.FreightForecastAboveEnterpriseMapper; import com.trafficaudit.freightforecast.mapper.FreightForecastAboveHistoryMapper; import com.trafficaudit.freightforecast.mapper.FreightForecastBaseMonthMapper; import com.trafficaudit.freightforecast.mapper.FreightForecastBelowResultMapper; import com.trafficaudit.freightforecast.mapper.FreightForecastReportRoundMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @Service public class FreightForecastService { public static final String STAGE_AUDIT = "AUDIT"; public static final String STAGE_FINAL = "FINAL"; public static final String BELOW_GROWTH = "GROWTH"; public static final String BELOW_ACTUAL = "ACTUAL"; public static final String REPORT_H2032 = "H2032"; public static final String BELOW_MODULE_ONLY = "MODULE_ONLY"; public static final String BELOW_SCALE_SPLIT_PLUS_MODULE = "SCALE_SPLIT_HISTORY_PLUS_MODULE"; public static final String FORECAST_MODULE_ONLY = "MODULE_ONLY"; public static final String FORECAST_HISTORY_PLUS_MODULE = "HISTORY_PLUS_MODULE"; private static final String STATUS_OK = "OK"; private static final String STATUS_NO_AUTH = "NO_AUTH"; private static final String STATUS_NO_TRACK = "NO_TRACK"; private static final String STATUS_NO_MILEAGE = "NO_MILEAGE"; @Resource private FreightForecastBaseMonthMapper baseMapper; @Resource private FreightForecastBelowResultMapper belowMapper; @Resource private FreightForecastAboveEnterpriseMapper aboveMapper; @Resource private FreightForecastAboveHistoryMapper historyMapper; @Resource private FreightForecastReportRoundMapper roundMapper; @Resource private DataImportService dataImportService; @Resource private H2032EnterpriseMonthlyMapper h2032Mapper; @Resource private TransportAuthVehicleMapper authMapper; @Resource private VehicleTrackMileageMapper trackMapper; @Resource private TrackMileageCitySourceRuleService trackCitySourceRuleService; @Resource private ScaleSplitTransportMapper scaleSplitMapper; @Resource private JdbcTemplate jdbcTemplate; @Transactional public List importBase(MultipartFile file, int statYear) throws Exception { validateYear(statYear); String fileName = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().trim(); List rows = FreightForecastBaseParser.parse( file.getInputStream(), statYear, fileName.length() > 255 ? fileName.substring(0, 255) : fileName); baseMapper.delete(new LambdaQueryWrapper() .eq(FreightForecastBaseMonth::getStatYear, statYear)); for (FreightForecastBaseMonth row : rows) { row.setCreatedAt(LocalDateTime.now()); row.setUpdatedAt(LocalDateTime.now()); baseMapper.insert(row); } return rows; } public Map aboveHistory(int statYear, String period) { validateYear(statYear); String normalizedPeriod = normalizePeriod(period); FreightForecastAboveHistory latest = latestHistory(statYear, normalizedPeriod); if (latest == null) { Map empty = new LinkedHashMap<>(); empty.put("available", false); empty.put("statYear", statYear); empty.put("requestedPeriod", normalizedPeriod); return empty; } return aboveHistorySummary(statYear, latest.getThroughPeriod()); } private Map aboveHistorySummary(int statYear, String throughPeriod) { List rows = historyRows(statYear, throughPeriod); double sourceTotal = FreightForecastAboveHistoryValues.cumulativeTotal(rows); double correctedTotal = rows.stream() .mapToDouble(row -> value(row.getSourceCumulativeForecast())).sum(); List> corrections = new ArrayList<>(); for (FreightForecastAboveHistory row : rows) { if (!Boolean.TRUE.equals(row.getCorrected())) continue; Map item = new LinkedHashMap<>(); item.put("city", row.getCity()); item.put("enterpriseName", row.getEnterpriseName()); item.put("sourceCumulativeWan", value(row.getSourceCumulativeForecast()) / 10000.0); item.put("correctedCumulativeWan", value(row.getCumulativeForecast()) / 10000.0); item.put("differenceWan", (value(row.getCumulativeForecast()) - value(row.getSourceCumulativeForecast())) / 10000.0); corrections.add(item); } Map summary = new LinkedHashMap<>(); summary.put("available", !rows.isEmpty()); summary.put("statYear", statYear); summary.put("throughPeriod", throughPeriod); summary.put("rowCount", rows.size()); summary.put("correctionCount", corrections.size()); summary.put("sourceTotalWan", correctedTotal / 10000.0); summary.put("correctedTotalWan", sourceTotal / 10000.0); summary.put("differenceWan", (sourceTotal - correctedTotal) / 10000.0); summary.put("sourceFileName", rows.isEmpty() ? null : rows.get(0).getSourceFileName()); summary.put("importedAt", rows.isEmpty() ? null : rows.get(0).getImportedAt()); summary.put("corrections", corrections); return summary; } public List baseMonths(int statYear) { validateYear(statYear); return baseMapper.selectList(new LambdaQueryWrapper() .eq(FreightForecastBaseMonth::getStatYear, statYear) .orderByAsc(FreightForecastBaseMonth::getReportMonth)); } @Transactional public Map calculateAbove(String period) { return calculateAboveInternal(normalizePeriod(period)); } private Map calculateAboveInternal(String period) { int year = Integer.parseInt(period.substring(0, 4)); List> registerRows = annualEnterprises(year); if (registerRows.isEmpty()) { throw new IllegalArgumentException(year + "年规上企业名录为空,不能测算规上周转量"); } Map authByName = loadAuth(period); Map> trackByName = loadTracks(period); Set mandatoryCitySources = trackCitySourceRuleService.mandatoryCities(period); aboveMapper.delete(new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, period)); int missingAuth = 0; int missingTrack = 0; int noMileage = 0; double total = 0.0; Set cities = new HashSet<>(); for (Map register : registerRows) { String name = text(register.get("enterprise_name")); String city = RegionUtil.normalizeCityName(text(register.get("city"))); String key = normalizeName(name); TransportAuthVehicle auth = authByName.get(key); VehicleTrackMileage track = chooseTrack(city, trackByName.get(key), mandatoryCitySources); if (auth == null) missingAuth++; if (track == null) missingTrack++; int tractors = auth == null || auth.getTractorCount() == null ? 0 : auth.getTractorCount(); double otherTons = auth == null || auth.getOtherTons() == null ? 0.0 : auth.getOtherTons(); double monthly = track == null || track.getMonthlyMileage() == null ? 0.0 : track.getMonthlyMileage(); double anomaly = track == null || track.getAnomalyMileage() == null ? 0.0 : track.getAnomalyMileage(); int tracked = track == null || track.getTrackedVehicles() == null ? 0 : track.getTrackedVehicles(); double effective = track == null ? 0.0 : TrackMileageSelector.effectiveMonthlyMileage(track); double forecast = 0.0; String status; if (auth == null) { status = STATUS_NO_AUTH; } else if (track == null) { status = STATUS_NO_TRACK; } else if (tracked <= 0) { status = STATUS_NO_MILEAGE; noMileage++; } else { status = STATUS_OK; forecast = FreightForecastFormula.aboveTurnover(tractors, otherTons, effective, tracked); total += forecast; } FreightForecastAboveEnterprise row = new FreightForecastAboveEnterprise(); row.setReportPeriod(period); row.setCity(city); row.setEnterpriseName(name); row.setTractorCount(tractors); row.setOtherTons(otherTons); row.setMonthlyMileage(monthly); row.setAnomalyMileage(anomaly); row.setTrackedVehicles(tracked); row.setEffectiveMileage(effective); row.setForecastTurnover(forecast); row.setTrackSource(track == null ? null : track.getDataSource()); row.setCalculationStatus(status); row.setCalculatedAt(LocalDateTime.now()); aboveMapper.insert(row); cities.add(city); } Map result = new LinkedHashMap<>(); result.put("period", period); result.put("enterpriseCount", registerRows.size()); result.put("cityCount", cities.size()); result.put("missingAuth", missingAuth); result.put("missingTrack", missingTrack); result.put("noMileage", noMileage); result.put("forecastTurnover", total); result.put("forecastTurnoverWan", total / 10000.0); return result; } public List aboveRows(String period, String city, String keyword) { String normalized = normalizePeriod(period); LambdaQueryWrapper wrapper = new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, normalized) .eq(hasText(city), FreightForecastAboveEnterprise::getCity, hasText(city) ? RegionUtil.normalizeCityName(city.trim()) : null) .and(hasText(keyword), w -> w.like(FreightForecastAboveEnterprise::getEnterpriseName, keyword.trim()) .or().like(FreightForecastAboveEnterprise::getCity, keyword.trim())) .orderByAsc(FreightForecastAboveEnterprise::getCity) .orderByAsc(FreightForecastAboveEnterprise::getEnterpriseName); return aboveMapper.selectList(wrapper); } @Transactional public FreightForecastBelowResult calculateBelow(BelowForecastRequest request) { if (request == null) throw new IllegalArgumentException("缺少规下测算参数"); String period = normalizePeriod(request.getPeriod()); int year = Integer.parseInt(period.substring(0, 4)); int month = Integer.parseInt(period.substring(5, 7)); FreightForecastBaseMonth base = baseMapper.selectOne( new LambdaQueryWrapper() .eq(FreightForecastBaseMonth::getStatYear, year) .eq(FreightForecastBaseMonth::getReportMonth, month)); if (base == null) { throw new IllegalArgumentException("未找到" + year + "年" + month + "月基期数据,请先导入42-2026年基数"); } String type = upper(request.getResultType()); if (!BELOW_GROWTH.equals(type) && !BELOW_ACTUAL.equals(type)) { throw new IllegalArgumentException("测算类型必须是 GROWTH(增速预测)或 ACTUAL(高速国省道实际数据)"); } FreightForecastBelowResult existing = belowMapper.selectOne( new LambdaQueryWrapper() .eq(FreightForecastBelowResult::getReportPeriod, period) .eq(FreightForecastBelowResult::getResultType, type)); FreightForecastBelowResult row = existing == null ? new FreightForecastBelowResult() : existing; row.setReportPeriod(period); row.setResultType(type); row.setBaseFreight(base.getBelowFreight()); row.setBaseTurnover(base.getBelowTurnover()); if (BELOW_GROWTH.equals(type)) { boolean freightAny = anyPresent(request.getHighwayFreightGrowth(), request.getProvincialFreightGrowth()); boolean freightComplete = allPresent(request.getHighwayFreightGrowth(), request.getProvincialFreightGrowth()); boolean turnoverAny = anyPresent(request.getHighwayTurnoverGrowth(), request.getProvincialTurnoverGrowth()); boolean turnoverComplete = allPresent(request.getHighwayTurnoverGrowth(), request.getProvincialTurnoverGrowth()); validateBelowMetricInput(freightAny, freightComplete, "货运量"); validateBelowMetricInput(turnoverAny, turnoverComplete, "周转量"); if (!freightComplete && !turnoverComplete) { throw new IllegalArgumentException("请至少完整填写货运量或周转量其中一项的两项增速"); } if (freightComplete) { requirePositive(base.getBelowFreight(), "货运量基期值"); row.setHighwayFreightBase(base.getBelowFreight()); row.setProvincialFreightBase(base.getBelowFreight()); row.setHighwayFreightGrowth(request.getHighwayFreightGrowth()); row.setProvincialFreightGrowth(request.getProvincialFreightGrowth()); row.setHighwayFreightCurrent(base.getBelowFreight() * (1.0 + request.getHighwayFreightGrowth())); row.setProvincialFreightCurrent(base.getBelowFreight() * (1.0 + request.getProvincialFreightGrowth())); double freight = FreightForecastFormula.belowForward(base.getBelowFreight(), request.getHighwayFreightGrowth(), request.getProvincialFreightGrowth()); row.setBelowFreight(freight); row.setBelowFreightYoy(FreightForecastFormula.growth(freight, base.getBelowFreight())); } if (turnoverComplete) { requirePositive(base.getBelowTurnover(), "周转量基期值"); row.setHighwayTurnoverBase(base.getBelowTurnover()); row.setProvincialTurnoverBase(base.getBelowTurnover()); row.setHighwayTurnoverGrowth(request.getHighwayTurnoverGrowth()); row.setProvincialTurnoverGrowth(request.getProvincialTurnoverGrowth()); row.setHighwayTurnoverCurrent(base.getBelowTurnover() * (1.0 + request.getHighwayTurnoverGrowth())); row.setProvincialTurnoverCurrent(base.getBelowTurnover() * (1.0 + request.getProvincialTurnoverGrowth())); double turnover = FreightForecastFormula.belowForward(base.getBelowTurnover(), request.getHighwayTurnoverGrowth(), request.getProvincialTurnoverGrowth()); row.setBelowTurnover(turnover); row.setBelowTurnoverYoy(FreightForecastFormula.growth(turnover, base.getBelowTurnover())); } } else { boolean freightAny = anyPresent(request.getHighwayFreightBase(), request.getProvincialFreightBase(), request.getHighwayFreightCurrent(), request.getProvincialFreightCurrent()); boolean freightComplete = allPresent(request.getHighwayFreightBase(), request.getProvincialFreightBase(), request.getHighwayFreightCurrent(), request.getProvincialFreightCurrent()); boolean turnoverAny = anyPresent(request.getHighwayTurnoverBase(), request.getProvincialTurnoverBase(), request.getHighwayTurnoverCurrent(), request.getProvincialTurnoverCurrent()); boolean turnoverComplete = allPresent(request.getHighwayTurnoverBase(), request.getProvincialTurnoverBase(), request.getHighwayTurnoverCurrent(), request.getProvincialTurnoverCurrent()); validateBelowMetricInput(freightAny, freightComplete, "货运量"); validateBelowMetricInput(turnoverAny, turnoverComplete, "周转量"); if (!freightComplete && !turnoverComplete) { throw new IllegalArgumentException("请至少完整填写货运量或周转量其中一项的基期值和本期值"); } if (freightComplete) { requirePositive(base.getBelowFreight(), "货运量基期值"); requirePositive(request.getHighwayFreightBase(), "高速货运量基期值"); requirePositive(request.getProvincialFreightBase(), "国省道货运量基期值"); row.setHighwayFreightBase(request.getHighwayFreightBase()); row.setProvincialFreightBase(request.getProvincialFreightBase()); row.setHighwayFreightCurrent(request.getHighwayFreightCurrent()); row.setProvincialFreightCurrent(request.getProvincialFreightCurrent()); row.setHighwayFreightGrowth(FreightForecastFormula.growth( request.getHighwayFreightCurrent(), request.getHighwayFreightBase())); row.setProvincialFreightGrowth(FreightForecastFormula.growth( request.getProvincialFreightCurrent(), request.getProvincialFreightBase())); double freight = FreightForecastFormula.belowForward(base.getBelowFreight(), row.getHighwayFreightGrowth(), row.getProvincialFreightGrowth()); row.setBelowFreight(freight); row.setBelowFreightYoy(FreightForecastFormula.growth(freight, base.getBelowFreight())); } if (turnoverComplete) { requirePositive(base.getBelowTurnover(), "周转量基期值"); requirePositive(request.getHighwayTurnoverBase(), "高速周转量基期值"); requirePositive(request.getProvincialTurnoverBase(), "国省道周转量基期值"); row.setHighwayTurnoverBase(request.getHighwayTurnoverBase()); row.setProvincialTurnoverBase(request.getProvincialTurnoverBase()); row.setHighwayTurnoverCurrent(request.getHighwayTurnoverCurrent()); row.setProvincialTurnoverCurrent(request.getProvincialTurnoverCurrent()); row.setHighwayTurnoverGrowth(FreightForecastFormula.growth( request.getHighwayTurnoverCurrent(), request.getHighwayTurnoverBase())); row.setProvincialTurnoverGrowth(FreightForecastFormula.growth( request.getProvincialTurnoverCurrent(), request.getProvincialTurnoverBase())); double turnover = FreightForecastFormula.belowForward(base.getBelowTurnover(), row.getHighwayTurnoverGrowth(), row.getProvincialTurnoverGrowth()); row.setBelowTurnover(turnover); row.setBelowTurnoverYoy(FreightForecastFormula.growth(turnover, base.getBelowTurnover())); } } // The table stores placeholder zeros for metrics that have not arrived yet. // normalizeBelowResultForOutput keeps those values out of the UI and cumulative analysis. if (row.getBelowFreight() == null) row.setBelowFreight(0.0); if (row.getBelowTurnover() == null) row.setBelowTurnover(0.0); String note = trimToLength(request.getNote(), 500); if (note != null) row.setNote(note); row.setCalculatedAt(LocalDateTime.now()); if (existing != null) { belowMapper.updateById(row); } else { belowMapper.insert(row); } return normalizeBelowResultForOutput(row); } public List belowResults(String period) { String normalized = normalizePeriod(period); List rows = belowMapper.selectList( new LambdaQueryWrapper() .eq(FreightForecastBelowResult::getReportPeriod, normalized) .orderByAsc(FreightForecastBelowResult::getResultType)); for (FreightForecastBelowResult row : rows) { normalizeBelowResultForOutput(row); } return rows; } @Transactional public FreightForecastReportRound importReport(MultipartFile file, String period, String stage, String note) throws Exception { String normalizedPeriod = normalizePeriod(period); String normalizedStage = normalizeStage(stage); int year = Integer.parseInt(normalizedPeriod.substring(0, 4)); Map annualCities = annualCityMap(year); if (annualCities.isEmpty()) { throw new IllegalArgumentException(year + "年规上企业名录为空,无法匹配货运月报企业"); } List parsed = FreightForecastReportParser.parse(file.getInputStream(), annualCities); for (FreightForecastReportRow row : parsed) { if (row.getTurnoverTotal() != null && row.getTurnoverTotal() < 0) { throw new IllegalArgumentException("企业【" + row.getEnterpriseName() + "】货物周转量为负数"); } if (row.getFreightTotal() != null && row.getFreightTotal() < 0) { throw new IllegalArgumentException("企业【" + row.getEnterpriseName() + "】货运量为负数"); } } ImportResult h2032Import = dataImportService.importH2032(file, normalizedPeriod); if (h2032Import.getFail() > 0) { String failDetails = h2032Import.getFailDetails() == null ? "" : String.join("\n", h2032Import.getFailDetails()); throw new IllegalArgumentException("货运月报写入失败,已整体回滚。" + failDetails); } if (h2032Import.getSuccess() != parsed.size()) { throw new IllegalArgumentException("货运月报写入数量不一致,已整体回滚:校验 " + parsed.size() + " 家,实际写入 " + h2032Import.getSuccess() + " 家"); } FreightForecastReportRound last = roundMapper.selectOne( new LambdaQueryWrapper() .eq(FreightForecastReportRound::getReportPeriod, normalizedPeriod) .eq(FreightForecastReportRound::getReportStage, normalizedStage) .orderByDesc(FreightForecastReportRound::getRevisionNo) .last("LIMIT 1")); int revision = last == null ? 1 : (last.getRevisionNo() == null ? 1 : last.getRevisionNo() + 1); String fileName = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().trim(); FreightForecastReportRound round = new FreightForecastReportRound(); round.setReportPeriod(normalizedPeriod); round.setReportStage(normalizedStage); round.setRevisionNo(revision); round.setFileName(trimToLength(fileName, 255)); round.setRowCount(parsed.size()); round.setNote(trimToLength(note, 500)); round.setImportedAt(LocalDateTime.now()); roundMapper.insert(round); return round; } public List reportRounds(String period) { String normalized = normalizePeriod(period); return roundMapper.selectList(new LambdaQueryWrapper() .eq(FreightForecastReportRound::getReportPeriod, normalized) .orderByDesc(FreightForecastReportRound::getImportedAt) .orderByDesc(FreightForecastReportRound::getRevisionNo)); } public FreightForecastAnalysis analyze(String period, String belowHistorySource, String forecastHistorySource) { String normalizedPeriod = normalizePeriod(period); int year = Integer.parseInt(normalizedPeriod.substring(0, 4)); int month = Integer.parseInt(normalizedPeriod.substring(5, 7)); String belowSource = normalizeBelowSource(belowHistorySource); String forecastSource = normalizeForecastSource(forecastHistorySource); FreightForecastReportRound currentRound = latestReportRound(normalizedPeriod); if (currentRound == null) { throw new IllegalArgumentException("当前报表期没有货运月报版本,请先导入审核中或定稿版本"); } Map currentRoundValues = h2032Values(normalizedPeriod, year); if (currentRoundValues.isEmpty()) { throw new IllegalArgumentException("当前报表期没有 H2032 企业月报数据"); } List currentForecastRows = aboveMapper.selectList( new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, normalizedPeriod)); if (currentForecastRows.isEmpty()) { throw new IllegalArgumentException("当前报表期尚未完成规上测算,请先在“规上测算”页执行测算"); } Map> reportSeries = new LinkedHashMap<>(); Map reportSourceLabels = new LinkedHashMap<>(); List missingReportMonths = new ArrayList<>(); for (int m = 1; m <= month; m++) { String p = year + "-" + two(m); Map values = m == month ? currentRoundValues : h2032Values(p, year); String label = m == month ? "H2032当前月报(" + stageLabel(currentRound.getReportStage()) + ")" : "H2032历史月报"; if (values.isEmpty()) missingReportMonths.add(p); reportSeries.put(m, values); reportSourceLabels.put(m, label); } if (!missingReportMonths.isEmpty()) { throw new IllegalArgumentException("规上累计上报数据缺少 H2032 月份:" + String.join("、", missingReportMonths) + ";请先补齐历史 H2032 月报"); } Map> forecastSeries = new LinkedHashMap<>(); for (int m = 1; m <= month; m++) { String p = year + "-" + two(m); List rows = m == month ? currentForecastRows : aboveMapper.selectList(new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, p)); forecastSeries.put(m, rows); } FreightForecastAboveHistory latestHistory = null; List historyRows = Collections.emptyList(); int historyThroughMonth = 0; if (FORECAST_HISTORY_PLUS_MODULE.equals(forecastSource)) { latestHistory = latestHistory(year, normalizedPeriod); if (latestHistory == null) { throw new IllegalArgumentException("未找到截至本月或更早月份的系统内置历史累计测算基准," + "请确认系统初始化数据已加载"); } historyRows = historyRows(year, latestHistory.getThroughPeriod()); if (historyRows.isEmpty()) { throw new IllegalArgumentException("历史测算来源没有企业数据,请重新导入"); } historyThroughMonth = Integer.parseInt(latestHistory.getThroughPeriod().substring(5, 7)); if (historyThroughMonth > month) { throw new IllegalArgumentException("历史测算截止期不能晚于当前报表期"); } } Map belowTurnoverSeries = new LinkedHashMap<>(); Map belowSourceLabels = new LinkedHashMap<>(); List missingBelowMonths = new ArrayList<>(); for (int m = 1; m <= month; m++) { String p = year + "-" + two(m); FreightForecastBelowResult result = preferredBelowTurnoverResult(p); if (result != null) { belowTurnoverSeries.put(m, value(result.getBelowTurnover())); belowSourceLabels.put(m, BELOW_ACTUAL.equals(result.getResultType()) ? "第二步实际值" : "第一步增速预测"); } else if (BELOW_SCALE_SPLIT_PLUS_MODULE.equals(belowSource) && m < month) { Double split = scaleSplitProvinceBelowTurnover(p); if (split != null) { belowTurnoverSeries.put(m, split); belowSourceLabels.put(m, "现有规上规下拆分表(历史)"); } else { missingBelowMonths.add(p); } } else { missingBelowMonths.add(p); } } if (!missingBelowMonths.isEmpty()) { throw new IllegalArgumentException("规下累计周转量缺少月份:" + String.join("、", missingBelowMonths) + ";请补齐测算结果或选择“拆分表历史 + 当前测算结果”来源"); } Map> lastYearReportByCity = h2032SeriesByCity(year - 1, month); Map> lastYearReportAll = h2032SeriesAll(year - 1, month); List baseMonths = baseMonths(year); if (baseMonths.size() < month) { throw new IllegalArgumentException("规下基期数据不完整,请先导入" + year + "年42-2026年基数"); } FreightForecastAnalysis analysis = new FreightForecastAnalysis(); analysis.setPeriod(normalizedPeriod); analysis.setMonth(month); analysis.setReportStage(currentRound.getReportStage()); analysis.setRoundId(currentRound.getId()); analysis.setRevisionNo(currentRound.getRevisionNo()); analysis.setReportFileName(currentRound.getFileName()); analysis.setReportHistorySource(REPORT_H2032); analysis.setForecastHistorySource(forecastSource); analysis.setBelowHistorySource(belowSource); if (latestHistory != null) { analysis.setHistoryThroughPeriod(latestHistory.getThroughPeriod()); analysis.setHistoryCorrectionCount((int) historyRows.stream() .filter(row -> Boolean.TRUE.equals(row.getCorrected())).count()); analysis.setHistoryCorrectionDifferenceWan(historyRows.stream() .mapToDouble(row -> value(row.getCumulativeForecast()) - value(row.getSourceCumulativeForecast())).sum() / 10000.0); } double monthlyForecast = sumForecast(currentForecastRows); double monthlyReport = sumReport(currentRoundValues); analysis.setMonthlyForecastWan(monthlyForecast / 10000.0); analysis.setMonthlyReportWan(monthlyReport / 10000.0); analysis.setMonthlyDiffRate(ratio(monthlyReport, monthlyForecast)); Map lastYearCurrentMonth = lastYearReportByCity.getOrDefault(month, Collections.emptyMap()); double lastYearMonthlyReport = sumValues(lastYearCurrentMonth); analysis.setMonthlyReportYoy(ratio(monthlyReport, lastYearMonthlyReport)); Map previousForecastByCity = Collections.emptyMap(); Double previousMonthDiffRate = null; if (month > 1) { int previousMonth = month - 1; if (latestHistory != null && previousMonth <= historyThroughMonth) { if (previousMonth >= 7) { previousForecastByCity = FreightForecastAboveHistoryValues.monthByCity(historyRows, previousMonth); double previousForecast = sumValues(previousForecastByCity); double previousReport = sumValues(cityReport( reportSeries.getOrDefault(previousMonth, Collections.emptyMap()))); previousMonthDiffRate = ratio(previousReport, previousForecast); } else { analysis.getWarnings().add("历史测算工作簿只能还原7月以后逐月测算," + "1-6月没有逐月测算来源,本月不计算上月差异率"); } } else { List previousRows = forecastSeries.get(previousMonth); assertValidForecastSnapshot(year + "-" + two(previousMonth), previousRows); previousForecastByCity = cityForecast(previousRows); double previousForecast = sumValues(previousForecastByCity); double previousReport = sumValues(cityReport( reportSeries.getOrDefault(previousMonth, Collections.emptyMap()))); previousMonthDiffRate = ratio(previousReport, previousForecast); } } analysis.setPreviousMonthDiffRate(previousMonthDiffRate); double cumulativeReport = 0.0; Map cumulativeReportByCity = new LinkedHashMap<>(); for (int m = 1; m <= month; m++) { Map values = reportSeries.get(m); cumulativeReport += sumReport(values); merge(cumulativeReportByCity, cityReport(values)); } double cumulativeForecast = 0.0; Map cumulativeForecastByCity = new LinkedHashMap<>(); List invalidForecastMonths = new ArrayList<>(); int moduleStartMonth = 1; if (latestHistory != null) { cumulativeForecast = FreightForecastAboveHistoryValues.cumulativeTotal(historyRows); merge(cumulativeForecastByCity, FreightForecastAboveHistoryValues.cumulativeByCity(historyRows)); moduleStartMonth = historyThroughMonth + 1; } for (int m = moduleStartMonth; m <= month; m++) { String p = year + "-" + two(m); List rows = forecastSeries.get(m); if (!isValidForecastSnapshot(rows)) { invalidForecastMonths.add(p); continue; } cumulativeForecast += sumForecast(rows); merge(cumulativeForecastByCity, cityForecast(rows)); } if (!invalidForecastMonths.isEmpty()) { throw new IllegalArgumentException("规上累计测算存在无效月份快照:" + String.join("、", invalidForecastMonths) + ";空快照或全零快照不能进入差异率报告,请先补齐并重新测算"); } analysis.setCumulativeForecastWan(cumulativeForecast / 10000.0); analysis.setCumulativeReportWan(cumulativeReport / 10000.0); analysis.setCumulativeDiffRate(ratio(cumulativeReport, cumulativeForecast)); double lastYearCumulativeReport = 0.0; Map lastYearCumulativeCity = new LinkedHashMap<>(); for (int m = 1; m <= month; m++) { lastYearCumulativeReport += sumValues(lastYearReportAll.getOrDefault(m, Collections.emptyMap())); merge(lastYearCumulativeCity, lastYearReportByCity.getOrDefault(m, Collections.emptyMap())); } analysis.setCumulativeReportYoy(ratio(cumulativeReport, lastYearCumulativeReport)); double monthlyBelow = belowTurnoverSeries.getOrDefault(month, 0.0); double cumulativeBelow = belowTurnoverSeries.values().stream().mapToDouble(Double::doubleValue).sum(); double lastYearBelow = baseMonths.stream().filter(x -> x.getReportMonth() != null && x.getReportMonth() <= month) .mapToDouble(x -> value(x.getBelowTurnover())).sum(); analysis.setMonthlyBelowTurnoverWan(monthlyBelow); analysis.setCumulativeBelowTurnoverWan(cumulativeBelow); analysis.setCurrentTotalCumulativeWan( FreightForecastFormula.totalTurnoverWan(cumulativeReport, cumulativeBelow)); analysis.setLastYearTotalCumulativeWan( FreightForecastFormula.totalTurnoverWan(lastYearCumulativeReport, lastYearBelow)); analysis.setTotalCumulativeYoy(FreightForecastFormula.totalTurnoverYoy( cumulativeReport, cumulativeBelow, lastYearCumulativeReport, lastYearBelow)); FreightForecastBelowResult currentBelow = preferredBelowTurnoverResult(normalizedPeriod); analysis.setBelowResultType(currentBelow == null ? null : currentBelow.getResultType()); Map currentForecastByCity = cityForecast(currentForecastRows); Map currentReportByCity = cityReport(currentRoundValues); Map previousReportByCity = month > 1 ? cityReport(reportSeries.getOrDefault(month - 1, Collections.emptyMap())) : Collections.emptyMap(); analysis.setCities(buildCityRows(month, currentForecastByCity, currentReportByCity, previousForecastByCity, previousReportByCity, cumulativeForecastByCity, cumulativeReportByCity, lastYearCumulativeCity, lastYearReportByCity)); analysis.setEnterprises(buildEnterpriseRows(year, currentRound, currentRoundValues, currentForecastRows)); if (currentRoundValues.size() < currentForecastRows.size()) { analysis.getWarnings().add("本期月报企业数 " + currentRoundValues.size() + " 少于规上测算企业数 " + currentForecastRows.size() + ",未上报企业按0参与差异分析"); } if (month == 1) analysis.getWarnings().add("1月没有上月差异率"); populateSources(analysis, year, month, currentRound, reportSourceLabels, belowSourceLabels, baseMonths, forecastSource, latestHistory, historyRows); analysis.setSourceSummary("当月上报=H2032当前工作数据(" + stageLabel(currentRound.getReportStage()) + "第" + currentRound.getRevisionNo() + "版);历史上报=H2032逐月"); return analysis; } public Map overview(String period) { String normalized = normalizePeriod(period); int year = Integer.parseInt(normalized.substring(0, 4)); int month = Integer.parseInt(normalized.substring(5, 7)); Map result = new LinkedHashMap<>(); result.put("period", normalized); result.put("baseMonths", baseMapper.selectCount(new LambdaQueryWrapper() .eq(FreightForecastBaseMonth::getStatYear, year))); result.put("aboveRows", aboveMapper.selectCount(new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, normalized))); result.put("belowRows", belowMapper.selectCount(new LambdaQueryWrapper() .eq(FreightForecastBelowResult::getReportPeriod, normalized))); result.put("auditRounds", roundMapper.selectCount(new LambdaQueryWrapper() .eq(FreightForecastReportRound::getReportPeriod, normalized) .eq(FreightForecastReportRound::getReportStage, STAGE_AUDIT))); result.put("finalRounds", roundMapper.selectCount(new LambdaQueryWrapper() .eq(FreightForecastReportRound::getReportPeriod, normalized) .eq(FreightForecastReportRound::getReportStage, STAGE_FINAL))); FreightForecastAboveHistory latest = latestHistory(year, normalized); int startMonth = 1; if (latest != null) { int historyMonth = Integer.parseInt(latest.getThroughPeriod().substring(5, 7)); if (historyMonth <= month) startMonth = historyMonth + 1; result.put("historyThroughPeriod", latest.getThroughPeriod()); } List missingForecast = new ArrayList<>(); for (int m = startMonth; m <= month; m++) { String p = year + "-" + two(m); List rows = aboveMapper.selectList( new LambdaQueryWrapper() .eq(FreightForecastAboveEnterprise::getReportPeriod, p)); if (!isValidForecastSnapshot(rows)) missingForecast.add(p); } result.put("missingForecastMonths", missingForecast); return result; } private List buildCityRows( int month, Map currentForecast, Map currentReport, Map previousForecast, Map previousReport, Map cumulativeForecastByCity, Map cumulativeReportByCity, Map lastYearCumulativeCity, Map> lastYearReportByCity) { Map lastYearMonth = lastYearReportByCity.getOrDefault(month, Collections.emptyMap()); List rows = new ArrayList<>(); for (String city : RegionUtil.cityList()) { FreightForecastAnalysis.CityRow row = new FreightForecastAnalysis.CityRow(); row.setCity(city); row.setMonthlyForecastWan(currentForecast.getOrDefault(city, 0.0) / 10000.0); row.setMonthlyReportWan(currentReport.getOrDefault(city, 0.0) / 10000.0); row.setMonthlyDiffRate(ratio(row.getMonthlyReportWan(), row.getMonthlyForecastWan())); row.setPreviousMonthDiffRate(month > 1 ? ratio(previousReport.getOrDefault(city, 0.0), previousForecast.getOrDefault(city, 0.0)) : null); row.setMonthlyReportYoy(ratio(row.getMonthlyReportWan(), lastYearMonth.getOrDefault(city, 0.0) / 10000.0)); row.setCumulativeReportWan(cumulativeReportByCity.getOrDefault(city, 0.0) / 10000.0); row.setCumulativeForecastWan(cumulativeForecastByCity.getOrDefault(city, 0.0) / 10000.0); row.setCumulativeReportYoy(ratio(row.getCumulativeReportWan(), lastYearCumulativeCity.getOrDefault(city, 0.0) / 10000.0)); row.setCumulativeDiffRate(ratio(row.getCumulativeReportWan(), row.getCumulativeForecastWan())); rows.add(row); } return rows; } private List buildEnterpriseRows( int year, FreightForecastReportRound round, Map reportValues, List forecastRows) { Map annualCities = annualCityMap(year); Map forecastByName = new LinkedHashMap<>(); for (FreightForecastAboveEnterprise row : forecastRows) { forecastByName.put(normalizeName(row.getEnterpriseName()), row); } Set names = new HashSet<>(); names.addAll(annualCities.keySet()); names.addAll(forecastByName.keySet()); names.addAll(reportValues.keySet()); List rows = new ArrayList<>(); for (String key : names) { FreightForecastAboveEnterprise forecast = forecastByName.get(key); ReportValue report = reportValues.get(key); FreightForecastAnalysis.EnterpriseRow row = new FreightForecastAnalysis.EnterpriseRow(); String displayName = forecast != null ? forecast.getEnterpriseName() : report != null ? report.name : displayName(key, annualCities); row.setEnterpriseName(displayName); row.setCity(forecast != null ? forecast.getCity() : report != null ? report.city : RegionUtil.normalizeCityName(annualCities.get(key))); double forecastValue = forecast == null ? 0.0 : value(forecast.getForecastTurnover()); double reportValue = report == null ? 0.0 : report.turnover; row.setForecastTurnoverWan(forecastValue / 10000.0); row.setReportedTurnoverWan(reportValue / 10000.0); row.setDiffRate(ratio(reportValue, forecastValue)); if (forecast == null) { row.setStatus("缺测算"); } else if (report == null) { row.setStatus("未上报"); } else if (reportValue == 0.0 && forecastValue == 0.0) { row.setStatus("双方均为0"); } else { row.setStatus("参与分析"); } rows.add(row); } rows.sort(Comparator.comparing(FreightForecastAnalysis.EnterpriseRow::getCity, Comparator.nullsLast(String::compareTo)) .thenComparing(FreightForecastAnalysis.EnterpriseRow::getEnterpriseName, Comparator.nullsLast(String::compareTo))); return rows; } private void populateSources(FreightForecastAnalysis analysis, int year, int month, FreightForecastReportRound round, Map reportLabels, Map belowLabels, List baseMonths, String forecastSource, FreightForecastAboveHistory latestHistory, List historyRows) { String currentPeriod = year + "-" + two(month); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "当月规上上报", stageLabel(round.getReportStage()) + "第" + round.getRevisionNo() + "版(" + nullToEmpty(round.getFileName()) + ")", currentPeriod, round.getRowCount(), "审核过程可多次导入,定稿版本单独留存")); Set reportSources = new HashSet<>(reportLabels.values()); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "累计规上上报", String.join(" + ", reportSources), year + "-01~" + currentPeriod, null, "按所选历史来源逐月求和,不做隐式合并")); if (latestHistory == null) { analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "累计规上测算", "freight_forecast_above_enterprise 规上测算快照", year + "-01~" + currentPeriod, null, "公式=(总牵引车数×31+其它车辆总吨位)×有效里程÷有里程车辆数")); } else { int historyMonth = Integer.parseInt(latestHistory.getThroughPeriod().substring(5, 7)); double correction = historyRows.stream() .mapToDouble(row -> value(row.getCumulativeForecast()) - value(row.getSourceCumulativeForecast())).sum() / 10000.0; int correctionCount = (int) historyRows.stream() .filter(row -> Boolean.TRUE.equals(row.getCorrected())).count(); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "累计规上测算(历史部分)", nullToEmpty(latestHistory.getSourceFileName()), year + "-01~" + latestHistory.getThroughPeriod(), historyRows.size(), "累计值按1-6月+7月...逐期列重建;修正" + correctionCount + "家,增加" + format(correction) + "万吨公里")); if (historyMonth < month) { analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "累计规上测算(模块部分)", "freight_forecast_above_enterprise 规上测算快照", year + "-" + two(historyMonth + 1) + "~" + currentPeriod, null, "只叠加历史截止月之后的模块逐月快照,空快照或全零快照拒绝进入差异率报告")); } } Set belowSources = new HashSet<>(belowLabels.values()); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "累计规下周转量", String.join(" + ", belowSources), year + "-01~" + currentPeriod, null, "每月优先采用第二步实际值,无第二步时采用第一步增速预测")); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "上年同期规上上报", "H2032 2025年月报", (year - 1) + "-01~" + (year - 1) + "-" + two(month), null, "用于累计同比与当月同比")); double baseTotal = baseMonths.stream().filter(x -> x.getReportMonth() != null && x.getReportMonth() <= month) .mapToDouble(x -> value(x.getBelowTurnover())).sum(); analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage( "上年同期规下基期", "42-2026年基数.xlsx 湖北页 L14:W15", (year - 1) + "-01~" + (year - 1) + "-" + two(month), baseMonths.size(), "基期累计=" + format(baseTotal) + " 万吨公里")); } private Map h2032Values(String period, int year) { List rows = h2032Mapper.selectList( new LambdaQueryWrapper() .eq(H2032EnterpriseMonthly::getReportPeriod, period)); if (rows.isEmpty()) return Collections.emptyMap(); Map annualCities = annualCityMap(year); Map result = new LinkedHashMap<>(); for (H2032EnterpriseMonthly row : rows) { String key = normalizeName(row.getEnterpriseName()); ReportValue value = new ReportValue(); value.name = row.getEnterpriseName(); String city = RegionUtil.normalizeCityName(RegionUtil.cityByCode(row.getRegionCode())); if (!hasText(city)) city = annualCities.get(key); value.city = city; value.freight = value(row.getFreightTotal()); value.turnover = value(row.getTurnoverTotal()); result.put(key, value); } return result; } private Map> h2032SeriesByCity(int year, int lastMonth) { Map> result = new LinkedHashMap<>(); for (int m = 1; m <= lastMonth; m++) { List rows = h2032Mapper.selectList( new LambdaQueryWrapper() .eq(H2032EnterpriseMonthly::getReportPeriod, year + "-" + two(m))); Map byCity = new LinkedHashMap<>(); for (H2032EnterpriseMonthly row : rows) { String city = RegionUtil.cityByCode(row.getRegionCode()); if (city == null) continue; byCity.merge(city, value(row.getTurnoverTotal()), Double::sum); } result.put(m, byCity); } return result; } private Map> h2032SeriesAll(int year, int lastMonth) { Map> result = new LinkedHashMap<>(); for (int m = 1; m <= lastMonth; m++) { List rows = h2032Mapper.selectList( new LambdaQueryWrapper() .eq(H2032EnterpriseMonthly::getReportPeriod, year + "-" + two(m))); Map all = new LinkedHashMap<>(); for (H2032EnterpriseMonthly row : rows) all.merge("ALL", value(row.getTurnoverTotal()), Double::sum); result.put(m, all); } return result; } private FreightForecastReportRound latestReportRound(String period) { return roundMapper.selectOne(new LambdaQueryWrapper() .eq(FreightForecastReportRound::getReportPeriod, period) .orderByDesc(FreightForecastReportRound::getImportedAt) .orderByDesc(FreightForecastReportRound::getRevisionNo) .orderByDesc(FreightForecastReportRound::getId) .last("LIMIT 1")); } private FreightForecastAboveHistory latestHistory(int statYear, String throughPeriod) { return historyMapper.selectOne(new LambdaQueryWrapper() .eq(FreightForecastAboveHistory::getStatYear, statYear) .le(FreightForecastAboveHistory::getThroughPeriod, throughPeriod) .orderByDesc(FreightForecastAboveHistory::getThroughPeriod) .last("LIMIT 1")); } private List historyRows(int statYear, String throughPeriod) { return historyMapper.selectList(new LambdaQueryWrapper() .eq(FreightForecastAboveHistory::getStatYear, statYear) .eq(FreightForecastAboveHistory::getThroughPeriod, throughPeriod) .orderByAsc(FreightForecastAboveHistory::getCity) .orderByAsc(FreightForecastAboveHistory::getEnterpriseName)); } private static boolean isValidForecastSnapshot(List rows) { if (rows == null || rows.isEmpty()) return false; double total = rows.stream().mapToDouble(row -> value(row.getForecastTurnover())).sum(); boolean hasOk = rows.stream().anyMatch(row -> STATUS_OK.equals(row.getCalculationStatus())); return hasOk && total > 0.0; } private static void assertValidForecastSnapshot(String period, List rows) { if (!isValidForecastSnapshot(rows)) { throw new IllegalArgumentException("规上测算快照无效:" + period + "为空、全零或全部缺少运政/轨迹数据,不能进入累计差异分析"); } } private FreightForecastBelowResult preferredBelowTurnoverResult(String period) { List rows = belowMapper.selectList( new LambdaQueryWrapper() .eq(FreightForecastBelowResult::getReportPeriod, period)); FreightForecastBelowResult growth = null; FreightForecastBelowResult actual = null; for (FreightForecastBelowResult row : rows) { FreightForecastBelowResult normalized = normalizeBelowResultForOutput(row); if (BELOW_ACTUAL.equals(normalized.getResultType())) actual = normalized; if (BELOW_GROWTH.equals(normalized.getResultType())) growth = normalized; } if (actual != null && actual.getBelowTurnover() != null) return actual; if (growth != null && growth.getBelowTurnover() != null) return growth; return null; } private static FreightForecastBelowResult normalizeBelowResultForOutput(FreightForecastBelowResult row) { if (row == null) return null; boolean freightInputsComplete = BELOW_GROWTH.equals(row.getResultType()) ? allPresent(row.getHighwayFreightGrowth(), row.getProvincialFreightGrowth()) : BELOW_ACTUAL.equals(row.getResultType()) && allPresent(row.getHighwayFreightBase(), row.getProvincialFreightBase(), row.getHighwayFreightCurrent(), row.getProvincialFreightCurrent()); boolean turnoverInputsComplete = BELOW_GROWTH.equals(row.getResultType()) ? allPresent(row.getHighwayTurnoverGrowth(), row.getProvincialTurnoverGrowth()) : BELOW_ACTUAL.equals(row.getResultType()) && allPresent(row.getHighwayTurnoverBase(), row.getProvincialTurnoverBase(), row.getHighwayTurnoverCurrent(), row.getProvincialTurnoverCurrent()); boolean hasFreight = freightInputsComplete || nonZero(row.getBelowFreight()); boolean hasTurnover = turnoverInputsComplete || nonZero(row.getBelowTurnover()); if (!hasFreight) { row.setBelowFreight(null); row.setBelowFreightYoy(null); } if (!hasTurnover) { row.setBelowTurnover(null); row.setBelowTurnoverYoy(null); } return row; } private Double scaleSplitProvinceBelowTurnover(String period) { List rows = scaleSplitMapper.selectList( new LambdaQueryWrapper() .eq(ScaleSplitTransport::getReportPeriod, period) .eq(ScaleSplitTransport::getPeriodType, "MONTH")); for (ScaleSplitTransport row : rows) { String region = RegionUtil.normalizeCityName(text(row.getRegionName())); if ("湖北省".equals(region) || "全省".equals(text(row.getRegionName()))) { return row.getBelowScaleTurnover(); } } return null; } private List> annualEnterprises(int year) { return jdbcTemplate.queryForList( "SELECT enterprise_name, city FROM h2032_enterprise_year WHERE stat_year = ? ORDER BY id", year); } private Map annualCityMap(int year) { Map result = new LinkedHashMap<>(); for (Map row : annualEnterprises(year)) { String key = normalizeName(text(row.get("enterprise_name"))); if (!key.isEmpty()) result.put(key, RegionUtil.normalizeCityName(text(row.get("city")))); } return result; } private Map loadAuth(String period) { List rows = authMapper.selectList( new LambdaQueryWrapper() .eq(TransportAuthVehicle::getReportPeriod, period) .orderByDesc(TransportAuthVehicle::getId)); Map result = new LinkedHashMap<>(); for (TransportAuthVehicle row : rows) { String key = normalizeName(row.getEnterpriseName()); if (!key.isEmpty() && !result.containsKey(key)) result.put(key, row); } return result; } private Map> loadTracks(String period) { List rows = trackMapper.selectList( new LambdaQueryWrapper() .eq(VehicleTrackMileage::getReportPeriod, period) .eq(VehicleTrackMileage::getEnterpriseCategory, VehicleTrackMileage.CATEGORY_ABOVE_SCALE) .orderByDesc(VehicleTrackMileage::getId)); Map> result = new LinkedHashMap<>(); for (VehicleTrackMileage row : rows) { String key = normalizeName(row.getEnterpriseName()); if (!key.isEmpty()) result.computeIfAbsent(key, ignored -> new ArrayList<>()).add(row); } return result; } private VehicleTrackMileage chooseTrack(String city, List candidates, Set mandatoryCitySources) { if (candidates == null || candidates.isEmpty()) return null; boolean mandatoryCity = mandatoryCitySources.contains(city); VehicleTrackMileage selected = null; for (VehicleTrackMileage candidate : candidates) { selected = TrackMileageSelector.choose(selected, candidate, mandatoryCity ? city : null); } return selected; } private Map cityForecast(List rows) { Map result = new LinkedHashMap<>(); for (FreightForecastAboveEnterprise row : rows) { result.merge(RegionUtil.normalizeCityName(row.getCity()), value(row.getForecastTurnover()), Double::sum); } return result; } private Map cityReport(Map values) { Map result = new LinkedHashMap<>(); for (ReportValue row : values.values()) { if (row.city == null) continue; String city = RegionUtil.normalizeCityName(row.city); result.merge(city, row.turnover, Double::sum); } return result; } private double sumForecast(List rows) { return rows.stream().mapToDouble(x -> value(x.getForecastTurnover())).sum(); } private double sumReport(Map values) { return values.values().stream().mapToDouble(x -> x.turnover).sum(); } private double sumValues(Map values) { return values.values().stream().mapToDouble(Double::doubleValue).sum(); } private void merge(Map target, Map source) { for (Map.Entry e : source.entrySet()) { target.merge(e.getKey(), e.getValue(), Double::sum); } } private static Double ratio(double numerator, double denominator) { return FreightForecastFormula.diffRate(numerator, denominator); } private static double value(Double value) { return value == null ? 0.0 : value; } private static String text(Object value) { return value == null ? "" : String.valueOf(value).trim(); } private static String normalizeName(String value) { return FreightForecastReportParser.normalizeName(value); } private static int cityIndex(String city) { return RegionUtil.cityList().indexOf(RegionUtil.normalizeCityName(city)); } private static String displayName(String key, Map annualCities) { // The annual map stores only city, so use the normalized key as a last-resort label. return annualCities.containsKey(key) ? key : key; } private static String normalizePeriod(String period) { if (period == null || !period.trim().matches("\\d{4}-\\d{2}")) { throw new IllegalArgumentException("请选择有效报表期(yyyy-MM)"); } String value = period.trim(); int month = Integer.parseInt(value.substring(5, 7)); if (month < 1 || month > 12) throw new IllegalArgumentException("报表期月份必须为01-12"); return value; } private static String normalizeStage(String stage) { String value = upper(stage); if (!STAGE_AUDIT.equals(value) && !STAGE_FINAL.equals(value)) { throw new IllegalArgumentException("月报阶段必须是 AUDIT(审核中)或 FINAL(定稿)"); } return value; } private static String normalizeForecastSource(String source) { String value = upper(source); if (!hasText(value)) return FORECAST_HISTORY_PLUS_MODULE; if (!FORECAST_MODULE_ONLY.equals(value) && !FORECAST_HISTORY_PLUS_MODULE.equals(value)) { throw new IllegalArgumentException("不支持的规上累计测算来源:" + source); } return value; } private static String normalizeBelowSource(String source) { String value = upper(source); if (!hasText(value)) return BELOW_SCALE_SPLIT_PLUS_MODULE; if (!BELOW_MODULE_ONLY.equals(value) && !BELOW_SCALE_SPLIT_PLUS_MODULE.equals(value)) { throw new IllegalArgumentException("不支持的规下累计来源:" + source); } return value; } private static void validateYear(int year) { if (year < 2000 || year > 2100) throw new IllegalArgumentException("年份不在有效范围内"); } private static void validateBelowMetricInput(boolean any, boolean complete, String metric) { if (!any || complete) return; throw new IllegalArgumentException(metric + "需同时填写高速和国省道两项指标"); } private static boolean anyPresent(Double... values) { for (Double value : values) { if (value != null) return true; } return false; } private static boolean nonZero(Double value) { return value != null && value != 0.0; } private static boolean allPresent(Double... values) { for (Double value : values) { if (value == null) return false; } return values.length > 0; } private static void require(Double value, String label) { if (value == null) throw new IllegalArgumentException("请填写" + label); } private static void requirePositive(double value, String label) { if (value <= 0.0) throw new IllegalArgumentException(label + "必须大于0"); } private static String stageLabel(String stage) { return STAGE_FINAL.equals(stage) ? "定稿版" : "审核中"; } private static String trimToLength(String value, int max) { if (value == null) return null; String trimmed = value.trim(); return trimmed.length() <= max ? trimmed : trimmed.substring(0, max); } private static boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } private static String normalizeCity(String city) { return RegionUtil.normalizeCityName(text(city)); } private static String upper(String value) { return value == null ? "" : value.trim().toUpperCase(); } private static String two(int value) { return value < 10 ? "0" + value : String.valueOf(value); } private static String nullToEmpty(String value) { return value == null ? "" : value; } private static String format(double value) { return String.format(java.util.Locale.ROOT, "%.4f", value); } private static final class ReportValue { private String name; private String city; private double freight; private double turnover; } }