<script lang="ts" setup>
import RecordDetailPop from './components/RecordDetailPop.vue'
import { XMessage } from '@/hooks'
import useAudio from '../../hardMode/hooks/useAudio.ts'

import confirmPop from '../../hardMode/components/confirmPop.vue'
import usePopup from '../../hardMode/hooks/usePopup.ts'
import useExam from './hooks/useExam.ts'
import WinningStreakAnimation from '@/components/WinningStreakAnimation.vue'
import SingleChoice from './components/single-choice/index.vue'
import SpellingBee from './components/spelling-bee/index.vue'
import type { Questions } from './type.ts'
import wordTestApi from '@/api/subject/wordTest'
import { watch } from 'vue'
import { nextTick } from 'vue'
import useCommonAudio from '@/hooks/useCommonAudio'

import { useReviewWordStore } from '@/stores/useReviewWordStore'
import { useRoute, useRouter } from 'vue-router'
import { globalBack } from '@/router/index.ts'
import { question_right, question_wrong } from '../../index.ts'
import hud from '@/utils/hud.ts'
import { familiarity_master } from '../index.ts'
import obj from '@/utils/obj.ts'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores/user.ts'

/* 确认退出弹窗 */
const router = useRouter()
const route = useRoute()
const confirmExitPop = usePopup()
function handleConfirm() {
  // state.Timer.stopTiming();
  // state.reset();
}
const onNetLoading = ref(false) // 是否在保存答题结果中
const showDetail = ref(false) // 一轮结束   结果弹框
const detail = ref([]) // 一轮结束   结果弹框数据
const audio = useAudio()

// 用户
const { userInfo } = storeToRefs(userStore())

const showAgainBtn = ref(false)
const state = useExam()
const questionChooseList = ref(state.questionsChooseTitleLib.value as Questions[])
const questionSpellList = ref(state.questionSpellTitleLib.value as Questions[])
const reviewWordStore = useReviewWordStore() // 今日单词复习
const curTopic = ref(0) // 当前题目序号
const showWinning = ref(false)
const usedTime = computed(() => {
  const time = state.Timer.takeUpTime.value
  const h = parseInt(String((time / 60 / 60) % 24), 10)
  const m = parseInt(String((time / 60) % 60), 10)
  const s = parseInt(String(time % 60), 10)

  if (time === undefined) return

  if (h > 0) {
    return `${h}h ${m}m`
  } else if (m > 0) {
    return `${m}m ${s}s`
  } else if (s > 0) {
    return `${s}s`
  } else {
    return '0'
  }
})
const sound = useCommonAudio(true)
const showEnlarge = ref()
const titlePicture = ref('')

const title = ref('') // 筛选条件标题
function toAnswer() {
  if (state.questions.answered === state.questions.total) return
  if (curTopic.value <= questionChooseList.value.length - 1) {
    state.curQuestion.value = questionChooseList.value[curTopic.value]
  } else {
    state.curQuestion.value =
      questionSpellList.value[
        questionSpellList.value.length - (state.questions.total - curTopic.value)
      ]
  }
  // state.pageType.value = 'answer';
  showWinning.value = true
}

const progress = computed(() => {
  return Math.trunc((state.questions.answered / state.questions.total) * 100)
})

watch(
  () => showWinning.value,
  nv => {
    if (nv) {
      setTimeout(() => {
        showWinning.value = false
      }, 1000)
    }
  },
)

function confirmExit() {
  const qs = state.questions
  const left = qs.total - qs.answered
  if (left > 0) {
    if (!userInfo.value.isTeacher && isMaster.value && !isOver.value) {
      hud.success(`每一个坚持到底的瞬间，都是离梦想更近一步的见证✨`)
      if (qs.answered > 0) {
        hud.success(`已经完成 ${qs.answered}/${qs.total} 题啦，加油！`)
      }
    } else {
      confirmExitPop.open()
    }
  } else {
    router.back()
  }
}

// 放大图片
function handleEnlargeImg(img: string) {
  showEnlarge.value = true
  titlePicture.value = img
}

