<template>
  <div class="course-stats">
    <a-page-header
      :title="courseName ? `${courseName} - 数据统计` : '数据统计'"
      @back="() => router.back()"
    />

    <a-spin :spinning="loading">
      <div style="margin-top: 16px;">
        <!-- 概览卡片 -->
        <a-row :gutter="16" style="margin-bottom: 24px;">
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="总授课次数"
                :value="stats.totalLessons || 0"
                prefix="📚"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="参与教师数"
                :value="stats.totalTeachers || 0"
                prefix="👨‍🏫"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="参与学生数"
                :value="stats.totalStudents || 0"
                prefix="👦"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="平均评分"
                :value="stats.avgRating || 0"
                :precision="1"
                prefix="⭐"
                suffix="/ 5"
              />
            </a-card>
          </a-col>
        </a-row>

        <!-- 详细统计 -->
        <a-row :gutter="16">
          <!-- 授课记录时间趋势 -->
          <a-col :span="12">
            <a-card title="授课记录趋势" :bordered="false">
              <div v-if="stats.lessonTrend && stats.lessonTrend.length > 0" style="height: 200px;">
                <a-row :gutter="[8, 16]">
                  <a-col
                    v-for="(item, index) in stats.lessonTrend"
                    :key="index"
                    :span="24 / stats.lessonTrend.length"
                  >
                    <div style="text-align: center;">
                      <div style="font-size: 12px; color: #666;">{{ item.date }}</div>
                      <div style="font-size: 20px; font-weight: bold; color: #1890ff; margin-top: 4px;">
                        {{ item.count }}
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </div>
              <a-empty v-else description="暂无数据" />
            </a-card>
          </a-col>

          <!-- 教师反馈分布 -->
          <a-col :span="12">
            <a-card title="教师反馈分布" :bordered="false">
              <div v-if="stats.feedbackDistribution">
                <a-row :gutter="[16, 16]">
                  <a-col :span="12">
                    <a-statistic
                      title="设计质量"
                      :value="stats.feedbackDistribution.designQuality || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                    <a-progress
                      :percent="(stats.feedbackDistribution.designQuality || 0) * 20"
                      status="active"
                      size="small"
                    />
                  </a-col>
                  <a-col :span="12">
                    <a-statistic
                      title="学生参与度"
                      :value="stats.feedbackDistribution.participation || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                    <a-progress
                      :percent="(stats.feedbackDistribution.participation || 0) * 20"
                      status="active"
                      size="small"
                    />
                  </a-col>
                  <a-col :span="12">
                    <a-statistic
                      title="目标达成度"
                      :value="stats.feedbackDistribution.goalAchievement || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                    <a-progress
                      :percent="(stats.feedbackDistribution.goalAchievement || 0) * 20"
                      status="active"
                      size="small"
                    />
                  </a-col>
                  <a-col :span="12">
                    <a-statistic
                      title="反馈数量"
                      :value="stats.feedbackDistribution.totalFeedbacks || 0"
                      suffix="条"
                    />
                  </a-col>
                </a-row>
              </div>
              <a-empty v-else description="暂无反馈数据" />
            </a-card>
          </a-col>
        </a-row>

        <a-row :gutter="16" style="margin-top: 16px;">
          <!-- 最近授课记录 -->
          <a-col :span="24">
            <a-card title="最近授课记录" :bordered="false">
              <a-table
                :columns="lessonColumns"
                :data-source="stats.recentLessons || []"
                :pagination="false"
                size="small"
                :loading="loading"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'teacher'">
                    {{ record.teacher?.name || '-' }}
                  </template>
                  <template v-else-if="column.key === 'class'">
                    {{ record.class?.name || '-' }}
                  </template>
                  <template v-else-if="column.key === 'date'">
                    {{ formatDate(record.startDatetime) }}
                  </template>
                  <template v-else-if="column.key === 'duration'">
                    {{ record.actualDuration || record.duration || '-' }} 分钟
                  </template>
                  <template v-else-if="column.key === 'status'">
                    <a-tag :color="getLessonStatusColor(record.status)">
                      {{ getLessonStatusText(record.status) }}
                    </a-tag>
                  </template>
                </template>
              </a-table>
              <div v-if="!stats.recentLessons || stats.recentLessons.length === 0" style="padding: 40px; text-align: center;">
                <a-empty description="暂无授课记录" />
              </div>
            </a-card>
          </a-col>
        </a-row>

        <a-row :gutter="16" style="margin-top: 16px;">
          <!-- 学生表现统计 -->
          <a-col :span="24">
            <a-card title="学生表现统计" :bordered="false">
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-card size="small">
                    <a-statistic
                      title="平均专注度"
                      :value="stats.studentPerformance?.avgFocus || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                  </a-card>
                </a-col>
                <a-col :span="6">
                  <a-card size="small">
                    <a-statistic
                      title="平均参与度"
                      :value="stats.studentPerformance?.avgParticipation || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                  </a-card>
                </a-col>
                <a-col :span="6">
                  <a-card size="small">
                    <a-statistic
                      title="平均兴趣度"
                      :value="stats.studentPerformance?.avgInterest || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                  </a-card>
                </a-col>
                <a-col :span="6">
                  <a-card size="small">
                    <a-statistic
                      title="平均理解度"
                      :value="stats.studentPerformance?.avgUnderstanding || 0"
                      :precision="1"
                      suffix="/ 5"
                    />
                  </a-card>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import * as courseApi from '@/api/course';

const router = useRouter();
const route = useRoute();

const loading = ref(false);
const courseName = ref('');
const stats = ref<any>({});

const lessonColumns = [
  { title: '教师', key: 'teacher', width: 120 },
  { title: '班级', key: 'class', width: 120 },
  { title: '授课时间', key: 'date', width: 150 },
  { title: '时长', key: 'duration', width: 100 },
  { title: '状态', key: 'status', width: 100 },
];

onMounted(async () => {
  await fetchCourseStats();
});

const fetchCourseStats = async () => {
  loading.value = true;
  try {
    const courseId = route.params.id as string;

    // 获取统计数据
    const statsData = await courseApi.getCourseStats(courseId);
    stats.value = statsData;

    // 从接口返回中获取课程名称
    courseName.value = statsData.courseName || '';
  } catch (error) {
    console.error('获取统计数据失败:', error);
    message.error('获取统计数据失败');
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

const getLessonStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PLANNED: 'default',
    IN_PROGRESS: 'processing',
    COMPLETED: 'success',
    CANCELLED: 'error',
  };
  return colorMap[status] || 'default';
};

const getLessonStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    PLANNED: '计划中',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return textMap[status] || status;
};
</script>

<style scoped lang="scss">
.course-stats {
  background: #f5f5f5;
  min-height: calc(100vh - 64px);

  :deep(.ant-page-header) {
    background: white;
    padding: 16px 24px;
  }

  :deep(.ant-card) {
    margin-bottom: 16px;
  }
}
</style>
