<script setup lang="ts">
import { shuffle } from '../tool.ts'
import { useAudio } from '@/hooks'
import { wordSortStore } from '@/stores'

const props = withDefaults(
  defineProps<{
    isEnd: boolean
    sentenceData: anyObj
  }>(),
  {
    isEnd: false,
    sentenceData: () => ({ wordList: [] }),
  },
)
const emits = defineEmits(['click', 'longTouch', 'plsySound'])
const selectWordList = ref<anyObj[]>([])
const wordStore = wordSortStore()
watch(
  () => props.sentenceData,
  () => {
    selectWordList.value = shuffle(props.sentenceData.wordList)
  },
)

const isLongPress = ref(false)
const timer = ref()

function handleClick(item: anyObj) {
  // 点击答案单词
  if (timer.value || isLongPress.value || props.isEnd || wordStore.isAudioEnd) {
    return
  }
  // emits('plsySound')
  // if (item.accent) {
  //   useAudio({
  //     url: item.accent,
  //     autoplay: true,
  //   })
  // }
  emits('click', item)
  item.selected = true
}

function clearAnswer() {
  selectWordList.value.forEach(item => {
    item.selected = false
  })
}
function back(val: anyObj) {
  for (const element of selectWordList.value) {
    if (element.wordId === val.wordId && element.selected && element.spell === val.spell) {
      element.selected = false
      break
    }
  }
}

const touchStart = (item: anyObj) => {
  isLongPress.value = false
  timer.value = setTimeout(() => {
    isLongPress.value = true
    emits('longTouch', item)
  }, 500) // 设置长按的阈值为500毫秒
}

const touchend = (item: anyObj) => {
  clearTimeout(timer.value)
  timer.value = null
  if (isLongPress.value) {
    // 移动端点击
    handleClick(item)
  }
}

defineExpose({
  clearAnswer,
  back,
})
</script>
<template>
  <div class="answer_content">
    <div class="answer_content_list">
      <div
        v-for="(item, index) in selectWordList"
        :key="item.wordId + index"
        :class="{ answer_content_list_item: true, hidden: item.selected }"
        @click="handleClick(item)"
        @touchstart="touchStart(item)"
        @touchend="touchend(item)"
      >
        <!-- @click="handleClick(item)" -->

        {{ item.spell }}
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
//
.answer_content {
  width: 100%;
  &_list {
    padding: 2.67vh 32px 1.5vh;
    display: flex;
    flex-wrap: wrap;
    background-color: #fffef5;
    border-radius: 1.67vh;
    box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.16);
    // border: 6px solid #fff01f;

    &_item {
      border-radius: 1.67vh;
      // border: 1px solid $font-color;
      background: #fff01f;
      box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.16);
      padding: 1vh 32px;
      margin-right: 16px;
      margin-bottom: 1.33vh;
      color: #4b4b68;
      text-align: center;
      font-family: $font-text;
      font-size: 2.33vh;
      font-style: normal;
      cursor: pointer;
      &:last-child {
        margin-right: 0;
      }
      &.hidden {
        pointer-events: none;
        opacity: 0;
      }
    }
  }
}
</style>
