<script setup lang="ts">
import { watch, ref, nextTick, computed } from 'vue'
import type { Level } from '@/page/subject/learnWord/hardMode/interface'
import { storeToRefs } from 'pinia'
import { useHardModeStore } from '@/stores/learnWord/useLearnWordStore'
import {
  useAnswer,
  WordTest,
  onNetLoading,
} from '@/page/subject/learnWord/hardMode/hooks/useAnswer'
import LazyLoad from '@/components/LazyLoad.vue'
import useAnimate from '@/page/subject/learnWord/hardMode/hooks/useAnimate'
import { useAudio } from '@/hooks'

import wordDetailApi from '@/api/subject/wordDetail'
import { question_right } from '@/page/subject/learnWord'
import { category_cn } from '../single-choice'
import hud from '@/utils/hud'
import { key_space_value } from '@/components/keyboard'
import { useRoute } from 'vue-router'

const props = defineProps<{
  currentLevel: Level
  isWordTest?: boolean
  modelValue?: boolean
  over?: boolean

  handleRight: () => void
}>()
const emit = defineEmits([
  'onCloseDetailPop',
  'handleOpenMask',
  'onTapEnlargeImg',
  'clickSurrender',
  'update:modelValue',
  'next',
])
const route = useRoute()
const review = route.query.title?.includes('掌握')

watch(
  () => props.isWordTest,
  nv => {
    WordTest.value = nv
  },
  {
    immediate: true,
  },
)

const OSS_URL = import.meta.env.VITE_OSS_URL

const wordType = ref(false)
const showMaskRef = ref(true)
const { gameProps, inputList, answer, showNext } = useAnswer(
  () => {
    // 答对了，需要清除定时器
    clearFailedTimer()
    props.handleRight && props.handleRight()
  },
  {
    playAccent,
  },
  props.isWordTest,
)
const propsNum = useHardModeStore()
const { glassNum, bombNum } = storeToRefs(propsNum)
const WORD_LABEL = [
  '原型',
  '第一人称单数',
  '第三人称单数',
  '一般过去式',
  '过去分词',
  '现在分词',
  '复数形式',
  '比较级',
  '最高级',
]
const isWordPlay = ref(false)

const shelfTopUrl = `${OSS_URL}/subject/book_shelf_top.svg`
const bottom_url = `${OSS_URL}/subject/book_shelf_bottom.svg`
const left_url = `${OSS_URL}/subject/book_shelf_left.svg`
const surrenderUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_surrender.svg`
const shengciben01Url = `${OSS_URL}/xuexiaole_clinet/icon/icon_shengciben_01.svg`
const shengciben02Url = `${OSS_URL}/xuexiaole_clinet/icon/icon_shengciben_02.svg`
const nextUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_next.svg`
const memoryTipsUrl = `${OSS_URL}/xuexiaole_clinet/icon/icon_memory_tips.png`
const countDownBg = `url(${OSS_URL}/icon/timeout_clock.png)`

// 倒计时
let failedTimer = 0 as any
let countDownText = ref('')
const showCountDown = 5

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

const { useProp } = useAnimate(
  {
    1: gameProps.glass.useEffect,
    2: gameProps.bomb.useEffect,
    3: gameProps.flag.useEffect,
  },
  {
    glassNum,
    bombNum,
  },
  inputList,
)

// 输入框文字的数量
const inputCount = computed(() => {
  // 不为null的数量
  return inputList.data.queen?.filter((i: any) => i).length
})

const isPlay = ref(false)
// 图片放大
function tapEnlargeImg() {
  if (props.currentLevel.titlePicture) {
    emit('onTapEnlargeImg', props.currentLevel.titlePicture)
  }
}
async function playAccent() {
  if (!props.currentLevel.accent) return
  await nextTick()
  isPlay.value = true
  useAudio({
    url: props.currentLevel.accent as string,
    autoplay: true,
    onEnded() {
      isPlay.value = false
    },
  })
}

