import { useGetCourseList } from './useGetCourseList'
import type { ExperimentType } from '../types'
import { getExperiment, getExperimentCompetition, submitCompetition, getExperimentExamList } from '../api'
import { useCookies } from '@vueuse/integrations/useCookies'

interface StudentStatus {
  has_submitted: boolean
}

interface Competition {
  name: string
  start_time: string
  end_time: string
  student_status: StudentStatus
  competition: string
  questions: string
}

export function useCompetition() {
  const cookies = useCookies()
  const competition = ref<Competition>()
  const { courses } = useGetCourseList()
  const experiments = ref<ExperimentType[]>([])
  const courseId = ref('')
  const experimentId = ref('')
  const biURL = computed<string>(() => {
    return `${import.meta.env.VITE_LAB_URL}&token=${cookies.get('TGC')}`
  })


  watchEffect(() => {
    if (courses.value.length) {
      courseId.value = courses.value[0].id
      experiments.value = courses.value[0].experiments
    }
  })
  watchEffect(() => {
    if (experiments.value.length) {
      experimentId.value = experiments.value[0].id
    }
  })
  const experimentInfo = ref<ExperimentType>()
  const fetchExperiment = async () => {
    return false
    const res = await getExperiment({ experiment_id: experimentId.value })
    experimentInfo.value = res.data.detail
  }
  const fetchExperimentCompetition = async () => {
    const res = await getExperimentCompetition({ experiment_id: experimentId.value })
    competition.value = res.data.detail
    if (res.data.detail.competition == '4') {
      fetchExamList()
    }
  }
  watchEffect(() => {
    if (experimentId.value) {
      fetchExperiment()
      fetchExperimentCompetition()
    }
  })
  const submit = async () => {
    await submitCompetition({ experiment_id: experimentId.value })
    await fetchExperimentCompetition()
  }

  const examList = ref<any[]>([])
  // 考试平台 URL
  const examURL = computed<string>(() => {
    if (!examList.value.length) return ''
    const [first] = examList.value
    return `${import.meta.env.VITE_EXAM_SHOW_URL}/exam/${first?.exam_id}`
    // return `https://dev.ezijing.com:5173/exam/7003551966412406784?has_time=0&has_submit=0&has_save=1&show_answer=1`
  })
  const fetchExamList = async () => {
    const res = await getExperimentExamList({ experiment_id: experimentId.value })
    const resCookies = res.data.cookies
    cookies.set(resCookies.key, resCookies.auth_key, { domain: '.ezijing.com', path: '/' })
    examList.value = res.data.items
  }


  return { competition, courseId, experimentId, experimentInfo, submit, fetchExamList, examURL, biURL }
}
