<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { category_cn, category_en, result_right, result_wrong, type_cn } from '..'
import type { SingleChoiceQuestion, Option } from '..'
import { $font_color } from '@/styles/variate'
import { OSS_URL, px2vw } from '@/utils'
import {
  bottomUrl,
  countDownBg,
  leftUrl,
  memoryTipsUrl,
  nextUrl,
  rightUrl,
  shelfTopUrl,
  surrenderUrl,
  useMain,
  wrongUrl,
} from '../hooks/main'
import useAudio from '@/hooks/useCommonAudio'

const props = defineProps<{
  // 是否结束了
  end: boolean
  // 是否为最后一题
  last: boolean
  // 题目数据
  data: SingleChoiceQuestion
  // 是否需要倒计时
  countDown?: boolean
}>()

const emits = defineEmits(['post-result', 'next'])

const sound = useAudio()
const soundBaseUrl = `${OSS_URL}/xuexiaole_clinet/sound`

const {
  countDownText,
  handleNext,
  handleSurrender,
  startTime,
  showSurrender,
  result,
  showNext,
  strangeIcon,
  handelStrange,
  showMemoryTips,
  handelMemoryTips,
} = useMain(props, emits)

/* 过滤括号里的内容 */
const filterParentheses = (str: string) => {
  return str.replace(/\（(.*)\）/, '').replace(/\((.*)\)/, '')
}

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

const memoryTipsData = computed(() => {
  const optionList = props.data.optionList
  if (!optionList?.length) return {}
  if (props.data.titleCategory === category_en) {
    const answer = optionList.find(item => item.answer) as any
    // 英文题干
    return {
      spell: props.data.wordSpell,
      chinese: answer.value,
      ipa: ipa.value,
      accent: props.data.accent,
      abbr: answer.abbr,
      tips: props.data.memoryTips,
    }
  } else {
    return {
      spell: props.data.wordSpell,
      chinese: props.data.title,
      ipa: ipa.value,
      accent: props.data.accent,
      abbr: props.data.abbr,
      tips: props.data.memoryTips,
    }
  }
})

// 音标
const ipa = computed(() => {
  let tips = props.data.titleTips
  tips = tips ? tips.replace('[', '').replace(']', '') : ''
  if (tips.indexOf('null') !== -1) {
    tips = ''
  }
  return tips
})

// 主喇叭
const mainHorn = ref()
const refGroup = ref<anyObj[]>([])
// 播放声音
const clickOption = (item: Option, index: number) => {
  // 已经出结果了
  if (result.value) {
    // 播放音频
    if (props.data.titleType === type_cn) {
      refGroup.value[index].handlePlay()
    }
  } else {
    // 还没有出结果
    if (item.answer) {
      result.value = result_right
      item.result = result_right

      // 题干是中文，播放成功音效
      if (props.data.titleCategory === category_cn) {
        sound.play(`${soundBaseUrl}/right.mp3`)
      }

      // 先显示绿色的打钩（延迟进入下一题）
      setTimeout(() => {
        handleNext()
      }, 200)
    } else {
      result.value = result_wrong
      item.result = result_wrong
    }
    // 发送结果
    emits('post-result', result.value, false, Date.now() - startTime.value)
  }
}

const setItemRef = (index: number) => {
  return (el: anyObj) => {
    refGroup.value[index] = el
  }
}

const getOptionClass = (option: Option) => {
  if (!result.value) return ''
  // 答案
  if (option.answer) return result_right
  // 其他选项
  return option.result || ''
}

