xyc
2026-11-12 cb13d459288e2732cb7adc30a8cf80121e3216db
traffic-audit-web/src/views/DataImport.vue
@@ -10,9 +10,14 @@
          <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-submenu index="/special-stats">
            <template slot="title">专项统计</template>
            <el-menu-item index="/holiday-stat">节假日</el-menu-item>
          </el-submenu>
          <el-menu-item index="/rules">规则管理</el-menu-item>
          <el-menu-item index="/users">用户管理</el-menu-item>
</el-menu>
          <el-menu-item v-if="operatorIsAdmin" index="/system-config">系统配置</el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <div class="page-scroll">
@@ -21,7 +26,8 @@
            <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>
                            style="width:240px" :picker-options="periodPickerOptions" @change="onPeriodChange"></el-date-picker>
            <div v-if="periodHint" class="tip" style="margin-top:6px">{{ periodHint }}</div>
          </el-card>
                    
@@ -43,7 +49,7 @@
                    <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>
                    <span v-if="importType === 'cityTaxiAuth'" class="slow-tip">该类型约 4 万+ 行,预计耗时 1 分钟以内</span>
                  </div>
                </div>
                <div v-if="isCityDirType(moduleSel[g.key])" class="module-file">
@@ -53,11 +59,17 @@
                </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 v-if="moduleSel[g.key] === 'h202'" class="tip" style="margin:0 0 6px">选择文件夹后,自动识别并导入目录内符合 H202 命名规则的全部 .xlsx 文件。</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>
                    <input v-if="moduleSel[g.key] === 'h202'" :ref="'folder' + g.key" type="file" webkitdirectory directory multiple accept=".xlsx"
                           style="display:none" @change="onFolderPicked(g.key, $event)">
                    <el-button v-if="moduleSel[g.key] === 'h202'" size="mini" type="primary" icon="el-icon-folder-opened"
                               :disabled="importing" title="选择文件夹后自动批量导入"
                               @click="pickH202Folder(g.key)">选择文件夹并导入</el-button>
                    <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>
@@ -76,6 +88,7 @@
              导入结果({{ period || '全部报表期' }})
              <el-button type="text" icon="el-icon-refresh" style="float:right" @click="loadData">刷新</el-button>
            </div>
            <div v-if="period" class="tip" style="margin-bottom:6px">仅显示当前报表期({{ period }})的导入记录;把上方报表期清空可查看全部期次。</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">
@@ -93,6 +106,24 @@
              </el-table-column>
            </el-table>
            <div v-else class="empty-tip">暂无导入失败记录</div>
            <div v-if="warnRowsFlat.length" class="tip" style="margin:12px 0 6px">
              共 {{ warnBatches.length }} 个批次含提醒,共 {{ warnRowsFlat.length }} 条(不阻断导入,供核对):
            </div>
            <el-table v-if="warnRowsFlat.length" :data="warnRowsFlat" border size="small" 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>
          </el-card>
            </div>
                        <div class="import-side" :class="{ 'side-open': sideOpen }">
@@ -152,7 +183,8 @@
        </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>
                   append-to-body :close-on-click-modal="true" :close-on-press-escape="true"
                   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>