function wordPlay() {
  isPlay.value = false
  isWordPlay.value = true
  useAudio({
    url: props.currentLevel.wordAccent,
    autoplay: true,
    onEnded() {
      isWordPlay.value = false
    },
  })
}

const handleWords = () => {
  wordType.value = !wordType.value
  showMaskRef.value = true
  emit('handleOpenMask', wordType.value)
  wordDetailApi
    .operateTag({
      id: props.currentLevel.wordId,
      meaningId: props.currentLevel.meaningId,
      levelId: props.currentLevel.levelId,
      knowFlag: null,
      strangeFlag: wordType.value ? 1 : 0,
    })
    .then(() => {
      hud.success(wordType.value ? '已加入生词本' : '已从生词本移除')
    })
    .catch(() => {
      showMaskRef.value = false
    })
}

const showMemoryTips = ref(false)
// 点击助记
function handelMemoryTips() {
  showMemoryTips.value = true
}
const memoryTipsData = computed(() => {
  const lv = props.currentLevel
  return {
    spell: lv.spell,
    chinese: lv.wordSimpleZnDesc,
    ipa: lv.wordAccentSpell,
    accent: lv.wordAccent,
    abbr: lv.abbr,
    tips: lv.memoryTips,
  }
})

const topic = computed(() => {
  if (answer.data.result === question_right) {
    return props.currentLevel.title?.replace(
      '_____',
      `<span style="color: #42C20B;text-decoration:underline; text-underline-offset:6px">${props.currentLevel.sentenceDisplaySpell}</span>`,
    )
  } else {
    return props.currentLevel.title
  }
})

watch(
  () => onNetLoading.value,
  nv => {
    emit('update:modelValue', nv)
  },
  {
    immediate: true,
  },
)

// 点击投降
function handleSurrender() {
  // 清除定时器
  clearFailedTimer()

  emit('clickSurrender')
  if (answer.data.result !== question_right) {
    useProp(3)
  }
}

// 点击下一题
function handleNext() {
  emit('next')
}

// 新的题目
watch(
  () => props.currentLevel,
  newValue => {
    if (!newValue?.levelId) return

    answer.load(newValue)
    wordType.value = newValue.strangeWord === 1 ? true : false
    if (newValue.accent) {
      playAccent()
    }
    // 倒计时
    setupFailedTimer()
  },
  { immediate: true },
)

// 新建倒计时定时器
function setupFailedTimer() {
  clearFailedTimer()
  if (!review) return

  // 单位（1个字母多少秒）
  // const reviewCount = Number(props.currentLevel.reviewSuccessful)
  let unit = 5
  // if (reviewCount === 0) {
  //   unit = 5
  // } else if (reviewCount === 1) {
  //   unit = 4
  // }
  // 秒
  let duration = props.currentLevel.wordSpell.length * unit
  if (duration <= showCountDown) {
    countDownText.value = `${duration}`
  }
  failedTimer = setInterval(() => {
    duration--
    if (duration <= showCountDown) {
      countDownText.value = `${duration}`
      if (duration <= 0) {
        // 直接投降
        handleSurrender()
      }
    }
  }, 1000)
}

function clearFailedTimer() {
  countDownText.value = ''
  clearInterval(failedTimer)
}

const showKeyboard = computed(
  () => props.currentLevel.charList && props.isWordTest && answer.data.result !== question_right,
)

