<template>
  <div v-if="isloading">
    <wordSkeleton></wordSkeleton>
  </div>
  <template v-else>
    <template v-if="detailData?.id">
      <div class="word_understand">
        <div class="word_understand_content">
          <wordGist
            ref="wordGistRef"
            :detailData="testData"
            :wordId="wordId"
            @toDetail="toDetail"
            @typeActive="typeActive"
            @stopAllLottie="stopAllLottie"
          ></wordGist>
          <listSkeleton v-if="isloading2"></listSkeleton>
          <div v-else>
            <wordForm
              ref="wordFormRef"
              :formList="detailData?.formList"
              :typeAbbrList="detailData?.typeAbbrList"
              :typeAbbr="detailData?.typeAbbr"
              @stopAllLottie="stopAllLottie"
            ></wordForm>
            <wordMeaning
              ref="wordMeaningRef"
              :meaningGroupVoList="detailData?.meaningGroupVoList"
              :spell="detailData?.spell"
              @viewVisible="viewVisible"
              @stopAllLottie="stopAllLottie"
            >
            </wordMeaning>
            <!-- <div class="come">本词典数据参考自：牛津词典</div> -->
          </div>
        </div>
      </div>
    </template>
    <!-- 空 -->
    <template v-else>
      <div class="word_understand">
        <!-- <div class="empty">
                    <image src="@/static/unity/search_empty.png" mode=""></image>
                </div> -->
        <Empty content="搜索结果为空" size="320"></Empty>
      </div>
    </template>
  </template>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import wordForm from './wordForm.vue'
import wordGist from './wordGist.vue'
import wordMeaning from './wordMeaning.vue'
import wordDetailApi from '@/api/subject/wordDetail'
import { useWordDetailStore, useTodayStatusStore } from '@/stores/wordDetail'
// import { highlightText, checkAttr } from './hook';
import wordSkeleton from '../skeleton/wordSkeleton.vue'
import listSkeleton from '../skeleton/listSkeleton.vue'

const props = defineProps<{
  id: any
  searchKey?: string
}>()

const emits = defineEmits(['viewVisible', 'updateSpell', 'searchEmpty', 'searchNoEmpty'])

interface formProps {
  enDesc: string
  usAccents: string
  brAccents: string
  labels: string
}
interface dataProps {
  id: any
  spell: string
  brAccents: string // 英音
  usAccents: string // 美音
  formList: formProps[] // 变形
  meaningGroupVoList: any[] // 词义列表
  meaningSimpleList?: any[]
  vocabularyWordList: any[]
  typeAbbrList: any[]
  strangeFlag: number
  knowFlag: number
  typeAbbr: string
  isplaybr?: boolean
  isplayus?: boolean
}
const detailData = ref<dataProps>({
  id: '',
  spell: '',
  brAccents: '', // 英音
  usAccents: '', // 美音
  formList: [], // 变形
  meaningGroupVoList: [], //
  meaningSimpleList: [],
  vocabularyWordList: [],
  strangeFlag: 0,
  knowFlag: 0,
  typeAbbrList: [],
  typeAbbr: '',
  isplaybr: false,
  isplayus: false,
})
const OSS_URL = import.meta.env.VITE_OSS_URL
const bg = `url(${OSS_URL}/urm/dictionaries_box.svg)`
const wordId = ref('')
const spell = ref()
const isloading = ref(false)
const isloading2 = ref(false)
const testData = ref()
const store = useWordDetailStore()
const statusStore = useTodayStatusStore()
const wordGistRef = ref<{
  stopAllLottie: () => void
}>()
const wordMeaningRef = ref<{
  stopAllChildLottie: () => void
}>()
const wordFormRef = ref<{
  stopAllLottie: () => void
}>()

const typeActive = (value: string, spell: string) => {
  searchDetail2({ typeAbbr: value, spell })
}

const toDetail = (value: string) => {
  searchDetail({ word: value })
}

// 停止所有喇叭动画
const stopAllLottie = () => {
  wordMeaningRef.value?.stopAllChildLottie()
  wordGistRef.value?.stopAllLottie()
  wordFormRef.value?.stopAllLottie()
}

const viewVisible = (value: boolean) => {
  emits('viewVisible', value)
}

