<template>
  <AdminLayout title="学习记录" subtitle="学习记录统计与管理">
    <div class="study-records">
      <!-- 统计图表区域 -->
      <div class="statistics-section">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>本周学习时长统计</span>
            </div>
          </template>
          <div ref="durationChartRef" class="chart-container"></div>
        </el-card>
      </div>

      <!-- 排行榜区域 -->
      <div class="rankings-section">
        <el-row :gutter="20">
          <!-- 学习时长排行榜 -->
          <el-col :span="12">
            <el-card class="ranking-card">
              <template #header>
                <div class="card-header">
                  <span>学习时长排行榜</span>
                </div>
              </template>
              <div class="ranking-list">
                <div v-for="(item, index) in durationRanking" :key="item.userId" class="ranking-item">
                  <span class="rank" :class="getRankClass(index)">{{ index + 1 }}</span>
                  <span class="username">{{ item.username }}</span>
                  <span class="value">{{ formatDuration(item.totalDuration) }}</span>
                </div>
                <el-empty v-if="!durationRanking.length" description="暂无数据" />
              </div>
            </el-card>
          </el-col>

          <!-- 任务完成排行榜 -->
          <el-col :span="12">
            <el-card class="ranking-card">
              <template #header>
                <div class="card-header">
                  <span>任务完成排行榜</span>
                </div>
              </template>
              <div class="ranking-list">
                <div v-for="(item, index) in taskCompletionRanking" :key="item.userId" class="ranking-item">
                  <span class="rank" :class="getRankClass(index)">{{ index + 1 }}</span>
                  <span class="username">{{ item.username }}</span>
                  <span class="value">{{ item.completedTaskCount }}个任务</span>
                </div>
                <el-empty v-if="!taskCompletionRanking.length" description="暂无数据" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <!-- 课程学习排行榜 -->
          <el-col :span="12">
            <el-card class="ranking-card">
              <template #header>
                <div class="card-header">
                  <span>热门课程排行榜</span>
                </div>
              </template>
              <div class="ranking-list">
                <div v-for="(item, index) in courseRanking" :key="item.resourceId" class="ranking-item">
                  <span class="rank" :class="getRankClass(index)">{{ index + 1 }}</span>
                  <span class="username">{{ item.resourceName }}</span>
                  <span class="value">{{ item.learnerCount }}人学习</span>
                </div>
                <el-empty v-if="!courseRanking.length" description="暂无数据" />
              </div>
            </el-card>
          </el-col>

          <!-- 文章学习排行榜 -->
          <el-col :span="12">
            <el-card class="ranking-card">
              <template #header>
                <div class="card-header">
                  <span>热门文章排行榜</span>
                </div>
              </template>
              <div class="ranking-list">
                <div v-for="(item, index) in articleRanking" :key="item.resourceId" class="ranking-item">
                  <span class="rank" :class="getRankClass(index)">{{ index + 1 }}</span>
                  <span class="username">{{ item.resourceName }}</span>
                  <span class="value">{{ item.learnerCount }}人阅读</span>
                </div>
                <el-empty v-if="!articleRanking.length" description="暂无数据" />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { ElCard, ElRow, ElCol, ElEmpty, ElMessage } from 'element-plus';
import { AdminLayout } from '@/views/admin';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { learningRecordApi } from '@/apis/study/learning-record';

defineOptions({
  name: 'StudyRecordsView'
});

// 图表实例
const durationChartRef = ref<HTMLDivElement>();
let durationChart: ECharts | null = null;

// 排行榜数据
const durationRanking = ref<any[]>([]);
const courseRanking = ref<any[]>([]);
const articleRanking = ref<any[]>([]);
const taskCompletionRanking = ref<any[]>([]);

onMounted(() => {
  loadChartsData();
  loadRankingsData();
});

onUnmounted(() => {
  if (durationChart) {
    durationChart.dispose();
  }
});

// 加载图表数据
async function loadChartsData() {
  try {
    const result = await learningRecordApi.getStudyRecordsCharts();
    if (result.success && result.data) {
      const durationByType = result.data.durationByType || [];
      await nextTick();
      initDurationChart(durationByType);
    }
  } catch (error) {
    console.error('加载图表数据失败:', error);
    ElMessage.error('加载图表数据失败');
  }
}

