<template>
  <section class="card">
    <h2>筛查流程</h2>
    <p class="muted">{{ statusText }}</p>
    <div class="progress"><span :style="{ width: progress + '%' }"></span></div>
    <div v-if="report" class="list-item">
      <span class="risk-badge">{{ riskLabel }}</span>
      <p style="margin-top: 8px">{{ report.summary }}</p>
      <div v-for="metric in report.metrics" :key="metric.name" class="metric-row">
        <span>{{ metric.name }}</span>
        <span>{{ metric.level }} · {{ metric.value }}%</span>
      </div>
      <button class="btn secondary" style="margin-top: 12px" @click="goReports">查看报告页</button>
    </div>
    <button class="btn" :disabled="running" @click="runFlow">一键联调（模拟上传+分析）</button>
  </section>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  createAnalysisTask,
  createUploadToken,
  directUpload,
  getReport,
  listChildren,
  registerVideo,
  saveLastReportId,
} from '../api'

const router = useRouter()
const progress = ref(0)
const statusText = ref('准备就绪')
const running = ref(false)
const report = ref<Awaited<ReturnType<typeof getReport>> | null>(null)
const lastReportId = ref<number | null>(null)

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

const riskLabel = ref('')

async function runFlow() {
  running.value = true
  report.value = null
  progress.value = 10
  statusText.value = '读取儿童档案…'
  try {
    const { list } = await listChildren()
    const child = list[0]
    if (!child) throw new Error('暂无儿童档案')

    progress.value = 30
    statusText.value = '获取上传凭证…'
    const token = await createUploadToken(child.id)

    if (token.storage === 'local') {
      progress.value = 50
      statusText.value = '直传本地存储…'
      const blob = new Blob([new Uint8Array([0, 0, 0, 24, 102, 116, 121, 112, 105, 115, 111, 109])], {
        type: 'video/mp4',
      })
      await directUpload(token.uploadUrl, token.uploadToken, token.objectKey, blob)
    }

    progress.value = 70
    statusText.value = '登记视频并提交分析…'
    const video = await registerVideo(child.id, token.objectKey)
    const task = await createAnalysisTask(child.id, video.id)
    if (!task.reportId) throw new Error('分析未完成')

    progress.value = 90
    statusText.value = '拉取报告…'
    report.value = await getReport(task.reportId)
    lastReportId.value = task.reportId
    saveLastReportId(task.reportId)
    riskLabel.value = riskMap[report.value.riskLevel] || report.value.riskLevel
    progress.value = 100
    statusText.value = '完成'
  } catch (err) {
    statusText.value = err instanceof Error ? err.message : '流程失败'
  } finally {
    running.value = false
  }
}

function goReports() {
  router.push('/reports')
}
</script>