function handleChoice(type: string) {
  if (state.questions.answered >= state.questions.total) return
  if (type === question_right) {
    // 正确
    curTopic.value++
    toAnswer()
  } else {
    showAgainBtn.value = false
  }
}

// 困难模式答对下一题
function next() {
  curTopic.value++
  state.questions.rightCount++ // 加1分
  state.questions.answered++
  state.winningStreak.cur.value++
  state.curQuestion.value.result = question_right
  toAnswer()
}

// 困难模式投降
function clickSurrender() {
  if (state.questions.answered === state.questions.total) return
  state.questions.answered++
  state.winningStreak.cur.value = 0
  state.curQuestion.value.result = question_wrong
}
// watch(
//     () => showNext.value,
//     nv => {
//         if (nv) {
//             clickSurrender();
//         }
//     },
// );

/* 测试结束 */
function over() {
  isOver.value = true
  hud.loading('统计中...')
  reviewWordStore.todayReviewWordNum = 1
  showAgainBtn.value = true
  state.Timer.stopTiming()
  nextTick(() => {
    wordTestApi
      .completeWordTest({
        id: state.curQuestion.value.sessionId,
        rightNum: state.questions.rightCount,
        totalNum: state.questions.total,
        comboNum: state.winningStreak.max.value,
        duration: state.Timer.takeUpTime.value * 1000,
        endTime: new Date().getTime(),
        sessionId: state.curQuestion.value.sessionId,
      })
      .then((res: any) => {
        showDetail.value = true
        detail.value = res
      })
      .finally(() => {
        hud.hideLoading()
      })
  })
}

defineOptions({
  name: 'TestList',
})

// 结束了
const isOver = ref(false)

/* 再练一次 或者下一题 */
function handleAgainOrNext() {
  // if (showAgainBtn.value && state.wordGraspFlag.value) {
  //     handleConfirm();
  //     // return uni.navigateBack();
  //     return router.back();
  // }

  if (!showAgainBtn.value) {
    curTopic.value++
    toAnswer()
    return
  }
  isOver.value = false

  hud.loading('加载中...')
  const wordGraspFlag = state.teachData.value.textBookFamiliarityActive || state.wordGraspFlag.value
  wordTestApi
    .getWordTestWords({
      size: state.numOfQuestions.value,
      testType: state.mode.value, // 0: 复习模式， 1：随机模式
      wordGraspFlag,
      startTime: new Date().getTime(),
      vocabularyId: state.wordGrade.value,
      textbookId: route.query.title ? state.teachData.value.textBookId : undefined,
    })
    .then((res: any) => {
      if (!res.chooseTitle && !res.spellTitle) {
        router.back()
        return XMessage.error('暂无单词')
      }
      curTopic.value = 0
      questionChooseList.value = res.chooseTitle
      questionSpellList.value = res.spellTitle
      state.reset()
      state.questionsChooseTitleLib.value = res.chooseTitle
      state.questionSpellTitleLib.value = res.spellTitle
      state.questions.total = res.chooseTitle.length + res.spellTitle.length
      state.Timer.startTiming() // 开始计时
      showAgainBtn.value = false
      nextTick(() => {
        toAnswer()
      })
    })
    .finally(() => {
      hud.hideLoading()
    })
}

watch(
  () => state.questions.answered,
  nv => {
    if (nv >= state.questions.total) {
      // over()
      if (state.questions.rightCount / state.questions.total < 0.6) {
        audio.play('show_fail.mp3')
      } else if (state.questions.rightCount / state.questions.total < 1) {
        audio.play('star_success.mp3')
      } else {
        audio.play('show_seal.mp3')
      }
      setTimeout(() => {
        sound.play('show_nextBtn.mp3')
      }, 1500)
    }
  },
)

watch(
  () => onNetLoading.value,
  nv => {
    if (nv) return
    setTimeout(() => {
      if (state.questions.answered >= state.questions.total) {
        over()
      }
    }, 150)
  },
)

const isMaster = computed(() =>
  obj.isEqualIgnoreNumberString(state.wordGraspFlag.value, familiarity_master),
)