// 加载排行榜数据
async function loadRankingsData() {
  try {
    const result = await learningRecordApi.getStudyRecordsRankings();
    if (result.success && result.data) {
      durationRanking.value = result.data.durationRanking || [];
      courseRanking.value = result.data.courseRanking || [];
      articleRanking.value = result.data.articleRanking || [];
      taskCompletionRanking.value = result.data.taskCompletionRanking || [];
    }
  } catch (error) {
    console.error('加载排行榜数据失败:', error);
    ElMessage.error('加载排行榜数据失败');
  }
}

// 初始化学习时长图表
function initDurationChart(data: any[]) {
  if (!durationChartRef.value) return;

  if (durationChart) {
    durationChart.dispose();
  }

  durationChart = echarts.init(durationChartRef.value);

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const duration = params.value;
        const hours = Math.floor(duration / 3600);
        const minutes = Math.floor((duration % 3600) / 60);
        const secs = duration % 60;
        
        let timeStr = '';
        if (hours > 0) timeStr += `${hours}小时`;
        if (minutes > 0) timeStr += `${minutes}分钟`;
        if (secs > 0 || timeStr === '') timeStr += `${secs}秒`;
        
        return `${params.name}<br/>学习时长: ${timeStr}<br/>学习人数: ${params.data.userCount}人`;
      }
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '学习时长统计',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: (params: any) => {
            const duration = params.value;
            const hours = Math.floor(duration / 3600);
            const minutes = Math.floor((duration % 3600) / 60);
            const secs = duration % 60;
            
            let timeStr = '';
            if (hours > 0) {
              timeStr = `${hours}h${minutes}m`;
            } else if (minutes > 0) {
              timeStr = `${minutes}m${secs}s`;
            } else {
              timeStr = `${secs}s`;
            }
            
            return `${params.name}\n${timeStr}`;
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: data.map(item => ({
          name: item.resourceType,
          value: item.totalDuration || 0,
          userCount: item.userCount || 0
        }))
      }
    ]
  };

  durationChart.setOption(option);

  // 响应式调整
  window.addEventListener('resize', () => {
    durationChart?.resize();
  });
}

// 格式化时长
function formatDuration(seconds: number): string {
  if (!seconds || seconds === 0) {
    return '0秒';
  }
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  
  let result = '';
  if (hours > 0) {
    result += `${hours}小时`;
  }
  if (minutes > 0) {
    result += `${minutes}分钟`;
  }
  if (secs > 0 || result === '') {
    result += `${secs}秒`;
  }
  
  return result;
}

// 获取排名样式
function getRankClass(index: number): string {
  if (index === 0) return 'rank-first';
  if (index === 1) return 'rank-second';
  if (index === 2) return 'rank-third';
  return '';
}
</script>

<style lang="scss" scoped>
.study-records {
  padding: 20px;
}

.statistics-section {
  margin-bottom: 20px;

  .chart-card {
    .card-header {
      font-weight: 600;
      font-size: 16px;
    }

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

.rankings-section {
  .ranking-card {
    height: 100%;
    .card-header {
      font-weight: 600;
      font-size: 16px;
    }

    .ranking-list {
      max-height: 400px;
      overflow-y: auto;

      .ranking-item {
        display: flex;
        align-items: center;
        padding: 12px;
        margin-bottom: 8px;
        background: #f5f7fa;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover {
          background: #e8edf3;
          // transform: translateX(5px);
        }

        .rank {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 32px;
          height: 32px;
          margin-right: 12px;
          font-weight: bold;
          border-radius: 50%;
          background: #909399;
          color: #fff;
          font-size: 14px;

          &.rank-first {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #333;
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
          }

          &.rank-second {
            background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
            color: #333;
            box-shadow: 0 2px 8px rgba(192, 192, 192, 0.4);
          }

          &.rank-third {
            background: linear-gradient(135deg, #cd7f32, #e09856);
            color: #fff;
            box-shadow: 0 2px 8px rgba(205, 127, 50, 0.4);
          }
        }

        .username {
          flex: 1;
          font-size: 14px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .value {
          font-size: 14px;
          font-weight: 600;
          color: #409eff;
        }
      }
    }
  }
}
</style>
