<template>
  <div class="report-container">
    <div class="page-header">
      <h1 class="page-title">成绩报告</h1>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="exportReport">
          <el-icon class="el-icon--left"><Download /></el-icon>
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 成绩概览 -->
    <div class="overview-section">
      <h2 class="section-title">成绩概览</h2>
      <div class="overview-cards">
        <div class="overview-card card" v-for="item in overviewData" :key="item.label">
          <div class="card-icon" :style="{ backgroundColor: item.bgColor }">
            <el-icon :size="32" :color="item.color">
              <component :is="item.icon" />
            </el-icon>
          </div>
          <div class="card-content">
            <div class="card-value">{{ item.value }}</div>
            <div class="card-label">{{ item.label }}</div>
            <div class="card-trend" :class="item.trend > 0 ? 'up' : 'down'">
              <el-icon><component :is="item.trend > 0 ? 'Top' : 'Bottom'" /></el-icon>
              {{ Math.abs(item.trend) }}%
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 成绩趋势图 -->
    <div class="trend-section card">
      <h2 class="section-title">成绩趋势</h2>
      <div class="chart-container" ref="trendChartRef"></div>
    </div>

    <!-- 科目分析 -->
    <div class="subject-section">
      <h2 class="section-title">科目分析</h2>
      <div class="subject-grid">
        <div class="subject-card card" v-for="subject in subjectData" :key="subject.name">
          <div class="subject-header">
            <h3>{{ subject.name }}</h3>
            <el-tag :type="getScoreTagType(subject.avgScore)">
              平均分：{{ subject.avgScore }}
            </el-tag>
          </div>
          <div class="subject-stats">
            <div class="stat-item">
              <span class="stat-label">考试次数</span>
              <span class="stat-value">{{ subject.examCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">最高分</span>
              <span class="stat-value">{{ subject.maxScore }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">最低分</span>
              <span class="stat-value">{{ subject.minScore }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">及格率</span>
              <span class="stat-value">{{ subject.passRate }}%</span>
            </div>
          </div>
          <div class="progress-wrapper">
            <el-progress :percentage="subject.progress" :color="getProgressColor(subject.progress)" />
          </div>
        </div>
      </div>
    </div>

    <!-- 最近考试记录 -->
    <div class="recent-section card">
      <h2 class="section-title">最近考试记录</h2>
      <el-table :data="recentExams" style="width: 100%">
        <el-table-column prop="date" label="考试时间" width="180" />
        <el-table-column prop="name" label="考试名称" />
        <el-table-column prop="subject" label="科目" width="120" />
        <el-table-column prop="score" label="总分" width="90">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score, scope.row.totalScore)">
              {{ scope.row.score }} / {{ scope.row.totalScore }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="各轮得分" width="200">
          <template #default="scope">
            <div class="round-scores-inline">
              <span v-for="round in scope.row.roundScores" :key="round.round" class="round-score-tag">
                第{{ round.round }}轮: 
                <strong :class="getRoundScoreClass(round.score, scope.row.totalScore)">{{ round.score }}分</strong>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="rank" label="排名" width="90">
          <template #default="scope">
            <span>{{ scope.row.rank }} / {{ scope.row.totalPeople }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="用时" width="100">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getExamReport } from '@/api/exam'
import type { ExamReportResponse } from '@/api/exam'

// 日期范围
const dateRange = ref<[Date, Date]>([
  new Date(new Date().setMonth(new Date().getMonth() - 3)),
  new Date()
])

// 概览数据（从API加载）
const overviewData = ref<any[]>([])

// 科目数据（从API加载）
const subjectData = ref<any[]>([])

// 最近考试记录（从API加载）
const recentExams = ref<any[]>([])

// 图表引用
const trendChartRef = ref()
let chartInstance: any = null

/**
 * 初始化图表
 */
const initChart = () => {
  if (!trendChartRef.value) return
  
  chartInstance = echarts.init(trendChartRef.value)
  
  // 初始化空图表，实际数据由loadReportData加载
  const option = {
    title: {
      text: '成绩趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '分数',
      min: 0,
      max: 100
    },
    series: []
  }
  
  chartInstance.setOption(option)
}

/**
 * 日期变化
 */
const handleDateChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    // 重新加载报告数据
    loadReportData()
  }
}

/**
 * 导出报告
 */
const exportReport = () => {
  ElMessage.success('报告导出成功')
}

/**
 * 获取分数标签类型
 */
const getScoreTagType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 60) return 'warning'
  return 'danger'
}

