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

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import AverageScoreChart from '@/components/class-analysis/AverageScoreChart.vue'
import ExamQuestionOverview from '@/components/class-analysis/ExamQuestionOverview.vue'
import { useHomeStore } from '@/store/home'

defineOptions({
  name: 'ClassAnalysisPage',
})

// 使用store
const homeStore = useHomeStore()

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

// 对比班级ID
const compareClassId = ref<number | null>(null)

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

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

// 班级选择选项（用于对比班级选择）
const classOptions = computed(() => homeStore.classOptions.map(cls => ({
  label: cls.label,
  value: cls.value,
})))

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

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

  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) {
  compareClassId.value = classId
  showCompareClassDialog.value = false
}

// 页面初始化
onMounted(async () => {
  try {
    // 如果store中没有数据，先获取选项数据
    if (homeStore.classOptions.length === 0) {
      await homeStore.fetchOptions()
    }
  }
  catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<template>
  <view class="class-analysis-page min-h-screen bg-slate-50">
    <!-- 导航栏 -->
    <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>

    <!-- 主要内容区域 -->
    <view class="p-4 space-y-4">
      <!-- 均分对比图表组件 -->
      <AverageScoreChart
        ref="chartRef"
        :selected-subject-id="selectedSubjectId"
        :compare-class-id="compareClassId"
        @open-compare-class-dialog="openCompareClassDialog"
      />

      <!-- 考试小题概览组件 -->
      <ExamQuestionOverview
        :selected-subject-id="selectedSubjectId"
      />
    </view>

    <!-- 对比班级选择弹窗 -->
    <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 text-center">
          <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"
            :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>

        <!-- 取消按钮 -->
        <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>
