<template>
  <section class="card">
    <h2>报告中心</h2>
    <p v-if="loading" class="muted">加载中…</p>
    <p v-else-if="error" class="error">{{ error }}</p>
    <template v-else>
      <div v-for="item in reports" :key="item.id" class="list-item">
        <strong>#{{ item.id }}</strong>
        <p>{{ item.summary }}</p>
        <p class="muted">风险：{{ riskLabel(item.riskLevel) }}</p>
        <button class="btn secondary" style="margin-top: 8px" @click="downloadPdf(item.id)">
          下载 PDF
        </button>
      </div>
      <p v-if="!reports.length" class="muted">暂无报告，请先在「筛查」页完成一次分析</p>
    </template>
  </section>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getLastReportId, getToken, listChildren, listReports, reportPdfUrl } from '../api'

const reports = ref<Array<{ id: number; summary: string; riskLevel: string }>>([])
const loading = ref(true)
const error = ref('')

const riskMap: Record<string, string> = {
  low: '正常',
  medium: '中度关注',
  high: '高度关注',
  normal: '良好',
}

function riskLabel(level: string) {
  return riskMap[level] || level
}

async function downloadPdf(reportId: number) {
  const token = getToken()
  const resp = await fetch(reportPdfUrl(reportId), {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  })
  if (!resp.ok) {
    error.value = 'PDF 下载失败'
    return
  }
  const blob = await resp.blob()
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `happy-up-report-${reportId}.pdf`
  link.click()
  URL.revokeObjectURL(url)
}

onMounted(async () => {
  try {
    const { list } = await listChildren()
    const child = list[0]
    if (!child) {
      reports.value = []
      return
    }
    const data = await listReports(child.id)
    reports.value = data.list
    const lastId = getLastReportId()
    if (lastId && !reports.value.some((item) => item.id === lastId)) {
      reports.value.unshift({ id: lastId, summary: '最近一次筛查报告', riskLevel: 'medium' })
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载失败'
  } finally {
    loading.value = false
  }
})
</script>
