package com.trafficaudit.dataimport.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.trafficaudit.common.util.RegionUtil; import com.trafficaudit.dataimport.entity.TransportAuthVehicle; import com.trafficaudit.dataimport.entity.VehicleTrackMileage; import com.trafficaudit.dataimport.mapper.TransportAuthVehicleMapper; import com.trafficaudit.dataimport.mapper.VehicleTrackMileageMapper; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.Collator; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Generates the monthly per-city workbooks distributed to the 17 cities. * * The workbook population is the current year's above-scale enterprise register, * not the union of data sources imported for the month. Missing monthly auth or * track data is therefore represented as zero. */ @Service public class TrackMileageCityDistributionService { private static final String XIAOGAN_CITY = "孝感市"; private static final String SHEET_NAME = "车辆数及轨迹"; private static final String[] HEADERS = { "市州", "企业名称", "总牵引车数", "总挂车数", "其它车辆数", "挂车总吨位(吨)", "其它车辆总吨位(吨)", "轨迹里程", "轨迹车辆" }; private static final int COLUMN_COUNT = HEADERS.length; private static final double MAX_ANOMALY_RATE = 1.0; private static final double MAX_ANOMALY_PER_VEHICLE = 10000.0; @Resource private JdbcTemplate jdbcTemplate; @Resource private TransportAuthVehicleMapper transportAuthVehicleMapper; @Resource private VehicleTrackMileageMapper vehicleTrackMileageMapper; public byte[] exportZip(String period) throws IOException { String normalizedPeriod = normalizePeriod(period); int statYear = Integer.parseInt(normalizedPeriod.substring(0, 4)); List> registerRows = jdbcTemplate.queryForList( "SELECT enterprise_name, city FROM h2032_enterprise_year WHERE stat_year = ? ORDER BY id", statYear); if (registerRows.isEmpty()) { throw new IllegalArgumentException(statYear + "年规上企业名录为空,无法生成分市州轨迹"); } Map authByName = loadAuthByName(normalizedPeriod); Map> trackByName = loadTrackByName(normalizedPeriod); Map> rowsByCity = new LinkedHashMap<>(); for (String city : RegionUtil.cityList()) { rowsByCity.put(city, new ArrayList<>()); } for (Map registerRow : registerRows) { String enterpriseName = text(registerRow.get("enterprise_name")); String city = RegionUtil.normalizeCityName(text(registerRow.get("city"))); if (enterpriseName.isEmpty() || !rowsByCity.containsKey(city)) { throw new IllegalStateException("规上企业名录存在无法识别的市州或企业名称:" + registerRow); } String key = normalizeEnterpriseName(enterpriseName); TransportAuthVehicle auth = authByName.get(key); VehicleTrackMileage track = chooseTrack(city, trackByName.get(key)); rowsByCity.get(city).add(new DistributionRow(city, enterpriseName, auth, track)); } Collator collator = Collator.getInstance(Locale.CHINA); Comparator byName = (a, b) -> collator.compare(a.enterpriseName, b.enterpriseName); for (List rows : rowsByCity.values()) { rows.sort(byName); } ByteArrayOutputStream zipBytes = new ByteArrayOutputStream(); try (ZipOutputStream zip = new ZipOutputStream(zipBytes)) { for (String city : RegionUtil.cityList()) { byte[] workbookBytes = buildCityWorkbook(rowsByCity.get(city)); String fileName = fileName(normalizedPeriod, city); ZipEntry entry = new ZipEntry(fileName); zip.putNextEntry(entry); zip.write(workbookBytes); zip.closeEntry(); } } return zipBytes.toByteArray(); } public String zipFileName(String period) { String normalizedPeriod = normalizePeriod(period); return displayMonth(normalizedPeriod) + "分市州轨迹.zip"; } private Map loadAuthByName(String period) { List rows = transportAuthVehicleMapper.selectList( new LambdaQueryWrapper() .eq(TransportAuthVehicle::getReportPeriod, period) .orderByDesc(TransportAuthVehicle::getId)); Map result = new HashMap<>(); for (TransportAuthVehicle row : rows) { String key = normalizeEnterpriseName(row.getEnterpriseName()); if (!key.isEmpty() && !result.containsKey(key)) { result.put(key, row); } } return result; } private Map> loadTrackByName(String period) { List rows = vehicleTrackMileageMapper.selectList( new LambdaQueryWrapper() .eq(VehicleTrackMileage::getReportPeriod, period) .eq(VehicleTrackMileage::getEnterpriseCategory, VehicleTrackMileage.CATEGORY_ABOVE_SCALE) .orderByDesc(VehicleTrackMileage::getId)); Map> result = new HashMap<>(); for (VehicleTrackMileage row : rows) { String key = normalizeEnterpriseName(row.getEnterpriseName()); if (!key.isEmpty()) { result.computeIfAbsent(key, ignored -> new ArrayList<>()).add(row); } } return result; } private VehicleTrackMileage chooseTrack(String city, List candidates) { if (candidates == null || candidates.isEmpty()) { return null; } if (XIAOGAN_CITY.equals(city)) { // Xiaogan must always use its own third-party source. Provincial data // is not a fallback for any Xiaogan enterprise. return latestBySource(candidates, VehicleTrackMileage.SOURCE_CITY_THIRD_PARTY); } VehicleTrackMileage provincial = latestBySource(candidates, VehicleTrackMileage.SOURCE_PROVINCIAL); VehicleTrackMileage citySource = latestBySource(candidates, VehicleTrackMileage.SOURCE_CITY_THIRD_PARTY); if (provincial == null) { return citySource; } if (citySource == null) { return provincial; } return mileagePerTrackedVehicle(citySource) > mileagePerTrackedVehicle(provincial) ? citySource : provincial; } private VehicleTrackMileage latestBySource(List candidates, String source) { for (VehicleTrackMileage candidate : candidates) { if (source.equals(candidate.getDataSource())) { return candidate; } } return null; } private double effectiveMileage(VehicleTrackMileage row) { if (row == null) { return 0.0; } double mileage = value(row.getMonthlyMileage()); if (VehicleTrackMileage.SOURCE_CITY_THIRD_PARTY.equals(row.getDataSource())) { // The city third-party files do not split normal and abnormal mileage. return mileage; } double anomaly = value(row.getAnomalyMileage()); int trackedVehicles = row.getTrackedVehicles() == null ? 0 : row.getTrackedVehicles(); double anomalyRate = mileage == 0.0 ? 0.0 : anomaly / mileage; double anomalyPerVehicle = trackedVehicles <= 0 ? 0.0 : anomaly / trackedVehicles; boolean excluded = anomalyRate > MAX_ANOMALY_RATE || anomalyPerVehicle > MAX_ANOMALY_PER_VEHICLE; return excluded ? mileage : mileage + anomaly; } private double mileagePerTrackedVehicle(VehicleTrackMileage row) { int trackedVehicles = row.getTrackedVehicles() == null ? 0 : row.getTrackedVehicles(); return trackedVehicles <= 0 ? -1.0 : effectiveMileage(row) / trackedVehicles; } private byte[] buildCityWorkbook(List rows) throws IOException { try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { XSSFSheet sheet = workbook.createSheet(SHEET_NAME); sheet.setDisplayGridlines(false); sheet.createFreezePane(0, 1); Styles styles = createStyles(workbook); XSSFRow header = sheet.createRow(0); header.setHeightInPoints(30); for (int i = 0; i < COLUMN_COUNT; i++) { XSSFCell cell = header.createCell(i); cell.setCellValue(HEADERS[i]); cell.setCellStyle(styles.header); } for (int i = 0; i < rows.size(); i++) { DistributionRow item = rows.get(i); XSSFRow row = sheet.createRow(i + 1); row.setHeightInPoints(24); setText(row, 0, item.city, styles.text); setText(row, 1, item.enterpriseName, styles.text); setNumber(row, 2, item.tractorCount(), styles.count); setNumber(row, 3, item.trailerCount(), styles.count); setNumber(row, 4, item.otherCount(), styles.count); setNumber(row, 5, item.trailerTons(), styles.tonnage); setNumber(row, 6, item.otherTons(), styles.tonnage); setNumber(row, 7, item.effectiveMileage(), styles.mileage); setNumber(row, 8, item.trackedVehicles(), styles.count); } int[] widths = {12, 38, 14, 14, 14, 19, 19, 18, 14}; for (int i = 0; i < widths.length; i++) { sheet.setColumnWidth(i, widths[i] * 256); } workbook.write(output); return output.toByteArray(); } } private Styles createStyles(XSSFWorkbook workbook) { Styles styles = new Styles(); Font headerFont = workbook.createFont(); headerFont.setFontName("SimHei"); headerFont.setFontHeightInPoints((short) 11); headerFont.setBold(true); styles.header = workbook.createCellStyle(); styles.header.setFont(headerFont); styles.header.setAlignment(HorizontalAlignment.CENTER); styles.header.setVerticalAlignment(VerticalAlignment.CENTER); applyBorders(styles.header); Font bodyFont = workbook.createFont(); bodyFont.setFontName("FangSong_GB2312"); bodyFont.setFontHeightInPoints((short) 11); styles.text = bodyStyle(workbook, bodyFont); styles.text.setAlignment(HorizontalAlignment.LEFT); styles.count = bodyStyle(workbook, bodyFont); styles.count.setAlignment(HorizontalAlignment.RIGHT); styles.count.setDataFormat(workbook.createDataFormat().getFormat("#,##0")); styles.tonnage = bodyStyle(workbook, bodyFont); styles.tonnage.setAlignment(HorizontalAlignment.RIGHT); styles.tonnage.setDataFormat(workbook.createDataFormat().getFormat("#,##0.000")); styles.mileage = bodyStyle(workbook, bodyFont); styles.mileage.setAlignment(HorizontalAlignment.RIGHT); styles.mileage.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00")); return styles; } private XSSFCellStyle bodyStyle(XSSFWorkbook workbook, Font font) { XSSFCellStyle style = workbook.createCellStyle(); style.setFont(font); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setWrapText(false); applyBorders(style); return style; } private void applyBorders(XSSFCellStyle style) { short color = org.apache.poi.ss.usermodel.IndexedColors.GREY_25_PERCENT.getIndex(); style.setBorderTop(BorderStyle.THIN); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setTopBorderColor(color); style.setBottomBorderColor(color); style.setLeftBorderColor(color); style.setRightBorderColor(color); } private void setText(XSSFRow row, int column, String value, XSSFCellStyle style) { XSSFCell cell = row.createCell(column); cell.setCellValue(value == null ? "" : value); cell.setCellStyle(style); } private void setNumber(XSSFRow row, int column, Number value, XSSFCellStyle style) { XSSFCell cell = row.createCell(column); cell.setCellValue(value == null ? 0.0 : value.doubleValue()); cell.setCellStyle(style); } private String fileName(String period, String city) { return displayMonth(period) + "规上企业车辆数及轨迹_" + city + ".xlsx"; } private String displayMonth(String period) { return period.substring(0, 4) + "年" + Integer.parseInt(period.substring(5, 7)) + "月"; } private 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 String normalizeEnterpriseName(String value) { return value == null ? "" : value.replaceAll("\\s+", "").trim(); } private String text(Object value) { return value == null ? "" : String.valueOf(value).trim(); } private double value(Double value) { return value == null ? 0.0 : value; } private final class DistributionRow { private final String city; private final String enterpriseName; private final TransportAuthVehicle auth; private final VehicleTrackMileage track; private DistributionRow(String city, String enterpriseName, TransportAuthVehicle auth, VehicleTrackMileage track) { this.city = city; this.enterpriseName = enterpriseName; this.auth = auth; this.track = track; } private int tractorCount() { return auth == null || auth.getTractorCount() == null ? 0 : auth.getTractorCount(); } private int trailerCount() { return auth == null || auth.getTrailerCount() == null ? 0 : auth.getTrailerCount(); } private int otherCount() { return auth == null || auth.getOtherCount() == null ? 0 : auth.getOtherCount(); } private double trailerTons() { return auth == null || auth.getTrailerTons() == null ? 0.0 : auth.getTrailerTons(); } private double otherTons() { return auth == null || auth.getOtherTons() == null ? 0.0 : auth.getOtherTons(); } private double effectiveMileage() { return TrackMileageCityDistributionService.this.effectiveMileage(track); } private int trackedVehicles() { return track == null || track.getTrackedVehicles() == null ? 0 : track.getTrackedVehicles(); } } private static final class Styles { private XSSFCellStyle header; private XSSFCellStyle text; private XSSFCellStyle count; private XSSFCellStyle tonnage; private XSSFCellStyle mileage; } }