<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const interviews = ref<any[]>([])

onMounted(async () => {
  await loadData()
})

async function loadData() {
  loading.value = true
  try {
    const response = await axios.get('/api/admin/interviews', {
      params: { page: 1, page_size: 100 }
    })
    if (response.data.code === 0) {
      interviews.value = response.data.data || []
    }
  } catch (error) {
    console.error('Load data error:', error)
  } finally {
    loading.value = false
  }
}

// 提取分数
function extractScore(scoreField: any, reportField: string): number {
  if (scoreField && !isNaN(Number(scoreField))) return Number(scoreField)
  if (!reportField) return 0
  const patterns = [/(\d+)\s*分/, /得分[：:]\s*(\d+)/, /(\d+)\/100/]
  for (const p of patterns) {
    const m = reportField?.match?.(p)
    if (m) return Number(m[1])
  }
  return 0
}

// 计算匹配度
function calculateMatchScore(row: any): number {
  const scores = [
    extractScore(row.sales_skill_score, row.sales_skill_report),
    extractScore(row.sales_concept_score, row.sales_concept_report),
    extractScore(row.competency_score, row.competency_report)
  ].filter(s => s > 0)
  if (scores.length === 0) return 0
  return Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
}

// 统计数据
const stats = computed(() => {
  const total = interviews.value.length
  const completed = interviews.value.filter(i => {
    const stageNum = parseInt(i.current_stage) || 0
    return stageNum >= 50
  }).length
  const ongoing = total - completed
  
  const validScores = interviews.value.map(i => calculateMatchScore(i)).filter(s => s > 0)
  const avgMatch = validScores.length > 0 
    ? Math.round(validScores.reduce((a, b) => a + b, 0) / validScores.length) 
    : 0
  
  const recommended = interviews.value.filter(i => calculateMatchScore(i) >= 70).length
  const highRisk = interviews.value.filter(i => i.risk_warning && i.risk_warning.length > 10).length
  
  return { total, completed, ongoing, avgMatch, recommended, highRisk }
})

// 匹配度分布
const matchDistribution = computed(() => {
  const ranges = [
    { label: '85-100', color: '#10b981', count: 0 },
    { label: '70-84', color: '#3b82f6', count: 0 },
    { label: '55-69', color: '#f59e0b', count: 0 },
    { label: '0-54', color: '#ef4444', count: 0 },
  ]
  
  interviews.value.forEach(i => {
    const score = calculateMatchScore(i)
    if (score >= 85) ranges[0].count++
    else if (score >= 70) ranges[1].count++
    else if (score >= 55) ranges[2].count++
    else if (score > 0) ranges[3].count++
  })
  
  return ranges
})

// 最近面试
const recentInterviews = computed(() => {
  return [...interviews.value]
    .sort((a, b) => {
      const timeA = new Date(a.bstudio_create_time || 0).getTime()
      const timeB = new Date(b.bstudio_create_time || 0).getTime()
      return timeB - timeA
    })
    .slice(0, 5)
})

// 优质候选人
const topCandidates = computed(() => {
  return [...interviews.value]
    .map(i => ({ ...i, matchScore: calculateMatchScore(i) }))
    .filter(i => i.matchScore > 0)
    .sort((a, b) => b.matchScore - a.matchScore)
    .slice(0, 5)
})

function formatTime(timeStr: string) {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
}

function getMatchColor(score: number) {
  if (score >= 85) return '#10b981'
  if (score >= 70) return '#3b82f6'
  if (score >= 55) return '#f59e0b'
  return '#ef4444'
}

// 根据 stage 数值获取面试阶段信息
function getStageInfo(stage: string | number) {
  const stageNum = typeof stage === 'string' ? parseInt(stage) || 0 : stage
  
  if (stageNum >= 50) {
    return { text: '已完成', color: '#10b981', isCompleted: true }
  } else if (stageNum >= 40) {
    return { text: '素质项', color: '#8b5cf6', isCompleted: false }
  } else if (stageNum >= 30) {
    return { text: '销售观', color: '#3b82f6', isCompleted: false }
  } else if (stageNum >= 20) {
    return { text: '销售技能', color: '#f59e0b', isCompleted: false }
  } else if (stageNum >= 10) {
    return { text: '简历上传', color: '#94a3b8', isCompleted: false }
  }
  return { text: '未开始', color: '#cbd5e1', isCompleted: false }
}