// 字母ABCD
watch(
  () => props.data.optionList,
  list => {
    if (!list?.length) return
    for (let i = 0; i < list.length; i++) {
      list[i].letter = String.fromCharCode(65 + i)
    }
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <div class="word-single-choice 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 && data.titleCategory === category_cn" class="img-box">
          <LazyLoad class="img" :src="data.titlePicture as any" @onTapEnlargeImg="tapEnlargeImg" />
        </div>
        <div v-if="data.titleCategory === category_cn" class="cn">
          <AbbrImg v-if="data.abbr" class="abbr" :abbr="data.abbr" />
          <span class="title">{{ filterParentheses(data.title as any) }}</span>
        </div>
        <div v-if="data.titleCategory === category_en" class="en" @click="mainHorn.handlePlay">
          <div class="title">
            {{ data.title }}
          </div>
          <div class="voice">
            <span class="text">{{ ipa }}</span>
            <HornC v-if="data.accent" ref="mainHorn" active readonly :src="data.accent" autoplay />
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <!-- 贴纸 -->
      <img class="sticker-left" :src="leftUrl" />
      <img class="sticker-bottom" :src="bottomUrl" />

      <!-- 选项 -->
      <div class="options">
        <div
          v-for="(item, idx) in data.optionList"
          :key="item.wordId"
          :class="`option ${getOptionClass(item)}`"
          @click="clickOption(item, idx)"
        >
          <div class="main">
            <LineFont class="letter" :text="item.letter" size="40" :borderColor="$font_color" />

            <AbbrImg v-if="item.valueCategory === category_cn" class="abbr" :abbr="item.abbr" />
            <HornC
              v-else-if="item.accent"
              :ref="setItemRef(idx) as any"
              :src="item.accent"
              :autoplay="false"
              readonly
            />
            <span
              class="text"
              :style="{
                fontSize: item.valueCategory === category_cn ? px2vw(36) : px2vw(48),
              }"
              >{{ item.value }}</span
            >
            <img class="result" :src="item.answer ? rightUrl : wrongUrl" alt="" />
          </div>
          <div v-if="showNext" class="sub">
            <AbbrImg v-if="item.valueCategory === category_en" class="abbr" :abbr="item.abbr" />
            <span class="text">{{ item.tips }}</span>
          </div>
        </div>
      </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-single-choice {
  .top {
    .en {
      .voice {
        display: flex;
        gap: 20px;
        align-items: center;
        margin-top: 1.67vh;
        .text {
          color: #585959;
          font-size: 3.33vh;
        }
      }
    }
  }
  .bottom {
    $option_w: 770px;
    $main_text_w: $option_w - 370px;
    $gap: 40px;
    $main_gap: 1.33vh;
    $main_p_w: 2.5vh;
    $letter_w: 8vh;
    $letter_border: 0.5vh;
    .options {
      display: flex;
      flex-wrap: wrap;
      width: $option_w * 2 + $gap;
      column-gap: $gap;
      row-gap: 2.5vh;
      z-index: 1;
      .option {
        width: $option_w;
        height: 16.67vh;
        cursor: pointer;

        $wrong_border: #d9574e;
        &.wrong {
          .main {
            background-color: #fff2f2;
            border: 0.5vh dashed $wrong_border;
            .result {
              display: inline-block;
            }
          }

          .letter {
            border-color: $wrong_border !important;
            background-color: #d9766f !important;
          }
        }

        $right_border: #8fcc00;
        &.right {
          .main {
            background-color: #fbfff2;
            border: 0.5vh solid $right_border;
            .result {
              display: inline-block;
            }
          }

          .letter {
            border-color: $right_border !important;
            background-color: #c1f052 !important;
          }
        }

        .main {
          border: 0.5vh solid transparent;
          border-radius: 1.67vh;
          display: flex;
          width: fit-content;
          align-items: center;
          column-gap: $main_gap;
          padding: 1.25vh $main_p_w;

          .letter {
            border-radius: 50%;
            width: $letter_w;
            height: $letter_w;
            line-height: $letter_w - $letter_border * 2;
            border: $letter_border solid #42c9c6;
            background-color: #9df9f7;
            text-align: center;
            box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25);
            &::after {
              left: 2.375vh;
            }
          }

          .result {
            display: none;
            width: 4vh;
            height: 4vh;
          }
          .text {
            word-break: break-all;
            max-width: $main_text_w;
            color: rgba(0, 0, 0, 0.75);
          }
        }

        .sub {
          display: flex;
          align-items: center;
          column-gap: 10px;
          padding-left: $main_p_w + $letter_w + $main_gap;
          margin-top: 1.67vh;
          .text {
            font-size: 3vh;
            line-height: 3vh;
            color: rgba(0, 0, 0, 0.65);
          }
        }
      }
    }
  }
}
</style>