@@ -170,8 +202,9 @@
<script>
import AppHeader from '@/components/AppHeader.vue'
import api from '@/api'
import { granularityOfMany, disabledDateFor, granularityHint, snapPeriod } from '@/utils/periodGranularity'
const TYPE_LABELS = {
  h2032: 'H203-2月报', transportAuth: '运政车辆', trackMileage: '轨迹里程', scaleSplit: '规上规下拆分',
  h2032: 'H203-2月报', h202: 'H202车辆拥有情况', transportAuth: '运政车辆', trackMileage: '轨迹里程', scaleSplit: '规上规下拆分',
  freightTurnover: '货运量周转量', passengerMonthly: 'H203-1旅客月报', passengerIndividual: '个体客运量/周转量',
  passengerAuth: '旅客运政车辆数', energyMonthly: 'H204能耗季报', energyAuth: '能耗车辆运政信息',
  investment: '投资月报(客运站场)', investmentLogistics: '投资月报(物流园区)', investmentSystem: '投资系统导出',
@@ -185,7 +218,7 @@
  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',
  H2032: 'h2032', H202: 'h202', 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',
@@ -193,6 +226,7 @@
  WYC_TOTAL: 'wycTotal', WYC_ORDER: 'wycOrder', WYC_ORDER_REPORT: 'wycOrderReport',
  INVEST_SYSTEM: 'investmentSystem'
}
const H202_FOLDER_FILE_PATTERN = /^RP_JTB_FreightVehicle_.+\.xlsx$/i
export default {
  components: { AppHeader },
  name: 'DataImport',
@@ -221,6 +255,7 @@
        {
          key: 'freight', name: '道路货运', types: [
            { value: 'h2032', label: '道路货物运输月度生产情况' },
            { value: 'h202', label: '公路货物营运车辆拥有情况(H202)' },
            { value: 'transportAuth', label: '运政车辆' },
            { value: 'trackMileage', label: '轨迹里程' },
            { value: 'scaleSplit', label: '规上规下拆分' },
@@ -278,15 +313,41 @@
    }
  },
  computed: {
    selectedImportTypes() {
      const out = []
      if (this.importType) out.push(this.importType)
      Object.keys(this.moduleSel || {}).forEach(k => { if (this.moduleSel[k]) out.push(this.moduleSel[k]) })
      return out
    },
    periodGranularity() { return granularityOfMany(this.selectedImportTypes) },
    periodPickerOptions() {
      const d = disabledDateFor(this.periodGranularity)
      return d ? { disabledDate: d } : {}
    },
    periodHint() { return granularityHint(this.periodGranularity) },
    // 年报暂不开放:隐藏入口(数据保留,后端实现后可移除 hidden)
    visibleGroups() { return this.groups.filter(g => !g.hidden) },
    failBatches() { return this.batches.filter(b => b.failRows > 0) },
    // 含提醒的批次:errorDetail 里有「【提醒 N 处】」段(未知码等,不阻断导入)
    warnBatches() { return this.batches.filter(b => b.errorDetail && String(b.errorDetail).indexOf('【提醒 ') >= 0) },
    failRowsFlat() {
      const out = []
      for (const b of this.failBatches) {
        const rows = this.parseFailDetails(b)
        const rows = this.parseFailDetails({ errorDetail: this.failDetailText(b) })
        if (!rows.length) {
          out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: '', reason: b.errorDetail || '该批次无失败明细' })
          out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: '', reason: this.failDetailText(b) || '该批次无失败明细' })
        } else {
          rows.forEach(r => out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: r.position, reason: r.reason }))
        }
      }
      return out
    },
    warnRowsFlat() {
      const out = []
      for (const b of this.warnBatches) {
        const rows = this.parseFailDetails({ errorDetail: this.warnDetailText(b) })
        if (!rows.length) {
          out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: '', reason: this.warnDetailText(b) || '该批次含提醒' })
        } else {
          rows.forEach(r => out.push({ importType: b.importType, reportPeriod: b.reportPeriod, fileName: b.fileName, position: r.position, reason: r.reason }))
        }
