<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { candidateApi } from '@/api'
import type { CandidateDetail } from '@/api'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const candidate = ref<CandidateDetail | null>(null)

// 雷达图数据
const radarData = computed(() => {
  if (!candidate.value?.scores) return []
  const { salesSkill, salesMindset, quality, motivation } = candidate.value.scores
  return [
    { name: '销售技能', value: salesSkill },
    { name: '销售观', value: salesMindset },
    { name: '素质项', value: quality },
    { name: '求职动机', value: motivation },
  ]
})

// 获取候选人详情
async function fetchDetail() {
  const sessionId = route.params.id as string
  if (!sessionId) {
    router.push('/admin')
    return
  }

  loading.value = true
  try {
    const response = await candidateApi.getDetail(sessionId)
    candidate.value = response.data
  } catch (error) {
    console.error('Fetch detail error:', error)
  } finally {
    loading.value = false
  }
}

// 导出 PDF
function handleExport() {
  if (!candidate.value) return
  const url = candidateApi.exportPdf(candidate.value.sessionId)
  window.open(url, '_blank')
}

// 返回列表
function goBack() {
  router.push('/admin')
}

// 格式化日期
function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 获取评分颜色
function getScoreColor(score: number) {
  if (score >= 80) return '#22c55e'
  if (score >= 60) return '#f59e0b'
  return '#ef4444'
}

onMounted(() => {
  fetchDetail()
})
</script>

<template>
  <div class="candidate-detail">
    <!-- 返回按钮 -->
    <div class="mb-4">
      <el-button text @click="goBack">
        <el-icon class="mr-1"><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <div v-loading="loading">
      <template v-if="candidate">
        <!-- 基本信息卡片 -->
        <div class="bg-white rounded-lg p-6 mb-6 shadow-sm">
          <div class="flex justify-between items-start">
            <div>
              <h1 class="text-2xl font-bold text-gray-800 mb-2">{{ candidate.name }}</h1>
              <div class="text-gray-500 space-y-1">
                <p>会话 ID：{{ candidate.sessionId }}</p>
                <p>面试时间：{{ formatDate(candidate.createdAt) }}</p>
                <p v-if="candidate.completedAt">
                  完成时间：{{ formatDate(candidate.completedAt) }}
                </p>
              </div>
            </div>
            <el-button type="primary" @click="handleExport">
              <el-icon class="mr-1"><Download /></el-icon>
              导出 PDF
            </el-button>
          </div>
        </div>

        <!-- 评分概览 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <!-- 综合评分 -->
          <div class="bg-white rounded-lg p-6 shadow-sm">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">综合评分</h2>
            <div class="text-center py-8">
              <div
                class="text-6xl font-bold mb-2"
                :style="{ color: getScoreColor(candidate.scores?.total || 0) }"
              >
                {{ candidate.scores?.total || 0 }}
              </div>
              <p class="text-gray-500">总分（满分 100）</p>
            </div>
          </div>

          <!-- 分项评分 -->
          <div class="bg-white rounded-lg p-6 shadow-sm">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">分项评分</h2>
            <div class="space-y-4">
              <div
                v-for="item in radarData"
                :key="item.name"
                class="flex items-center"
              >
                <span class="w-20 text-gray-600">{{ item.name }}</span>
                <el-progress
                  :percentage="item.value"
                  :stroke-width="12"
                  :color="getScoreColor(item.value)"
                  class="flex-1"
                />
                <span
                  class="w-12 text-right font-medium"
                  :style="{ color: getScoreColor(item.value) }"
                >
                  {{ item.value }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分析报告 -->
        <div class="bg-white rounded-lg p-6 mb-6 shadow-sm">
          <h2 class="text-lg font-semibold text-gray-800 mb-4">分析报告</h2>
          <div class="prose max-w-none text-gray-600 leading-relaxed">
            {{ candidate.analysis || '暂无分析报告' }}
          </div>
        </div>

        <!-- 简历内容 -->
        <div class="bg-white rounded-lg p-6 mb-6 shadow-sm">
          <h2 class="text-lg font-semibold text-gray-800 mb-4">简历内容</h2>
          <div class="bg-gray-50 rounded-lg p-4 text-gray-600 whitespace-pre-wrap">
            {{ candidate.resume || '暂无简历内容' }}
          </div>
        </div>

        <!-- 面试记录 -->
        <div class="bg-white rounded-lg p-6 shadow-sm">
          <h2 class="text-lg font-semibold text-gray-800 mb-4">面试记录</h2>
          <div class="bg-gray-50 rounded-lg p-4 text-gray-600 whitespace-pre-wrap max-h-96 overflow-y-auto">
            {{ candidate.interviewLog || '暂无面试记录' }}
          </div>
        </div>
      </template>

      <template v-else-if="!loading">
        <el-empty description="未找到候选人信息" />
      </template>
    </div>
  </div>
</template>

<style scoped>
.prose {
  line-height: 1.8;
}
</style>
