import type { ModelTeacherAnalysisClassInfo, ModelTeacherAnalysisExamInfo } from '@/api/data-contracts'
import { whenever } from '@vueuse/core'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { teacherScoreAnalysisApi } from '@/api'
import { useUserStorage } from '@/composables/useUserStorage'

export interface SelectOption {
  label: string
  value: number
  examSubjectId?: number
  subjectId?: number
  gradeKey?: number
}

// 班级信息类型
export interface ClassItem {
  label: string
  value: number
  gradeKey: number
}

/**
 * 首页状态管理
 */
export const useHomeStore = defineStore(
  'homeStore',
  () => {
    // 数据存储
    const loading = ref(false)
    const examDataMap = ref<Map<number, ModelTeacherAnalysisExamInfo>>(new Map())
    const classList = ref<ClassItem[]>([])

    // 已选择的数据（使用 useUserStorage 实现基于用户的持久化）
    const selectedClassId = useUserStorage<number>('home_selectedClassId', 0)
    const selectedExamId = useUserStorage<number>('home_selectedExamId', 0)
    const selectedSubjectId = useUserStorage<number>('home_selectedSubjectId', 0)
    const selectedExamSubjectId = useUserStorage<number>('home_selectedExamSubjectId', 0)
    const selectedGradeKey = useUserStorage<number>('home_selectedGradeKey', 0)

    // 计算属性：考试选项
    const examOptions = computed((): SelectOption[] => {
      return Array.from(examDataMap.value.values()).map(exam => ({
        label: exam.exam_name || '',
        value: exam.exam_id || 0,
      }))
    })

    // 计算属性：班级选项
    const classOptions = computed((): SelectOption[] => {
      return classList.value.map(item => ({
        label: item.label,
        value: item.value,
        gradeKey: item.gradeKey,
      }))
    })

    // 计算属性：根据选中考试获取科目选项
    const subjectOptions = computed((): SelectOption[] => {
      if (!selectedExamId.value) {
        return []
      }
      const examData = examDataMap.value.get(selectedExamId.value)
      if (!examData?.subjects) {
        return []
      }
      return examData.subjects.map(subject => ({
        label: subject.subject_name || '',
        value: subject.exam_subject_id || 0,
        examSubjectId: subject.exam_subject_id || 0,
        subjectId: subject.subject_id || 0,
      }))
    })

    /**
     * 获取选项数据
     */
    const fetchOptions = async () => {
      try {
        loading.value = true
        const response = await teacherScoreAnalysisApi.dataList()

        if (response) {
          // 处理班级数据并建立班级到年级的映射
          classList.value = (response.class_list || []).map((item: ModelTeacherAnalysisClassInfo) => {
            if (!item.class_key || !item.grade_key) {
              return null
            }
            const classKey = item.class_key
            const gradeKey = item.grade_key

            return {
              label: `${item.grade || ''} ${item.class || ''}`.trim(),
              value: classKey,
              gradeKey,
            }
          }).filter(item => item !== null) as ClassItem[]

          // 处理考试数据，存储到 map 中
          examDataMap.value.clear()
          ;(response.exam_list || []).forEach((exam: ModelTeacherAnalysisExamInfo) => {
            if (exam.exam_id) {
              examDataMap.value.set(exam.exam_id, exam)
            }
          })

          console.log('数据获取完成:')
          console.log('classList数量:', classList.value.length)
          console.log('examDataMap数量:', examDataMap.value.size)
        }
      }
      catch (error) {
        console.error('获取选项数据失败:', error)
        throw error
      }
      finally {
        loading.value = false
      }
    }

    /**
     * 当考试选择改变时，自动选择第一个科目
     */
    const onExamChange = (examId: number | null) => {
      selectedExamId.value = examId
      selectedSubjectId.value = subjectOptions.value[0].subjectId || null
      selectedExamSubjectId.value = subjectOptions.value[0].examSubjectId || null
    }

    /**
     * 设置选项数据（兼容旧接口）
     */
    const setOptions = (exams: SelectOption[], classes: SelectOption[], subjects: SelectOption[]) => {
      // 这个方法保留是为了兼容性，但推荐使用fetchOptions
      console.warn('setOptions is deprecated, use fetchOptions instead')
    }

    /**
     * 清空所有选择
     */
    const clearSelections = () => {
      selectedClassId.value = null
      selectedExamId.value = null
      selectedSubjectId.value = null
      selectedExamSubjectId.value = null
    }

    /**
     * 重置store状态
     */
    const reset = () => {
      classList.value = []
      examDataMap.value.clear()
      loading.value = false
      clearSelections()
    }

    // 监听考试ID变化，自动选择第一个科目
    whenever(selectedExamId, (examId) => {
      selectedSubjectId.value = subjectOptions.value[0].subjectId || null
      selectedExamSubjectId.value = subjectOptions.value[0].examSubjectId || null
    })

    onMounted(async () => {
      await fetchOptions()

      // 如果有默认选择，获取统计数据
      if (examOptions.value.length > 0 && classOptions.value.length > 0) {
      // 设置默认选择
        if (!selectedExamId.value) {
          selectedExamId.value = examOptions.value[0]?.value as number
        }
        if (!selectedClassId.value) {
          selectedClassId.value = classOptions.value[0]?.value as number
        }
        if (!selectedExamSubjectId.value && subjectOptions.value.length > 0) {
          selectedExamSubjectId.value = subjectOptions.value[0]?.value as number
        }
      }
    })

    return {
      // 数据状态
      loading,

      // 选项数据（计算属性）
      examOptions,
      classOptions,
      subjectOptions,

      // 已选择的数据
      selectedClassId,
      selectedExamId,
      selectedSubjectId,
      selectedExamSubjectId,
      selectedGradeKey,

      // 方法
      fetchOptions,
      onExamChange,
      setOptions,
      clearSelections,
      reset,
    }
  },
)
