zhizhijie
2026-10-20 b61e35eb8675a3716585d90a571fc2b0183b6a58
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>
                    
@@ -76,6 +82,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 +100,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 }">
@@ -150,6 +175,20 @@
                       :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="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>
          <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>
@@ -157,6 +196,7 @@
<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: '规上规下拆分',
  freightTurnover: '货运量周转量', passengerMonthly: 'H203-1旅客月报', passengerIndividual: '个体客运量/周转量',
@@ -193,6 +233,7 @@
      clearDialog: false,
      clearScope: 'all',
      clearTypes: [],
      resultDialog: { visible: false, title: '', html: '', rows: [], columns: [], fileName: '', level: '' },
      sideOpen: false,
      result: '',
      error: '',
@@ -264,15 +305,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 }))
        }
@@ -328,6 +395,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: {
@@ -463,11 +541,15 @@
            (f.city ? '(' + f.city + ')' : '') + ':解析 ' + (f.success || 0) + ' 条' +
            (f.error ? ' <span style="color:#F56C6C">' + f.error + '</span>' : '') + '</div>'
          ).join('')
          this.$alert(html, (label || type) + ' 批量导入完成:共 ' + d.total + ' 个文件' +
            (d.fail > 0 ? ',失败 ' + d.fail + ' 条' : '') + '(成功 ' + d.success + ' 条)', {
            dangerouslyUseHTMLString: true,
            type: errCount > 0 ? 'warning' : 'success',
            confirmButtonText: '知道了'
          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)
@@ -505,12 +587,16 @@
            (f.city ? '(' + f.city + ')' : '') + ':解析 ' + (f.success || 0) + ' 个项目' +
            (f.error ? ' <span style="color:#F56C6C">' + f.error + '</span>' : '') + '</div>'
          ).join('')
          this.$alert(html, '市州单表批量导入完成:共 ' + d.total + ' 条,成功 ' + d.success + ' 条' +
            (d.fail > 0 ? ',失败 ' + d.fail + ' 条' : '') +
            '(十五五项目匹配 ' + d.fiveYearMatched + '/' + d.fiveYearTemplateProjects + ')', {
            dangerouslyUseHTMLString: true,
            type: errCount > 0 ? 'warning' : 'success',
            confirmButtonText: '知道了'
          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()
        })
@@ -523,16 +609,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 {
        this.$alert((msg || '数据导入失败,详见下方失败记录').replace(/\n/g, '<br>'), '数据导入失败', {
          dangerouslyUseHTMLString: true,
          type: 'error',
          confirmButtonText: '知道了'
      if (row.status !== 'success') {
        this.showResultDialog({
          title: '数据导入失败',
          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() }
@@ -545,7 +657,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(() => {})
    },
@@ -646,14 +768,68 @@
                '<br/>实际:' + (x.actualValue || '') + ' 基准:' + (x.thresholdValue || '') +
                '<br/>差异:' + (x.deviation || '') + '</div>'
            }).join('')
            this.$alert(html, '投资数据与投资系统不一致(' + pending.length + ' 条)', {
              dangerouslyUseHTMLString: true, type: 'warning', confirmButtonText: '知道了'
            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)
    },
  /** 失败明细文本(去掉「【提醒 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 []
@@ -723,3 +899,17 @@
.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>