import { watchEffect, ref, reactive } from 'vue'
import type { Questions } from '../type'

/* 计时器 */
function useTimer() {
  const takeUpTime = ref(0) // 耗时

  let clock: number

  /* 开始计时 */
  function startTiming() {
    clearInterval(clock)
    clock = setInterval(() => {
      takeUpTime.value++
    }, 1000) as any
  }

  /* 结束计时 */
  function stopTiming() {
    clearInterval(clock)
  }

  function reset() {
    takeUpTime.value = 0
    clearInterval(clock)
  }

  return {
    takeUpTime,
    startTiming,
    stopTiming,
    reset,
  }
}

function useWinningStreak() {
  const max = ref(0) // 最大连胜数
  const cur = ref(0) // 当前连胜数

  function reset() {
    max.value = 0
    cur.value = 0
  }

  /* 如果当前连胜数大于最大连胜数，则将当前连胜数赋值给最大连胜数 */
  watchEffect(() => {
    if (cur.value > max.value) {
      max.value = cur.value
    }
  })

  return {
    max,
    cur,
    reset,
  }
}

/* 单词测试的共享状态 */
const questions = reactive({
  rightCount: 0,
  total: 35,
  answered: 0,
})
const winningStreak = useWinningStreak()
const Timer = useTimer()
const questionSpellTitleLib = ref([] as Questions[])
const questionsChooseTitleLib = ref([] as Questions[])
const curQuestion = ref({} as Questions)
const mode = ref(0) // 0: 复习模式， 1：随机模式    3：教材模式    4：阶段模式
const pageType = ref('answer') // list: 打开列表页， answer： 打开答题页
const numOfQuestions = ref(20)
const wordGraspFlag = ref(0)
const wordGrade = ref('')
// 教材测试筛选数据
const teachData = ref({
  textBookId: '',
  textBookFamiliarityActive: '', // 熟练度
})
function reset() {
  questions.rightCount = 0
  questions.answered = 0

  curQuestion.value = {} as any
  winningStreak.reset()
  Timer.reset()
}

export default function useExam() {
  return {
    mode,
    Timer,
    questions,
    curQuestion,
    winningStreak,
    reset,
    questionSpellTitleLib,
    questionsChooseTitleLib,
    pageType,
    numOfQuestions,
    wordGraspFlag,
    teachData,
    wordGrade,
  }
}