@@ -296,13 +357,14 @@
    templateName() {
      const map = {
        h2032: '模板_交企统H203-2表_道路货物运输月度生产情况.xlsx',
        h202: 'RP_JTB_FreightVehicle_全省.xlsx(导入前将文件名“全省”和表内 L3 报表日期改为实际地区、报表期末日期)',
        transportAuth: '模板_运政车辆.xlsx',
        trackMileage: '模板_轨迹里程.xlsx',
        scaleSplit: '模板_规上规下拆分运输量.xlsx',
        freightTurnover: '模板_货运量周转量.xlsx',
        passengerMonthly: '公路旅客运输月度生产情况.xlsx(含运政车辆数sheet)',
        passengerAuth: '模板_公路旅客运政车辆数.xls(支持 企业代码/企业名称/车辆数/载客位数 与 运政库导出 OWNERNAME/总车辆数/客位数)',
        passengerIndividual: '个体客运量汇总.xlsx(列:所属地区/企业代码/企业名称/个体客运量/个体旅客周转量)',
        passengerIndividual: '模板_个体客运(2026.7).xlsx(标题月份需与报表期一致;列:市州/个体车辆数/个体客运量/个体旅客周转量)',
        energyMonthly: '道路货运车辆能源消耗情况(2026年).xlsx(能耗明细+运政车辆信息两sheet)',
        energyAuth: '模板_能耗车辆运政信息.xlsx(列:车牌号/车辆类型/燃料类型/标记吨位/准牵引质量)',
        investment: '7月客运站投资明细表(市州汇总大表,给领导).xlsx',
@@ -322,13 +384,14 @@
    templateUrl() {
      const map = {
        h2032: '货运/模板_交企统H203-2表_道路货物运输月度生产情况.xlsx',
        h202: '货运/RP_JTB_FreightVehicle_全省.xlsx',
        transportAuth: '货运/模板_运政车辆.xlsx',
        trackMileage: '货运/模板_轨迹里程.xlsx',
        scaleSplit: '货运/模板_规上规下拆分运输量.xlsx',
        freightTurnover: '货运/模板_货运量周转量.xlsx',
        passengerMonthly: '公路旅客/模板_交企统H203-1表_公路旅客运输月度生产情况.xlsx',
        passengerAuth: '公路旅客/模板_公路旅客运政车辆数.xls',
        passengerIndividual: '公路旅客/个体客运量汇总.xlsx',
        passengerIndividual: '公路旅客/模板_个体客运(2026.7).xlsx',
        energyMonthly: '能耗/模板_道路货运车辆能源消耗情况(2026).xlsx',
        energyAuth: '能耗/模板_能耗车辆运政信息.xlsx',
        cityBus: '城市客运/生成_城市公交客运量分市州明细.xlsx',
@@ -342,6 +405,17 @@
        investmentSystem: '投资/模板_查询结果(投资系统-客运+物流 2026.7).xls'
      }
      return map[this.importType] || ''
    }
  },
  watch: {
    // 期次粒度跟着数据类型走:选到能耗季报时自动把报表期对齐到季度末月
    periodGranularity() {
      const snapped = snapPeriod(this.period, this.periodGranularity)
      if (snapped && snapped !== this.period) {
        this.period = snapped
        const hint = granularityHint(this.periodGranularity)
        if (hint) this.$message.warning(hint + '(已自动调整为 ' + snapped + ')')
      }
    }
  },
  methods: {
@@ -373,6 +447,7 @@
    endpoint(t) {
      const map = {
        h2032: '/import/h2032',
        h202: '/import/h202',
        transportAuth: '/import/transportAuth',
        trackMileage: '/import/trackMileage',
        scaleSplit: '/import/scaleSplit',
@@ -393,6 +468,37 @@
        wycOrderReport: '/import/wycOrderReport'
      }
      return map[t] || ''
    },
    pickH202Folder(key) {
      if (this.importing) { this.$message.warning('正在导入中,请稍候再选择文件夹'); return }
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      const ref = this.$refs['folder' + key]
      const input = Array.isArray(ref) ? ref[0] : ref
      if (!input) { this.$message.error('文件夹选择控件未就绪,请刷新页面后重试'); return }
      input.value = ''
      input.click()
    },
    onFolderPicked(key, event) {
      const input = event && event.target
      const selected = Array.from((input && input.files) || [])
      if (input) input.value = ''
      const type = this.moduleSel[key]
      if (type !== 'h202' || !selected.length) return
      if (this.importing) { this.$message.warning('正在导入中,请稍候再选择文件夹'); return }
      if (!this.period) { this.$message.warning('请先选择报表期'); return }
      const fileList = selected
        .filter(f => H202_FOLDER_FILE_PATTERN.test(f.name))
        .sort((a, b) => String(a.webkitRelativePath || a.name).localeCompare(String(b.webkitRelativePath || b.name), 'zh-CN'))
      const ignored = selected.length - fileList.length
      if (!fileList.length) {
        this.$message.warning('所选文件夹中没有符合 H202 命名规则的 .xlsx 文件')
        return
      }
      this.$set(this.files, type, fileList)
      this.$set(this.fileNames, type, fileList.map(f => f.name))
      if (ignored > 0) this.$message.warning('已忽略 ' + ignored + ' 个不符合 H202 命名规则的文件')
      this.importing = true
      this.batchImport(type, key, fileList).finally(() => { this.importing = false })
    },
    onFilePicked(key, file) {
      const type = this.moduleSel[key]
@@ -545,16 +651,42 @@
    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 {
      if (row.status !== 'success') {
        this.showResultDialog({
          title: '数据导入失败',
          html: (msg || '数据导入失败,详见下方失败记录').replace(/\n/g, '<br>'),
          html: this.escapeHtml(msg || '数据导入失败,详见下方失败记录').replace(/\n/g, '<br>'),
          level: 'error'
        })
        return
      }
      const lines = msg.split('\n').map(s => s.trim()).filter(s => s)
      const head = lines.length ? lines[0] : '数据导入成功'
      // 全部成功:只给一条短提示,不弹窗(能耗等成功导入不该打扰);
      // 长文本塞进 el-message 会被撑成横贯屏幕的长条,所以这里也只取首行。
      const failMatch = msg.match(/失败\s*(\d+)\s*条/)
      const failCount = failMatch ? Number(failMatch[1]) : 0
      if (failCount > 0) {
        // 有失败行:保留详情弹窗(含行号),满足"导入失败要在页面显示行号"
        this.showResultDialog({
          title: '导入完成(部分失败,见明细)',
          html: lines.map(l => this.escapeHtml(l)).join('<br>'),
          level: 'warning'
        })
        return
      }
      const warnMatch = msg.match(/以下\s*(\d+)\s*处为提醒/)
      let text = head
      if (warnMatch) text += ';另有 ' + warnMatch[1] + ' 处提醒'
      this.$message({ message: text, type: warnMatch ? 'warning' : 'success', duration: 4000 })
    },
    /** 弹窗内容用 v-html 渲染,统一转义,避免消息里的 < > & 破坏 DOM */
    escapeHtml(v) {
      return String(v === null || v === undefined ? '' : v)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
    },
    importOne(row) {
      if (!this.period) { this.$message.warning('请先选择报表期'); return Promise.resolve() }
@@ -567,7 +699,17 @@
        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 || '导入成功' })
        .then(res => {
          // axios 拦截器只拆出 response.data(业务包 Result),必须自行判 code:
          // 后端解析/校验异常时返回 code=500 且原因在 message 里,旧写法会把失败显示成「导入成功」。
          if (res && res.code !== undefined && res.code !== 200) {
            row.status = 'fail'
            row.message = res.message || '导入失败'
          } else {
            row.status = 'success'
            row.message = (res && res.data) || '导入成功'
          }
        })
        .catch(e => { row.status = 'fail'; row.message = (e.response && e.response.data && e.response.data.message) || '导入失败' })
        .finally(() => {})
    },
@@ -718,6 +860,19 @@
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
  /** 失败明细文本(去掉「【提醒 N 处】」及其后的提醒段) */
    failDetailText(b) {
      const t = String((b && b.errorDetail) || '')
      const i = t.indexOf('【提醒 ')
      return (i >= 0 ? t.slice(0, i) : t).trim()
    },
    /** 提醒明细文本(「【提醒 N 处】」之后的部分) */
    warnDetailText(b) {
      const t = String((b && b.errorDetail) || '')
      const i = t.indexOf('【提醒 ')
      if (i < 0) return ''
      return t.slice(i).replace(/^【提醒\s*\d+\s*处】\s*/, '').trim()
    },
  parseFailDetails(row) {
    if (!row || !row.errorDetail) return []
    const lines = String(row.errorDetail).split(/\r?\n/)