import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { teacherAnalysisDataUsingGet } from '@/service/laoshichengjifenxi'

export interface SelectOption {
  label: string
  value: number
}

// 考试科目组合数据类型
export interface ExamSubjectItem {
  examId: number
  examName: string
  examSubjectId: number
  subjectName: string
}

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

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

    // 已选择的数据
    const selectedClassId = ref<number | null>(null)
    const selectedExamId = ref<number | null>(null)
    const selectedSubjectId = ref<number | null>(null)
    const selectedGradeKey = ref<number | null>(null)

    // 计算属性：唯一的考试列表
    const examOptions = computed((): SelectOption[] => {
      console.log('examOptions计算属性被调用，examSubjectList长度:', examSubjectList.value.length)
      const examMap = new Map<number, string>()
      examSubjectList.value.forEach((item) => {
        if (!examMap.has(item.examId)) {
          examMap.set(item.examId, item.examName)
        }
      })
      const result = Array.from(examMap.entries()).map(([id, name]) => ({
        label: name,
        value: id,
      }))
      console.log('examOptions计算结果:', result)
      return result
    })

    // 计算属性：班级列表
    const classOptions = computed((): SelectOption[] => {
      console.log('classOptions计算属性被调用，classList长度:', classList.value.length)
      const result = classList.value.map(item => ({
        label: item.label,
        value: item.value,
      }))
      console.log('classOptions计算结果:', result)
      return result
    })

    // 计算属性：根据选中考试过滤的科目列表
    const subjectOptions = computed((): SelectOption[] => {
      if (!selectedExamId.value) {
        return []
      }
      return examSubjectList.value
        .filter(item => item.examId === selectedExamId.value)
        .map(item => ({
          label: item.subjectName,
          value: item.examSubjectId,
        }))
    })

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

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

            // 建立班级到年级的映射
            classGradeMap.value.set(classKey, gradeKey)

            return {
              label: `${item.grade || ''} ${item.class || ''}`.trim(),
              value: classKey,
              gradeKey,
            }
          })

          // 存储考试科目组合数据
          examSubjectList.value = (response.exam_list || []).map((item: any) => ({
            examId: item.exam_id || 0,
            examName: item.exam_name || '',
            examSubjectId: item.exam_subject_id || 0,
            subjectName: item.subject_name || '',
          }))

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

    /**
     * 当班级选择改变时，自动设置对应的年级
     */
    const onClassChange = (classId: number | null) => {
      selectedClassId.value = classId
      if (classId) {
        selectedGradeKey.value = classGradeMap.value.get(classId) || null
      }
      else {
        selectedGradeKey.value = null
      }
    }

    /**
     * 当考试选择改变时，清空科目选择
     */
    const onExamChange = (examId: number | null) => {
      selectedExamId.value = examId
      selectedSubjectId.value = 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
      selectedGradeKey.value = null
    }

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

    return {
      // 数据状态
      loading,

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

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

      // 方法
      fetchOptions,
      onClassChange,
      onExamChange,
      setOptions,
      clearSelections,
      reset,
    }
  },
  {
    persist: true,
  },
)
