import wordDetailApi from '@/api/subject/wordDetail'
import useAudio from '@/hooks/useCommonAudio'
import { OSS_URL } from '@/utils'
import hud from '@/utils/hud'
import { level_type_advance, result_wrong } from '..'

export const shelfTopUrl = `${OSS_URL}/subject/book_shelf_top.svg`
export const bottomUrl = `${OSS_URL}/subject/book_shelf_bottom.svg`
export const leftUrl = `${OSS_URL}/subject/book_shelf_left.svg`
export const wrongUrl = `${OSS_URL}/xuexiaole_clinet/normalMode/cross.png`
export const rightUrl = `${OSS_URL}/xuexiaole_clinet/normalMode/tick.png`
export const surrenderUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_surrender.svg`
export const shengciben01Url = `${OSS_URL}/xuexiaole_clinet/icon/icon_shengciben_01.svg`
export const shengciben02Url = `${OSS_URL}/xuexiaole_clinet/icon/icon_shengciben_02.svg`
export const nextUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_next.svg`
export const memoryTipsUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_memory_tips.png`
export const countDownBg = `url(${OSS_URL}/icon/timeout_clock.png)`

export const useMain = (props: any, emits: any) => {
  // 开始的时间
  const startTime = ref(0)
  // 播放音频
  const sound = useAudio(true)

  // 是否已经出结果
  const result = ref(undefined as any)

  // 显示投降按钮
  const showSurrender = computed(() => result.value === undefined)

  // 下一题按钮
  const showNext = computed(() => {
    // 如果还没有出结果，不显示
    if (!result.value) return false
    // 最后一题，不显示
    if (props.last) return false
    // 答题情况
    return result.value === result_wrong
  })

  const isMarked = ref(false)

  // 生词本图标
  const strangeIcon = computed(() => {
    if (isMarked.value) {
      return shengciben02Url
    } else {
      return shengciben01Url
    }
  })

  const showMemoryTips = ref(false)
  // 点击助记
  const handelMemoryTips = () => {
    showMemoryTips.value = true
  }

  // 倒计时
  const countDownText = ref('')
  // 5秒内显示
  const showCountDown = 5
  // 到时间就失败
  let failedTimer = 0 as any
  // 到时间就自动进入下一题
  let nextTimer = 0 as any

  const startFailedTimer = () => {
    if (!props.countDown) return
    stopFailedTimer()

    // 选择题倒计时
    const initCountDown = 10
    let duration = initCountDown
    if (props.data.levelType === level_type_advance) {
      // 拼写
      duration = Math.ceil(props.data.spell.length * 3)
      duration = Math.max(duration, initCountDown)
    }
    if (duration <= showCountDown) {
      countDownText.value = `${duration}`
    }
    failedTimer = setInterval(() => {
      duration--
      if (duration <= showCountDown) {
        countDownText.value = `${duration}`
        if (duration <= 0) {
          // 直接投降
          handleSurrender()
        }
      }
    }, 1000)
  }

  const stopFailedTimer = () => {
    if (!props.countDown) return
    countDownText.value = ''
    clearInterval(failedTimer)
  }

  const startNextTimer = () => {
    if (!props.countDown) return
    stopNextTimer()

    // 倒计时多少秒
    let duration = Math.max(5, Math.ceil((props.data.wordSpell?.length || 0) * 1.5))
    if (duration <= showCountDown) {
      countDownText.value = `${duration}`
    }
    nextTimer = setInterval(() => {
      duration--
      if (duration <= showCountDown) {
        countDownText.value = `${duration}`
        if (duration <= 0) {
          // 直接下一题
          handleNext()
        }
      }
    }, 1000)
  }

  const stopNextTimer = () => {
    if (!props.countDown) return
    countDownText.value = ''
    clearInterval(nextTimer)
  }

  const stopAllTimers = () => {
    stopNextTimer()
    stopFailedTimer()
  }

  // 点击生词本
  const handelStrange = () => {
    isMarked.value = !isMarked.value
    wordDetailApi
      .operateTag({
        id: props.data.wordId,
        meaningId: props.data.meaningId,
        levelId: props.data.levelId,
        knowFlag: null,
        strangeFlag: isMarked.value ? 1 : 0,
      })
      .then(() => {
        hud.success(isMarked.value ? '已加入生词本' : '已从生词本移除')
      })
  }

  // 点击投降
  const handleSurrender = () => {
    // 标记为错误
    result.value = result_wrong
    // 发送结果
    emits('post-result', result.value, true, Date.now() - startTime.value)
  }

  // 点击下一题
  const handleNext = () => {
    emits('next')
  }

  watch(
    () => result.value,
    () => {
      if (result.value !== undefined) {
        // 只要出结果了，就停止定时器
        stopAllTimers()

        if (result.value === result_wrong) {
          // 错误了，就开始下一题的定时器
          startNextTimer()
        }
      }
    },
  )

  watch(
    () => props.end,
    () => {
      if (props.end) {
        stopAllTimers()
      }
    },
  )

  watch(
    () => props.data,
    () => {
      // 没有题目
      if (!props.data.levelId) return

      stopAllTimers()

      nextTick(() => {
        // 清空结果
        result.value = undefined
        // 设置开始时间
        startTime.value = Date.now()
        // 开始定时器
        startFailedTimer()
      })
    },
    {
      immediate: true,
    },
  )

  // 监控下一题按钮的显示或隐藏
  watch(
    () => showNext.value,
    () => {
      if (!showNext.value) return
      // 播放音频
      sound.play('show_nextBtn.mp3')
    },
  )

  onUnmounted(() => {
    stopAllTimers()
  })

  return {
    handleNext,
    handleSurrender,
    strangeIcon,
    handelStrange,
    sound,
    result,
    showNext,
    showMemoryTips,
    handelMemoryTips,
    showSurrender,
    countDownText,
    startTime,
  }
}
