<template>
  <module-page-shell title="资料查看">
    <div class="workbench-material-page" v-loading="loading">
      <workbench-summary :cards="summaryCards" />

      <section class="panel">
        <div class="panel__header">
          <h3>资料查看与下载</h3>
        </div>

        <el-table :data="pagedRows" size="small" class="workbench-material-table">
          <el-table-column label="资料类型" prop="category" min-width="140" />
          <el-table-column label="资料名称" prop="materialName" min-width="260" show-overflow-tooltip />
          <el-table-column label="上传人" prop="ownerName" min-width="110" />
          <el-table-column label="状态" min-width="110">
            <template slot-scope="scope">
              <span :class="['status-pill', scope.row.uploaded ? 'status-pill--success' : 'status-pill--warning']">
                {{ scope.row.status }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="上传时间" min-width="160">
            <template slot-scope="scope">
              {{ scope.row.submitDate || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="预览" min-width="100" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.uploaded" size="mini" @click="handlePreview(scope.row)">预览</el-button>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="下载" min-width="100" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.uploaded" size="mini" @click="handleDownload(scope.row)">下载</el-button>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="materialRows.length > 0"
          :total="materialRows.length"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="handlePagination"
        />
      </section>

      <el-dialog
        :visible.sync="previewOpen"
        width="980px"
        top="5vh"
        append-to-body
        custom-class="material-preview-dialog"
      >
        <span slot="title" class="dialog-title">{{ previewState.title || '资料预览' }}</span>
        <div class="preview-body">
          <iframe v-if="previewState.type === 'pdf'" :src="previewState.url" class="preview-frame"></iframe>
          <img v-else-if="previewState.type === 'image'" :src="previewState.url" class="preview-image" />
          <pre v-else-if="previewState.type === 'text'" class="preview-text">{{ previewState.text }}</pre>
          <div v-else class="preview-placeholder">
            <i class="el-icon-document"></i>
            <p>当前文件类型暂不支持在线预览，可直接下载查看。</p>
            <p>{{ previewState.title }}</p>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewOpen = false">关闭</el-button>
          <el-button v-if="previewState.row" @click="handleDownload(previewState.row)">下载资料</el-button>
          <el-button v-if="previewState.type === 'unsupported'" type="primary" @click="openPreviewInNewWindow">新窗口打开</el-button>
        </div>
      </el-dialog>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import WorkbenchSummary from './components/WorkbenchSummary'
import { getPreviewUrl, loadWorkbenchSnapshot, normalizeResourcePath, resolvePreviewType } from './shared'

export default {
  name: 'RiskWorkbenchMaterial',
  components: {
    ModulePageShell,
    WorkbenchSummary
  },
  data() {
    return {
      loading: false,
      summaryCards: [],
      materialRows: [],
      pageNum: 1,
      pageSize: 10,
      previewOpen: false,
      previewState: {
        title: '',
        type: 'unsupported',
        url: '',
        text: '',
        row: null
      }
    }
  },
  computed: {
    pagedRows() {
      const pageNum = Number(this.pageNum) || 1
      const pageSize = Number(this.pageSize) || 10
      const start = (pageNum - 1) * pageSize
      return this.materialRows.slice(start, start + pageSize)
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    async loadPage() {
      this.loading = true
      try {
        const snapshot = await loadWorkbenchSnapshot()
        this.summaryCards = snapshot.summaryCards
        this.materialRows = snapshot.materialRows
        this.handlePagination()
      } finally {
        this.loading = false
      }
    },
    async handlePreview(row) {
      const url = getPreviewUrl(row.filePath)
      const type = resolvePreviewType(row.materialName || row.filePath)
      this.previewState = {
        title: row.materialName,
        type,
        url,
        text: '',
        row
      }
      this.previewOpen = true
      if (type === 'text') {
        try {
          const response = await fetch(url, { credentials: 'include' })
          this.previewState.text = await response.text()
        } catch (error) {
          this.previewState.text = '文本预览加载失败，请直接下载查看。'
        }
      }
    },
    handleDownload(row) {
      if (!row.filePath) {
        this.$message.warning('当前资料暂无可下载文件')
        return
      }
      this.$download.resource(normalizeResourcePath(row.filePath))
    },
    handlePagination() {
      const pageSize = Number(this.pageSize) || 10
      const totalPages = Math.max(1, Math.ceil(this.materialRows.length / pageSize))
      if (this.pageNum > totalPages) {
        this.pageNum = totalPages
      }
    },
    openPreviewInNewWindow() {
      if (this.previewState.url) {
        window.open(this.previewState.url, '_blank')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.workbench-material-page {
  display: flex;
  flex-direction: column;
}

.panel {
  padding: 12px 14px;
  border: 1px solid #e4e8ef;
  border-radius: 6px;
  background: #fff;
}

.panel__header {
  margin-bottom: 12px;
}

.panel__header h3 {
  margin: 0;
  color: #2f3542;
  font-size: 16px;
}

.status-pill {
  display: inline-flex;
  align-items: center;
  min-height: 24px;
  padding: 0 10px;
  border-radius: 999px;
  font-size: 12px;
}

.status-pill--success {
  color: #67c23a;
  background: #f0f9eb;
}

.status-pill--warning {
  color: #e6a23c;
  background: #fdf6ec;
}

.workbench-material-table ::v-deep th {
  padding: 11px 0;
}

.workbench-material-table ::v-deep td {
  padding: 10px 0;
}

.workbench-material-table ::v-deep .cell {
  line-height: 22px;
}

.workbench-material-table ::v-deep .el-button--mini {
  min-height: 28px;
}

.preview-body {
  min-height: 420px;
}

.preview-frame {
  width: 100%;
  min-height: 68vh;
  border: none;
}

.preview-image {
  display: block;
  max-width: 100%;
  max-height: 68vh;
  margin: 0 auto;
}

.preview-text {
  min-height: 420px;
  padding: 16px;
  border-radius: 6px;
  background: #f8fafc;
  white-space: pre-wrap;
}

.preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 420px;
  color: #98a2b3;
  gap: 10px;
  text-align: center;
}

.preview-placeholder i {
  font-size: 40px;
}
</style>
