import type { Exercises, Option } from '../interface'
import { $sleep } from '@/utils/tool'
import useCommonAudio from '@/hooks/useCommonAudio'
import { useAudio } from '@/hooks'
import { question_right, question_wrong } from '../..'

/* 答题程序，实现答题逻辑，调用正确和错误时的回调函数 */
export default function useAnswer(handle: anyObj, getRightRect?: () => void) {
  onMounted(() => {
    window.addEventListener('keydown', keyBoardInput2)
  })
  onUnmounted(() => {
    window.removeEventListener('keydown', keyBoardInput2)
  })
  function keyBoardInput2(e: any) {
    const _this = answer.data
    let selected = null
    if (e.key === 'a' || e.key === 'A' || e.key === '1') {
      selected = _this.currentData.optionList[0]
    } else if (e.key === 'b' || e.key === 'B' || e.key === '2') {
      selected = _this.currentData.optionList[1]
    } else if (e.key === 'c' || e.key === 'C' || e.key === '3') {
      selected = _this.currentData.optionList[2]
    } else if (e.key === 'd' || e.key === 'D' || e.key === '4') {
      selected = _this.currentData.optionList[3]
    }
    if (selected) {
      answer.answering(selected.answer, selected)
    }
  }

  const sound = useCommonAudio(true)
  const answer = {
    data: reactive({
      canClick: true,
      result: null as string | null,
      currentData: {} as Exercises,
      startTime: 0,
    }),
    load(data: any) {
      const _this = this.data
      _this.currentData = data
      _this.startTime = new Date().getTime()
      _this.currentData.optionList?.forEach(item => {
        item.result = ''
      })
      _this.result = null
      _this.canClick = true
    },
    async answering(result: boolean, optionItem: Option, isSpecial = false) {
      const _this = answer.data
      // console.log('点击');
      if (!_this.canClick) return // 答对时自动进入下一关，在此之前不允许再次点击
      // if (!_this.canClick && !optionItem.accent)
      //     return;
      // else if (!_this.canClick && optionItem.accent) {
      //     if (_this.result === question_right) return;
      //     useAudio({
      //         url: optionItem.accent,
      //         autoplay: true,
      //     });
      //     return;
      // }
      _this.canClick = false
      _this.currentData.usedTime = Math.round((new Date().getTime() - _this.startTime) / 1000)

      if (result) {
        _this.result = question_right
        optionItem.result = question_right
        if (optionItem.accent) {
          let did = false
          function handleRight() {
            if (did) return
            did = true
            handle.handleRight(_this.currentData)
          }
          // 播放声音最多等待1500毫秒
          setTimeout(handleRight, 1250)
          useAudio({
            url: optionItem.accent,
            autoplay: true,
            onEnded() {
              handleRight()
            },
            onError() {
              // 播放失败了，代码也要往下走
              handleRight()
            },
          })
          return
        }
        // sound.play('right.mp3')

        await $sleep(500)
        handle.handleRight(_this.currentData)
      } else {
        _this.result = question_wrong
        if (!isSpecial) {
          optionItem.result = question_wrong
          sound.play('error.mp3')

          // 延迟展示正确答案
          // await $sleep(800)
        }
        /* 显示正确答案 */
        _this.currentData.optionList.forEach(item => {
          if (item.answer) {
            item.result = question_right
          }
        })

        // sound.play('show_answer.mp3')
        // await $sleep(300)
        // sound.play('show_answer.mp3')
        handle.handleError({ ..._this.currentData, surrender: isSpecial ? 1 : 0 })
        // await $sleep(500)
        if (!handle.noNeedNext) {
          sound.play('show_nextBtn.mp3')
        }
      }
    },
  }

  return answer
}
