<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { Option } from '@/page/subject/learnWord/word-table/test/type'
import useAnswer from '@/page/subject/learnWord/normalMode/hooks/useAnswer'
import useExam from '@/page/subject/learnWord/word-table/test/hooks/useExam'
import wordTestApi from '@/api/subject/wordTest'
import wordDetailApi from '@/api/subject/wordDetail'
import { category_cn, category_en, single_choice_cn, single_choice_en } from '.'
import hud from '@/utils/hud'
import { question_right, question_wrong } from '../../../..'
import { $font_color } from '@/styles/variate'
import { px2vw } from '@/utils'

const props = defineProps<{
  meaningId?: string
  title?: string
  optionList?: Option[]
  memoryTips?: any
  accent?: string
  abbr?: string
  titleType?: number
  titleTips?: string
  titleCategory?: number
  titlePicture?: string
  result?: string
  sessionId?: string
  wordId?: string
  strangeWord?: number
  levelId?: string
  levelType?: string | number
  titleFrom?: string | number
  wordSpell?: string
  modelValue?: boolean
  // 是否为最后一题
  isLast?: boolean
}>()
const emits = defineEmits(['update:modelValue', 'enlargeImg', 'getChoice', 'next'])

const OSS_URL = import.meta.env.VITE_OSS_URL
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 wrongUrl = `${OSS_URL}/xuexiaole_clinet/normalMode/cross.png`
const rightUrl = `${OSS_URL}/xuexiaole_clinet/normalMode/tick.png`
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 answer = useAnswer({
  handleRight,
  handleError,
})
const exam = useExam()
const isSurrender = ref(false)

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

// 图片放大
function tapEnlargeImg() {
  emits('enlargeImg', props.titlePicture)
}

// 答对了
function handleRight() {
  exam.questions.rightCount++ // 加1分
  exam.questions.answered++
  exam.winningStreak.cur.value++
  exam.curQuestion.value.result = question_right
  emits('getChoice', question_right)
  // exam.pageType.value = 'list';
  return postResult(1)
}

// 答错了
function handleError() {
  exam.questions.answered++
  exam.winningStreak.cur.value = 0
  exam.curQuestion.value.result = question_wrong
  emits('getChoice', question_wrong)

  return postResult(0)
}

// 点击投降
function handleSurrender() {
  if (answer.data.result) return

  isSurrender.value = true

  answer.answering(false, props.optionList?.find(item => item.answer) as any, true)
}
function postResult(answerResult: number) {
  return new Promise((resolve, reject) => {
    emits('update:modelValue', true)
    wordTestApi
      .saveWordTest({
        duration: new Date().getTime() - answer.data.startTime,
        questionType: 0,
        saveTime: new Date().getTime(),
        sessionId: props.sessionId,
        levelId: props.levelId,
        testResult: answerResult,
        wordId: props.wordId,
        surrender: isSurrender.value ? 1 : 0,
        imageUrl: props.titlePicture,
        meaningId: props.meaningId,
        levelType: props.levelType,
        titleFrom: props.titleFrom,
      })
      .then((res: any) => {
        if (!(res?.data.code === 200)) {
          wordTestApi
            .saveWordTest({
              duration: new Date().getTime() - answer.data.startTime,
              questionType: 0,
              saveTime: new Date().getTime(),
              sessionId: props.sessionId,
              levelId: props.levelId,
              testResult: answerResult,
              wordId: props.wordId,
              surrender: 0,
              imageUrl: props.titlePicture,
              meaningId: props.meaningId,
              levelType: props.levelType,
              titleFrom: props.titleFrom,
            })
            .then((res: any) => {
              emits('update:modelValue', false)

              if (res.data.data) {
                resolve('')
              }
            })
        } else {
          emits('update:modelValue', false)
        }
      })
    isSurrender.value = false
  })
}

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

// 下一题按钮
const showNext = computed(() => {
  // 答错了 && 不是最后一题
  return props.result === question_wrong && !props.isLast
})

const isMarked = ref(false)
watch(
  () => props.wordId,
  () => {
    isMarked.value = props.strangeWord === 1
  },
  {
    immediate: true,
  },
)

const showMemoryTips = ref(false)
// 点击助记
function handelMemoryTips() {
  showMemoryTips.value = true
}
const memoryTipsData = computed(() => {
  if (!props.optionList?.length) return {}
  const answer = props.optionList.find(item => item.answer) as any
  if (props.titleCategory === category_en) {
    // 英文题干
    return {
      spell: props.wordSpell,
      chinese: answer.value,
      ipa: ipa.value,
      accent: props.accent,
      abbr: answer.abbr,
      tips: props.memoryTips,
    }
  } else {
    return {
      spell: props.wordSpell,
      chinese: props.title,
      ipa: ipa.value,
      accent: props.accent,
      abbr: props.abbr,
      tips: props.memoryTips,
    }
  }
})

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

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

function isWrong(result: any) {
  return result === question_wrong
}

function getResultClass(result: any) {
  if (result === question_right) {
    return question_right
  } else if (result === question_wrong) {
    return question_wrong
  }
  return ''
}

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

const refGroup = ref<anyObj[]>([])
// 播放声音
function clickOption(item: Option, index: number) {
  if (!props.result) {
    answer.answering(item.answer, item as any)
  } else if (isWrong(props?.result) && props.titleType === single_choice_cn) {
    refGroup.value[index].handlePlay()
  }
}

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

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

watch(
  () => props.meaningId,
  () => {
    answer.load(props)
  },
  { immediate: true },
)
</script>

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

      <!-- 选项 -->
      <div class="options">
        <div
          v-for="(item, idx) in optionList"
          :key="item.wordId"
          :class="`option ${getResultClass(item.result)}`"
          @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="isWrong(item.result) ? wrongUrl : rightUrl" 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 && 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-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';

.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>
