import type { Ref } from 'vue'
import { getExperimentQuestionList, getTeacherGroups, getTeacherTags, getTeacherMaterials } from '@/api/question'
import { useUserStore } from '@/stores/user'

type QuesitonItem = {
  experiment_id: string
  id: string
  type: string
}

type OptionItem = {
  id: string
  name: string
}

type MaterialItem = {
  id: string
  name: string
  type: string
  content: ''
}

export function useQuestion(questionType: string | Ref<string>, type?: string) {
  questionType = shallowRef(questionType)
  const useStore = useUserStore()
  // 试题列表
  const questionList = ref<QuesitonItem[]>([])
  const fetchQuestionList = async () => {
    const res = await getExperimentQuestionList()
    questionList.value = res.data.items
  }

  const hasQuestion = computed(() => {
    return !!questionList.value.find((item) => item.type === questionType.value)
  })

  onMounted(async () => {
    if (useStore.role?.id === 1) {
      await fetchQuestionList()
    }
    if (hasQuestion.value) {
      if (questionType.value == '202') await fetchTeacherTagList()
      if (questionType.value == '301' || questionType.value == '302') await fetchTeacherGroupList()
      if (['401', '402', '403', '404', '405', '406', '407', '408'].includes(questionType.value)) {
        await fetchTeacherMaterialList()
      }
    }
  })

  const teacherGroupList = ref<OptionItem[]>([])
  const fetchTeacherGroupList = async () => {
    const res = await getTeacherGroups({ type })
    teacherGroupList.value = res.data.items
  }

  const teacherTagList = ref<OptionItem[]>([])
  const fetchTeacherTagList = async () => {
    const res = await getTeacherTags()
    teacherTagList.value = res.data.items
  }

  const teacherMaterialAllList = ref<MaterialItem[]>([])
  const teacherMaterialList = computed(() => {
    const questionTypes: any = {
      '401': 1,
      '402': 2,
      '403': 3,
      '404': 4,
      '405': 5,
      '406': 6,
      '407': 7,
      '408': 8,
    }
    return teacherMaterialAllList.value.filter((item) => item.type == questionTypes[questionType.value])
  })
  const fetchTeacherMaterialList = async () => {
    const res = await getTeacherMaterials()
    teacherMaterialAllList.value = res.data.items
  }

  return {
    hasQuestion,
    questionList,
    fetchQuestionList,
    teacherGroupList,
    fetchTeacherGroupList,
    teacherTagList,
    fetchTeacherTagList,
    teacherMaterialList,
    fetchTeacherMaterialList,
  }
}