const handleListImage = (list: any[]) => {
  for (const par of list) {
    for (const item of par.meaningVoList || []) {
      item.image = item.image && !Array.isArray(item.image) ? item.image.split(',') : []
      // item.image.unshift( `@/static/wordDetail/video.mp4`)
      // item.subTypeStr = checkAttr(item.subTypeStr);
      for (const child of item.sentenceVoList || []) {
        // child.content = highlightText(child.content, child.lightIndexList || []);
        child.enDesc = child.content
        if (child.image && !Array.isArray(child.image)) {
          child.image = child.image.split(',')
          // child.image.unshift( `@/static/wordDetail/video.mp4`)
        } else {
          child.image = []
        }
      }
    }
  }
}

// 切换词性
const searchDetail2 = (postdata?: { spell?: string; typeAbbr?: string }) => {
  // 缓存有数据
  let result: any = store.detailData?.find((item: any) => {
    return item.attr === postdata?.typeAbbr
  })

  if (result) {
    detailData.value = result.data
    return
  }
  isloading2.value = true
  wordDetailApi
    .getWord({
      ...postdata,
      spell: postdata?.spell || spell.value,
    })
    .then((res: any) => {
      detailData.value = res.data.data
      // 处理图片、文字高亮、词性
      handleListImage(detailData.value?.meaningGroupVoList || [])
      // 缓存不同词性下的释义和例句
      store.setDetailData(
        {
          attr: postdata?.typeAbbr || (detailData.value?.typeAbbrList || [])[0],
          data: res.data.data,
        },
        res.data.data?.spell,
      )
    })
    .catch(err => {
      console.log(err)
    })
    .finally(() => {
      isloading2.value = false
    })
}

// 第一次请求
const searchDetail = (postdata?: { spell?: string; typeAbbr?: string; word?: string }) => {
  if (store.keyword && (store.keyword !== spell.value || store.keyword !== postdata?.word)) {
    // 单词切换时清空缓存
    store.clearAllData()
    if (!postdata) return
    if (postdata.spell || postdata.word) {
      detailData.value.spell = postdata.spell || postdata.word || ''
    }
  } else {
    // 缓存有数据
    let result: any = store.detailData?.find((item: any) => {
      return item.attr === postdata?.typeAbbr
    })
    if (result) {
      detailData.value = result.data
      return
    }
  }
  // load.show();
  isloading.value = true
  wordDetailApi
    .getWord({
      ...postdata,
      spell: postdata?.word || spell.value,
    })
    .then((res: any) => {
      // 点击当前单词的其他形式（如过去式），跳转到该形式的单词详情
      postdata?.word && emits('updateSpell', postdata?.word)
      if (!res.data.data) {
        emits('searchEmpty')
        return
      }
      emits('searchNoEmpty')
      if (!postdata?.typeAbbr) {
        detailData.value = res.data.data
        testData.value = JSON.parse(JSON.stringify(detailData.value))
      } else {
        detailData.value = res.data.data
      }
      wordId.value = detailData.value?.id
      // 处理图片
      handleListImage(detailData.value?.meaningGroupVoList || [])
      // 存储数据
      store.setDetailData(
        {
          attr: postdata?.typeAbbr || (detailData.value.typeAbbrList || [])[0],
          data: res.data.data,
        },
        res.data.data?.spell,
      )
      // 进入详情，就修改查看单词状态
      statusStore.checkStatus = true
    })
    .catch(err => {
      console.log(err)
    })
    .finally(() => {
      setTimeout(() => {
        isloading.value = false
      }, 500)
    })
}

watch(
  () => props.id,
  (newValue, oldValue) => {
    wordId.value = newValue
  },
  {
    // deep: true,
    immediate: true,
  },
)
watch(
  () => props.searchKey,
  (newValue, oldValue) => {
    spell.value = newValue
    searchDetail({ spell: spell.value })
  },
  {
    deep: true,
  },
)
</script>
<style lang="scss" scoped>
.word_understand {
  width: 144vh;
  height: 90vh;
  background-image: v-bind(bg);
  background-repeat: no-repeat;
  background-size: contain;
  padding: 7.17vh 10.67vh 5.67vh;
  box-sizing: border-box;
  .word_understand_content {
    padding-top: 5vh;
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
    // scrollbar-color: transparent transparent;
    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      color: transparent;
      display: none;
    }
  }
}
.come {
  display: flex;
  justify-content: flex-end;
  margin-top: 0.67vh;
  font-size: 1.67vh;
  color: #b7b6af;
}

.empty {
  height: 100% !important;
}
</style>