onUnmounted(() => {
  clearFailedTimer()
})
</script>
<template>
  <div class="spelling-bee question-box">
    <div class="top">
      <div class="top-box">
        <img :src="shelfTopUrl" alt="" />
        <img :src="shelfTopUrl" alt="" />
      </div>
      <div class="trunk">
        <div v-if="currentLevel.titlePicture" class="img-box">
          <LazyLoad
            class="img"
            :src="currentLevel.titlePicture as any"
            @onTapEnlargeImg="tapEnlargeImg"
          />
        </div>
        <div v-if="currentLevel.titleCategory === category_cn" class="cn">
          <AbbrImg class="abbr" :abbr="currentLevel.abbr" />
          <span class="title">{{ currentLevel.title }}</span>
        </div>
        <div v-else class="sentence">
          <div class="main" @click="playAccent">
            <div class="content">
              <div class="english" v-html="topic"></div>
              <div class="chinese">{{ currentLevel?.titleTips }}</div>
            </div>
            <Horn v-if="currentLevel.accent" :active="isPlay" :width="60" />
          </div>
          <div
            v-if="
              answer.data.result === question_right &&
              currentLevel.sentenceMeaningWordFormLabel &&
              currentLevel.sentenceMeaningWordFormLabel !== 1
            "
            class="extra"
          >
            <span class="form">{{ currentLevel.sentenceMeaningWordSpell }}</span> <span>是</span>
            <span class="prototype">{{ currentLevel.wordSpell }}</span
            ><span>的</span>
            <span class="form_name">{{
              WORD_LABEL[currentLevel.sentenceMeaningWordFormLabel - 1] || WORD_LABEL[0]
            }}</span>
          </div>
        </div>
      </div>
    </div>
    <div
      :class="{
        bottom: true,
        'size-below-16': inputList.data.length <= 16,
        'size-above-16': inputList.data.length > 16,
      }"
    >
      <!-- 贴纸 -->
      <img class="sticker-left" :src="left_url" />
      <img class="sticker-bottom" :src="bottom_url" />

      <!-- 倒计时 -->
      <div
        v-if="countDownText"
        :style="{
          backgroundImage: countDownBg,
        }"
        class="count-down"
      >
        {{ countDownText }}
      </div>

      <!-- 答案 -->
      <div v-if="showNext || over" class="result">
        <div class="chinese" @click="wordPlay">
          <AbbrImg v-if="currentLevel.abbr" class="abbr" :abbr="currentLevel.abbr" />
          <span class="text">{{ currentLevel.wordSimpleZnDesc }}</span>
          <Horn :active="isWordPlay" />
        </div>
        <div class="voice" @click="wordPlay">
          <span class="accent">{{ currentLevel.wordAccentSpell || '' }}</span>
        </div>
        <div class="letters">
          <span
            v-for="(item, index) in inputList.data.queen"
            :key="index"
            class="letter animate__prop"
            :style="{
              '--delay': 0.3 * index + 's',
            }"
            >{{ item.value }}</span
          >
        </div>
      </div>
      <!-- 答题板 -->
      <div v-if="showKeyboard" class="board">
        <div class="chinese" @click="wordPlay">
          <AbbrImg v-if="currentLevel.abbr" class="abbr" :abbr="currentLevel.abbr" />
          <span class="text">{{ currentLevel.wordSimpleZnDesc }}</span>
          <Horn :active="isWordPlay" />
        </div>
        <div class="letters">
          <span
            v-for="index in inputList.data.length"
            :key="index"
            class="letter"
            :class="{
              [answer.data.result as any]: true,
              space: inputList.data.queen[index - 1]?.value === key_space_value,
            }"
          >
            {{ inputList.data.queen[index - 1]?.value }}
          </span>
          <keyboard-item
            class="remove"
            :iconHeight="40"
            :iconWidth="36"
            :count="inputCount"
            value="Backspace"
            iconName="icon_keyboard_remove"
            @click="inputList.backspace()"
          />
        </div>

        <keyboard :keyList="currentLevel.charList" @chooseAnswer="inputList.choose($event)" />
      </div>

      <!-- 助记 -->
      <span
        v-if="showNext && currentLevel.memoryTips"
        class="button second-button"
        @click="handelMemoryTips"
      >
        <img :src="memoryTipsUrl" alt="" />
      </span>
      <!-- 生词本按钮 -->
      <span v-if="showNext" class="button" @click="handleWords">
        <img :src="strangeIcon" alt="" />
      </span>
      <!-- 投降按钮 -->
      <span v-else class="button" @click="handleSurrender">
        <img :src="surrenderUrl" alt="" />
      </span>
      <!-- 下一题按钮 -->
      <span v-if="showNext" class="next-question animate__slideInRight" @click="handleNext">
        <img
          :class="['animate__animated', 'animate__infinite', 'animate__breath']"
          :src="nextUrl"
          alt=""
        /><span>下</span><span>一</span><span>题</span></span
      >
    </div>
    <div class="middle-line"></div>
    <memory-tips v-model="showMemoryTips" :data="memoryTipsData as any" />
  </div>