function viewDetail(id: string) {
  if (id && id !== '[]') {
    router.push(`/admin/interviews/${id}`)
  }
}
</script>

<template>
  <div class="dashboard">
    <!-- 欢迎语 -->
    <div class="welcome-section">
      <h1>欢迎回来</h1>
      <p>这是您的 AI 面试系统数据概览</p>
    </div>

    <!-- 统计卡片 - 骨架屏 -->
    <div class="stats-grid" v-if="loading">
      <div v-for="i in 4" :key="i" class="stat-card skeleton-stat">
        <div class="skeleton-icon"></div>
        <div class="skeleton-stat-body">
          <div class="skeleton-line w-40"></div>
          <div class="skeleton-line w-60"></div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 - 数据 -->
    <div class="stats-grid" v-else>
      <div class="stat-card gradient-blue">
        <div class="stat-icon">
          <el-icon :size="28"><User /></el-icon>
        </div>
        <div class="stat-body">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总面试数</div>
        </div>
        <div class="stat-decoration"></div>
      </div>
      
      <div class="stat-card gradient-green">
        <div class="stat-icon">
          <el-icon :size="28"><SuccessFilled /></el-icon>
        </div>
        <div class="stat-body">
          <div class="stat-value">{{ stats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-decoration"></div>
      </div>
      
      <div class="stat-card gradient-purple">
        <div class="stat-icon">
          <el-icon :size="28"><TrendCharts /></el-icon>
        </div>
        <div class="stat-body">
          <div class="stat-value">{{ stats.avgMatch }}%</div>
          <div class="stat-label">平均匹配度</div>
        </div>
        <div class="stat-decoration"></div>
      </div>
      
      <div class="stat-card gradient-orange">
        <div class="stat-icon">
          <el-icon :size="28"><Star /></el-icon>
        </div>
        <div class="stat-body">
          <div class="stat-value">{{ stats.recommended }}</div>
          <div class="stat-label">推荐录用</div>
        </div>
        <div class="stat-decoration"></div>
      </div>
    </div>

    <!-- 图表区域 - 骨架屏 -->
    <div class="charts-row" v-if="loading">
      <div class="chart-card">
        <div class="skeleton-line w-30" style="height: 20px; margin-bottom: 20px;"></div>
        <div class="skeleton-bars">
          <div v-for="i in 4" :key="i" class="skeleton-bar-row">
            <div class="skeleton-line w-20"></div>
            <div class="skeleton-line flex-1"></div>
            <div class="skeleton-line w-20"></div>
          </div>
        </div>
      </div>
      <div class="chart-card">
        <div class="skeleton-line w-30" style="height: 20px; margin-bottom: 20px;"></div>
        <div class="skeleton-donut"></div>
      </div>
    </div>

    <!-- 图表区域 - 数据 -->
    <div class="charts-row">
      <!-- 匹配度分布 -->
      <div class="chart-card">
        <h3>匹配度分布</h3>
        <div class="distribution-chart">
          <div 
            v-for="(item, idx) in matchDistribution" 
            :key="idx"
            class="dist-bar-container"
          >
            <div class="dist-label">{{ item.label }}</div>
            <div class="dist-bar-wrapper">
              <div 
                class="dist-bar"
                :style="{ 
                  width: `${(item.count / (stats.total || 1)) * 100}%`,
                  background: item.color
                }"
              ></div>
            </div>
            <div class="dist-count">{{ item.count }}人</div>
          </div>
        </div>
        <div class="distribution-legend">
          <span v-for="(item, idx) in matchDistribution" :key="idx" class="legend-item">
            <span class="legend-dot" :style="{ background: item.color }"></span>
            {{ item.label }}分
          </span>
        </div>
      </div>

      <!-- 状态分布 -->
      <div class="chart-card">
        <h3>面试状态</h3>
        <div class="status-chart">
          <div class="donut-chart">
            <svg viewBox="0 0 100 100">
              <circle 
                cx="50" cy="50" r="40" 
                fill="none" 
                stroke="#f1f5f9" 
                stroke-width="12"
              />
              <circle 
                cx="50" cy="50" r="40" 
                fill="none" 
                stroke="#10b981" 
                stroke-width="12"
                :stroke-dasharray="`${(stats.completed / (stats.total || 1)) * 251.2} 251.2`"
                stroke-linecap="round"
                transform="rotate(-90 50 50)"
              />
            </svg>
            <div class="donut-center">
              <div class="donut-value">{{ Math.round((stats.completed / (stats.total || 1)) * 100) }}%</div>
              <div class="donut-label">完成率</div>
            </div>
          </div>
          <div class="status-legend">
            <div class="legend-row">
              <span class="legend-dot" style="background: #10b981"></span>
              <span class="legend-text">已完成</span>
              <span class="legend-num">{{ stats.completed }}</span>
            </div>
            <div class="legend-row">
              <span class="legend-dot" style="background: #f59e0b"></span>
              <span class="legend-text">进行中</span>
              <span class="legend-num">{{ stats.ongoing }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表区域 - 骨架屏 -->
    <div class="lists-row" v-if="loading">
      <div class="list-card" v-for="i in 2" :key="i">
        <div class="skeleton-line w-30" style="height: 20px; margin-bottom: 16px;"></div>
        <div class="skeleton-list">
          <div v-for="j in 4" :key="j" class="skeleton-list-item">
            <div class="skeleton-avatar-sm"></div>
            <div class="skeleton-list-info">
              <div class="skeleton-line w-40"></div>
              <div class="skeleton-line w-60"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表区域 - 数据 -->
    <div class="lists-row" v-else>
      <!-- 最近面试 -->
      <div class="list-card">
        <div class="list-header">
          <h3>最近面试</h3>
          <el-button text type="primary" @click="router.push('/admin/interviews')">
            查看全部
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="list-body">
          <div 
            v-for="item in recentInterviews" 
            :key="item.session_id"
            class="list-item"
            @click="viewDetail(item.session_id)"
          >
            <div class="item-avatar" :style="{ background: `hsl(${(item.candidate_name || '').charCodeAt(0) * 10}, 70%, 60%)` }">
              {{ (item.candidate_name || '?').charAt(0) }}
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.candidate_name || '未知' }}</div>
              <div class="item-time">{{ formatTime(item.bstudio_create_time) }}</div>
            </div>
            <el-tag 
              :type="getStageInfo(item.current_stage).isCompleted ? 'success' : 'info'"
              size="small"
              effect="light"
              :style="{ borderColor: getStageInfo(item.current_stage).color, color: getStageInfo(item.current_stage).color }"
            >
              {{ getStageInfo(item.current_stage).text }}
            </el-tag>
          </div>
          <el-empty v-if="recentInterviews.length === 0" description="暂无数据" :image-size="60" />
        </div>
      </div>

      <!-- 优质候选人 -->
      <div class="list-card">
        <div class="list-header">
          <h3>优质候选人</h3>
          <el-tag type="success" effect="light" size="small">Top 5</el-tag>
        </div>
        <div class="list-body">
          <div 
            v-for="(item, idx) in topCandidates" 
            :key="item.session_id"
            class="list-item"
            @click="viewDetail(item.session_id)"
          >
            <div class="item-rank" :class="{ gold: idx === 0, silver: idx === 1, bronze: idx === 2 }">
              {{ idx + 1 }}
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.candidate_name || '未知' }}</div>
              <div class="item-score">
                <el-progress 
                  :percentage="item.matchScore" 
                  :stroke-width="6"
                  :color="getMatchColor(item.matchScore)"
                  :show-text="false"
                  style="width: 80px"
                />
              </div>
            </div>
            <div class="item-match" :style="{ color: getMatchColor(item.matchScore) }">
              {{ item.matchScore }}%
            </div>
          </div>
          <el-empty v-if="topCandidates.length === 0" description="暂无数据" :image-size="60" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 骨架屏样式 */
