xyc
2 小时以前 5b41c8896ef7850be2672e45b69bb58e149729ec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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<Map<String, Object>> 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<String, TransportAuthVehicle> authByName = loadAuthByName(normalizedPeriod);
        Map<String, List<VehicleTrackMileage>> trackByName = loadTrackByName(normalizedPeriod);
 
        Map<String, List<DistributionRow>> rowsByCity = new LinkedHashMap<>();
        for (String city : RegionUtil.cityList()) {
            rowsByCity.put(city, new ArrayList<>());
        }
 
        for (Map<String, Object> 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<DistributionRow> byName =
                (a, b) -> collator.compare(a.enterpriseName, b.enterpriseName);
        for (List<DistributionRow> 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<String, TransportAuthVehicle> loadAuthByName(String period) {
        List<TransportAuthVehicle> rows = transportAuthVehicleMapper.selectList(
                new LambdaQueryWrapper<TransportAuthVehicle>()
                        .eq(TransportAuthVehicle::getReportPeriod, period)
                        .orderByDesc(TransportAuthVehicle::getId));
        Map<String, TransportAuthVehicle> 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<String, List<VehicleTrackMileage>> loadTrackByName(String period) {
        List<VehicleTrackMileage> rows = vehicleTrackMileageMapper.selectList(
                new LambdaQueryWrapper<VehicleTrackMileage>()
                        .eq(VehicleTrackMileage::getReportPeriod, period)
                        .eq(VehicleTrackMileage::getEnterpriseCategory, VehicleTrackMileage.CATEGORY_ABOVE_SCALE)
                        .orderByDesc(VehicleTrackMileage::getId));
        Map<String, List<VehicleTrackMileage>> 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<VehicleTrackMileage> 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<VehicleTrackMileage> 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<DistributionRow> 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;
    }
}