<script setup lang="ts">
import { changeSymbolPosition } from '../tool.ts'
import sentenceCollectApi from '@/api/subject/sentenceCollect'
import { useAudio } from '@/hooks'
import { wordSortStore } from '@/stores'

const props = withDefaults(
  defineProps<{
    modelValue: boolean
    onResult: boolean
    sentenceData: anyObj
    currentSelectWordList: anyObj[]
    numData: anyObj
  }>(),
  {
    numData: () => ({
      current: 0,
      totol: 0,
    }),
    modelValue: false,
    onResult: false,
    sentenceData: () => ({ wordList: [] }),
    currentSelectWordList: () => [],
  },
)
const emits = defineEmits(['update:modelValue', 'count', 'changeCollect', 'plsySound', 'longTouch'])
const wordStore = wordSortStore()

const OSS_URL = import.meta.env.VITE_OSS_URL
const senseHandUrl = `${OSS_URL}/urm/sense_hand.svg`
const answerList = ref<anyObj[]>([])
const isSurrender = ref(false) // 是否投降
const isLongPress = ref(false)
const timer = ref()

watch(
  () => props.sentenceData,
  () => {
    isSurrender.value = false
    answerList.value = changeSymbolPosition(props.sentenceData.wordList)
  },
  {
    immediate: true,
  },
)
watch(
  () => props.currentSelectWordList,
  nv => {
    let index = 0
    answerList.value.forEach(item => {
      if (!item.isSymbol && nv.length > index) {
        if (!item.correct && !item.wrong) {
          const flag = nv[index].spell.toLowerCase() === item.spell.toLowerCase()
          emits('count', flag)
          item[flag ? 'correct' : 'wrong'] = true
          item.answerIndex = index
        }
        index++
      } else {
        delete item.correct
        delete item.wrong
      }
    })
    if (answerList.value.every(item => item.isSymbol || item.correct)) {
      emits('update:modelValue', true)
      // const url = props.currentSelectWordList[props.currentSelectWordList.length - 1].accent
      // if (url) {
      //   wordStore.changeAudioFlag(true)
      //   useAudio({
      //     url: url,
      //     onEnded: () => {
      //       // 最后一个单词播完之后再下一句
      //       emits('update:modelValue', true)
      //       wordStore.changeAudioFlag(false)
      //     },
      //     onError: () => {
      //       emits('update:modelValue', true)
      //       wordStore.changeAudioFlag(false)
      //     },
      //   })
      // } else {
      //   emits('update:modelValue', true)
      // }
    }
  },
  {
    deep: true,
  },
)
const playSound = ref(false)

function handlePlaySound() {
  if (
    (!props.onResult && (!props.sentenceData.accent || playSound.value || props.modelValue)) ||
    wordStore.isAudioEnd
  ) {
    return
  }
  emits('plsySound')
  playSound.value = true
  useAudio({
    url: props.sentenceData.accent,
    onEnded: res => {
      playSound.value = false
    },
    onError: res => {
      playSound.value = false
    },
  })
}
function handleCollect() {
  // 收藏/取消操作
  if (props.sentenceData.collect) {
    sentenceCollectApi.cancelCollectSentence({ sentenceId: [props.sentenceData.sentenceId] })
  } else {
    sentenceCollectApi.collectSentence({ sentenceId: [props.sentenceData.sentenceId] })
  }
  emits('changeCollect', props.sentenceData.collect ? 0 : 1)
}

function clickAnswer(item: anyObj) {
  const sound = props.modelValue
    ? item.accent
    : props.currentSelectWordList[item.answerIndex]?.accent

  if (item.isSymbol || !sound || playSound.value || wordStore.isAudioEnd) return
  emits('plsySound')
  playSound.value = true
  useAudio({
    // props.currentSelectWordList[item.answerIndex]?.spell
    url: sound,
    onEnded: res => {
      playSound.value = false
    },
    onError: res => {
      playSound.value = false
    },
  })
}

function onSurrenderCount() {
  // 投降
  isSurrender.value = true
  answerList.value.forEach(item => {
    if (!item.isSymbol) {
      item.wrong = true
    }
  })
  emits('update:modelValue', true)
}
const touchStart = (item: anyObj, hasWord: anyObj) => {
  if (!hasWord || !item) return
  isLongPress.value = false
  timer.value = setTimeout(() => {
    isLongPress.value = true
    emits('longTouch', hasWord)
  }, 500) // 设置长按的阈值为500毫秒
}

const touchend = (item: anyObj) => {
  clearTimeout(timer.value)
  timer.value = null
  if (isLongPress.value) {
    // 移动端点击
    clickAnswer(item)
  }
}
defineExpose({
  onSurrenderCount,
  playSound,
})
</script>
<template>
  <div class="current-topic topic-box">
    <div class="tool">
      <div class="sentenceCount">{{ numData.current + 1 }}/{{ numData.totol }}</div>
      <div class="icons">
        <div v-if="modelValue" class="sound tool-icon">
          <Horn v-if="playSound" :active="playSound" width="40" class="play_icon"></Horn>
          <Icon
            v-else
            name="playSound"
            size="48"
            class="play_icon"
            @click="handlePlaySound()"
          ></Icon>
        </div>
        <Icon
          :name="sentenceData.collect ? 'collect_yellow' : 'collect_grey'"
          size="48"
          @click="handleCollect()"
        ></Icon>
      </div>
    </div>
    <div class="topic_content">
      <div class="topic_content_title">
        <div class="title">
          {{ sentenceData.znDesc }}
        </div>
      </div>
      <div class="topic_content_answer">
        <div
          v-for="(item, index) in answerList"
          :key="index"
          :class="{
            topic_content_answer_item: true,
            istrue: item.correct || item.isSymbol,
            isfalse: item.wrong,
            isSurrender: isSurrender,
          }"
          @click="clickAnswer(item)"
          @touchstart="touchStart(item, props.currentSelectWordList[item.answerIndex])"
          @touchend="touchend(item)"
        >
          <div class="spell">
            {{
              item.isSymbol || modelValue
                ? item.displaySpell
                : item.correct || item.wrong
                  ? (props.currentSelectWordList[item.answerIndex]?.spell ?? '')
                  : ''
            }}
          </div>
        </div>
      </div>
    </div>
    <div
      class="hands"
      :style="{
        display: numData.current ? 'flex' : 'none',
      }"
    >
      <img :src="senseHandUrl" alt="" />
      <img :src="senseHandUrl" alt="" />
    </div>
  </div>
</template>
<style lang="scss" scoped>
@use './topic.scss' as *;
$border_c: #fff01f;
.current-topic {
  background-color: #fffef5;
  margin-bottom: 0.42vh;

  .tool {
    color: #fab900;
  }

  .topic_content {
    &_title {
      background-color: $border_c;
    }

    &_answer {
      &_item {
        width: 4.83vh;
        background: #93a0b8;
        box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25) inset;

        &.istrue {
          border-color: $border_c;
        }
      }
    }
  }
}
</style>
