<template>
  <module-page-shell title="报告归档查询">
    <div class="report-archive-page">
      <section class="panel query-list-panel">
        <div class="panel__header">
          <h3>报告归档查询</h3>
        </div>

        <div class="project-filter-bar">
          <div class="project-filter-bar__field project-filter-bar__field--narrow">
            <el-select v-model="queryForm.projectName" clearable placeholder="全部">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in projectOptions"
                :key="item.projectId"
                :label="item.projectName"
                :value="item.projectName"
              />
            </el-select>
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--keyword report-archive-page__field--search">
            <el-input v-model="queryForm.reportNo" placeholder="报告编号" clearable />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--keyword report-archive-page__field--search">
            <el-input v-model="queryForm.projectKeyword" placeholder="项目名称" clearable />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--date">
            <el-date-picker
              v-model="queryForm.archiveDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="年 / 月 / 日"
            />
          </div>
          <div class="project-filter-bar__actions">
            <el-button type="primary" class="project-filter-bar__button" @click="applyFilters">查询</el-button>
            <el-button class="project-filter-bar__button" @click="resetFilters">重置</el-button>
          </div>
        </div>

        <el-table v-loading="loading" :data="pagedRows" class="archive-table">
          <el-table-column label="报告编号" prop="reportNo" min-width="200" />
          <el-table-column label="项目编号" prop="projectCode" min-width="160" />
          <el-table-column label="项目名称" prop="projectName" min-width="240" />
          <el-table-column label="版本" prop="version" min-width="100" />
          <el-table-column label="归档时间" min-width="140">
            <template slot-scope="scope">
              {{ scope.row.archiveDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="120">
            <template slot-scope="scope">
              <span class="status-pill">{{ scope.row.reportStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="140" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" @click="handleDownload(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>

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

      <el-dialog :visible.sync="detailOpen" width="760px" append-to-body>
        <span slot="title" class="dialog-title">归档详情</span>
        <div v-if="detailRow" class="detail-panel">
          <div class="detail-row"><span class="detail-row__label">报告编号</span>{{ detailRow.reportNo }}</div>
          <div class="detail-row"><span class="detail-row__label">项目编号</span>{{ detailRow.projectCode }}</div>
          <div class="detail-row"><span class="detail-row__label">项目名称</span>{{ detailRow.projectName }}</div>
          <div class="detail-row"><span class="detail-row__label">模板</span>{{ detailRow.templateName }}</div>
          <div class="detail-row"><span class="detail-row__label">版本</span>{{ detailRow.version }}</div>
          <div class="detail-row"><span class="detail-row__label">归档时间</span>{{ detailRow.archiveTime }}</div>
          <div class="detail-row"><span class="detail-row__label">风险等级</span>{{ detailRow.riskLevel }}</div>
          <div class="detail-row"><span class="detail-row__label">平均评分</span>{{ detailRow.averageScore }}</div>
          <div class="detail-row"><span class="detail-row__label">状态</span>{{ detailRow.reportStatus }}</div>
          <div class="detail-row detail-row--multiline"><span class="detail-row__label">风险结论</span>{{ detailRow.conclusion }}</div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="detailOpen = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(detailRow)">下载报告</el-button>
        </div>
      </el-dialog>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import { listProject } from '@/api/risk/project'
import {
  buildConclusion,
  buildReportNo,
  formatScore,
  readReportStore,
  resolveRiskLevel,
  todayString
} from '@/views/project/shared/workbench'

export default {
  name: 'RiskReportArchive',
  components: {
    ModulePageShell
  },
  data() {
    return {
      loading: false,
      projectOptions: [],
      archiveRows: [],
      queryForm: {
        projectName: '',
        reportNo: '',
        projectKeyword: '',
        archiveDate: '',
        pageNum: 1,
        pageSize: 10
      },
      appliedFilters: {
        projectName: '',
        reportNo: '',
        projectKeyword: '',
        archiveDate: ''
      },
      detailOpen: false,
      detailRow: null
    }
  },
  computed: {
    filteredRows() {
      const reportNo = (this.appliedFilters.reportNo || '').trim().toLowerCase()
      const projectKeyword = (this.appliedFilters.projectKeyword || '').trim().toLowerCase()
      return this.archiveRows.filter(item => {
        const hitProject = !this.appliedFilters.projectName || item.projectName === this.appliedFilters.projectName
        const hitReportNo = !reportNo || `${item.reportNo || ''}`.toLowerCase().includes(reportNo)
        const hitProjectName = !projectKeyword || `${item.projectName || ''}`.toLowerCase().includes(projectKeyword)
        const hitArchiveDate = !this.appliedFilters.archiveDate || item.archiveDate === this.appliedFilters.archiveDate
        return hitProject && hitReportNo && hitProjectName && hitArchiveDate
      })
    },
    pagedRows() {
      const pageNum = Number(this.queryForm.pageNum) || 1
      const pageSize = Number(this.queryForm.pageSize) || 10
      const start = (pageNum - 1) * pageSize
      return this.filteredRows.slice(start, start + pageSize)
    }
  },
  created() {
    this.refreshData()
  },
  activated() {
    this.refreshData()
  },
  methods: {
    async refreshData() {
      this.loading = true
      try {
        const response = await listProject({ pageNum: 1, pageSize: 1000 })
        this.projectOptions = (response.rows || []).map(item => ({
          projectId: item.projectId,
          projectCode: item.projectCode || '',
          projectName: item.projectName || ''
        }))
        this.archiveRows = this.buildArchiveRows(this.projectOptions)
        this.applyFilters()
        this.handlePagination()
      } finally {
        this.loading = false
      }
    },
    buildArchiveRows(projects) {
      const reportStore = readReportStore()
      const generatedRows = projects.reduce((rows, project, index) => {
        const stored = reportStore[project.projectName]
        if (!stored || stored.reportStatus !== '已生成') {
          return rows
        }
        rows.push(this.normalizeArchiveRow(project, stored, index))
        return rows
      }, [])

      if (generatedRows.length > 0) {
        return generatedRows.sort((a, b) => `${b.archiveTime}`.localeCompare(`${a.archiveTime}`))
      }

      return projects.slice(0, 2).map((project, index) => this.buildDemoArchiveRow(project, index))
    },
    normalizeArchiveRow(project, record, index) {
      const archiveTime = record.archiveTime || `${todayString()} 09:00`
      return {
        rowId: `${project.projectCode || project.projectName}-${index}`,
        reportNo: record.reportNo || buildReportNo(project.projectCode),
        projectCode: project.projectCode || '',
        projectName: project.projectName || '',
        version: record.version || 'v1.0',
        archiveTime,
        archiveDate: `${archiveTime}`.slice(0, 10),
        reportStatus: record.reportStatus || '已生成',
        templateName: record.templateName || '内部模板_v1.0',
        riskLevel: record.riskLevel || '中风险',
        averageScore: record.averageScore || '84',
        conclusion: record.conclusion || buildConclusion(record.riskLevel || '中风险', Number(record.averageScore || 84))
      }
    },
    buildDemoArchiveRow(project, index) {
      const archiveDate = this.shiftDate(index === 0 ? 0 : -12)
      const averageScore = 86 - index * 4
      const riskLevel = resolveRiskLevel(averageScore)
      return {
        rowId: `${project.projectCode || project.projectName}-demo-${index}`,
        reportNo: `RPT-${archiveDate.replace(/-/g, '')}-${String(397 - index * 396).padStart(3, '0')}`,
        projectCode: project.projectCode || '',
        projectName: project.projectName || '',
        version: `v1.${index}`,
        archiveTime: `${archiveDate} 10:00`,
        archiveDate,
        reportStatus: '已生成',
        templateName: '内部模板_v1.0',
        riskLevel,
        averageScore: formatScore(averageScore),
        conclusion: buildConclusion(riskLevel, averageScore)
      }
    },
    shiftDate(offsetDays) {
      const now = new Date()
      now.setDate(now.getDate() + offsetDays)
      const year = now.getFullYear()
      const month = `${now.getMonth() + 1}`.padStart(2, '0')
      const day = `${now.getDate()}`.padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    applyFilters() {
      this.queryForm.pageNum = 1
      this.appliedFilters = { ...this.queryForm }
    },
    resetFilters() {
      this.queryForm = {
        projectName: '',
        reportNo: '',
        projectKeyword: '',
        archiveDate: '',
        pageNum: 1,
        pageSize: 10
      }
      this.applyFilters()
    },
    handlePagination() {
      const pageSize = Number(this.queryForm.pageSize) || 10
      const totalPages = Math.max(1, Math.ceil(this.filteredRows.length / pageSize))
      if (this.queryForm.pageNum > totalPages) {
        this.queryForm.pageNum = totalPages
      }
    },
    handleView(row) {
      this.detailRow = row
      this.detailOpen = true
    },
    handleDownload(row) {
      if (!row) {
        return
      }
      const html = `
        <html>
          <head>
            <meta charset="utf-8" />
            <title>${row.reportNo}</title>
          </head>
          <body>
            <h1>${row.projectName} 报告归档文件</h1>
            <p>报告编号：${row.reportNo}</p>
            <p>项目编号：${row.projectCode}</p>
            <p>模板：${row.templateName}</p>
            <p>版本：${row.version}</p>
            <p>归档时间：${row.archiveTime}</p>
            <p>状态：${row.reportStatus}</p>
            <p>平均评分：${row.averageScore}</p>
            <p>风险等级：${row.riskLevel}</p>
            <p>风险结论：${row.conclusion}</p>
          </body>
        </html>
      `
      const blob = new Blob(['\ufeff', html], { type: 'application/msword;charset=utf-8' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${row.reportNo}.doc`
      link.click()
      URL.revokeObjectURL(link.href)
      this.$message.success('已开始下载归档报告')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/project-filter-bar.scss";
@import "~@/styles/query-list-panel.scss";

.report-archive-page {
  display: flex;
  flex-direction: column;
}

.report-archive-page .project-filter-bar__field--keyword {
  flex: 0 1 300px;
  max-width: 340px;
  min-width: 220px;
}

.report-archive-page__field--search {
  flex: 0 1 300px;
  max-width: 340px;
  min-width: 220px;
}

.archive-table {
  margin-bottom: 12px;
}

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

.detail-panel {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-row {
  display: flex;
  align-items: center;
  min-height: 42px;
  padding: 0 14px;
  border: 1px solid #e4e8ef;
  border-radius: 6px;
  color: #303133;
  gap: 8px;
}

.detail-row__label {
  min-width: 72px;
  font-weight: 600;
}

.detail-row--multiline {
  align-items: flex-start;
  padding: 12px 14px;
  line-height: 1.7;
}

@media screen and (max-width: 768px) {
  .detail-row {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px 14px;
  }
}
</style>
