xyc
2026-11-11 5e9f38f4b1807f862d11a4979efac672724fd5ef
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
395
396
397
package com.trafficaudit.dataimport.service;
 
import com.trafficaudit.common.util.RegionUtil;
import com.trafficaudit.dataimport.entity.H202FreightVehicleOwnership;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
 
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * Strict parser for the transport authority H202 workbook.
 * Excel numbers are read from the raw XLSX decimal text before BigDecimal.
 */
public final class H202WorkbookParser {
    public static final String TYPE_LABEL = "\u516c\u8def\u8d27\u7269\u8425\u8fd0\u8f66\u8f86\u62e5\u6709\u60c5\u51b5(H202)";
    public static final String SHEET_NAME = "RP_JTB_FreightVehicle";
    private static final String TITLE = "\u516c\u8def\u8d27\u7269\u8425\u8fd0\u8f66\u8f86\u62e5\u6709\u60c5\u51b5";
    private static final ThreadLocal<DataFormatter> FORMATTER = new ThreadLocal<DataFormatter>() {
        @Override
        protected DataFormatter initialValue() {
            return new DataFormatter();
        }
    };
    private static final Pattern FILE_REGION = Pattern.compile(
        "^RP_JTB_FreightVehicle_(.+?)\\.xlsx$", Pattern.CASE_INSENSITIVE);
    private static final Pattern DATE_PATTERN = Pattern.compile(
        "(\\d{4})\\s*[/.-]\\s*(\\d{1,2})\\s*[/.-]\\s*(\\d{1,2})");
    private static final String[] COLUMN_LABELS = {
        "\u603b\u8ba1", "\u4e2a\u4f53", "\u5927\u578b", "\u5927\u578b-\u91cd\u578b",
        "\u5927\u578b-\u91cd\u578b-\u4e2a\u4f53", "\u5927\u578b-\u4e2a\u4f53", "\u4e2d\u578b",
        "\u4e2d\u578b-\u4e2a\u4f53", "\u5c0f\u578b", "\u5c0f\u578b-\u4e2a\u4f53"
    };
 
    private H202WorkbookParser() {
    }
 
