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

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

/**
 * 首页状态管理
 */
export const useHomeStore = defineStore(
  'homeStore',
  () => {
    // 获取 userStore
    const userStore = useUserStore()

    // 数据存储
    const loading = ref(false)
    const examDataMap = ref<Map<number, ModelTeacherAnalysisExamInfo>>(new Map())

    // 已选择的数据（使用 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 examOptions = computed((): SelectOption[] => {
      return Array.from(examDataMap.value.values()).map(exam => ({
        label: exam.exam_name || '',
        value: exam.exam_id || 0,
      }))
    })

    // 计算属性：班级选项（带角色权限筛选）
    const classOptions = computed((): SelectOption[] => {
      if (!selectedExamId.value) {
        return []
      }
      const examData = examDataMap.value.get(selectedExamId.value)
      if (!examData?.classes) {
        return []
      }
      const allClasses = examData.classes.map((item, index) => ({
        label: `${item.grade_name || ''} ${item.class_name || ''}`.trim(),
        value: index,
        classKey: item.class_key,
        gradeKey: Number(item.grade_key),
      })) || []

      // 如果没有选择角色，返回所有班级
      const currentRole = userStore.selectedRole
      if (!currentRole) {
        return allClasses
      }

      // 根据角色类型筛选班级
      return allClasses.filter((classItem) => {
        // 1. 任课老师 (role_key: 1): 只能访问特定科目的特定班级
        if (currentRole.role_key === 1) {
          return currentRole.grade_key === classItem.gradeKey && currentRole.class_key === classItem.classKey
        }

        // 2. 班主任 (role_key: 2): 可以访问管理的班级
        if (currentRole.role_key === 2) {
          return currentRole.grade_key === classItem.gradeKey && currentRole.class_key === classItem.classKey
        }

        // 3. 年级主任 (role_key: 3): 可以访问对应年级的所有班级
        if (currentRole.role_key === 3) {
          return currentRole.grade_key === classItem.gradeKey
        }

        // 4. 学科组长 (role_key: 4): 可以访问对应科目的所有班级（在当前角色的年级内）
        if (currentRole.role_key === 4) {
          // 学科组长可以看当前角色年级的所有班级
          return currentRole.grade_key === classItem.gradeKey
        }

        return false
      })
    })

    const selectedClassKey = computed(() => {
      return classOptions.value.find(item => item.value === selectedClassId.value)?.classKey || 0
    })

    const selectedGradeKey = computed(() => {
      return classOptions.value.find(item => item.value === selectedClassId.value)?.gradeKey || 0
    })

    // 计算属性：根据选中考试获取科目选项（带角色权限筛选）
    const subjectOptions = computed((): SelectOption[] => {
      if (!selectedExamId.value) {
        return []
      }
      const examData = examDataMap.value.get(selectedExamId.value)
      if (!examData?.subjects) {
        return []
      }

      // 先生成所有科目选项
      const allSubjects = 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 currentRole = userStore.selectedRole
      if (!currentRole) {
        return allSubjects
      }

      // 根据角色类型筛选科目
      return allSubjects.filter((subjectItem) => {
        // 1. 任课老师 (role_key: 1): 只能访问特定科目
        if (currentRole.role_key === 1) {
          return currentRole.subject_id === subjectItem.subjectId
        }

        // 2. 班主任 (role_key: 2): 可以访问所有科目
        if (currentRole.role_key === 2) {
          return true
        }

        // 3. 年级主任 (role_key: 3): 可以访问所有科目
        if (currentRole.role_key === 3) {
          return true
        }

        // 4. 学科组长 (role_key: 4): 只能访问负责的科目
        if (currentRole.role_key === 4) {
          return currentRole.subject_id === subjectItem.subjectId
        }

        return false
      })
    })

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

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

          if (!selectedExamId.value) {
            selectedExamId.value = examOptions.value[0]?.value as number
          }

          console.log('数据获取完成:')
          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
      if (subjectOptions.value.length > 0) {
        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 = () => {
      examDataMap.value.clear()
      loading.value = false
      clearSelections()
    }

    // 监听考试ID变化，自动选择第一个科目
    whenever(selectedExamId, (examId) => {
      if (subjectOptions.value.length > 0) {
        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,
      selectedClassKey,
      selectedGradeKey,

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