/**
 * 获取进度条颜色
 */
const getProgressColor = (percentage: number) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 80) return '#409eff'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 获取分数样式类
 */
const getScoreClass = (score: number, total: number) => {
  const percentage = (score / total) * 100
  if (percentage >= 90) return 'score-excellent'
  if (percentage >= 80) return 'score-good'
  if (percentage >= 60) return 'score-pass'
  return 'score-fail'
}

/**
 * 获取轮次分数样式类
 */
const getRoundScoreClass = (score: number, total: number) => {
  const percentage = (score / total) * 100
  if (percentage >= 90) return 'score-excellent'
  if (percentage >= 80) return 'score-good'
  if (percentage >= 60) return 'score-pass'
  return 'score-fail'
}

/**
 * 格式化时长
 */
const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return hours > 0 ? `${hours}小时${minutes}分` : `${minutes}分钟`
}

/**
 * 格式化日期为 YYYY-MM-DD（使用本地时间，避免时区问题）
 */
const formatLocalDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 加载成绩报告数据
 */
const loadReportData = async () => {
  try {
    const params: any = {}
    
    // 添加时间范围参数（使用本地时间格式化，避免UTC时区偏移问题）
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = formatLocalDate(dateRange.value[0])
      params.end_date = formatLocalDate(dateRange.value[1])
    }
    
    const response = await getExamReport(params)
    // request.ts返回的是 {code, message, data}，直接访问response.data
    const reportData = response.data as ExamReportResponse
    
    if (!reportData || !reportData.overview) {
      console.error('成绩报告数据为空:', response)
      ElMessage.error('成绩报告数据格式错误')
      return
    }
    
    // 适配概览数据
    overviewData.value = [
      {
        label: '平均成绩',
        value: reportData.overview.avg_score.toFixed(1),
        icon: 'TrendCharts',
        color: '#667eea',
        bgColor: 'rgba(102, 126, 234, 0.1)',
        trend: 5.2  // TODO: 计算趋势
      },
      {
        label: '考试总数',
        value: reportData.overview.total_exams.toString(),
        icon: 'Document',
        color: '#f56c6c',
        bgColor: 'rgba(245, 108, 108, 0.1)',
        trend: 12.8
      },
      {
        label: '及格率',
        value: reportData.overview.pass_rate.toFixed(1) + '%',
        icon: 'CircleCheck',
        color: '#67c23a',
        bgColor: 'rgba(103, 194, 58, 0.1)',
        trend: 3.4
      },
      {
        label: '答题总数',
        value: reportData.overview.total_questions.toString(),
        icon: 'Trophy',
        color: '#e6a23c',
        bgColor: 'rgba(230, 162, 60, 0.1)',
        trend: -2.1
      }
    ]
    
    // 适配科目分析数据
    subjectData.value = reportData.subjects.map((s: any) => ({
      name: s.course_name,
      avgScore: s.avg_score,
      examCount: s.exam_count,
      maxScore: s.max_score,
      minScore: s.min_score,
      passRate: s.pass_rate,
      progress: s.avg_score
    }))
    
    // 适配最近考试记录
    recentExams.value = reportData.recent_exams.map((e: any) => {
      // 计算用时
      const duration = e.duration_seconds || 0
      
      // 构建三轮得分数组（过滤null值）
      const roundScores: Array<{round: number, score: number}> = []
      if (e.round_scores.round1 !== null) {
        roundScores.push({ round: 1, score: e.round_scores.round1 })
      }
      if (e.round_scores.round2 !== null) {
        roundScores.push({ round: 2, score: e.round_scores.round2 })
      }
      if (e.round_scores.round3 !== null) {
        roundScores.push({ round: 3, score: e.round_scores.round3 })
      }
      
      return {
        date: e.start_time,
        name: e.course_name + ' 考试',
        subject: e.course_name,
        score: e.score || 0,
        totalScore: e.total_score,
        rank: 0,  // TODO: 后续可以添加排名功能
        totalPeople: 0,
        duration: duration,
        roundScores: roundScores
      }
    })
    
    // 更新趋势图
    updateTrendChart(reportData.trends)
    
    ElMessage.success('成绩报告加载成功')
  } catch (error: any) {
    console.error('加载成绩报告失败:', error)
    ElMessage.error('加载成绩报告失败')
  }
}

