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
<template>
  <el-container direction="vertical">
    <app-header title="交通统计报表审核系统 - 数据导入"></app-header>
    <el-container>
      <el-aside width="200px">
        <el-menu ref="sideMenu" router :default-active="$route.path" @select="onMenuSelect">
          <el-menu-item index="/dashboard">工作台</el-menu-item>
          <el-menu-item index="/import">数据导入</el-menu-item>
          <el-menu-item index="/data">数据查看</el-menu-item>
          <el-menu-item index="/explain">企业解释</el-menu-item>
          <el-menu-item index="/audit">审核结果</el-menu-item>
          <el-menu-item index="/report">报表生成</el-menu-item>
          <el-menu-item index="/rules">规则管理</el-menu-item>
          <el-menu-item index="/users">用户管理</el-menu-item>
</el-menu>
      </el-aside>
      <el-main>
        <div class="page-scroll">
          <h3>导入业务数据</h3>
          <div class="import-layout">
            <div class="import-main">          <el-card shadow="hover" class="import-card" style="margin-bottom:15px">
            <div class="card-head">报表期</div>
            <el-date-picker v-model="period" type="month" placeholder="选择月份" value-format="yyyy-MM"
                            style="width:240px" @change="onPeriodChange"></el-date-picker>
          </el-card>
 
                    
          <el-card shadow="hover" class="import-card" style="margin-bottom:15px">
            <div class="card-head">选择数据类型</div>
            <div class="module-tabs-head">
              <el-radio-group v-model="activeModule" size="small" @change="onModuleSwitch">
                <el-radio-button v-for="g in visibleGroups" :key="g.key" :label="g.key">{{ g.name }}</el-radio-button>
              </el-radio-group>
            </div>
            <div v-for="g in visibleGroups" :key="g.key" v-show="activeModule === g.key" class="module-tab-pane">
              <div class="module-sel">
                                <div class="module-sel-row">
                  <el-select v-model="moduleSel[g.key]" placeholder="选择数据类型" style="width:260px"
                             @change="onModuleChange(g.key)" clearable>
                    <el-option v-for="t in typeList(g)" :key="t.value" :label="t.label" :value="t.value"></el-option>
                  </el-select>
                  <div v-if="importType" class="tpl-box">
                    <span class="tpl-name">模板:{{ templateName }}</span>
                    <el-link v-if="templateUrl" type="primary" icon="el-icon-download" :underline="false"
                             @click="downloadTemplate">下载模板</el-link>
                    <span v-if="importType === 'cityTaxiAuth'" class="slow-tip">该类型约 4 万+ 行,预计耗时 5 分钟左右</span>
                  </div>
                </div>
                <div v-if="isCityDirType(moduleSel[g.key])" class="module-file">
                  <div class="tip">无需选文件:自动扫描 docs/投资/输入/…/{{ period ? Number(period.slice(5)) : 'X' }}月 目录下全部市州报表,逐文件容错解析入库(项目主档+月度,含本月完成/建设阶段/形象进度;十五五项目自动标记)。</div>
                  <el-button size="mini" type="primary" icon="el-icon-upload2" :loading="cityDirLoading"
                             @click="importCityDir(moduleSel[g.key])">从目录批量导入</el-button>
                </div>
                <div v-else-if="moduleSel[g.key] && !isDirOnlyType(moduleSel[g.key])" class="module-file">
                  <div class="file-name" :title="fileNamesText(moduleSel[g.key])">{{ fileNamesText(moduleSel[g.key]) || '未选择文件' }}</div>
                  <div class="file-btns">
                    <el-upload action="#" :auto-upload="false" :show-file-list="false" multiple :accept="acceptOf(moduleSel[g.key])"
                               :ref="'up' + g.key" :on-change="f => onFilePicked(g.key, f)" style="display:inline-block">
                      <el-button size="mini" type="primary" plain icon="el-icon-folder-opened" :disabled="importing">选择文件</el-button>
                    </el-upload>
                    <el-button size="mini" type="primary" icon="el-icon-upload2" :loading="importing" :disabled="importing || !fileCount(moduleSel[g.key])"
                               @click="importNow(g.key)">{{ fileCount(moduleSel[g.key]) > 1 ? '批量导入 ' + fileCount(moduleSel[g.key]) + ' 个文件' : '立即导入' }}</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
 
 
          
 
          
 
                              <el-card shadow="never" style="margin-top:15px" class="batch-card">
            <div slot="header" class="card-head">
              导入结果({{ period || '全部报表期' }})
              <el-button type="text" icon="el-icon-refresh" style="float:right" @click="loadData">刷新</el-button>
            </div>
            <div v-if="failBatches.length" class="tip" style="margin-bottom:6px">共 {{ failBatches.length }} 个批次存在失败数据,失败明细共 {{ failRowsFlat.length }} 条:</div>
            <el-table v-if="failBatches.length" :data="failRowsFlat" border size="small" v-loading="batchLoading" style="width:100%">
              <el-table-column label="导入类型" width="140">
                <template slot-scope="s">{{ typeLabel(s.row.importType) }}</template>
              </el-table-column>
              <el-table-column prop="reportPeriod" label="报表期" width="90"></el-table-column>
              <el-table-column label="文件名" min-width="200" show-overflow-tooltip>
                <template slot-scope="s">{{ s.row.fileName }}</template>
              </el-table-column>
              <el-table-column label="失败位置" width="230">
                <template slot-scope="s"><span v-if="s.row.position">{{ s.row.position }}</span><span v-else>—</span></template>
              </el-table-column>
              <el-table-column label="失败原因" min-width="300">
                <template slot-scope="s">{{ s.row.reason }}</template>
              </el-table-column>
            </el-table>
            <div v-else class="empty-tip">暂无导入失败记录</div>
          </el-card>
            </div>
                        <div class="import-side" :class="{ 'side-open': sideOpen }">
              <div class="side-toggle" @click="sideOpen = !sideOpen" :title="sideOpen ? '收起进度' : '展开进度'">
                <i :class="sideOpen ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"></i>
                <span class="side-toggle-text">{{ sideOpen ? '收起进度' : '导入进度' }}</span>
              </div>
              <div v-show="sideOpen" class="side-content">
                <div class="side-head">
                  <span>本月导入进度({{ period || '未选择报表期' }})</span>
                  <el-button type="text" icon="el-icon-refresh" @click="loadData">刷新</el-button>
                </div>
                <div v-if="period" class="side-danger">
                  <el-button size="mini" type="danger" plain icon="el-icon-delete"
                             :disabled="clearing || importing" @click="openClearDialog">清空数据…</el-button>
                  <span class="side-danger-tip">按报表期清库,用于整月重导</span>
                </div>
                <div v-if="!period" class="tip">请先在上方选择报表期</div>
                <div v-else class="overview-grid">
                  <div class="ov-row" v-for="g in visibleGroups" :key="g.key">
                    <div class="ov-group">{{ g.name }}</div>
                    <div class="ov-item" v-for="t in typeList(g)" :key="t.value" :class="overviewState(t.value).cls">
                      <div class="ov-name">{{ t.label }}</div>
                      <div class="ov-status">{{ overviewState(t.value).text }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-dialog title="清空数据" :visible.sync="clearDialog" width="560px" append-to-body :close-on-click-modal="false">
          <div class="clear-dlg">
            <div class="clear-period">报表期:<b>{{ period }}</b></div>
            <el-radio-group v-model="clearScope">
              <el-radio label="all">清空该报表期全部已导入数据</el-radio>
              <el-radio label="types">只清空指定类型</el-radio>
            </el-radio-group>
            <div v-if="clearScope === 'types'" class="clear-types">
              <el-select v-model="clearTypes" multiple filterable collapse-tags placeholder="选择要清空的数据类型" style="width:100%">
                <el-option-group v-for="g in clearableGroups()" :key="g.key" :label="g.name">
                  <el-option v-for="t in typeList(g)" :key="t.value" :value="t.value"
                             :label="t.label + '(' + overviewState(t.value).text + ')'"></el-option>
                </el-option-group>
              </el-select>
              <div class="tip" style="margin-top:6px">可多选;未导入的类型没有数据可删。</div>
            </div>
            <div class="clear-warn">
              将删除所选范围内该报表期的数据库数据,并同步删除对应审核结果、已审核标记与导入批次记录(投资项目主档保留)。此操作不可撤销,请确认已有备份或准备重新导入。
            </div>
          </div>
          <span slot="footer">
            <el-button @click="clearDialog = false">取消</el-button>
            <el-button type="danger" :loading="clearing"
                       :disabled="clearScope === 'types' && !clearTypes.length" @click="confirmClear">确认清空</el-button>
          </span>
        </el-dialog>
        <!-- 导入结果弹窗:可拖动、内容区滚动、底部按钮固定可见(原 $alert 内容长时底部按钮会被挤出屏幕) -->
        <el-dialog :title="resultDialog.title" :visible.sync="resultDialog.visible" width="860px" top="5vh"
                   append-to-body :close-on-click-modal="false" custom-class="import-result-dialog" v-dialog-drag>
          <div v-if="resultDialog.level" class="ird-level" :class="'ird-' + resultDialog.level">
            {{ resultDialog.level === 'error' ? '导入失败' : (resultDialog.level === 'warning' ? '存在需要确认的内容' : '导入成功') }}
          </div>
          <div class="ird-body" v-html="resultDialog.html"></div>
          <span slot="footer">
            <el-button v-if="resultDialog.rows.length" size="small" icon="el-icon-download"
                       @click="exportResultDialog">导出明细</el-button>
            <el-button type="primary" @click="resultDialog.visible = false">确认</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
import AppHeader from '@/components/AppHeader.vue'
import api from '@/api'
const TYPE_LABELS = {
  h2032: 'H203-2月报', transportAuth: '运政车辆', trackMileage: '轨迹里程', scaleSplit: '规上规下拆分',
  freightTurnover: '货运量周转量', passengerMonthly: 'H203-1旅客月报', passengerIndividual: '个体客运量/周转量',
  passengerAuth: '旅客运政车辆数', energyMonthly: 'H204能耗季报', energyAuth: '能耗车辆运政信息',
  investment: '投资月报(客运站场)', investmentLogistics: '投资月报(物流园区)', investmentSystem: '投资系统导出',
  investCityPassenger: '市州单表(客运站场)', investCityLogistics: '市州单表(物流园区)',
  'INVEST_客运站场_CITY': '市州单表(客运站场)', 'INVEST_物流园区_CITY': '市州单表(物流园区)',
  cityBus: '城市公交月报', cityTaxi: '巡游出租月报', cityTaxiAuth: '出租车运政车辆',
  wycTotal: '网约车总数', wycOrder: '网约车订单及全省总量', wycOrderReport: '网约车订单报告',
  H2032: 'H203-2月报', H2031: 'H203-1旅客月报', H204: 'H204能耗季报', PASSENGER_AUTH: '旅客运政车辆数',
  PASSENGER_INDIVIDUAL: '个体客运量/周转量', ENERGY_AUTH: '能耗车辆运政信息', TRANSPORT_AUTH: '运政车辆',
  TRACK_MILEAGE: '轨迹里程', SCALE_SPLIT: '规上规下拆分', FREIGHT_TURNOVER: '货运量周转量',
  INVEST_SYSTEM: '投资系统导出', CITY_BUS: '城市公交月报', CITY_TAXI: '巡游出租月报', CITY_TAXI_AUTH: '出租车运政车辆', WYC_TOTAL: '网约车总数', WYC_ORDER: '网约车订单及全省总量', WYC_ORDER_REPORT: '网约车订单报告'
}
const BATCH_TYPE_MAP = {
  H2032: 'h2032', TRANSPORT_AUTH: 'transportAuth', TRACK_MILEAGE: 'trackMileage',
  SCALE_SPLIT: 'scaleSplit', FREIGHT_TURNOVER: 'freightTurnover',
  H2031: 'passengerMonthly', PASSENGER_AUTH: 'passengerAuth', PASSENGER_INDIVIDUAL: 'passengerIndividual',
  H204: 'energyMonthly', ENERGY_AUTH: 'energyAuth',
  CITY_BUS: 'cityBus', CITY_TAXI: 'cityTaxi', CITY_TAXI_AUTH: 'cityTaxiAuth',
  WYC_TOTAL: 'wycTotal', WYC_ORDER: 'wycOrder', WYC_ORDER_REPORT: 'wycOrderReport',
  INVEST_SYSTEM: 'investmentSystem'
}
export default {
  components: { AppHeader },
  name: 'DataImport',
  data() {
    return {
      importType: 'h2032',
      period: (() => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') })(),
      cityDirLoading: false,
      importing: false,
      clearing: false,
      clearDialog: false,
      clearScope: 'all',
      clearTypes: [],
      resultDialog: { visible: false, title: '', html: '', rows: [], columns: [], fileName: '', level: '' },
      sideOpen: false,
      result: '',
      error: '',
      batches: [],
      batchLoading: false,
      moduleSel: { freight: 'h2032', passenger: '', city: '', energy: '', invest: '' },
      activeModule: 'freight',
      files: {},
      fileNames: {},
      overview: {},
      groups: [
        {
          key: 'freight', name: '道路货运', types: [
            { value: 'h2032', label: '道路货物运输月度生产情况' },
            { value: 'transportAuth', label: '运政车辆' },
            { value: 'trackMileage', label: '轨迹里程' },
            { value: 'scaleSplit', label: '规上规下拆分' },
            { value: 'freightTurnover', label: '货运量周转量' }
          ]
        },
        {
          key: 'passenger', name: '公路旅客', types: [
            { value: 'passengerMonthly', label: '公路旅客运输月度生产情况' },
            { value: 'passengerAuth', label: '运政车辆数' },
            { value: 'passengerIndividual', label: '个体客运量/周转量' }
          ]
        },
        {
          key: 'city', name: '城市客运', types: [
            { value: 'cityBus', label: '城市公共交通月度运营情况' },
            { value: 'cityTaxi', label: '巡游出租汽车运营服务情况月报' },
            { value: 'cityTaxiAuth', label: '出租车运政车辆' },
            { value: 'wycTotal', label: '网约车总数' },
            { value: 'wycOrder', label: '网约车订单及全省总量', hidden: true },
            { value: 'wycOrderReport', label: '网约车订单报告' }
          ]
        },
        {
          key: 'invest', name: '站场投资', types: [
            { value: 'investment', label: '投资月报(客运站场)' },
            { value: 'investmentLogistics', label: '投资月报(物流园区)' },
            { value: 'investmentSystem', label: '投资系统导出' },
            { value: 'investCityPassenger', label: '市州单表批量导入(客运站场)' },
            { value: 'investCityLogistics', label: '市州单表批量导入(物流园区)' }
          ]
        },
        {
          key: 'energy', name: '货运能耗季报', types: [
            { value: 'energyMonthly', label: '道路货运车辆能源消耗情况' },
            { value: 'energyAuth', label: '能耗车辆运政信息' }
          ]
        },
        {
          key: 'annual', hidden: true, name: '年报', types: [
            { value: 'annualCompanyBasic', label: '单位基本情况' },
            { value: 'annualEnterpriseFinance', label: '法人企业财务状况' },
            { value: 'annualPassengerEnergy', label: '公路旅客运输能源消耗情况' },
            { value: 'annualBusOperation', label: '公共汽电车运营情况' },
            { value: 'annualMetroVehicles', label: '城市轨道交通车辆及线路情况' },
            { value: 'annualMetroStaff', label: '城市轨道交通人员及运营情况' },
            { value: 'annualFerry', label: '城市客运轮渡运营情况' },
            { value: 'annualPublicEnergy', label: '公共交通能源消耗情况' },
            { value: 'annualCityInfrastructureOperators', label: '城市客运基础设施情况、城市客运经营业户情况' },
            { value: 'annualTaxiOwnership', label: '巡游出租汽车营运车辆拥有情况' },
            { value: 'annualTaxiProduction', label: '巡游出租汽车运输生产情况' }
          ]
        }
      ]
    }
  },
  computed: {
    // 年报暂不开放:隐藏入口(数据保留,后端实现后可移除 hidden)
    visibleGroups() { return this.groups.filter(g => !g.hidden) },
    failBatches() { return this.batches.filter(b => b.failRows > 0) },
    failRowsFlat() {
      const out = []
      for (const b of this.failBatches) {
        const rows = this.parseFailDetails(b)
        if (!rows.length) {
          out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: '', reason: b.errorDetail || '该批次无失败明细' })
        } else {
          rows.forEach(r => out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: r.position, reason: r.reason }))
        }
      }
      return out
    },
    templateName() {
      const map = {
        h2032: '模板_交企统H203-2表_道路货物运输月度生产情况.xlsx',
        transportAuth: '模板_运政车辆.xlsx',
        trackMileage: '模板_轨迹里程.xlsx',
        scaleSplit: '模板_规上规下拆分运输量.xlsx',
        freightTurnover: '模板_货运量周转量.xlsx',
        passengerMonthly: '公路旅客运输月度生产情况.xlsx(含运政车辆数sheet)',
        passengerAuth: '模板_公路旅客运政车辆数.xls(支持 企业代码/企业名称/车辆数/载客位数 与 运政库导出 OWNERNAME/总车辆数/客位数)',
        passengerIndividual: '个体客运量汇总.xlsx(列:所属地区/企业代码/企业名称/个体客运量/个体旅客周转量)',
        energyMonthly: '道路货运车辆能源消耗情况(2026年).xlsx(能耗明细+运政车辆信息两sheet)',
        energyAuth: '模板_能耗车辆运政信息.xlsx(列:车牌号/车辆类型/燃料类型/标记吨位/准牵引质量)',
        investment: '7月客运站投资明细表(市州汇总大表,给领导).xlsx',
        investmentLogistics: '7月物流站场投资明细.xls(分项目投资完成情况sheet)',
        investmentSystem: '查询结果(投资系统-客运+物流 2026.7).xls',
        investCityPassenger: '—(批量扫描目录,无需模板)',
        investCityLogistics: '—(批量扫描目录,无需模板)',
        cityBus: '导入_城市公共交通月度运营情况(YYYY年M月).xls/.xlsx(企业级明细,取公共汽电车字段)',
        cityTaxi: '导入_巡游出租汽车运营服务情况月报(YYYY年M月).xls(市州级17行)',
        cityTaxiAuth: '导入模板_出租车信息(运政车辆信息).xlsx(车辆级明细,用于运营车数对比)',
        wycTotal: '模板_网约车总数.xlsx(A列=月份,B-E=全省客运量/城市内/周转量/城市内周转量)',
        wycOrder: '模板_网约车订单及全省总量.xlsx(A列=月份,B-E=全省pin,F=订单合计,G-W=17市州订单)',
        wycOrderReport: '模板_网约车订单.docx(《网约车行业YYYY年M月运行监测情况分析报告》,自动解析附件表「地市名称…订单数总数」的 17 市州订单)'
      }
      return map[this.importType] || ''
    },
    templateUrl() {
      const map = {
        h2032: '货运/模板_交企统H203-2表_道路货物运输月度生产情况.xlsx',
        transportAuth: '货运/模板_运政车辆.xlsx',
        trackMileage: '货运/模板_轨迹里程.xlsx',
        scaleSplit: '货运/模板_规上规下拆分运输量.xlsx',
        freightTurnover: '货运/模板_货运量周转量.xlsx',
        passengerMonthly: '公路旅客/模板_交企统H203-1表_公路旅客运输月度生产情况.xlsx',
        passengerAuth: '公路旅客/模板_公路旅客运政车辆数.xls',
        passengerIndividual: '公路旅客/个体客运量汇总.xlsx',
        energyMonthly: '能耗/模板_道路货运车辆能源消耗情况(2026).xlsx',
        energyAuth: '能耗/模板_能耗车辆运政信息.xlsx',
        cityBus: '城市客运/生成_城市公交客运量分市州明细.xlsx',
        cityTaxi: '城市客运/生成_巡游出租客运量分市州明细.xlsx',
        cityTaxiAuth: '城市客运/导入模板_出租车信息(运政车辆信息).xlsx',
        wycTotal: '城市客运/模板_网约车总数.xlsx',
        wycOrder: '城市客运/模板_网约车订单及全省总量.xlsx',
        wycOrderReport: '城市客运/模板_网约车订单.docx',
        investment: '投资/输入/客运(客运站)/更新_7月客运站投资明细表(市州汇总大表,给领导).xlsx',
        investmentLogistics: '投资/输入/物流(物流园区)/更新_7月物流站场投资明细.xls',
        investmentSystem: '投资/模板_查询结果(投资系统-客运+物流 2026.7).xls'
      }
      return map[this.importType] || ''
    }
  },
  methods: {
    typeLabel(t) { return TYPE_LABELS[t] || t },
    downloadTemplate() {
      if (!this.templateUrl) return
      const name = this.templateUrl.split('/').pop()
      api.get('/templates/' + this.templateUrl, { responseType: 'blob' })
        .then(res => {
          const blob = res instanceof Blob ? res : new Blob([res])
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = name
          document.body.appendChild(a)
          a.click()
          window.URL.revokeObjectURL(url)
          document.body.removeChild(a)
        })
        .catch(() => this.$message.error('模板下载失败,请稍后重试'))
    },
    onModuleChange(key) {
      this.importType = this.moduleSel[key] || ''
    },
    onModuleSwitch() {
      this.importType = this.moduleSel[this.activeModule] || ''
    },
    onPeriodChange() { this.loadData() },
    endpoint(t) {
      const map = {
        h2032: '/import/h2032',
        transportAuth: '/import/transportAuth',
        trackMileage: '/import/trackMileage',
        scaleSplit: '/import/scaleSplit',
        freightTurnover: '/import/freightTurnover',
        passengerMonthly: '/import/passengerMonthly',
        passengerAuth: '/import/passengerAuth',
        passengerIndividual: '/import/passengerIndividual',
        energyMonthly: '/import/energyMonthly',
        energyAuth: '/import/energyAuth',
        investment: '/import/investment',
        investmentLogistics: '/import/investment',
        investmentSystem: '/import/investmentSystem',
        cityBus: '/import/cityBus',
        cityTaxi: '/import/cityTaxi',
        cityTaxiAuth: '/import/cityTaxiAuth',
        wycTotal: '/import/wycTotal',
        wycOrder: '/import/wycOrder',
        wycOrderReport: '/import/wycOrderReport'
      }
      return map[t] || ''
    },
    onFilePicked(key, file) {
      const type = this.moduleSel[key]
      if (!type) return
      if (this.importing) { this.$message.warning('正在导入中,请稍候再选择文件'); return }
      const list = (this.files[type] || []).filter(f => f.name !== file.name)
      list.push(file.raw)
      this.$set(this.files, type, list)
      this.$set(this.fileNames, type, list.map(f => f.name))
      const up = this.$refs['up' + key]
      if (up && up.clearFiles) up.clearFiles()
    },
    importNow(key) {
      const type = this.moduleSel[key]
      if (!type) return
      if (this.isDirOnlyType(type)) {
        this.importCityDir(type)
        this.moduleSel[key] = ''
        this.importType = ''
        return
      }
      const fileList = this.files[type] || []
      if (!fileList.length) { this.$message.warning('请先为该类型选择文件'); return }
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      if (this.importing) { this.$message.warning('正在导入中,请稍候…'); return }
      this.importing = true
      if (fileList.length > 1 || type === 'investment' || type === 'investmentLogistics') {
        this.batchImport(type, key, fileList).finally(() => { this.importing = false })
        return
      }
      const file = fileList[0]
      const g = this.groups.find(x => x.key === key)
      const t = g.types.find(x => x.value === type)
      const row = {
        id: Date.now() + Math.random(),
        moduleKey: key,
        moduleName: g.name,
        type,
        typeLabel: t.label,
        file,
        fileName: this.fileNames[type] || file.name,
        status: 'pending',
        message: ''
      }
      this.importOne(row).then(() => {
        this.showImportResult(row)
        if ((row.type === 'investment' || row.type === 'investmentLogistics') && row.status === 'success') {
          this.checkInvest(this.period)
        }
        this.afterImport()
        this.moduleSel[key] = ''
        this.importType = ''
        this.files[type] = null
        this.$delete(this.fileNames, type)
      }).finally(() => { this.importing = false })
    },
    fileCount(type) { return (this.files[type] || []).length },
    fileNamesText(type) {
      const list = this.fileNames[type] || []
      return list.length ? '已选 ' + list.length + ' 个文件:' + list.join('、') : ''
    },
    batchImport(type, key, fileList) {
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      const fd = new FormData()
      fd.append('type', type)
      fd.append('period', this.period)
      fileList.forEach(f => fd.append('files', f))
      const g = this.groups.find(x => x.key === key)
      const label = g ? g.name : type
      this.$message({ message: '正在批量导入 ' + fileList.length + ' 个文件…', duration: 3000 })
      return api.post('/import/batch', fd, { timeout: 600000 })
        .then(res => {
          const d = (res && res.data) || {}
          if (!d.files) {
            this.$message.error((res && res.message) || '批量导入失败')
            return
          }
          const files = d.files || []
          const errCount = files.filter(f => f.error || f.success === 0).length
          const html = files.map(f =>
            '<div style="margin:6px 0;line-height:1.6"><b>' + (f.fileName || '') + '</b>' +
            (f.city ? '(' + f.city + ')' : '') + ':解析 ' + (f.success || 0) + ' 条' +
            (f.error ? ' <span style="color:#F56C6C">' + f.error + '</span>' : '') + '</div>'
          ).join('')
          this.showResultDialog({
            title: (label || type) + ' 批量导入完成:共 ' + d.total + ' 个文件' +
              (d.fail > 0 ? ',失败 ' + d.fail + ' 条' : '') + '(成功 ' + d.success + ' 条)',
            html: html,
            level: errCount > 0 ? 'warning' : 'success',
            columns: [{ key: 'fileName', label: '文件名' }, { key: 'city', label: '市州' },
                      { key: 'success', label: '解析条数' }, { key: 'error', label: '错误' }],
            rows: files.map(f => ({ fileName: f.fileName || '', city: f.city || '', success: f.success || 0, error: f.error || '' })),
            fileName: (label || '批量导入') + '_' + this.period + '_导入结果'
          })
          if (type === 'investment' || type === 'investmentLogistics') {
            this.checkInvest(this.period)
          }
          this.afterImport()
          this.files[type] = null
          this.$delete(this.fileNames, type)
        })
        .catch(e => {
          if (e && e._toast) return
          this.$message.error((e.response && e.response.data && e.response.data.message) || '批量导入失败')
        })
    },
    acceptOf(type) { return type === 'wycOrderReport' ? '.docx,.doc' : '.xlsx,.xls,.et' },
    isCityDirType(t) { return t === 'investCityPassenger' || t === 'investCityLogistics' },
    isDirOnlyType(t) { return t === 'investCityPassenger' || t === 'investCityLogistics' },
    importCityDir(type) {
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      const category = (type === 'investCityPassenger' || type === 'investment') ? '客运站场' : '物流园区'
      const fd = new FormData()
      fd.append('period', this.period)
      fd.append('category', category)
      this.cityDirLoading = true
      api.post('/import/investCityBatch', fd, { timeout: 300000 })
        .then(res => {
          const d = (res && res.data) || {}
          if (!d.files) {
            this.$message.error((res && res.message) || '批量导入失败(请确认报表期目录存在)')
            return
          }
          const files = d.files || []
          const errCount = files.filter(f => f.error || f.success === 0).length
          const html = files.map(f =>
            '<div style="margin:6px 0;line-height:1.6"><b>' + (f.fileName || '') + '</b>' +
            (f.city ? '(' + f.city + ')' : '') + ':解析 ' + (f.success || 0) + ' 个项目' +
            (f.error ? ' <span style="color:#F56C6C">' + f.error + '</span>' : '') + '</div>'
          ).join('')
          this.showResultDialog({
            title: '市州单表批量导入完成:共 ' + d.total + ' 条,成功 ' + d.success + ' 条' +
              (d.fail > 0 ? ',失败 ' + d.fail + ' 条' : '') +
              '(十五五项目匹配 ' + d.fiveYearMatched + '/' + d.fiveYearTemplateProjects + ')',
            html: html,
            level: errCount > 0 ? 'warning' : 'success',
            columns: [{ key: 'fileName', label: '文件名' }, { key: 'city', label: '市州' },
                      { key: 'success', label: '解析项目数' }, { key: 'error', label: '错误' }],
            rows: files.map(f => ({ fileName: f.fileName || '', city: f.city || '', success: f.success || 0, error: f.error || '' })),
            fileName: '市州单表导入结果_' + this.period
          })
          this.afterImport()
        })
        .catch(e => {
          if (e && e._toast) return
          this.$message.error((e.response && e.response.data && e.response.data.message) || '批量导入失败')
        })
        .finally(() => { this.cityDirLoading = false })
    },
    showImportResult(row) {
      if (!row || !row.status) return
      const msg = (row.message || '').toString()
      if (row.status === 'success') {
        const text = (msg && msg.indexOf('导入') !== -1) ? msg : '数据导入成功'
        this.$message({ message: text, type: 'success', duration: 5000 })
      } else {
        this.showResultDialog({
          title: '数据导入失败',
          html: (msg || '数据导入失败,详见下方失败记录').replace(/\n/g, '<br>'),
          level: 'error'
        })
      }
    },
    importOne(row) {
      if (!this.period) { this.$message.warning('请先选择报表期'); return Promise.resolve() }
      row.status = 'uploading'
      row.message = ''
      const fd = new FormData()
      fd.append('file', row.file)
      fd.append('period', this.period)
      if (row.type === 'investment' || row.type === 'investmentLogistics') {
        fd.append('category', row.type === 'investment' ? '客运站场' : '物流园区')
      }
      return api.post(this.endpoint(row.type), fd, { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 600000 })
        .then(res => { row.status = 'success'; row.message = res.data || '导入成功' })
        .catch(e => { row.status = 'fail'; row.message = (e.response && e.response.data && e.response.data.message) || '导入失败' })
        .finally(() => {})
    },
    afterImport() { this.loadData() },
    loadData() {
      if (this.batchLoading) return
      this.batchLoading = true
      const params = { limit: 200 }
      if (this.period) params.period = this.period
      api.get('/import/batches', { params })
        .then(res => {
          const records = (res.data && res.data.records) || []
          this.batches = records.slice(0, 50)
          const map = {}
          records.forEach(r => {
            const key = this.batchKeyToType(r.importType)
            if (!key) return
            const cur = map[key]
            if (!cur || (cur.latestId || 0) < (r.id || 0)) {
              map[key] = { totalRows: r.totalRows, successRows: r.successRows, failRows: r.failRows, latestId: r.id }
            }
          })
          if (map.wycOrderReport && !map.wycOrder) map.wycOrder = map.wycOrderReport
          this.overview = map
        })
        .catch(e => { if (!e || !e._toast) this.$message.error('导入记录加载失败,请刷新重试') })
        .finally(() => { this.batchLoading = false })
    },
    openClearDialog() {
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      if (this.importing) { this.$message.warning('正在导入数据,请等待导入完成后再清空'); return }
      this.clearScope = 'all'
      this.clearTypes = []
      this.clearDialog = true
    },
    clearableGroups() {
      return this.groups.filter(g => !g.hidden)
    },
    // 单个数据类型也可隐藏(hidden: true):入口、概览、清空下拉统一过滤
    typeList(g) {
      return (g && g.types ? g.types : []).filter(t => !t.hidden)
    },
    confirmClear() {
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      if (this.clearing) return
      if (this.clearScope === 'types' && !this.clearTypes.length) { this.$message.warning('请选择要清空的数据类型'); return }
      const scopeText = this.clearScope === 'all'
        ? '该报表期全部已导入数据'
        : '以下 ' + this.clearTypes.length + ' 个类型:' + this.clearTypes.map(t => this.typeLabel(t)).join('、')
      this.$confirm('将清空 ' + this.period + ' 的' + scopeText + ',并同步删除对应审核结果、已审核标记与导入批次记录。此操作不可撤销,是否继续?',
        '清空确认', { type: 'warning', confirmButtonText: '确认清空', cancelButtonText: '取消' })
        .then(() => {
          this.clearing = true
          const params = { period: this.period }
          if (this.clearScope === 'types') params.types = this.clearTypes.join(',')
          return api.post('/import/clear', null, { params, timeout: 600000 })
            .then(res => {
              const d = (res && res.data) || {}
              this.$message.success('已清空 ' + this.period + ' 数据:业务数据 ' + (d.dataRows || 0) +
                ' 行、审核结果 ' + (d.auditRows || 0) + ' 行、导入批次 ' + (d.batchRows || 0) + ' 条,可以重新导入')
              this.clearDialog = false
              this.loadData()
            })
            .catch(e => {
              if (e && e._toast) return
              this.$message.error((e.response && e.response.data && e.response.data.message) || '清空失败,请稍后重试')
            })
            .finally(() => { this.clearing = false })
        }).catch(() => {})
    },
    batchKeyToType(k) {
      if (BATCH_TYPE_MAP[k]) return BATCH_TYPE_MAP[k]
      if (k && k.indexOf('INVEST_') === 0) {
        if (k.indexOf('_CITY') >= 0) return k === 'INVEST_物流园区_CITY' ? 'investCityLogistics' : 'investCityPassenger'
        return k === 'INVEST_物流园区' ? 'investmentLogistics' : 'investment'
      }
      return ''
    },
    overviewState(type) {
      const o = this.overview[type]
      if (!o) return { cls: 'ov-empty', text: '未导入' }
      if (o.failRows > 0) return { cls: 'ov-fail', text: '部分失败(失败 ' + o.failRows + ' 行)' }
      if (o.successRows > 0) return { cls: 'ov-ok', text: '已导入 ' + o.successRows + ' 行' }
      return { cls: 'ov-empty', text: '无数据' }
    },
    checkInvest(period) {
      const fd = new FormData()
      fd.append('period', period)
      fd.append('reportType', 'INVEST')
      api.post('/audit/execute', fd, { timeout: 120000 })
        .then(res => {
          const list = res.data || []
          const pending = list.filter(x => x.status === 'PENDING')
          if (pending.length > 0) {
            const html = pending.map(x => {
              const name = x.enterpriseName || x.actualValue || ''
              return '<div style="margin:8px 0;line-height:1.6"><b>' + (x.ruleName || '') + '</b>:' + name +
                '<br/>实际:' + (x.actualValue || '') + ' 基准:' + (x.thresholdValue || '') +
                '<br/>差异:' + (x.deviation || '') + '</div>'
            }).join('')
            this.showResultDialog({
              title: '投资数据与投资系统不一致(' + pending.length + ' 条)',
              html: html,
              level: 'warning',
              columns: [{ key: 'rule', label: '规则' }, { key: 'name', label: '项目/企业' },
                        { key: 'actual', label: '实际值' }, { key: 'base', label: '基准值' }, { key: 'dev', label: '差异' }],
              rows: pending.map(x => ({
                rule: x.ruleName || '',
                name: x.enterpriseName || x.actualValue || '',
                actual: x.actualValue || '',
                base: x.thresholdValue || '',
                dev: x.deviation || ''
              })),
              fileName: '投资数据与投资系统不一致_' + this.period
            })
          } else {
            this.$message.success('已与投资系统核对,本月数据一致')
          }
        })
        .catch(() => {})
    },
  showResultDialog(opts) {
      const o = opts || {}
      this.resultDialog = {
        visible: true,
        title: o.title || '导入结果',
        html: o.html || '',
        level: o.level || '',
        rows: o.rows || [],
        columns: o.columns || [],
        fileName: o.fileName || ('导入结果_' + (this.period || ''))
      }
    },
    exportResultDialog() {
      const cols = this.resultDialog.columns || []
      const rows = this.resultDialog.rows || []
      if (!cols.length || !rows.length) { this.$message.warning('没有可导出的明细'); return }
      const esc = v => '"' + String(v === null || v === undefined ? '' : v).replace(/"/g, '""') + '"'
      const lines = [cols.map(c => esc(c.label)).join(',')]
      rows.forEach(r => lines.push(cols.map(c => esc(r[c.key])).join(',')))
      const blob = new Blob(['\ufeff' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = this.resultDialog.fileName + '.csv'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
  parseFailDetails(row) {
    if (!row || !row.errorDetail) return []
    const lines = String(row.errorDetail).split(/\r?\n/)
    const out = []
    lines.forEach((line, i) => {
      if (!line || !line.trim()) return
      const m = line.match(/^第\s*(\d+)\s*行[((]([^))]*)[))]\s*[::]\s*([\s\S]*)$/)
      if (m) out.push({ no: i + 1, position: '第 ' + m[1] + ' 行(' + m[2] + ')', reason: m[3].trim() })
      else out.push({ no: i + 1, position: '', reason: line.trim() })
    })
    return out
  },
  },
  mounted() {
    this.loadData()
  }
}
</script>
<style scoped>
.el-header { background: #409EFF; color: white; line-height: 60px; font-size: 18px; }
.import-card { margin-bottom: 0; }
.import-layout { display: flex; align-items: flex-start; gap: 15px; }
.import-main { flex: 1; min-width: 0; }
.import-side { position: relative; flex-shrink: 0; width: 34px; overflow: hidden; border: 1px solid #EBEEF5; border-radius: 4px; background: #FAFAFA; transition: width .2s ease; }
.import-side.side-open { width: 340px; }
.side-toggle { display: flex; flex-direction: column; align-items: center; cursor: pointer; color: #409EFF; padding: 10px 0; user-select: none; white-space: nowrap; }
.side-toggle i { font-size: 15px; }
.side-toggle-text { writing-mode: vertical-lr; letter-spacing: 4px; margin-top: 8px; font-size: 13px; }
.import-side.side-open .side-toggle { flex-direction: row; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #EBEEF5; }
.import-side.side-open .side-toggle-text { writing-mode: horizontal-tb; letter-spacing: normal; margin-top: 0; }
.side-content { padding: 8px 12px 12px; max-height: calc(100vh - 220px); overflow-y: auto; overscroll-behavior: contain; }
.side-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-weight: 600; margin-bottom: 6px; }
.side-danger { display: flex; align-items: center; gap: 8px; margin: 4px 0 10px; padding: 6px 8px; background: #FEF0F0; border: 1px solid #FDE2E2; border-radius: 4px; }
.side-danger-tip { font-size: 12px; color: #F56C6C; line-height: 1.3; }
.clear-dlg { line-height: 1.7; }
.clear-period { margin-bottom: 6px; }
.clear-types { margin-top: 10px; }
.clear-warn { margin-top: 12px; padding: 8px 10px; background: #FEF0F0; border: 1px solid #FDE2E2; border-radius: 4px; color: #F56C6C; font-size: 12px; line-height: 1.6; }
.import-side .overview-grid { display: block; }
.import-side .ov-row { display: block; margin-bottom: 6px; }
.import-side .ov-group { width: auto; }
.import-side .ov-item { margin-bottom: 4px; }
.card-head { font-weight: 600; margin-bottom: 6px; }
.module-sel { max-width: 1100px; }
.module-sel-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.tpl-box { display: flex; align-items: center; gap: 8px; min-width: 0; color: #606266; font-size: 13px; }
.tpl-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 480px; }
.group-label { font-size: 13px; color: #606266; font-weight: 600; margin-bottom: 6px; padding-left: 6px; border-left: 3px solid #409EFF; }
.module-file { margin-top: 8px; }
.file-name { font-size: 12px; color: #606266; background: #F5F7FA; border: 1px solid #EBEEF5; border-radius: 4px; padding: 4px 8px; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-btns { display: flex; gap: 6px; }
.tip { font-size: 12px; color: #909399; margin-top: 6px; line-height: 1.5; }
.slow-tip { font-size: 12px; color: #E6A23C; margin-left: 8px; }
.overview-grid { display: flex; flex-direction: column; gap: 8px; }
.ov-row { display: flex; align-items: stretch; gap: 8px; }
.ov-group { flex: none; width: 90px; display: flex; align-items: center; font-weight: 600; color: #606266; font-size: 13px; }
.ov-item { flex: 1; min-width: 0; border: 1px solid #EBEEF5; border-radius: 6px; padding: 6px 8px; background: #FAFAFA; }
.ov-item.ov-ok { background: #F0F9EB; border-color: #E1F3D8; }
.ov-item.ov-fail { background: #FDF6EC; border-color: #FAECD8; }
.ov-name { font-size: 12px; color: #303133; }
.ov-status { font-size: 12px; margin-top: 2px; }
.ov-ok .ov-status { color: #67C23A; }
.ov-fail .ov-status { color: #E6A23C; }
.ov-empty .ov-status { color: #C0C4CC; }
.empty-tip { padding: 24px 0; text-align: center; color: #C0C4CC; font-size: 13px; }
.module-tabs-head { margin-bottom: 10px; }
.module-tab-pane { min-height: 120px; }
</style>
 
<style>
/* 导入结果弹窗:el-dialog 默认 append-to-body,DOM 挂在 body 上,scoped 选择器匹配不到,必须写全局 */
.import-result-dialog { border-radius: 10px; overflow: hidden; }
.import-result-dialog .el-dialog__header { cursor: move; user-select: none; -webkit-user-select: none; }
.import-result-dialog .el-dialog__headerbtn { cursor: pointer; }
.import-result-dialog .el-dialog__body { max-height: calc(100vh - 210px); overflow-y: auto; overscroll-behavior: contain; padding: 12px 20px; }
.import-result-dialog .el-dialog__footer { border-top: 1px solid #EBEEF5; padding: 10px 20px; }
.import-result-dialog .ird-body { line-height: 1.7; font-size: 13px; color: #303133; }
.import-result-dialog .ird-level { margin-bottom: 8px; font-weight: 600; }
.import-result-dialog .ird-success { color: #67C23A; }
.import-result-dialog .ird-warning { color: #E6A23C; }
.import-result-dialog .ird-error { color: #F56C6C; }
</style>