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

const router = useRouter()

const interviews = ref<any[]>([])
const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
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 avgMatch = interviews.value.reduce((sum, i) => sum + (calculateMatchScore(i) || 0), 0) / (total || 1)
  const highMatch = interviews.value.filter(i => calculateMatchScore(i) >= 80).length
  
  return { total, completed, avgMatch: Math.round(avgMatch), highMatch }
})

// 筛选后的数据
const filteredInterviews = computed(() => {
  let result = [...interviews.value]
  
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    result = result.filter(i => 
      (i.candidate_name || '').toLowerCase().includes(kw) ||
      (i.session_id || '').toLowerCase().includes(kw)
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(i => {
      const stageNum = parseInt(i.current_stage) || 0
      if (statusFilter.value === 'completed') return stageNum >= 50
      if (statusFilter.value === 'ongoing') return stageNum < 50
      return true
    })
  }
  
  return result
})

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

async function loadInterviews() {
  loading.value = true
  try {
    const response = await axios.get('/api/admin/interviews', {
      params: {
        page: pagination.value.page,
        page_size: pagination.value.pageSize
      }
    })
    
    if (response.data.code === 0) {
      interviews.value = response.data.data || []
      pagination.value.total = interviews.value.length
    }
  } catch (error) {
    console.error('Load interviews error:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 计算匹配度（综合评分）
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)
}

// 提取分数
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+)/, /评分[：:]\s*(\d+)/, /(\d+)\/100/]
  for (const p of patterns) {
    const m = reportField.match(p)
    if (m) return Number(m[1])
  }
  return 0
}

// 获取匹配度等级
function getMatchLevel(score: number) {
  if (score >= 85) return { text: '强烈推荐', color: '#10b981', bg: 'rgba(16, 185, 129, 0.1)' }
  if (score >= 70) return { text: '推荐', color: '#3b82f6', bg: 'rgba(59, 130, 246, 0.1)' }
  if (score >= 55) return { text: '待定', color: '#f59e0b', bg: 'rgba(245, 158, 11, 0.1)' }
  return { text: '不推荐', color: '#ef4444', bg: 'rgba(239, 68, 68, 0.1)' }
}

// 获取风险等级
function getRiskLevel(row: any): { level: string; color: string } {
  const hasWarning = row.risk_warning && row.risk_warning.length > 10
  const matchScore = calculateMatchScore(row)
  
  if (hasWarning && matchScore < 60) return { level: '高风险', color: '#ef4444' }
  if (hasWarning || matchScore < 70) return { level: '中风险', color: '#f59e0b' }
  return { level: '低风险', color: '#10b981' }
}

function formatTime(timeStr: string) {
  if (!timeStr) return '-'
  return timeStr.split(' +')[0]?.replace('T', ' ') || timeStr
}

// 根据 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(row: any) {
  const id = row.session_id || row.id
  if (!id || id === '[]') {
    ElMessage.warning('该记录没有有效的 session_id')
    return
  }
  router.push(`/admin/interviews/${id}`)
}

