<template>
  <module-page-shell title="报告生成与导出">
    <div class="project-report-page">
      <section class="report-panel">
        <div class="report-panel__left">
          <div class="panel__header">
            <h3>报告生成与导出</h3>
          </div>

          <div class="project-filter-bar">
            <div class="project-filter-bar__field project-filter-bar__field--project">
              <el-select v-model="projectForm.projectName" filterable placeholder="请选择项目">
                <el-option
                  v-for="item in projectOptions"
                  :key="item.projectId"
                  :label="item.projectName"
                  :value="item.projectName"
                />
              </el-select>
            </div>
            <div class="project-filter-bar__actions">
              <el-button type="primary" class="project-filter-bar__button" @click="handleSelectProject">选择项目</el-button>
            </div>
          </div>

          <div class="field-box"><span class="field-box__label">项目名称</span>{{ summary.projectName || '-' }}</div>
          <div class="field-box field-box--select">
            <span class="field-box__label">报告模板选择</span>
            <el-select v-model="templateName" class="field-box__select">
              <el-option
                v-for="item in templateOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
          <div class="field-box"><span class="field-box__label">报告状态</span>{{ summary.reportStatus }}</div>
          <div class="field-box"><span class="field-box__label">版本</span>{{ summary.version }}</div>
          <div class="field-box"><span class="field-box__label">报告编号</span>{{ summary.reportNo }}</div>
          <div class="field-box"><span class="field-box__label">归档时间</span>{{ summary.archiveTime }}</div>
          <div class="field-box"><span class="field-box__label">风险结论</span><span class="field-box__accent">{{ summary.conclusion }}</span></div>

          <div class="actions">
            <el-button type="primary" @click="handleGenerateReport">生成报告</el-button>
            <el-button :disabled="summary.reportStatus !== '已生成'" @click="handleExportReport">导出Word/PDF</el-button>
          </div>
        </div>

        <div class="report-panel__right">
          <div class="summary-preview">
            <div class="summary-preview__title">报告摘要预览</div>
            <div class="summary-preview__content">
              <p>项目：{{ summary.projectCode || '-' }} {{ summary.projectName || '' }}</p>
              <p>资料完整度：{{ summary.materialUploaded }}/{{ summary.materialTotal }}</p>
              <p>任务完成度：{{ summary.completedTasks }}/{{ summary.totalTasks }}</p>
              <p>平均评分：{{ summary.averageScore }}</p>
              <p>风险等级：{{ summary.riskLevel }}</p>
              <p>报告编号：{{ summary.reportNo }}</p>
              <p>报告状态：{{ summary.reportStatus }}</p>
            </div>
          </div>
        </div>
      </section>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import { listProject } from '@/api/risk/project'
import { listMaterial } from '@/api/risk/material'
import {
  REPORT_TEMPLATE_OPTIONS,
  buildConclusion,
  buildMaterialSummary,
  buildReportNo,
  buildScoreRows,
  computeAverageScore,
  formatScore,
  getProjectTasks,
  nextVersion,
  normalizeMaterialRecord,
  nowString,
  readReportStore,
  readTaskStore,
  resolveRiskLevel,
  writeReportStore
} from '@/views/project/shared/workbench'