/**
 * 更新趋势图数据
 */
const updateTrendChart = (trends: any[]) => {
  if (!chartInstance || trends.length === 0) return
  
  const dates = trends.map(t => t.date.split('-').slice(1).join('-'))  // MM-DD格式
  const scores = trends.map(t => t.avg_score)
  
  const option = {
    title: {
      text: '成绩趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['平均分'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '分数',
      min: 0,
      max: 100
    },
    series: [
      {
        name: '平均分',
        type: 'line',
        smooth: true,
        data: scores,
        itemStyle: { color: '#667eea' },
        lineStyle: { width: 2 }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    initChart()
    loadReportData()  // 加载真实数据
  })
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style lang="scss" scoped>
.report-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }

    .header-actions {
      display: flex;
      gap: 12px;

      .el-button {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
      }
    }
  }

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
  }

  .overview-section {
    margin-bottom: 32px;

    .overview-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
      gap: 20px;

      .overview-card {
        display: flex;
        align-items: center;
        gap: 20px;
        padding: 24px;

        .card-icon {
          width: 64px;
          height: 64px;
          border-radius: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .card-content {
          flex: 1;

          .card-value {
            font-size: 32px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }

          .card-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
          }

          .card-trend {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            padding: 2px 8px;
            border-radius: 4px;

            &.up {
              color: #67c23a;
              background-color: rgba(103, 194, 58, 0.1);
            }

            &.down {
              color: #f56c6c;
              background-color: rgba(245, 108, 108, 0.1);
            }
          }
        }
      }
    }
  }

  .trend-section {
    margin-bottom: 32px;
    padding: 24px;

    .chart-container {
      height: 400px;
      width: 100%;
    }
  }

  .subject-section {
    margin-bottom: 32px;

    .subject-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 20px;

      .subject-card {
        padding: 20px;

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

          h3 {
            font-size: 16px;
            font-weight: 600;
            color: #333;
          }
        }

        .subject-stats {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;
          margin-bottom: 16px;

          .stat-item {
            display: flex;
            justify-content: space-between;
            font-size: 14px;

            .stat-label {
              color: #666;
            }

            .stat-value {
              font-weight: 600;
              color: #333;
            }
          }
        }

        .progress-wrapper {
          margin-top: 12px;
        }
      }
    }
  }

  .recent-section {
    padding: 24px;

    .score-excellent {
      color: #67c23a;
      font-weight: 600;
    }

    .score-good {
      color: #409eff;
      font-weight: 600;
    }

    .score-pass {
      color: #e6a23c;
    }

    .score-fail {
      color: #f56c6c;
    }

    .round-scores-inline {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .round-score-tag {
        font-size: 12px;
        color: #666;
        
        strong {
          font-weight: 600;
          margin-left: 4px;

          &.score-excellent {
            color: #67c23a;
          }

          &.score-good {
            color: #409eff;
          }

          &.score-pass {
            color: #e6a23c;
          }

          &.score-fail {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .report-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-actions {
        width: 100%;
        flex-direction: column;

        .el-date-picker,
        .el-button {
          width: 100%;
        }
      }
    }

    .overview-cards {
      grid-template-columns: 1fr !important;
    }

    .subject-grid {
      grid-template-columns: 1fr !important;
    }
  }
}
</style>