async function deleteInterview(row: any) {
  const id = row.session_id || row.id
  if (!id || id === '[]') return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除候选人 "${row.candidate_name}" 的面试记录吗？`,
      '确认删除',
      { type: 'warning' }
    )
    
    await axios.delete(`/api/admin/interviews/${id}`)
    ElMessage.success('删除成功')
    await loadInterviews()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<template>
  <div class="interviews-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>面试管理</h1>
        <p class="subtitle">查看和管理所有面试记录</p>
      </div>
      <el-button type="primary" @click="loadInterviews" :loading="loading" class="refresh-btn">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue">
          <el-icon :size="24"><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总面试数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green">
          <el-icon :size="24"><SuccessFilled /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon purple">
          <el-icon :size="24"><TrendCharts /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.avgMatch }}%</div>
          <div class="stat-label">平均匹配度</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon orange">
          <el-icon :size="24"><Star /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.highMatch }}</div>
          <div class="stat-label">优质候选人</div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索候选人姓名或 ID..."
        prefix-icon="Search"
        clearable
        class="search-input"
      />
      <el-select v-model="statusFilter" placeholder="筛选状态" clearable class="status-select">
        <el-option label="全部" value="" />
        <el-option label="已完成" value="completed" />
        <el-option label="进行中" value="ongoing" />
      </el-select>
    </div>

    <!-- 面试列表 -->
    <div class="interviews-list">
      <!-- 加载骨架屏 -->
      <template v-if="loading">
        <div v-for="i in 4" :key="i" class="interview-card skeleton">
          <div class="candidate-section">
            <div class="skeleton-avatar"></div>
            <div class="skeleton-info">
              <div class="skeleton-line w-40"></div>
              <div class="skeleton-line w-60"></div>
            </div>
          </div>
          <div class="skeleton-bar-section">
            <div class="skeleton-line w-full"></div>
            <div class="skeleton-line w-80"></div>
          </div>
          <div class="skeleton-scores">
            <div class="skeleton-line w-full"></div>
            <div class="skeleton-line w-full"></div>
            <div class="skeleton-line w-full"></div>
          </div>
          <div class="skeleton-risk"></div>
          <div class="skeleton-actions">
            <div class="skeleton-btn"></div>
            <div class="skeleton-btn-sm"></div>
          </div>
        </div>
      </template>

      <!-- 实际数据列表 -->
      <template v-else>
        <div 
          v-for="interview in filteredInterviews" 
          :key="interview.session_id || interview.id"
          class="interview-card"
          @click="viewDetail(interview)"
        >
        <!-- 候选人信息 -->
        <div class="candidate-section">
          <div class="avatar" :style="{ background: `hsl(${(interview.candidate_name || '').charCodeAt(0) * 10}, 70%, 60%)` }">
            {{ (interview.candidate_name || '?').charAt(0) }}
          </div>
          <div class="candidate-info">
            <div class="candidate-name">{{ interview.candidate_name || '未知候选人' }}</div>
            <div class="candidate-meta">
              <el-icon><Clock /></el-icon>
              {{ formatTime(interview.bstudio_create_time) }}
            </div>
          </div>
          <el-tag 
            :type="getStageInfo(interview.current_stage).isCompleted ? 'success' : 'info'"
            effect="light"
            size="small"
            class="status-tag"
            :style="{ borderColor: getStageInfo(interview.current_stage).color, color: getStageInfo(interview.current_stage).color }"
          >
            {{ getStageInfo(interview.current_stage).text }}
          </el-tag>
        </div>

        <!-- 匹配度 -->
        <div class="match-section">
          <div class="match-header">
            <span class="match-label">岗位匹配度</span>
            <span 
              class="match-badge"
              :style="{ 
                color: getMatchLevel(calculateMatchScore(interview)).color,
                background: getMatchLevel(calculateMatchScore(interview)).bg
              }"
            >
              {{ getMatchLevel(calculateMatchScore(interview)).text }}
            </span>
          </div>
          <div class="match-bar">
            <div 
              class="match-fill" 
              :style="{ 
                width: `${calculateMatchScore(interview)}%`,
                background: getMatchLevel(calculateMatchScore(interview)).color
              }"
            ></div>
          </div>
          <div class="match-value">{{ calculateMatchScore(interview) }}%</div>
        </div>

        <!-- 维度评分 -->
        <div class="scores-section">
          <div class="score-item">
            <span class="score-label">销售技能</span>
            <span class="score-value">{{ extractScore(interview.sales_skill_score, interview.sales_skill_report) || '-' }}</span>
          </div>
          <div class="score-item">
            <span class="score-label">销售观</span>
            <span class="score-value">{{ extractScore(interview.sales_concept_score, interview.sales_concept_report) || '-' }}</span>
          </div>
          <div class="score-item">
            <span class="score-label">素质项</span>
            <span class="score-value">{{ extractScore(interview.competency_score, interview.competency_report) || '-' }}</span>
          </div>
        </div>

        <!-- 风险标识 -->
        <div class="risk-section">
          <div 
            class="risk-indicator"
            :style="{ color: getRiskLevel(interview).color }"
          >
            <el-icon><Warning /></el-icon>
            {{ getRiskLevel(interview).level }}
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions-section">
          <el-button type="primary" size="small" @click.stop="viewDetail(interview)">
            查看详情
          </el-button>
          <el-button type="danger" size="small" plain @click.stop="deleteInterview(interview)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>

      <el-empty v-if="filteredInterviews.length === 0" description="暂无面试记录" class="empty-state" />
      </template>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="filteredInterviews.length > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        background
      />
    </div>
  </div>
</template>

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

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

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 700;
  color: #1a1a2e;
  margin: 0;
}

.subtitle {
  color: #64748b;
  font-size: 14px;
  margin-top: 4px;
}

.refresh-btn {
  border-radius: 10px;
  padding: 12px 20px;
}

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

.stat-card {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

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

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

.stat-label {
  font-size: 13px;
  color: #64748b;
  margin-top: 2px;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.search-input {
  width: 320px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 10px;
  padding: 8px 16px;
  height: 40px;
}

.status-select {
  width: 160px;
}

.status-select :deep(.el-input__wrapper) {
  border-radius: 10px;
  height: 40px;
}

.status-select :deep(.el-select__wrapper) {
  border-radius: 10px;
  min-height: 40px;
  padding: 0 16px;
}

/* 面试列表 */
.interviews-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 200px;
}

/* 骨架屏 */
.interview-card.skeleton {
  pointer-events: none;
}

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

.skeleton-info {
  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-40 { width: 40%; }
.skeleton-line.w-60 { width: 60%; }
.skeleton-line.w-80 { width: 80%; }
.skeleton-line.w-full { width: 100%; }

.skeleton-bar-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 200px;
}

.skeleton-scores {
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 120px;
}

.skeleton-scores .skeleton-line {
  height: 12px;
}

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

.skeleton-actions {
  display: flex;
  gap: 8px;
}

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

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

@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* 空状态 */
.empty-state {
  background: #fff;
  border-radius: 16px;
  padding: 48px 24px;
}

.interview-card {
  background: #fff;
  border-radius: 16px;
  padding: 20px 24px;
  display: grid;
  grid-template-columns: 240px 200px 200px 100px auto;
  align-items: center;
  gap: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.interview-card:hover {
  border-color: #667eea;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  transform: translateX(4px);
}

/* 候选人信息 */
.candidate-section {
  display: flex;
  align-items: center;
  gap: 14px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 20px;
  font-weight: 600;
  flex-shrink: 0;
}

.candidate-name {
  font-size: 15px;
  font-weight: 600;
  color: #1a1a2e;
  margin-bottom: 4px;
}

.candidate-meta {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #94a3b8;
}

.status-tag {
  margin-left: auto;
}

/* 匹配度 */
.match-section {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.match-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

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

.match-badge {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 6px;
}

.match-bar {
  height: 6px;
  background: #f1f5f9;
  border-radius: 3px;
  overflow: hidden;
}

.match-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

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

/* 维度评分 */
.scores-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.score-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.score-label {
  color: #94a3b8;
}

.score-value {
  font-weight: 600;
  color: #334155;
}

/* 风险标识 */
.risk-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 操作按钮 */
.actions-section {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式 */
@media (max-width: 1400px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .interview-card {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .candidate-section {
    border-bottom: 1px solid #f1f5f9;
    padding-bottom: 16px;
  }
  
  .match-section,
  .scores-section,
  .risk-section {
    padding-left: 62px;
  }
  
  .actions-section {
    justify-content: flex-start;
    padding-left: 62px;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-bar {
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
  }
  
  .status-select {
    width: 100%;
  }
}
</style>