export default {
  name: 'ProjectReportExport',
  components: {
    ModulePageShell
  },
  data() {
    return {
      projectOptions: [],
      allMaterials: [],
      taskStore: {},
      reportStore: {},
      projectForm: {
        projectName: ''
      },
      currentProjectName: '',
      templateName: REPORT_TEMPLATE_OPTIONS[0],
      templateOptions: REPORT_TEMPLATE_OPTIONS
    }
  },
  computed: {
    currentProject() {
      return this.projectOptions.find(item => item.projectName === this.currentProjectName) || null
    },
    currentTasks() {
      return getProjectTasks(this.taskStore, this.currentProjectName)
    },
    currentReport() {
      return this.reportStore[this.currentProjectName] || null
    },
    materialSummary() {
      return buildMaterialSummary(this.currentProjectName, this.allMaterials)
    },
    summary() {
      const average = computeAverageScore(this.currentTasks)
      const riskLevel = this.currentReport ? this.currentReport.riskLevel : resolveRiskLevel(average)
      return {
        projectCode: this.currentProject ? this.currentProject.projectCode : '-',
        projectName: this.currentProjectName || '-',
        materialUploaded: this.currentReport ? this.currentReport.materialUploaded : this.materialSummary.uploaded,
        materialTotal: this.currentReport ? this.currentReport.materialTotal : this.materialSummary.total,
        completedTasks: this.currentTasks.filter(item => item.submissionStatus === '已提交').length,
        totalTasks: this.currentTasks.length,
        averageScore: this.currentReport ? this.currentReport.averageScore : formatScore(average),
        riskLevel,
        reportNo: this.currentReport ? this.currentReport.reportNo : '未生成',
        reportStatus: this.currentReport ? this.currentReport.reportStatus : '未生成',
        version: this.currentReport ? this.currentReport.version : '-',
        archiveTime: this.currentReport ? this.currentReport.archiveTime : '-',
        conclusion: this.currentReport ? this.currentReport.conclusion : buildConclusion(riskLevel, average)
      }
    }
  },
  created() {
    this.refreshData()
  },
  activated() {
    this.refreshData()
  },
  methods: {
    resolvePreferredProjectName(currentProjectName = '') {
      const routeProjectName = `${this.$route.query.projectName || ''}`.trim()
      const names = this.projectOptions.map(item => item.projectName)
      if (routeProjectName && names.includes(routeProjectName)) {
        return routeProjectName
      }
      if (currentProjectName && names.includes(currentProjectName)) {
        return currentProjectName
      }
      return this.projectOptions[0] ? this.projectOptions[0].projectName : ''
    },
    async refreshData() {
      const [projectRes, materialRes] = await Promise.all([
        listProject({ pageNum: 1, pageSize: 1000 }),
        listMaterial({ pageNum: 1, pageSize: 1000 })
      ])
      this.projectOptions = (projectRes.rows || []).map(item => ({
        projectId: item.projectId,
        projectCode: item.projectCode || '',
        projectName: item.projectName || ''
      }))
      this.allMaterials = (materialRes.rows || []).map(item => normalizeMaterialRecord(item))
      this.taskStore = readTaskStore()
      this.reportStore = readReportStore()
      this.projectForm.projectName = this.resolvePreferredProjectName(this.projectForm.projectName)
      this.handleSelectProject()
    },
    handleSelectProject() {
      this.taskStore = readTaskStore()
      this.reportStore = readReportStore()
      this.currentProjectName = this.projectForm.projectName
      const record = this.reportStore[this.currentProjectName]
      if (record && record.templateName) {
        this.templateName = record.templateName
        return
      }
      this.templateName = REPORT_TEMPLATE_OPTIONS[0]
    },
    handleGenerateReport() {
      if (!this.currentProject) {
        this.$message.warning('请先选择项目')
        return
      }
      const previous = this.currentReport
      const average = computeAverageScore(this.currentTasks)
      const riskLevel = resolveRiskLevel(average)
      const record = {
        projectCode: this.currentProject.projectCode || '',
        projectName: this.currentProject.projectName,
        templateName: this.templateName,
        version: nextVersion(previous && previous.version),
        reportNo: buildReportNo(this.currentProject.projectCode),
        archiveTime: nowString(),
        averageScore: formatScore(average),
        riskLevel,
        reportStatus: '已生成',
        materialUploaded: this.materialSummary.uploaded,
        materialTotal: this.materialSummary.total,
        conclusion: buildConclusion(riskLevel, average)
      }
      this.reportStore = writeReportStore({
        ...this.reportStore,
        [this.currentProjectName]: record
      })
      this.$message.success('报告已生成，可继续导出')
    },
    handleExportReport() {
      if (!this.currentReport) {
        this.$message.warning('请先生成报告')
        return
      }
      const scoreRows = buildScoreRows(this.currentTasks)
      const html = `
        <html>
          <head>
            <meta charset="utf-8" />
            <title>${this.currentReport.reportNo}</title>
          </head>
          <body>
            <h1>${this.currentProjectName} 风险评估报告</h1>
            <p>报告编号：${this.currentReport.reportNo}</p>
            <p>模板：${this.currentReport.templateName}</p>
            <p>版本：${this.currentReport.version}</p>
            <p>归档时间：${this.currentReport.archiveTime}</p>
            <p>资料完整度：${this.currentReport.materialUploaded}/${this.currentReport.materialTotal}</p>
            <p>平均评分：${this.currentReport.averageScore}</p>
            <p>风险等级：${this.currentReport.riskLevel}</p>
            <p>风险结论：${this.currentReport.conclusion}</p>
            <h2>评分汇总</h2>
            <ul>${scoreRows.map(item => `<li>${item.label}：${formatScore(item.score)}</li>`).join('')}</ul>
          </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 = `${this.currentReport.reportNo || this.currentProjectName}.doc`
      link.click()
      URL.revokeObjectURL(link.href)
      this.$message.success('已导出报告文件')
    }
  }
}
</script>

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

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

.project-report-page .project-filter-bar__field--project {
  flex: 0 1 280px;
  max-width: 320px;
  min-width: 220px;
}

.report-panel {
  display: grid;
  grid-template-columns: 1.2fr 1fr;
  gap: 14px;
}

.report-panel__left,
.report-panel__right {
  border: 1px solid #e4e8ef;
  border-radius: 8px;
  background: #fff;
  padding: 14px 16px;
}

.panel__header {
  margin-bottom: 12px;
}

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

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.field-box {
  display: flex;
  align-items: center;
  min-height: 40px;
  margin-top: 10px;
  padding: 0 14px;
  border: 1px solid #e4e8ef;
  border-radius: 6px;
  color: #303133;
  gap: 8px;
}

.field-box__label {
  font-weight: 600;
  color: #303133;
}

.field-box__accent {
  color: #f59e0b;
}

.field-box--select {
  padding: 10px 14px;
  align-items: center;
}

.field-box__select {
  width: 360px;
}

.actions {
  margin-top: 12px;
}

.summary-preview__content {
  margin-top: 12px;
  min-height: 180px;
  padding: 12px 14px;
  border: 1px solid #e4e8ef;
  border-radius: 6px;
  background: #fafbfd;
  color: #4b5563;
  line-height: 1.9;
}

.summary-preview__content p {
  margin: 0;
}

@media screen and (max-width: 1100px) {
  .report-panel {
    grid-template-columns: 1fr;
  }
}

@media screen and (max-width: 768px) {
  .actions {
    flex-direction: column;
    align-items: stretch;
  }

  .field-box__select {
    width: 100%;
    min-width: 0;
  }

  .field-box {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px 14px;
  }
}
</style>
