<template>
  <div class="statistics-container">
    <div class="page-header">
      <h1 class="page-title">统计分析</h1>
      <div class="header-filters">
        <el-select 
          v-model="selectedSubject" 
          placeholder="选择科目" 
          @change="handleSubjectChange"
          :loading="coursesLoading"
        >
          <el-option label="全部科目" value="" />
          <el-option 
            v-for="course in courseList" 
            :key="course.id" 
            :label="course.name" 
            :value="course.id" 
          />
        </el-select>
        <el-select v-model="selectedPeriod" placeholder="时间范围" @change="handlePeriodChange">
          <el-option label="最近一周" value="week" />
          <el-option label="最近一月" value="month" />
          <el-option label="最近三月" value="quarter" />
          <el-option label="最近半年" value="halfYear" />
          <el-option label="最近一年" value="year" />
        </el-select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" :size="50"><Loading /></el-icon>
      <p>数据加载中...</p>
    </div>

    <!-- 数据内容 -->
    <div v-else-if="!hasError">
      <!-- 关键指标 -->
      <div class="metrics-section">
        <div class="metric-card card" v-for="metric in keyMetrics" :key="metric.name">
          <div class="metric-header">
            <span class="metric-name">{{ metric.name }}</span>
            <el-tooltip :content="metric.description" placement="top">
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="metric-value" :style="{ color: metric.color }">
            {{ metric.value }}{{ metric.unit }}
          </div>
          <div class="metric-compare">
            <span>环比</span>
            <span class="compare-value" :class="metric.change > 0 ? 'up' : 'down'">
              {{ metric.change > 0 ? '+' : '' }}{{ metric.change }}%
            </span>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-grid">
        <!-- 成绩分布图 -->
        <div class="chart-card card">
          <h3 class="chart-title">成绩分布</h3>
          <div class="chart-container" ref="distributionChartRef"></div>
        </div>

        <!-- 难度分析图 -->
        <div class="chart-card card">
          <h3 class="chart-title">题目难度分析</h3>
          <div class="chart-container" ref="difficultyChartRef"></div>
        </div>

        <!-- 知识点掌握度 -->
        <div class="chart-card card">
          <h3 class="chart-title">知识点掌握度</h3>
          <div class="chart-container" ref="knowledgeChartRef"></div>
        </div>

        <!-- 学习时长统计 -->
        <div class="chart-card card">
          <h3 class="chart-title">学习时长统计</h3>
          <div class="chart-container" ref="timeChartRef"></div>
        </div>
      </div>

      <!-- 详细数据表格 -->
      <div class="detail-section card">
        <div class="section-header">
          <h3 class="section-title">详细数据</h3>
          <el-button link type="primary" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
        <el-table :data="detailData" style="width: 100%">
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="examCount" label="考试次数" width="100" />
          <el-table-column prop="avgScore" label="平均分" width="100">
            <template #default="scope">
              {{ scope.row.avgScore.toFixed(1) }}
            </template>
          </el-table-column>
          <el-table-column prop="studyTime" label="学习时长" width="120">
            <template #default="scope">
              {{ scope.row.studyTime }} 小时
            </template>
          </el-table-column>
          <el-table-column prop="practiceCount" label="练习题数" width="100">
            <template #default="scope">
              {{ scope.row.questionCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="accuracy" label="正确率" width="100">
            <template #default="scope">
              {{ typeof scope.row.accuracy === 'number' ? scope.row.accuracy.toFixed(1) : '0.0' }}%
            </template>
          </el-table-column>
          <el-table-column prop="improvement" label="进步指数" width="150">
            <template #default="scope">
              <el-progress 
                :percentage="scope.row.improvement || 0" 
                :color="getProgressColor(scope.row.improvement || 0)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-result icon="error" title="数据加载失败" :sub-title="errorMessage">
        <template #extra>
          <el-button type="primary" @click="loadAllData">重试</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, InfoFilled, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { courseApi, type Course } from '@/api/course'
import {
  getKeyMetrics,
  getScoreDistribution,
  getDifficultyAnalysis,
  getKnowledgeMastery,
  getStudyTimeStats,
  getDetailData
} from '@/api/statistics'
import type {
  ScoreDistributionResponse,
  DifficultyAnalysisResponse,
  KnowledgeMasteryItem,
  StudyTimeStatsResponse,
  DetailDataItem
} from '@/api/statistics'

// 选择的科目和时间范围
const selectedSubject = ref<number | string>('')
const selectedPeriod = ref('month')

// 加载状态
const loading = ref(false)
const coursesLoading = ref(false)
const hasError = ref(false)
const errorMessage = ref('')

// 课程列表
const courseList = ref<Course[]>([])

// 图表引用
const distributionChartRef = ref()
const difficultyChartRef = ref()
const knowledgeChartRef = ref()
const timeChartRef = ref()
let distributionChart: any = null
let difficultyChart: any = null
let knowledgeChart: any = null
let timeChart: any = null

// 图表数据缓存（用于延迟初始化）
const chartDataCache = ref<{
  distribution: ScoreDistributionResponse | null
  difficulty: DifficultyAnalysisResponse | null
  knowledge: KnowledgeMasteryItem[] | null
  time: StudyTimeStatsResponse | null
}>({
  distribution: null,
  difficulty: null,
  knowledge: null,
  time: null
})

// 关键指标
const keyMetrics = ref([
  {
    name: '学习效率',
    value: 0,
    unit: '%',
    change: 0,
    color: '#667eea',
    description: '正确题数/总练习题数'
  },
  {
    name: '知识覆盖率',
    value: 0,
    unit: '%',
    change: 0,
    color: '#764ba2',
    description: '已学知识点/总知识点数'
  },
  {
    name: '平均用时',
    value: 0,
    unit: '分/题',
    change: 0,
    color: '#f093fb',
    description: '每道题平均用时'
  },
  {
    name: '进步速度',
    value: 0,
    unit: '%',
    change: 0,
    color: '#4facfe',
    description: '近期分数提升幅度'
  }
])

// 详细数据
const detailData = ref<DetailDataItem[]>([])

/**
 * 加载课程列表
 */
const loadCourses = async () => {
  try {
    coursesLoading.value = true
    const response = await courseApi.list({
      page: 1,
      size: 100,
    })
    if (response.code === 200 && response.data) {
      courseList.value = response.data.items || []
    }
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    coursesLoading.value = false
  }
}

/**
 * 加载关键指标
 */
const loadKeyMetrics = async () => {
  try {
    const params: any = { period: selectedPeriod.value }
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    const response = await getKeyMetrics(params)
    
    if (response.code === 200 && response.data) {
      const data = response.data as any
      
      // 后端返回的是嵌套对象结构
      keyMetrics.value[0].value = data.learningEfficiency?.value || 0
      keyMetrics.value[0].change = data.learningEfficiency?.change || 0
      
      keyMetrics.value[1].value = data.knowledgeCoverage?.value || 0
      keyMetrics.value[1].change = data.knowledgeCoverage?.change || 0
      
      keyMetrics.value[2].value = data.avgTimePerQuestion?.value || 0
      keyMetrics.value[2].change = data.avgTimePerQuestion?.change || 0
      
      keyMetrics.value[3].value = data.progressSpeed?.value || 0
      keyMetrics.value[3].change = data.progressSpeed?.change || 0
    }
  } catch (error: any) {
    console.error('加载关键指标失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载成绩分布数据（仅获取数据，不初始化图表）
 */
const loadScoreDistribution = async () => {
  console.log('📊 loadScoreDistribution 开始')
  try {
    const params: any = { period: selectedPeriod.value }
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    console.log('📊 调用 getScoreDistribution API', params)
    const response = await getScoreDistribution(params)
    console.log('📊 getScoreDistribution 响应:', response)
    
    if (response.code === 200 && response.data) {
      const data = response.data as ScoreDistributionResponse
      console.log('✅ 成绩分布数据已缓存', data)
      chartDataCache.value.distribution = data
    } else {
      console.warn('⚠️ API 返回数据无效', response)
    }
  } catch (error: any) {
    console.error('❌ 加载成绩分布失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载难度分析数据（仅获取数据，不初始化图表）
 */
const loadDifficultyAnalysis = async () => {
  try {
    const params: any = { period: selectedPeriod.value }
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    const response = await getDifficultyAnalysis(params)
    
    if (response.code === 200 && response.data) {
      const data = response.data as DifficultyAnalysisResponse
      console.log('✅ 难度分析数据已缓存', data)
      chartDataCache.value.difficulty = data
    }
  } catch (error: any) {
    console.error('加载难度分析失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载知识点掌握度数据（仅获取数据，不初始化图表）
 */
const loadKnowledgeMastery = async () => {
  try {
    const params: any = {}
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    const response = await getKnowledgeMastery(params)
    
    if (response.code === 200 && response.data) {
      const data = response.data as KnowledgeMasteryItem[]
      console.log('✅ 知识点掌握度数据已缓存', data)
      chartDataCache.value.knowledge = data as any
    }
  } catch (error: any) {
    console.error('加载知识点掌握度失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载学习时长数据（仅获取数据，不初始化图表）
 */
const loadStudyTimeStats = async () => {
  try {
    const params: any = { period: selectedPeriod.value }
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    const response = await getStudyTimeStats(params)
    
    if (response.code === 200 && response.data) {
      const data = response.data as StudyTimeStatsResponse
      console.log('✅ 学习时长数据已缓存', data)
      chartDataCache.value.time = data
    }
  } catch (error: any) {
    console.error('加载学习时长失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载详细数据
 */
const loadDetailData = async () => {
  try {
    const params: any = { period: selectedPeriod.value }
    if (selectedSubject.value && selectedSubject.value !== '') {
      params.course_id = selectedSubject.value
    }
    
    const response = await getDetailData(params)
    
    if (response.code === 200 && response.data) {
      detailData.value = response.data as DetailDataItem[]
    }
  } catch (error: any) {
    console.error('加载详细数据失败:', error)
    // 不再throw error，让其他模块能够独立加载
  }
}

/**
 * 加载所有数据
 */
const loadAllData = async () => {
  loading.value = true
  hasError.value = false
  errorMessage.value = ''
  
  try {
    await Promise.all([
      loadKeyMetrics(),
      loadScoreDistribution(),
      loadDifficultyAnalysis(),
      loadKnowledgeMastery(),
      loadStudyTimeStats(),
      loadDetailData()
    ])
  } catch (error: any) {
    hasError.value = true
    errorMessage.value = error.message || '数据加载失败，请稍后重试'
    ElMessage.error(errorMessage.value)
  } finally {
    loading.value = false
    // 等待DOM渲染完成后再初始化所有图表
    await nextTick()
    // 使用 requestAnimationFrame 确保 DOM 完全渲染
    requestAnimationFrame(() => {
      setTimeout(() => {
        initAllCharts()
      }, 200)
    })
  }
}

/**
 * 统一初始化所有图表（确保DOM已渲染）
 */
const initAllCharts = () => {
  console.log('🎨 initAllCharts 开始，检查缓存数据')
  
  // 检查关键 DOM 元素是否已渲染
  const refsReady = distributionChartRef.value && difficultyChartRef.value && 
                    knowledgeChartRef.value && timeChartRef.value
  
  if (!refsReady) {
    console.warn('⚠️ 图表容器 DOM 未完全准备好，延迟 300ms 后重试')
    setTimeout(() => {
      initAllCharts()
    }, 300)
    return
  }
  
  if (chartDataCache.value.distribution) {
    console.log('📊 初始化成绩分布图表')
    initDistributionChart(chartDataCache.value.distribution)
  }
  
  if (chartDataCache.value.difficulty) {
    console.log('📊 初始化难度分析图表')
    initDifficultyChart(chartDataCache.value.difficulty)
  }
  
  if (chartDataCache.value.knowledge) {
    console.log('📊 初始化知识点掌握度图表')
    initKnowledgeChart(chartDataCache.value.knowledge)
  }
  
  if (chartDataCache.value.time) {
    console.log('📊 初始化学习时长图表')
    initTimeChart(chartDataCache.value.time)
  }
  
  console.log('✅ initAllCharts 完成')
}

/**
 * 科目变化
 */
const handleSubjectChange = () => {
  loadAllData()
}

/**
 * 时间范围变化
 */
const handlePeriodChange = () => {
  loadAllData()
}

/**
 * 导出数据
 */
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

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

/**
 * 初始化成绩分布图
 */
const initDistributionChart = (data: ScoreDistributionResponse) => {
  console.log('🎨 initDistributionChart 被调用', { 
    hasRef: !!distributionChartRef.value,
    data 
  })
  
  if (!distributionChartRef.value) {
    console.warn('⚠️ distributionChartRef.value 不存在，跳过初始化')
    return
  }
  
  if (!distributionChart) {
    console.log('📊 创建新的 distribution 图表实例')
    try {
      distributionChart = echarts.init(distributionChartRef.value)
      console.log('✅ distribution 图表创建成功')
    } catch (error) {
      console.error('❌ 创建 distribution 图表失败:', error)
      return
    }
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        name: '成绩分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: data.excellent, name: '优秀(90-100)', itemStyle: { color: '#67c23a' } },
          { value: data.good, name: '良好(80-89)', itemStyle: { color: '#409eff' } },
          { value: data.medium, name: '中等(70-79)', itemStyle: { color: '#e6a23c' } },
          { value: data.pass, name: '及格(60-69)', itemStyle: { color: '#f56c6c' } },
          { value: data.fail, name: '不及格(<60)', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  
  distributionChart.setOption(option)
  console.log('✅ 成绩分布图表已更新')
}

/**
 * 初始化难度分析图
 */
const initDifficultyChart = (data: DifficultyAnalysisResponse) => {
  if (!difficultyChartRef.value) {
    console.warn('⚠️ difficultyChartRef.value 不存在，跳过初始化')
    return
  }
  
  if (!difficultyChart) {
    try {
      difficultyChart = echarts.init(difficultyChartRef.value)
    } catch (error) {
      console.error('❌ 创建 difficulty 图表失败:', error)
      return
    }
  }
  
  const keys = Object.keys(data)
  const values = Object.values(data)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    radar: {
      indicator: keys.map(key => ({
        name: key,
        max: 100
      })),
      radius: '65%'
    },
    series: [
      {
        name: '正确率',
        type: 'radar',
        data: [
          {
            value: values,
            name: '题目难度正确率',
            areaStyle: {
              color: 'rgba(102, 126, 234, 0.2)'
            },
            itemStyle: {
              color: '#667eea'
            }
          }
        ]
      }
    ]
  }
  
  difficultyChart.setOption(option)
}

/**
 * 初始化知识点掌握度图
 */
const initKnowledgeChart = (data: KnowledgeMasteryItem[]) => {
  if (!knowledgeChartRef.value) {
    console.warn('⚠️ knowledgeChartRef.value 不存在，跳过初始化')
    return
  }
  
  if (!knowledgeChart) {
    try {
      knowledgeChart = echarts.init(knowledgeChartRef.value)
    } catch (error) {
      console.error('❌ 创建 knowledge 图表失败:', error)
      return
    }
  }
  
  const names = data.map(item => item.name)
  const masteries = data.map(item => item.mastery)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '掌握度',
        type: 'bar',
        data: masteries,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#667eea' },
            { offset: 1, color: '#764ba2' }
          ])
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%'
        }
      }
    ]
  }
  
  knowledgeChart.setOption(option)
}

/**
 * 初始化学习时长图
 */
const initTimeChart = (data: StudyTimeStatsResponse) => {
  if (!timeChartRef.value) {
    console.warn('⚠️ timeChartRef.value 不存在，跳过初始化')
    return
  }
  
  if (!timeChart) {
    try {
      timeChart = echarts.init(timeChartRef.value)
    } catch (error) {
      console.error('❌ 创建 time 图表失败:', error)
      return
    }
  }
  
  const option = {
    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: data.labels
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}h'
      }
    },
    series: [
      {
        name: '学习时长',
        type: 'line',
        smooth: true,
        data: data.studyTime,
        itemStyle: {
          color: '#667eea'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102, 126, 234, 0.5)' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
          ])
        }
      },
      {
        name: '练习时长',
        type: 'line',
        smooth: true,
        data: data.practiceTime,
        itemStyle: {
          color: '#f093fb'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(240, 147, 251, 0.5)' },
            { offset: 1, color: 'rgba(240, 147, 251, 0.1)' }
          ])
        }
      }
    ]
  }
  
  timeChart.setOption(option)
}

/**
 * 组件挂载时初始化
 */
onMounted(() => {
  console.log('🚀 统计分析页面已挂载')
  // 加载课程列表
  loadCourses()
  
  // 加载所有统计数据
  nextTick(() => {
    loadAllData()
  })
  
  // 响应式处理
  window.addEventListener('resize', handleResize)
})

/**
 * 组件卸载时清理资源
 */
onUnmounted(() => {
  // 销毁图表实例
  distributionChart?.dispose()
  difficultyChart?.dispose()
  knowledgeChart?.dispose()
  timeChart?.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})

/**
 * 窗口大小改变处理
 */
const handleResize = () => {
  distributionChart?.resize()
  difficultyChart?.resize()
  knowledgeChart?.resize()
  timeChart?.resize()
}
</script>

<style lang="scss" scoped>
.statistics-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  
  .header-filters {
    display: flex;
    gap: 12px;
  }
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  
  p {
    margin-top: 16px;
    color: #909399;
    font-size: 14px;
  }
}

.metrics-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
  
  .metric-card {
    .metric-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      
      .metric-name {
        font-size: 14px;
        color: #606266;
      }
      
      .info-icon {
        color: #909399;
        cursor: pointer;
        
        &:hover {
          color: #409eff;
        }
      }
    }
    
    .metric-value {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 8px;
    }
    
    .metric-compare {
      font-size: 12px;
      color: #909399;
      
      .compare-value {
        margin-left: 4px;
        
        &.up {
          color: #67c23a;
        }
        
        &.down {
          color: #f56c6c;
        }
      }
    }
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
  
  .chart-card {
    .chart-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 16px 0;
    }
    
    .chart-container {
      width: 100%;
      height: 300px;
    }
  }
}

.detail-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }
}
</style>
