xyc
9 小时以前 1c9505d00bd076898cdc5a7d916106e175a91119
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
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<FreightForecastBaseMonth> importBase(MultipartFile file, int statYear) throws Exception {
        validateYear(statYear);
        String fileName = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().trim();
        List<FreightForecastBaseMonth> rows = FreightForecastBaseParser.parse(
                file.getInputStream(), statYear, fileName.length() > 255 ? fileName.substring(0, 255) : fileName);
        baseMapper.delete(new LambdaQueryWrapper<FreightForecastBaseMonth>()
                .eq(FreightForecastBaseMonth::getStatYear, statYear));
        for (FreightForecastBaseMonth row : rows) {
            row.setCreatedAt(LocalDateTime.now());
            row.setUpdatedAt(LocalDateTime.now());
            baseMapper.insert(row);
        }
        return rows;
    }
 
    public Map<String, Object> aboveHistory(int statYear, String period) {
        validateYear(statYear);
        String normalizedPeriod = normalizePeriod(period);
        FreightForecastAboveHistory latest = latestHistory(statYear, normalizedPeriod);
        if (latest == null) {
            Map<String, Object> empty = new LinkedHashMap<>();
            empty.put("available", false);
            empty.put("statYear", statYear);
            empty.put("requestedPeriod", normalizedPeriod);
            return empty;
        }
        return aboveHistorySummary(statYear, latest.getThroughPeriod());
    }
 
    private Map<String, Object> aboveHistorySummary(int statYear, String throughPeriod) {
        List<FreightForecastAboveHistory> rows = historyRows(statYear, throughPeriod);
        double sourceTotal = FreightForecastAboveHistoryValues.cumulativeTotal(rows);
        double correctedTotal = rows.stream()
                .mapToDouble(row -> value(row.getSourceCumulativeForecast())).sum();
        List<Map<String, Object>> corrections = new ArrayList<>();
        for (FreightForecastAboveHistory row : rows) {
            if (!Boolean.TRUE.equals(row.getCorrected())) continue;
            Map<String, Object> 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<String, Object> 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<FreightForecastBaseMonth> baseMonths(int statYear) {
        validateYear(statYear);
        return baseMapper.selectList(new LambdaQueryWrapper<FreightForecastBaseMonth>()
                .eq(FreightForecastBaseMonth::getStatYear, statYear)
                .orderByAsc(FreightForecastBaseMonth::getReportMonth));
    }
 
    @Transactional
    public Map<String, Object> calculateAbove(String period) {
        return calculateAboveInternal(normalizePeriod(period));
    }
 
    private Map<String, Object> calculateAboveInternal(String period) {
        int year = Integer.parseInt(period.substring(0, 4));
        List<Map<String, Object>> registerRows = annualEnterprises(year);
        if (registerRows.isEmpty()) {
            throw new IllegalArgumentException(year + "年规上企业名录为空,不能测算规上周转量");
        }
        Map<String, TransportAuthVehicle> authByName = loadAuth(period);
        Map<String, List<VehicleTrackMileage>> trackByName = loadTracks(period);
        Set<String> mandatoryCitySources = trackCitySourceRuleService.mandatoryCities(period);
 
        aboveMapper.delete(new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                .eq(FreightForecastAboveEnterprise::getReportPeriod, period));
 
        int missingAuth = 0;
        int missingTrack = 0;
        int noMileage = 0;
        double total = 0.0;
        Set<String> cities = new HashSet<>();
        for (Map<String, Object> 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<String, Object> 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<FreightForecastAboveEnterprise> aboveRows(String period, String city, String keyword) {
        String normalized = normalizePeriod(period);
        LambdaQueryWrapper<FreightForecastAboveEnterprise> wrapper =
                new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                        .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<FreightForecastBaseMonth>()
                        .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<FreightForecastBelowResult>()
                        .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<FreightForecastBelowResult> belowResults(String period) {
        String normalized = normalizePeriod(period);
        List<FreightForecastBelowResult> rows = belowMapper.selectList(
                new LambdaQueryWrapper<FreightForecastBelowResult>()
                        .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<String, String> annualCities = annualCityMap(year);
        if (annualCities.isEmpty()) {
            throw new IllegalArgumentException(year + "年规上企业名录为空,无法匹配货运月报企业");
        }
        List<FreightForecastReportRow> 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<FreightForecastReportRound>()
                        .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<FreightForecastReportRound> reportRounds(String period) {
        String normalized = normalizePeriod(period);
        return roundMapper.selectList(new LambdaQueryWrapper<FreightForecastReportRound>()
                .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<String, ReportValue> currentRoundValues = h2032Values(normalizedPeriod, year);
        if (currentRoundValues.isEmpty()) {
            throw new IllegalArgumentException("当前报表期没有 H2032 企业月报数据");
        }
 
        List<FreightForecastAboveEnterprise> currentForecastRows = aboveMapper.selectList(
                new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                        .eq(FreightForecastAboveEnterprise::getReportPeriod, normalizedPeriod));
        if (currentForecastRows.isEmpty()) {
            throw new IllegalArgumentException("当前报表期尚未完成规上测算,请先在“规上测算”页执行测算");
        }
 
        Map<Integer, Map<String, ReportValue>> reportSeries = new LinkedHashMap<>();
        Map<Integer, String> reportSourceLabels = new LinkedHashMap<>();
        List<String> missingReportMonths = new ArrayList<>();
        for (int m = 1; m <= month; m++) {
            String p = year + "-" + two(m);
            Map<String, ReportValue> 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<Integer, List<FreightForecastAboveEnterprise>> forecastSeries = new LinkedHashMap<>();
        for (int m = 1; m <= month; m++) {
            String p = year + "-" + two(m);
            List<FreightForecastAboveEnterprise> rows = m == month ? currentForecastRows
                    : aboveMapper.selectList(new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                    .eq(FreightForecastAboveEnterprise::getReportPeriod, p));
            forecastSeries.put(m, rows);
        }
 
        FreightForecastAboveHistory latestHistory = null;
        List<FreightForecastAboveHistory> 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<Integer, Double> belowTurnoverSeries = new LinkedHashMap<>();
        Map<Integer, String> belowSourceLabels = new LinkedHashMap<>();
        List<String> 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<Integer, Map<String, Double>> lastYearReportByCity = h2032SeriesByCity(year - 1, month);
        Map<Integer, Map<String, Double>> lastYearReportAll = h2032SeriesAll(year - 1, month);
        List<FreightForecastBaseMonth> 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<String, Double> lastYearCurrentMonth = lastYearReportByCity.getOrDefault(month, Collections.emptyMap());
        double lastYearMonthlyReport = sumValues(lastYearCurrentMonth);
        analysis.setMonthlyReportYoy(ratio(monthlyReport, lastYearMonthlyReport));
 
        Map<String, Double> 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<FreightForecastAboveEnterprise> 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<String, Double> cumulativeReportByCity = new LinkedHashMap<>();
        for (int m = 1; m <= month; m++) {
            Map<String, ReportValue> values = reportSeries.get(m);
            cumulativeReport += sumReport(values);
            merge(cumulativeReportByCity, cityReport(values));
        }
 
        double cumulativeForecast = 0.0;
        Map<String, Double> cumulativeForecastByCity = new LinkedHashMap<>();
        List<String> 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<FreightForecastAboveEnterprise> 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<String, Double> 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<String, Double> currentForecastByCity = cityForecast(currentForecastRows);
        Map<String, Double> currentReportByCity = cityReport(currentRoundValues);
        Map<String, Double> 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<String, Object> overview(String period) {
        String normalized = normalizePeriod(period);
        int year = Integer.parseInt(normalized.substring(0, 4));
        int month = Integer.parseInt(normalized.substring(5, 7));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("period", normalized);
        result.put("baseMonths", baseMapper.selectCount(new LambdaQueryWrapper<FreightForecastBaseMonth>()
                .eq(FreightForecastBaseMonth::getStatYear, year)));
        result.put("aboveRows", aboveMapper.selectCount(new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                .eq(FreightForecastAboveEnterprise::getReportPeriod, normalized)));
        result.put("belowRows", belowMapper.selectCount(new LambdaQueryWrapper<FreightForecastBelowResult>()
                .eq(FreightForecastBelowResult::getReportPeriod, normalized)));
        result.put("auditRounds", roundMapper.selectCount(new LambdaQueryWrapper<FreightForecastReportRound>()
                .eq(FreightForecastReportRound::getReportPeriod, normalized)
                .eq(FreightForecastReportRound::getReportStage, STAGE_AUDIT)));
        result.put("finalRounds", roundMapper.selectCount(new LambdaQueryWrapper<FreightForecastReportRound>()
                .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<String> missingForecast = new ArrayList<>();
        for (int m = startMonth; m <= month; m++) {
            String p = year + "-" + two(m);
            List<FreightForecastAboveEnterprise> rows = aboveMapper.selectList(
                    new LambdaQueryWrapper<FreightForecastAboveEnterprise>()
                            .eq(FreightForecastAboveEnterprise::getReportPeriod, p));
            if (!isValidForecastSnapshot(rows)) missingForecast.add(p);
        }
        result.put("missingForecastMonths", missingForecast);
        return result;
    }
 
    private List<FreightForecastAnalysis.CityRow> buildCityRows(
            int month, Map<String, Double> currentForecast, Map<String, Double> currentReport,
            Map<String, Double> previousForecast, Map<String, Double> previousReport,
            Map<String, Double> cumulativeForecastByCity, Map<String, Double> cumulativeReportByCity,
            Map<String, Double> lastYearCumulativeCity,
            Map<Integer, Map<String, Double>> lastYearReportByCity) {
        Map<String, Double> lastYearMonth = lastYearReportByCity.getOrDefault(month, Collections.emptyMap());
 
        List<FreightForecastAnalysis.CityRow> 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<FreightForecastAnalysis.EnterpriseRow> buildEnterpriseRows(
            int year, FreightForecastReportRound round,
            Map<String, ReportValue> reportValues,
            List<FreightForecastAboveEnterprise> forecastRows) {
        Map<String, String> annualCities = annualCityMap(year);
        Map<String, FreightForecastAboveEnterprise> forecastByName = new LinkedHashMap<>();
        for (FreightForecastAboveEnterprise row : forecastRows) {
            forecastByName.put(normalizeName(row.getEnterpriseName()), row);
        }
        Set<String> names = new HashSet<>();
        names.addAll(annualCities.keySet());
        names.addAll(forecastByName.keySet());
        names.addAll(reportValues.keySet());
 
        List<FreightForecastAnalysis.EnterpriseRow> 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<Integer, String> reportLabels,
                                 Map<Integer, String> belowLabels, List<FreightForecastBaseMonth> baseMonths,
                                 String forecastSource, FreightForecastAboveHistory latestHistory,
                                 List<FreightForecastAboveHistory> historyRows) {
        String currentPeriod = year + "-" + two(month);
        analysis.getSources().add(new FreightForecastAnalysis.SourceCoverage(
                "当月规上上报", stageLabel(round.getReportStage()) + "第" + round.getRevisionNo() + "版("
                        + nullToEmpty(round.getFileName()) + ")", currentPeriod, round.getRowCount(),
                "审核过程可多次导入,定稿版本单独留存"));
        Set<String> 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<String> 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<String, ReportValue> h2032Values(String period, int year) {
        List<H2032EnterpriseMonthly> rows = h2032Mapper.selectList(
                new LambdaQueryWrapper<H2032EnterpriseMonthly>()
                        .eq(H2032EnterpriseMonthly::getReportPeriod, period));
        if (rows.isEmpty()) return Collections.emptyMap();
        Map<String, String> annualCities = annualCityMap(year);
        Map<String, ReportValue> 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<Integer, Map<String, Double>> h2032SeriesByCity(int year, int lastMonth) {
        Map<Integer, Map<String, Double>> result = new LinkedHashMap<>();
        for (int m = 1; m <= lastMonth; m++) {
            List<H2032EnterpriseMonthly> rows = h2032Mapper.selectList(
                    new LambdaQueryWrapper<H2032EnterpriseMonthly>()
                            .eq(H2032EnterpriseMonthly::getReportPeriod, year + "-" + two(m)));
            Map<String, Double> 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<Integer, Map<String, Double>> h2032SeriesAll(int year, int lastMonth) {
        Map<Integer, Map<String, Double>> result = new LinkedHashMap<>();
        for (int m = 1; m <= lastMonth; m++) {
            List<H2032EnterpriseMonthly> rows = h2032Mapper.selectList(
                    new LambdaQueryWrapper<H2032EnterpriseMonthly>()
                            .eq(H2032EnterpriseMonthly::getReportPeriod, year + "-" + two(m)));
            Map<String, Double> 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<FreightForecastReportRound>()
                .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<FreightForecastAboveHistory>()
                .eq(FreightForecastAboveHistory::getStatYear, statYear)
                .le(FreightForecastAboveHistory::getThroughPeriod, throughPeriod)
                .orderByDesc(FreightForecastAboveHistory::getThroughPeriod)
                .last("LIMIT 1"));
    }
 
    private List<FreightForecastAboveHistory> historyRows(int statYear, String throughPeriod) {
        return historyMapper.selectList(new LambdaQueryWrapper<FreightForecastAboveHistory>()
                .eq(FreightForecastAboveHistory::getStatYear, statYear)
                .eq(FreightForecastAboveHistory::getThroughPeriod, throughPeriod)
                .orderByAsc(FreightForecastAboveHistory::getCity)
                .orderByAsc(FreightForecastAboveHistory::getEnterpriseName));
    }
 
    private static boolean isValidForecastSnapshot(List<FreightForecastAboveEnterprise> 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<FreightForecastAboveEnterprise> rows) {
        if (!isValidForecastSnapshot(rows)) {
            throw new IllegalArgumentException("规上测算快照无效:" + period
                    + "为空、全零或全部缺少运政/轨迹数据,不能进入累计差异分析");
        }
    }
 
    private FreightForecastBelowResult preferredBelowTurnoverResult(String period) {
        List<FreightForecastBelowResult> rows = belowMapper.selectList(
                new LambdaQueryWrapper<FreightForecastBelowResult>()
                        .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<ScaleSplitTransport> rows = scaleSplitMapper.selectList(
                new LambdaQueryWrapper<ScaleSplitTransport>()
                        .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<Map<String, Object>> annualEnterprises(int year) {
        return jdbcTemplate.queryForList(
                "SELECT enterprise_name, city FROM h2032_enterprise_year WHERE stat_year = ? ORDER BY id", year);
    }
 
    private Map<String, String> annualCityMap(int year) {
        Map<String, String> result = new LinkedHashMap<>();
        for (Map<String, Object> 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<String, TransportAuthVehicle> loadAuth(String period) {
        List<TransportAuthVehicle> rows = authMapper.selectList(
                new LambdaQueryWrapper<TransportAuthVehicle>()
                        .eq(TransportAuthVehicle::getReportPeriod, period)
                        .orderByDesc(TransportAuthVehicle::getId));
        Map<String, TransportAuthVehicle> 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<String, List<VehicleTrackMileage>> loadTracks(String period) {
        List<VehicleTrackMileage> rows = trackMapper.selectList(
                new LambdaQueryWrapper<VehicleTrackMileage>()
                        .eq(VehicleTrackMileage::getReportPeriod, period)
                        .eq(VehicleTrackMileage::getEnterpriseCategory, VehicleTrackMileage.CATEGORY_ABOVE_SCALE)
                        .orderByDesc(VehicleTrackMileage::getId));
        Map<String, List<VehicleTrackMileage>> 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<VehicleTrackMileage> candidates,
                                             Set<String> 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<String, Double> cityForecast(List<FreightForecastAboveEnterprise> rows) {
        Map<String, Double> result = new LinkedHashMap<>();
        for (FreightForecastAboveEnterprise row : rows) {
            result.merge(RegionUtil.normalizeCityName(row.getCity()), value(row.getForecastTurnover()), Double::sum);
        }
        return result;
    }
 
    private Map<String, Double> cityReport(Map<String, ReportValue> values) {
        Map<String, Double> 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<FreightForecastAboveEnterprise> rows) {
        return rows.stream().mapToDouble(x -> value(x.getForecastTurnover())).sum();
    }
 
    private double sumReport(Map<String, ReportValue> values) {
        return values.values().stream().mapToDouble(x -> x.turnover).sum();
    }
 
    private double sumValues(Map<String, Double> values) {
        return values.values().stream().mapToDouble(Double::doubleValue).sum();
    }
 
    private void merge(Map<String, Double> target, Map<String, Double> source) {
        for (Map.Entry<String, Double> 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<String, String> 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;
    }
}