<script setup lang="ts">
import LazyLoad from '@/components/LazyLoad.vue'
import { key_space_value } from '@/components/keyboard'
import { category_cn, result_right, result_wrong, type SpellQuestion } from '..'
import { question_right } from '@/page/subject/learnWord'
import {
  bottomUrl,
  countDownBg,
  leftUrl,
  memoryTipsUrl,
  nextUrl,
  shelfTopUrl,
  surrenderUrl,
  useMain,
} from '../hooks/main'

const props = defineProps<{
  // 是否结束了
  end: boolean
  last: boolean
  data: SpellQuestion
  // 是否需要倒计时
  countDown?: boolean
  open?: boolean
}>()

const emit = defineEmits(['post-result', 'next'])
const {
  countDownText,
  showSurrender,
  result,
  showNext,
  strangeIcon,
  handelStrange,
  showMemoryTips,
  handelMemoryTips,
  handleNext,
  handleSurrender,
  startTime,
} = useMain(props, emit)

const WORD_LABEL = [
  '原型',
  '第一人称单数',
  '第三人称单数',
  '一般过去式',
  '过去分词',
  '现在分词',
  '复数形式',
  '比较级',
  '最高级',
]

// 主喇叭
const mainHorn = ref()
// 输入框的喇叭
const inputHorn = ref()
// 显示答案时的喇叭
const answerHorn = ref()

// 是否答错了
const tryWrong = ref(false)

// 图片放大
const tapEnlargeImg = () => {}

const memoryTipsData = computed(() => {
  const lv = props.data
  return {
    spell: lv.spell,
    chinese: lv.wordSimpleZnDesc,
    ipa: lv.wordAccentSpell,
    accent: lv.wordAccent,
    abbr: lv.abbr,
    tips: lv.memoryTips,
  }
})

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

// 按下的键盘
const keyDownItems = ref([] as any)
// 按下的字母
const keyDownChars = ref([] as any)

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

    // 恢复状态
    tryWrong.value = false

    // 清空键盘
    keyDownItems.value = []
    keyDownChars.value = []
  },
  {
    immediate: true,
  },
)

const showAnswer = computed(() => {
  return result.value === result_wrong || props.end
})

const showKeyboard = computed(() => {
  return props.data.charList && result.value === undefined && !props.end
})

// 按下键盘
const onKeyDown = (data: any) => {
  data.count -= 1
  keyDownItems.value.push(data)
  keyDownChars.value.push(data.value)
}

// 按退格键
const backspace = () => {
  keyDownChars.value.pop()
  const item = keyDownItems.value.pop()
  if (item) {
    item.count += 1
  }
}

watch(
  () => keyDownItems.value,
  () => {
    if (!keyDownItems.value.length) return

    if (keyDownItems.value.length === props.data.spell.length) {
      let spell = ''
      for (const c of keyDownChars.value) {
        spell += c
      }
      if (spell === props.data.spell) {
        // 答对了
        result.value = result_right
        // 先发送结果
        emit('post-result', result_right, false, Date.now() - startTime.value)
        // 再进入下一题
        handleNext()
      } else {
        tryWrong.value = true
      }
    } else {
      tryWrong.value = false
    }
  },
  { deep: true },
)
</script>
<template>
  <div v-if="data" class="word-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="data.titlePicture" class="img-box">
          <LazyLoad class="img" :src="data.titlePicture as any" @onTapEnlargeImg="tapEnlargeImg" />
        </div>
        <div v-if="data.titleCategory === category_cn" class="cn">
          <AbbrImg class="abbr" :abbr="data.abbr" />
          <span class="title">{{ data.title }}</span>
        </div>
        <div v-else class="sentence">
          <div class="main" @click="mainHorn?.handlePlay">
            <div class="content">
              <div class="english" v-html="topic"></div>
              <div class="chinese">{{ data?.titleTips }}</div>
            </div>
            <HornC v-if="data.accent" ref="mainHorn" active readonly autoplay :src="data.accent" />
          </div>
          <div
            v-if="
              result === question_right &&
              data.sentenceMeaningWordFormLabel &&
              data.sentenceMeaningWordFormLabel !== 1
            "
            class="extra"
          >
            <span class="form">{{ data.sentenceMeaningWordSpell }}</span> <span>是</span>
            <span class="prototype">{{ data.wordSpell }}</span
            ><span>的</span>
            <span class="form_name">{{
              WORD_LABEL[data.sentenceMeaningWordFormLabel - 1] || WORD_LABEL[0]
            }}</span>
          </div>
        </div>
      </div>
    </div>
    <div
      :class="{
        bottom: true,
        'size-below-16': data.spell.length <= 16,
        'size-above-16': data.spell.length > 16,
      }"
    >
      <!-- 贴纸 -->
      <img class="sticker-left" :src="leftUrl" />
      <img class="sticker-bottom" :src="bottomUrl" />

      <!-- 答案 -->
      <div v-if="showAnswer" class="result">
        <div class="chinese" @click="answerHorn?.handlePlay">
          <AbbrImg v-if="data.abbr" class="abbr" :abbr="data.abbr" />
          <span class="text">{{ data.wordSimpleZnDesc }}</span>
          <HornC v-if="data.wordAccent" ref="answerHorn" active readonly :src="data.wordAccent" />
        </div>
        <div class="voice">
          <span class="accent">{{ data.wordAccentSpell || '' }}</span>
        </div>
        <div class="letters">
          <span
            v-for="(item, index) in data.spell"
            :key="index"
            class="letter animate__prop"
            :style="{
              '--delay': 0.3 * index + 's',
            }"
            >{{ item }}</span
          >
        </div>
      </div>
      <!-- 答题板 -->
      <div v-if="showKeyboard" class="board">
        <div class="chinese" @click="inputHorn?.handlePlay">
          <AbbrImg v-if="data.abbr" class="abbr" :abbr="data.abbr" />
          <span class="text">{{ data.wordSimpleZnDesc }}</span>
          <HornC v-if="data.wordAccent" ref="inputHorn" active readonly :src="data.wordAccent" />
        </div>
        <div class="letters">
          <span
            v-for="index in data.spell.length"
            :key="index"
            class="letter"
            :class="{
              wrong: tryWrong,
              space: keyDownChars[index - 1] === key_space_value,
            }"
          >
            {{ keyDownChars[index - 1] }}
          </span>
          <keyboard-item
            class="remove"
            :iconHeight="40"
            :iconWidth="36"
            :count="result !== undefined ? 0 : keyDownItems.length"
            value="Backspace"
            iconName="icon_keyboard_remove"
            @click="backspace()"
          />
        </div>

        <keyboard
          :open="open"
          :disabled="end"
          :keyList="data.charList"
          @chooseAnswer="onKeyDown($event)"
        />
      </div>

      <!-- 助记 -->
      <span
        v-if="showNext && data.memoryTips"
        class="button second-button"
        @click="handelMemoryTips"
      >
        <img :src="memoryTipsUrl" alt="" />
      </span>
      <!-- 生词本按钮 -->
      <span v-if="showNext" class="button" @click="handelStrange">
        <img :src="strangeIcon" alt="" />
      </span>
      <!-- 投降按钮 -->
      <span v-if="showSurrender" 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
      v-if="countDownText"
      :style="{
        backgroundImage: countDownBg,
      }"
      class="count-down"
    >
      {{ countDownText }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '../index.scss' as *;

.word-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 {
      cursor: pointer;
      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>
