<script setup lang="ts">
import { computed, onMounted, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { exportReport, fetchClassRanking, fetchMastery, fetchQuestionErrors, fetchReportOverview, fetchReportTrends } from '@/api/admin'

use([CanvasRenderer, LineChart, BarChart, GridComponent, TooltipComponent, LegendComponent])

const overview = shallowRef<Record<string, number>>({})
const trends = shallowRef<Array<Record<string, unknown>>>([])
const errors = shallowRef<Array<Record<string, unknown>>>([])
const ranking = shallowRef<Array<Record<string, unknown>>>([])
const mastery = shallowRef<{ banks: Array<Record<string, unknown>>; categories: Array<Record<string, unknown>> }>({
  banks: [],
  categories: [],
})

const trendOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  legend: { data: ['练习次数', '总题数'] },
  grid: { left: 36, right: 18, top: 36, bottom: 28 },
  xAxis: { type: 'category', data: trends.value.map((item) => item.day) },
  yAxis: { type: 'value' },
  series: [
    { name: '练习次数', type: 'line', smooth: true, data: trends.value.map((item) => Number(item.attempts ?? 0)) },
    { name: '总题数', type: 'bar', data: trends.value.map((item) => Number(item.total_questions ?? 0)) },
  ],
}))

const masteryOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  grid: { left: 36, right: 18, top: 24, bottom: 58 },
  xAxis: {
    type: 'category',
    axisLabel: { rotate: 28 },
    data: mastery.value.banks.map((item) => item.name),
  },
  yAxis: { type: 'value', max: 100 },
  series: [
    {
      name: '掌握度',
      type: 'bar',
      data: mastery.value.banks.map((item) => Number(item.accuracy ?? 0)),
    },
  ],
}))

async function load() {
  overview.value = (await fetchReportOverview()).data
  trends.value = (await fetchReportTrends()).data
  errors.value = (await fetchQuestionErrors()).data.items
  ranking.value = (await fetchClassRanking()).data
  mastery.value = (await fetchMastery()).data
}

async function exportData() {
  await exportReport()
  ElMessage.success('报表已导出到 storage/app/exports')
}

onMounted(load)
</script>

<template>
  <section class="report-page">
    <div class="toolbar mb-4">
      <div class="flex-1">
        <h1 class="page-title">统计报表</h1>
        <p class="muted text-sm mt-1">查看练习趋势、正确率、错题和题目错误率。</p>
      </div>
      <ElButton type="primary" @click="exportData">导出报表</ElButton>
    </div>

    <div class="report-stats">
      <article v-for="(value, key) in overview" :key="key" class="stat-card">
        <span>{{ key }}</span>
        <strong>{{ value }}</strong>
      </article>
    </div>

    <section class="panel p-5 mt-4">
      <h2 class="page-title mb-3">近 14 天趋势</h2>
      <VChart class="trend-chart" :option="trendOption" autoresize />
    </section>

    <section class="panel p-5 mt-4">
      <div class="report-split">
        <div>
          <h2 class="page-title mb-3">题库掌握度</h2>
          <VChart class="mastery-chart" :option="masteryOption" autoresize />
        </div>
        <div>
          <h2 class="page-title mb-3">分类掌握度</h2>
          <ElTable :data="mastery.categories" row-key="id" height="320">
            <ElTableColumn prop="bank_name" label="题库" min-width="120" show-overflow-tooltip />
            <ElTableColumn prop="name" label="分类" min-width="120" show-overflow-tooltip />
            <ElTableColumn prop="attempts" label="作答" width="80" />
            <ElTableColumn prop="accuracy" label="掌握度" width="100">
              <template #default="{ row }">{{ row.accuracy }}%</template>
            </ElTableColumn>
          </ElTable>
        </div>
      </div>
    </section>

    <section class="panel p-5 mt-4">
      <h2 class="page-title mb-3">班级排行</h2>
      <ElTable :data="ranking" row-key="id">
        <ElTableColumn prop="name" label="班级" min-width="160" />
        <ElTableColumn prop="members_count" label="成员" width="90" />
        <ElTableColumn prop="attempts" label="练习次数" width="110" />
        <ElTableColumn prop="total_questions" label="作答题数" width="110" />
        <ElTableColumn prop="accuracy" label="正确率" width="100">
          <template #default="{ row }">{{ row.accuracy }}%</template>
        </ElTableColumn>
      </ElTable>
    </section>

    <section class="panel p-5 mt-4">
      <h2 class="page-title mb-3">题目错误率</h2>
      <ElTable :data="errors" row-key="id">
        <ElTableColumn prop="content" label="题干" min-width="280" show-overflow-tooltip />
        <ElTableColumn prop="attempts" label="作答次数" />
        <ElTableColumn prop="wrong_count" label="错误次数" />
      </ElTable>
    </section>
  </section>
</template>

<style scoped>
.report-stats {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 14px;
}

.stat-card {
  padding: 18px;
  border: 1px solid var(--qq-line);
  border-radius: 8px;
  background: white;
}

.stat-card span {
  display: block;
  color: var(--qq-muted);
}

.stat-card strong {
  font-size: 28px;
}

.trend-chart {
  width: 100%;
  height: 320px;
}

.mastery-chart {
  width: 100%;
  height: 320px;
}

.report-split {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(320px, 0.9fr);
  gap: 18px;
}

@media (max-width: 900px) {
  .report-split {
    grid-template-columns: 1fr;
  }
}
</style>