    public static ParsedWorkbook parse(Workbook workbook, String fileName, String reportPeriod) {
        if (workbook == null) {
            throw new IllegalArgumentException("\u672a\u63d0\u4f9b H202 \u5de5\u4f5c\u7c3f");
        }
        Sheet sheet = workbook.getSheet(SHEET_NAME);
        if (sheet == null) {
            throw new IllegalArgumentException(TYPE_LABEL + " \u4e0e\u6587\u4ef6\u5185\u5bb9\u4e0d\u7b26\uff1a\u672a\u627e\u5230 sheet\u3010"
                + SHEET_NAME + "\u3011");
        }
        Row titleRow = sheet.getRow(1);
        String title = text(titleRow == null ? null : titleRow.getCell(0));
        if (!TITLE.equals(title)) {
            throw new IllegalArgumentException(TYPE_LABEL + " \u4e0e\u6587\u4ef6\u5185\u5bb9\u4e0d\u7b26\uff1aA2 \u5e94\u4e3a\u3010"
                + TITLE + "\u3011\uff0c\u5b9e\u9645\u4e3a\u3010" + title + "\u3011");
        }
        validateHeaders(sheet);
        String regionName = regionFromFileName(fileName);
        Row metaRow = sheet.getRow(2);
        LocalDate reportDate = parseReportDate(metaRow == null ? null : metaRow.getCell(11));
        if (reportDate == null) {
            throw new IllegalArgumentException("\u672a\u8bfb\u53d6\u5230\u62a5\u8868\u65e5\u671f\uff0c\u8bf7\u68c0\u67e5 L3 \u5355\u5143\u683c\uff1a\u5e94\u4e3a\u300c\u62a5\u8868\u65e5\u671f\uff1a2026/9/30\u300d");
        }
        String reportMonth = String.format("%04d-%02d", reportDate.getYear(), reportDate.getMonthValue());
        if (reportPeriod == null || !reportPeriod.matches("\\d{4}-\\d{2}")) {
            throw new IllegalArgumentException("\u62a5\u8868\u671f\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c\u5e94\u4e3a yyyy-MM");
        }
        if (!reportPeriod.equals(reportMonth)) {
            throw new IllegalArgumentException("\u6587\u4ef6\u62a5\u8868\u65e5\u671f " + reportDate
                + " \u4e0e\u6240\u9009\u62a5\u8868\u671f " + reportPeriod + " \u4e0d\u4e00\u81f4");
        }
 
        List<H202FreightVehicleOwnership> rows = new ArrayList<H202FreightVehicleOwnership>();
        Set<String> seenCodes = new LinkedHashSet<String>();
        String currentItemName = null;
        for (int rowIndex = 8; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                continue;
            }
            String code = normalizeCode(text(row.getCell(2)));
            boolean hasValue = hasAnyValue(row);
            if (code.isEmpty()) {
                if (hasValue) {
                    throw new IllegalArgumentException("\u7b2c " + (rowIndex + 1)
                        + " \u884c\u6709\u6570\u503c\u4f46\u6307\u6807\u4ee3\u7801\u4e3a\u7a7a");
                }
                continue;
            }
            if (!code.matches("\\d{2}")) {
                throw new IllegalArgumentException("\u7b2c " + (rowIndex + 1)
                    + " \u884c\u6307\u6807\u4ee3\u7801\u4e0d\u5408\u6cd5\uff1a" + code);
            }
            if (!seenCodes.add(code)) {
                throw new IllegalArgumentException("\u6307\u6807\u4ee3\u7801 " + code + " \u5728\u7b2c "
                    + (rowIndex + 1) + " \u884c\u91cd\u590d");
            }
            String sourceName = text(row.getCell(0));
            if (!sourceName.isEmpty()) {
                currentItemName = sourceName;
            }
            if (currentItemName == null || currentItemName.isEmpty()) {
                throw new IllegalArgumentException("\u7b2c " + (rowIndex + 1)
                    + " \u884c\u6307\u6807\u540d\u79f0\u4e3a\u7a7a\uff0c\u4e14\u65e0\u4e0a\u65b9\u6307\u6807\u540d\u53ef\u7ee7\u627f");
            }
 
            H202FreightVehicleOwnership entity = new H202FreightVehicleOwnership();
            entity.setReportPeriod(reportPeriod);
            entity.setRegionName(regionName);
            entity.setReportDate(reportDate);
            entity.setItemCode(code);
            entity.setItemName(currentItemName);
            entity.setUnit(text(row.getCell(1)));
            entity.setSourceFileName(fileName);
            entity.setTotalValue(decimal(row, 3));
            entity.setIndividualValue(decimal(row, 4));
            entity.setLargeValue(decimal(row, 5));
            entity.setLargeHeavyValue(decimal(row, 6));
            entity.setLargeHeavyIndividualValue(decimal(row, 7));
            entity.setLargeIndividualValue(decimal(row, 8));
            entity.setMediumValue(decimal(row, 9));
            entity.setMediumIndividualValue(decimal(row, 10));
            entity.setSmallValue(decimal(row, 11));
            entity.setSmallIndividualValue(decimal(row, 12));
            rows.add(entity);
        }
 