@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.skeleton-stat {
  background: #fff !important;
  color: transparent !important;
}

.skeleton-icon {
  width: 56px;
  height: 56px;
  border-radius: 14px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e8e8e8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-stat-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.skeleton-line {
  height: 14px;
  border-radius: 4px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e8e8e8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-line.w-20 { width: 20%; }
.skeleton-line.w-30 { width: 30%; }
.skeleton-line.w-40 { width: 40%; height: 24px; }
.skeleton-line.w-60 { width: 60%; }
.skeleton-line.flex-1 { flex: 1; }

.skeleton-bars {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.skeleton-bar-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.skeleton-bar-row .skeleton-line {
  height: 24px;
}

.skeleton-donut {
  width: 140px;
  height: 140px;
  border-radius: 50%;
  margin: 20px auto;
  background: linear-gradient(90deg, #f0f0f0 25%, #e8e8e8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.skeleton-list-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
}

.skeleton-avatar-sm {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e8e8e8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  flex-shrink: 0;
}

.skeleton-list-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.skeleton-list-info .skeleton-line {
  height: 12px;
}

/* 欢迎语 */
.welcome-section {
  margin-bottom: 28px;
}

.welcome-section h1 {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a2e;
  margin: 0 0 8px;
}

.welcome-section p {
  color: #64748b;
  font-size: 15px;
  margin: 0;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 28px;
}

.stat-card {
  border-radius: 20px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  color: #fff;
  position: relative;
  overflow: hidden;
}

.gradient-blue { background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); }
.gradient-green { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.gradient-purple { background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%); }
.gradient-orange { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 2px;
}

.stat-decoration {
  position: absolute;
  right: -20px;
  bottom: -20px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

/* 图表区域 */
.charts-row {
  display: grid;
  grid-template-columns: 1.5fr 1fr;
  gap: 20px;
  margin-bottom: 28px;
}

.chart-card {
  background: #fff;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.chart-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a2e;
  margin: 0 0 20px;
}

/* 匹配度分布 */
.distribution-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.dist-bar-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.dist-label {
  width: 60px;
  font-size: 13px;
  color: #64748b;
  text-align: right;
}

.dist-bar-wrapper {
  flex: 1;
  height: 24px;
  background: #f1f5f9;
  border-radius: 12px;
  overflow: hidden;
}

.dist-bar {
  height: 100%;
  border-radius: 12px;
  transition: width 0.5s ease;
  min-width: 4px;
}

.dist-count {
  width: 50px;
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}

.distribution-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f1f5f9;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

/* 状态分布 */
.status-chart {
  display: flex;
  align-items: center;
  gap: 32px;
  justify-content: center;
}

.donut-chart {
  width: 160px;
  height: 160px;
  position: relative;
}

.donut-chart svg {
  width: 100%;
  height: 100%;
}

.donut-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.donut-value {
  font-size: 28px;
  font-weight: 700;
  color: #1a1a2e;
}

.donut-label {
  font-size: 12px;
  color: #64748b;
}

.status-legend {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-text {
  font-size: 14px;
  color: #64748b;
  min-width: 60px;
}

.legend-num {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a2e;
}

/* 列表区域 */
.lists-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.list-card {
  background: #fff;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.list-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a2e;
  margin: 0;
}

.list-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.list-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.list-item:hover {
  background: #f8fafc;
}

.item-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: 600;
  flex-shrink: 0;
}

.item-rank {
  width: 28px;
  height: 28px;
  border-radius: 8px;
  background: #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: #64748b;
  flex-shrink: 0;
}

.item-rank.gold { background: #fef3c7; color: #d97706; }
.item-rank.silver { background: #e2e8f0; color: #64748b; }
.item-rank.bronze { background: #fed7aa; color: #c2410c; }

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a1a2e;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-time {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 2px;
}

.item-score {
  margin-top: 4px;
}

.item-match {
  font-size: 16px;
  font-weight: 700;
}

/* 响应式 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-row {
    grid-template-columns: 1fr;
  }
  
  .lists-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
