<route lang="jsonc">
{
  "style": {
    "navigationStyle": "custom",
    "navigationBarTitleText": "班级分析"
  }
}
</route>

<script lang="ts" setup>
import type { ExamQuestionStat } from '@/service/types'
import { whenever } from '@vueuse/core'
import { computed, ref } from 'vue'
import AverageScoreChart from '@/components/class-analysis/AverageScoreChart.vue'
import ExamQuestionOverview from '@/components/class-analysis/ExamQuestionOverview.vue'
import { teacherAnalysisQuestionStatUsingPost } from '@/service/laoshixiaotichengjifenxi'
import { useHomeStore } from '@/store/home'

defineOptions({
  name: 'ClassAnalysisPage',
})

// 使用store
const homeStore = useHomeStore()

// 选中的科目ID，0表示全科
const selectedSubjectId = ref(0)

// z-paging 引用
const pagingRef = ref<ZPagingRef>()

// 考试题目统计列表
const examQuestionList = ref<ExamQuestionStat[]>([])

// 查询考试题目统计列表
async function queryExamQuestionList(pageNo: number, pageSize: number) {
  if (selectedSubjectId.value === 0) {
    pagingRef.value?.complete([])
    return
  }

  const result = await teacherAnalysisQuestionStatUsingPost({
    body: {
      grade_key: homeStore.selectedGradeKey || 0,
      class_key: homeStore.selectedClassId || 0,
      subject_id: selectedSubjectId.value,
      page: pageNo,
      page_size: pageSize,
    },
  })

  pagingRef.value?.complete(result?.exam_question_list || [])
}

// 对比班级选择弹窗
const showCompareClassDialog = ref(false)

// 图表组件引用
const chartRef = ref<InstanceType<typeof AverageScoreChart>>()

// 班级选择选项（用于对比班级选择，过滤掉当前班级）
const classOptions = computed(() =>
  homeStore.classOptions
    .filter(cls => cls.value !== homeStore.selectedClassId)
    .map(cls => ({
      label: cls.label,
      value: cls.value,
    })),
)

// 当前对比班级ID（从子组件获取）
const compareClassId = computed(() => chartRef.value?.compareClassId || null)

// 科目选项（包含全科）
const subjectTabs = computed(() => {
  const tabs = [
    { name: 'all', title: '全科', subjectId: 0 },
  ]

  homeStore.subjectOptions.forEach((subject) => {
    tabs.push({
      name: `subject-${subject.subjectId}`,
      title: subject.label,
      subjectId: subject.subjectId || 0,
    })
  })

  return tabs
})

// 当前选中的科目标签
const activeTab = computed({
  get: () => selectedSubjectId.value === 0 ? 'all' : `subject-${selectedSubjectId.value}`,
  set: (value) => {
    if (value === 'all') {
      selectedSubjectId.value = 0
    }
    else {
      const subjectId = Number.parseInt(value.replace('subject-', ''))
      selectedSubjectId.value = subjectId
    }
  },
})

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 科目切换处理
function handleTabClick({ name }: { name: string }) {
  activeTab.value = name
}

// 打开对比班级选择
function openCompareClassDialog() {
  showCompareClassDialog.value = true
}

// 选择对比班级
function handleCompareClassChange(classId: number) {
  if (chartRef.value) {
    chartRef.value.compareClassId = classId
  }
  showCompareClassDialog.value = false
}

whenever(() => selectedSubjectId.value, () => {
  pagingRef.value?.reload()
})
</script>

<template>
  <view class="class-analysis-page min-h-screen bg-slate-50">
    <!-- 主要内容区域 - z-paging 包裹 -->
    <z-paging
      ref="pagingRef"
      v-model="examQuestionList"
      :refresher-enabled="true"
      :auto="true"
      :default-page-size="5"
      @query="queryExamQuestionList"
    >
      <template #top>
        <!-- 导航栏 -->
        <wd-navbar placeholder fixed>
          <template #left>
            <div class="flex items-center" @tap="goBack">
              <wd-icon name="arrow-left" size="20px" />
            </div>
          </template>
          <template #title>
            <text class="text-lg font-semibold">班级分析</text>
          </template>
        </wd-navbar>

        <!-- 科目选择标签栏 -->
        <wd-tabs
          v-model="activeTab"
          sticky
          class="bg-white"
          @click="handleTabClick"
        >
          <wd-tab
            v-for="tab in subjectTabs"
            :key="tab.name"
            :name="tab.name"
            :title="tab.title"
          />
        </wd-tabs>
      </template>

      <view class="p-4">
        <!-- 均分对比图表组件 -->
        <AverageScoreChart
          ref="chartRef"
          :selected-subject-id="selectedSubjectId"
          @open-compare-class-dialog="openCompareClassDialog"
        />
      </view>

      <!-- 考试小题概览组件 -->
      <view v-if="selectedSubjectId !== 0" class="rounded-xl bg-white p-4 shadow-sm">
        <view class="mb-4">
          <text class="text-lg text-slate-800 font-semibold">考试小题概览</text>
        </view>
        <ExamQuestionOverview :data-list="examQuestionList" />
      </view>
    </z-paging>

    <!-- 对比班级选择弹窗 -->
    <wd-popup
      v-model="showCompareClassDialog"
      position="center"
      custom-style="border-radius: 16px; width: 80%; max-width: 400px;"
    >
      <view class="p-6">
        <!-- 标题 -->
        <view class="mb-6 flex items-center justify-between">
          <text class="text-lg text-gray-800 font-semibold">选择对比班级</text>
        </view>

        <!-- 班级列表 -->
        <view class="max-h-80 overflow-y-auto space-y-2">
          <view
            v-for="cls in classOptions"
            :key="cls.value"
            class="border border-gray-200 rounded-lg p-3 text-center transition-all"
            :class="compareClassId === cls.value ? 'border-blue-500 bg-blue-50' : 'hover:bg-gray-50'"
            @tap="handleCompareClassChange(cls.value)"
          >
            <text class="text-sm text-gray-800">{{ cls.label }}</text>
          </view>

          <!-- 空状态 -->
          <view v-if="classOptions.length === 0" class="py-8 text-center">
            <text class="text-sm text-gray-500">暂无其他班级</text>
          </view>
        </view>

        <!-- 取消按钮 -->
        <view class="mt-6">
          <wd-button type="info" class="w-full" @click="showCompareClassDialog = false">
            取消
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss">
.class-analysis-page {
  // 页面样式
}
</style>