onMounted(() => {
  title.value = (route.query.title as string) || ''
  if (
    state.questionSpellTitleLib.value.length > 0 ||
    state.questionsChooseTitleLib.value.length > 0
  ) {
    questionChooseList.value = state.questionsChooseTitleLib.value
    questionSpellList.value = state.questionSpellTitleLib.value
    state.Timer.startTiming() // 开始计时
    toAnswer()
  } else {
    router.push('/subject/learnWord/word-table-test')
    router.replace('/subject/learnWord/word-table')
    // router.replace(
    //   state.wordGraspFlag.value ? '/subject/learnWord/word-table' : '/subject/learnWord/testRecords',
    // )
  }
})

onUnmounted(() => {
  state.Timer.stopTiming()
  state.reset()
  state.wordGraspFlag.value = 0
  state.wordGrade.value = ''
  state.teachData.value = {
    textBookId: '',
    textBookFamiliarityActive: '',
  }
})
</script>

<template>
  <div class="page__container">
    <BackBar class="back-bar" show-only @click="confirmExit" />
    <new-progress-bar class="progress-bar" :progress="progress" />
    <div class="title-bar">
      <heart-bg />
      <div class="title-item">耗时：{{ usedTime }}</div>
      <div class="title-item">
        正确：{{ state.questions.rightCount }}/{{ state.questions.total }}
      </div>
      <div class="title-item">最好连击：{{ state.winningStreak.max }}</div>
    </div>
    <div class="content">
      <single-choice
        v-if="curTopic < questionChooseList.length"
        v-bind="state.curQuestion.value as any"
        v-model="onNetLoading"
        :is-last="state.questions.answered === state.questions.total"
        @enlargeImg="handleEnlargeImg"
        @getChoice="handleChoice"
        @next="handleAgainOrNext"
      />
      <spelling-bee
        v-else
        id="hardModeBox"
        v-model="onNetLoading"
        :currentLevel="(state.curQuestion.value || []) as any"
        :handleRight="next"
        isWordTest
        class="hard-mode"
        :over="isOver"
        @clickSurrender="clickSurrender"
        @onTapEnlargeImg="handleEnlargeImg"
        @next="handleAgainOrNext"
      />
      <WinningStreakAnimation v-if="showWinning" :num="state.winningStreak.cur.value" />
    </div>
    <div class="bottom-title">{{ title }}</div>
    <div id="learn-audio"></div>
  </div>
  <EnlargePicture v-if="showEnlarge" v-model="showEnlarge" :picture="titlePicture" />
  <confirmPop v-model="confirmExitPop.status.value" :confirmCallBack="handleConfirm"></confirmPop>
  <RecordDetailPop
    v-model="showDetail"
    v-bind="detail as any"
    islastPop
    @back="globalBack"
    @next="handleAgainOrNext"
  />
</template>

<style lang="scss" scoped>
.page__container {
  position: relative;
  height: 100%;
  overflow: auto;
  padding-top: 2.67vh;
  @include main_bg;

  .title-bar {
    position: relative;
    width: 1085px;
    height: 7.67vh;
    background-color: #a0fcf8;
    border-top-left-radius: 40px;
    border-top-right-radius: 40px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    overflow: hidden;

    .title-item {
      flex: 1;
      text-align: center;
      font-size: 3.33vh;
      font-family: $font-text;
      color: rgba(0, 0, 0, 0.65);
      z-index: 1;
    }
  }

  .content {
    padding: 0 32px;
    position: relative;
    top: -0.08vh;
  }

  .back-bar {
    position: absolute;
    top: 2.67vh;
    left: $space-6;
    z-index: 1;
  }

  .progress-bar {
    position: absolute;
    top: 2.67vh;
    right: 32px;
    z-index: 1;
  }

  .bottom-title {
    text-align: center;
    color: #4b4b68;
    font-size: 2.33vh;
    height: 2.67vh;
    line-height: 2.67vh;
    margin-top: 1vh;
    font-family: $font-text;
  }
}
</style>