</template>

<style lang="scss" scoped>
@import '../question-box.scss';

.spelling-bee {
  .top {
    .trunk {
      .sentence {
        display: flex;
        flex-direction: column;
        row-gap: 2.67vh;
        align-items: center;

        .main {
          display: flex;
          align-items: center;
          column-gap: 20px;

          .content {
            display: flex;
            flex-direction: column;
            row-gap: 1.67vh;
            .english {
              color: rgba(0, 0, 0, 0.85);
              font-size: 4vh;
              max-width: 1200px;
            }
            .chinese {
              color: rgba(0, 0, 0, 0.65);
              font-size: 3.33vh;
            }
          }
        }
        .extra {
          background-color: rgba(255, 255, 255, 0.65);
          box-shadow: inset 0 0.17vh 0 rgba(255, 255, 255, 0.85);
          color: rgba(0, 0, 0, 0.85);
          font-size: 3.17vh;
          padding: 0.83vh 40px;
          border-radius: 1.33vh;
          display: flex;
          align-items: center;
          column-gap: 5px;

          .form,
          .prototype,
          .form_name {
            color: #ff5c00;
          }
        }
      }
    }
  }

  .bottom {
    position: relative;

    .count-down {
      position: absolute;
      background-size: 100%;
      top: 10px;
      left: 10px;
      width: 15vh;
      height: 15.97vh;
      padding-top: 3vh;
      font-size: 7vh;
      font-family: $font-special;
      text-align: center;
      color: #db0e29;
    }

    &.size-below-16 {
      .letter {
        width: 6vh;
        height: 6vh;
        line-height: 5.33vh;
        font-size: 3.67vh;
      }
    }

    &.size-above-16 {
      .letter {
        width: 4.83vh;
        height: 4.83vh;
        line-height: 4.17vh;
        font-size: 3.17vh;
      }

      :deep(.keyboard-item) {
        transform: scale(0.8);
      }
    }

    .chinese {
      display: flex;
      align-items: center;
      column-gap: 15px;

      .text {
        color: rgba(0, 0, 0, 0.85);
        font-size: 3.5vh;
      }
    }

    .letters {
      display: flex;
      align-items: center;
      row-gap: 0.83vh;
      column-gap: 24px;
      justify-content: center;
      width: 1600px;
      flex-wrap: wrap;

      .letter {
        cursor: pointer;
        text-align: center;
        border-radius: 0.83vh;
        background-color: #d6f2ff;
        border: 0.33vh solid #53aee7;
        font-family: $font-special;
        color: rgba(0, 0, 0, 0.75);

        &.space {
          border-color: #b5b7b5;
          background-color: #d4d4d4;
        }

        &.wrong {
          background-color: #fcc0c0;
          border-color: #cc1818;
        }
      }
    }

    .board {
      display: flex;
      flex-direction: column;
      align-items: center;
      row-gap: 2.08vh;
      z-index: 2;
    }

    .result {
      display: flex;
      flex-direction: column;
      align-items: center;
      row-gap: 1.67vh;
      z-index: 2;

      .voice {
        .accent {
          font-size: 3.5vh;
          color: rgba(0, 0, 0, 0.65);
        }
      }

      .letters {
        .letter {
          background-color: #c1f052;
          border-color: #8fcc00;
          --delay: 0s;
          &.animate__prop {
            visibility: hidden;
            animation: show 0.6s linear forwards;
            animation-delay: var(--delay);
          }
        }
      }
    }
  }
}

@keyframes show {
  0% {
    transform: scale(1);
    visibility: visible;
  }
  40% {
    transform: scale(1.5);
    visibility: visible;
  }
  100% {
    transform: scale(1);
    visibility: visible;
  }
}
</style>