        validateContiguousCodes(seenCodes);
        recomputeTotals(rows);
        return new ParsedWorkbook(regionName, reportDate, rows);
    }
 
    private static void validateContiguousCodes(Set<String> seenCodes) {
        int expected = 1;
        for (String code : seenCodes) {
            String expectedCode = String.format("%02d", expected);
            if (!expectedCode.equals(code)) {
                throw new IllegalArgumentException("H202 \u6307\u6807\u4ee3\u7801\u5fc5\u987b\u4ece 01 \u5f00\u59cb\u8fde\u7eed\uff1a"
                    + "\u671f\u671b " + expectedCode + "\uff0c\u5b9e\u9645 " + code);
            }
            expected++;
        }
        if (expected <= 2) {
            throw new IllegalArgumentException("H202 \u6307\u6807\u4ee3\u7801\u4e0d\u5b8c\u6574");
        }
    }
 
    private static void recomputeTotals(List<H202FreightVehicleOwnership> rows) {
        H202FreightVehicleOwnership vehicleTotal = requireCode(rows, "01", "\u603b\u8ba1", "\u8f86");
        H202FreightVehicleOwnership tonnageTotal = requireCode(rows, "02", "\u603b\u8ba1", "\u5428\u4f4d");
        H202FreightVehicleOwnership truckVehicle = requireItem(rows, "1.\u8d27\u8f66", "\u8f86");
        H202FreightVehicleOwnership tractorVehicle = requireItem(rows, "2.\u7275\u5f15\u8f66", "\u8f86");
        H202FreightVehicleOwnership trailerVehicle = requireItem(rows, "3.\u6302\u8f66", "\u8f86");
        H202FreightVehicleOwnership otherVehicle = requireItem(rows, "\u4e8c\u3001\u5176\u5b83\u8f7d\u8d27\u673a\u52a8\u8f66", "\u8f86");
        H202FreightVehicleOwnership truckTonnage = requireItem(rows, "1.\u8d27\u8f66", "\u5428\u4f4d");
        H202FreightVehicleOwnership trailerTonnage = requireItem(rows, "3.\u6302\u8f66", "\u5428\u4f4d");
        H202FreightVehicleOwnership otherTonnage = requireItem(rows, "\u4e8c\u3001\u5176\u5b83\u8f7d\u8d27\u673a\u52a8\u8f66", "\u5428\u4f4d");
 
        vehicleTotal.setTotalValue(addRequired(vehicleTotal,
            new H202FreightVehicleOwnership[]{truckVehicle, tractorVehicle, trailerVehicle, otherVehicle}));
        tonnageTotal.setTotalValue(addRequired(tonnageTotal,
            new H202FreightVehicleOwnership[]{truckTonnage, trailerTonnage, otherTonnage}));
    }
 
    private static H202FreightVehicleOwnership requireCode(List<H202FreightVehicleOwnership> rows,
                                                           String code, String itemName, String unit) {
        H202FreightVehicleOwnership found = null;
        for (H202FreightVehicleOwnership row : rows) {
            if (!code.equals(row.getItemCode())) {
                continue;
            }
            if (found != null) {
                throw new IllegalArgumentException("H202 \u6307\u6807\u4ee3\u7801\u91cd\u590d\uff1a" + code);
            }
            found = row;
        }
        if (found == null) {
            throw new IllegalArgumentException("H202 \u7f3a\u5c11\u603b\u8ba1\u6307\u6807\uff1a" + code);
        }
        if (!itemName.equals(found.getItemName()) || !unit.equals(found.getUnit())) {
            throw new IllegalArgumentException("H202 \u6307\u6807 " + code + " \u7684\u540d\u79f0\u6216\u5355\u4f4d\u4e0d\u7b26\uff1a"
                + found.getItemName() + "/" + found.getUnit());
        }
        return found;
    }
 
    private static H202FreightVehicleOwnership requireItem(List<H202FreightVehicleOwnership> rows,
                                                           String itemName, String unit) {
        H202FreightVehicleOwnership found = null;
        for (H202FreightVehicleOwnership row : rows) {
            if (!itemName.equals(row.getItemName()) || !unit.equals(row.getUnit())) {
                continue;
            }
            if (found != null) {
                throw new IllegalArgumentException("H202 \u5206\u9879\u6307\u6807\u91cd\u590d\uff1a" + itemName + "/" + unit);
            }
            found = row;
        }
        if (found == null) {
            throw new IllegalArgumentException("H202 \u7f3a\u5c11\u5206\u9879\u6307\u6807\uff1a" + itemName + "/" + unit);
        }
        return found;
    }
 
    private static BigDecimal addRequired(H202FreightVehicleOwnership totalRow,
                                          H202FreightVehicleOwnership[] parts) {
        BigDecimal sum = BigDecimal.ZERO;
        for (H202FreightVehicleOwnership part : parts) {
            if (part.getTotalValue() == null) {
                throw new IllegalArgumentException("H202 \u5206\u9879\u603b\u8ba1\u4e3a\u7a7a\uff0c\u65e0\u6cd5\u91cd\u7b97\uff1a"
                    + part.getItemCode() + " " + part.getItemName() + "/" + part.getUnit());
            }
            sum = sum.add(part.getTotalValue());
        }
        if (sum.scale() < 0) {
            sum = sum.setScale(0);
        }
        return sum.stripTrailingZeros();
    }
 
    public static String regionFromFileName(String fileName) {
        if (fileName == null) {
            throw new IllegalArgumentException("\u6587\u4ef6\u540d\u4e3a\u7a7a\uff0c\u65e0\u6cd5\u8bc6\u522b\u5730\u533a");
        }
        String baseName = new java.io.File(fileName).getName();
        Matcher matcher = FILE_REGION.matcher(baseName);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("\u6587\u4ef6\u540d\u4e0d\u7b26\u5408 H202 \u547d\u540d\u89c4\u5219\uff1aRP_JTB_FreightVehicle_\u5730\u533a.xlsx");
        }
        String region = RegionUtil.normalizeCityName(matcher.group(1));
        if (!"\u6e56\u5317\u7701".equals(region) && !RegionUtil.CITY_LIST.contains(region)) {
            throw new IllegalArgumentException("\u65e0\u6cd5\u4ece\u6587\u4ef6\u540d\u8bc6\u522b\u6e56\u5317\u7701\u6216 17 \u4e2a\u5e02\u5dde\uff1a"
                + matcher.group(1));
        }
        return region;
    }
 
    private static void validateHeaders(Sheet sheet) {
        Row header = sheet.getRow(4);
        String[] expected = {"\u6307\u6807\u540d\u79f0", "\u8ba1\u91cf", "\u4ee3\u7801", "\u603b\u8ba1", "\u4e2a\u4f53",
            "\u5927\u578b", "", "", "", "\u4e2d\u578b", "", "\u5c0f\u578b", ""};
        for (int col = 0; col < expected.length; col++) {
            if (expected[col].isEmpty()) {
                continue;
            }
            String actual = text(header == null ? null : header.getCell(col));
            if (!expected[col].equals(actual)) {
                throw new IllegalArgumentException(TYPE_LABEL + " \u8868\u5934\u4e0e\u6a21\u677f\u4e0d\u4e00\u81f4\uff1a"
                    + CellReference.convertNumToColString(col) + "5 \u5e94\u4e3a\u3010" + expected[col]
                    + "\u3011\uff0c\u5b9e\u9645\u4e3a\u3010" + actual + "\u3011");
            }
        }
    }
 
    private static boolean hasAnyValue(Row row) {
        for (int col = 3; col <= 12; col++) {
            Cell cell = row.getCell(col);
            if (cell == null || cell.getCellType() == CellType.BLANK) {
                continue;
            }
            String value = text(cell);
            if (!value.isEmpty() && !isDash(value)) {
                return true;
            }
        }
        return false;
    }
 
    private static BigDecimal decimal(Row row, int col) {
        Cell cell = row.getCell(col);
        String label = COLUMN_LABELS[col - 3];
        String itemName = text(row.getCell(0));
        if (itemName.isEmpty() && row.getRowNum() > 0) {
            itemName = text(row.getSheet().getRow(row.getRowNum() - 1).getCell(0));
        }
        String context = "\u7b2c " + (row.getRowNum() + 1) + " \u884c " + CellReference.convertNumToColString(col)
            + " \u5217\u300c" + label + "\u300d" + (itemName.isEmpty() ? "" : "\uff08" + itemName + "\uff09");
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            return null;
        }
        CellType type = cell.getCellType();
        if (type == CellType.FORMULA) {
            throw new IllegalArgumentException(context
                + "\u4e0d\u652f\u6301\u516c\u5f0f\uff0c\u8bf7\u5c06\u5176\u8f6c\u4e3a\u6570\u503c\u6216\u6587\u672c\u540e\u518d\u5bfc\u5165");
        }
        if (type == CellType.NUMERIC) {
            return parseDecimal(rawNumericText(cell, context), context);
        }
        if (type == CellType.STRING) {
            return parseDecimal(cell.getStringCellValue(), context);
        }
        throw new IllegalArgumentException(context + "\u4e0d\u662f\u6709\u6548\u6570\u5b57\uff1a" + text(cell));
    }
 
    private static BigDecimal parseDecimal(String raw, String context) {
        if (raw == null) {
            return null;
        }
        String value = raw.trim();
        if (value.isEmpty() || isDash(value)) {
            return null;
        }
        String compact = value.replace(",", "").replace("\u00a0", "").replace(" ", "");
        BigDecimal decimal;
        try {
            decimal = new BigDecimal(compact).stripTrailingZeros();
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(context + "\u4e0d\u662f\u6709\u6548\u6570\u5b57\uff1a" + value, e);
        }
        if (decimal.scale() < 0) {
            decimal = decimal.setScale(0);
        }
        if (decimal.scale() > 15 || decimal.precision() - decimal.scale() > 15) {
            throw new IllegalArgumentException(context + "\u8d85\u51fa DECIMAL(30,15) \u8303\u56f4\uff1a" + value);
        }
        return decimal;
    }
 
    private static String rawNumericText(Cell cell, String context) {
        if (!(cell instanceof XSSFCell)) {
            throw new IllegalArgumentException(context + "\u4ec5\u652f\u6301 .xlsx \u539f\u59cb\u6570\u503c\uff0c\u8bf7\u53e6\u5b58\u4e3a .xlsx");
        }
        String raw = ((XSSFCell) cell).getRawValue();
        if (raw == null || raw.trim().isEmpty()) {
            throw new IllegalArgumentException(context + "\u672a\u8bfb\u53d6\u5230\u539f\u59cb\u6570\u503c");
        }
        return raw;
    }
 
    private static LocalDate parseReportDate(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            return cell.getLocalDateTimeCellValue().toLocalDate();
        }
        String value = text(cell);
        Matcher matcher = DATE_PATTERN.matcher(value);
        if (!matcher.find()) {
            return null;
        }
        return LocalDate.of(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)),
            Integer.parseInt(matcher.group(3)));
    }
 
    private static boolean isDash(String value) {
        return "-".equals(value) || "\u2014".equals(value) || "\u2013".equals(value);
    }
 
    private static String normalizeCode(String value) {
        String code = value == null ? "" : value.trim();
        if (code.matches("\\d")) {
            return "0" + code;
        }
        return code;
    }
 
    private static String text(Cell cell) {
        if (cell == null) {
            return "";
        }
        return FORMATTER.get().formatCellValue(cell).trim();
    }
 
    public static final class ParsedWorkbook {
        private final String regionName;
        private final LocalDate reportDate;
        private final List<H202FreightVehicleOwnership> rows;
 
        ParsedWorkbook(String regionName, LocalDate reportDate, List<H202FreightVehicleOwnership> rows) {
            this.regionName = regionName;
            this.reportDate = reportDate;
            this.rows = rows;
        }
 
        public String getRegionName() {
            return regionName;
        }
 
        public LocalDate getReportDate() {
            return reportDate;
        }
 
        public List<H202FreightVehicleOwnership> getRows() {
            return rows;
        }
    }
}