<script setup lang="ts">
import languageSenseApi from '@/api/subject/languageSense'
import TopicItem from './component/TopicItem.vue'
import CurrentTopic from './component/CurrentTopic.vue'
import Answer from './component/Answer.vue'
import Tools from './component/Tools.vue'
import WordCard from './component/WordCard.vue'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores'
import router from '@/router'
import { wordSortStore } from '@/stores'
import { useAudio } from '@/hooks'
import { $XXL } from '@/utils'
import { XMessage } from '@/hooks'
import { useRoute } from 'vue-router'
import { dialog } from '@/components/mj/mj-dialog'

const emits = defineEmits(['editUser'])
const route = useRoute()
const { userInfo } = storeToRefs(userStore())

const OSS_URL = import.meta.env.VITE_OSS_URL
const figureBoy = `url(${OSS_URL}/urm/ip_boy.png) center / contain no-repeat`
const figureGirl = `url(${OSS_URL}/urm/ip_girl.png) center / contain no-repeat`
const wordStore = wordSortStore()
const answer = ref()
const currentNumber = ref(0) // 当前第几题
const currentSelectWordList = ref<anyObj[]>([]) // 当前已经选择的答案集合
const isEnd = ref(false) // 是否全部答对
const beforeTopicRef = ref()
const currentTopicBox = ref()
const currentTopic = ref()
const topicListBorder = ref()
const topicListContent = ref()
const showDia = ref(false) // 单词弹框
const wordData = ref<anyObj>({ meaningList: [] }) // 弹词弹框数据
const showLoad = ref(true)
const onResult = ref(false) // 展示统计按钮
const titleData = ref('')
const grade = route.query.grade as any
const userRecodeTotolData = ref({
  // 本次答题总数据
  costTime: 0, // 时长 单位秒
  faultCount: 0, // 错误次数
  sessionId: '',
  successCount: 0, // 	正确次数
  surrenderCount: 0, //	投降次数
})
const userRecodeData = ref({
  // 单词答题数据
  costTime: 0, // 时长 单位秒
  faultCount: 0, // 错误次数
  sessionId: '',
  sentenceId: '',
  successCount: 0, // 	正确次数
  surrenderCount: 0, //	投降次数
})

watch(
  () => isEnd.value,
  nv => {
    if (nv) {
      onend()
    }
  },
)

const sentenceData = ref<anyObj>({
  sentenceList: [],
  wordMap: {},
})
const paddingTop = ref('')
function clickTools(item: anyObj) {
  if (isEnd.value || wordStore.isAudioEnd) return
  //  点击下方工具
  switch (item.name) {
    case '回退':
      //
      if (currentSelectWordList.value.length === 0) return
      answer.value.back(currentSelectWordList.value.pop())
      break
    case '清除':
      if (currentSelectWordList.value.length === 0) return
      currentSelectWordList.value = []
      answer.value.clearAnswer()
      break
    case '投降':
      userRecodeData.value.surrenderCount++
      userRecodeTotolData.value.surrenderCount++
      userRecodeData.value.faultCount = 0
      currentTopic.value.onSurrenderCount()
      scrollToElement()
      break
  }
}
const scrollToElement = async () => {
  nextTick(() => {
    currentTopicBox.value?.scrollIntoView({
      behavior: 'smooth',
    })
  })
  setTimeout(() => {
    paddingTop.value = '0px'
  }, 300)
}

function clickAnswer(item: anyObj) {
  scrollToElement()
  currentSelectWordList.value.push(item)
}

function onend() {
  const time = Math.floor((Number(new Date()) - userRecodeData.value.costTime) / 1000)
  const url = sentenceData.value.sentenceList[currentNumber.value].accent
  userRecodeData.value.costTime = time
  userRecodeData.value.sentenceId = sentenceData.value.sentenceList[currentNumber.value].sentenceId
  userRecodeTotolData.value.costTime = userRecodeTotolData.value.costTime + time
  recordSentence()

  playSound()
  currentTopic.value.playSound = true
  // 播放音频

  if (url) {
    useAudio({
      url: url,
      autoplay: true,
      id: 'x-audio-sentenceSort',
      onEnded: () => {
        onEndFn()
      },
      onError: () => {
        onEndFn()
      },
    })
  } else {
    onEndFn()
  }
}
function onEndFn() {
  currentTopic.value.playSound = false
  if (currentNumber.value >= sentenceData.value.sentenceList.length - 1) {
    // 最后一题
    endTopic()
    return
  }
  currentNumber.value++
  paddingTop.value = '1100px'
  nextTick(() => {
    beforeTopicRef.value?.scrollIntoView(false)
  })
  onClear()
  scrollToElement()
}

function endTopic() {
  // 最后一题答对或者投降
  onResult.value = true
  userRecodeTotolData.value.successCount =
    sentenceData.value.sentenceList.length - userRecodeTotolData.value.surrenderCount
  languageSenseApi
    .saveSentenceRecordHistory({ learnType: 1, ...userRecodeTotolData.value })
    .then((res: any) => {
      wordStore.setShowData(res.data.data)
    })
}

function onClear() {
  isEnd.value = false
  currentSelectWordList.value = []
  answer.value.clearAnswer()
  Object.assign(userRecodeData.value, {
    costTime: Number(new Date()),
    faultCount: 0,
    sentenceId: '',
    successCount: 0,
    surrenderCount: 0,
  })
}
function changeWord() {
  wordData.value.strangeFlag = wordData.value.strangeFlag ? 0 : 1
  // init();
}
function onLoaded() {}

function longTouch(item: anyObj) {
  // 长安
  wordData.value = sentenceData.value.wordMap[item.wordId]
  if (wordData.value?.meaningList.length > 0) {
    wordData.value.spell = item.spell
    wordData.value.meaningId = item.meaningId
    showDia.value = true
  }
}
function count(flag: boolean) {
  // 计数错误
  if (!flag) {
    userRecodeData.value.faultCount++
  }
}

function recordSentence() {
  userRecodeData.value.successCount = userRecodeData.value.surrenderCount ? 0 : 1
  userRecodeTotolData.value.faultCount += userRecodeData.value.faultCount
  languageSenseApi.saveSentenceRecord(userRecodeData.value)
}

function goStatistics() {
  // 统计
  wordStore.setData(userRecodeTotolData.value)
  router.replace(`/subject/languageSense/statistics?grade=${grade}`)
}

function playSound() {
  sentenceData.value.sentenceList.forEach((item: anyObj) => (item.onPlay = false))
  currentTopic.value.playSound = false
}

function clickBack() {
  if (onResult.value) return router.replace('/subject/languageSense')
  dialog.show({
    content: '退出后此次答题进度不记录，确定退出吗？',
    ok: () => {
      router.replace('/subject/languageSense')
    },
  })
}

function init() {
  // const fq = wordStore.postData.sessionId ? getSentenceBySessionId : getSentenceById;
  // // 再来一次   或者新的
  languageSenseApi
    .getSentenceById(grade)
    .then((res: any) => {
      try {
        onClear()
        sentenceData.value.sentenceList = res.data.data.sentenceList
        sentenceData.value.wordMap = res.data.data.wordMap
        nextTick(() => scrollToElement())
        showLoad.value = false
        userRecodeTotolData.value.sessionId = userRecodeData.value.sessionId =
          res.data.data.sessionId
        userRecodeData.value.costTime = userRecodeData.value.costTime || Number(new Date())
        titleData.value =
          (res.data.data.topicEn || '') +
          (res.data.data.topicZn ? `（${res.data.data.topicZn}）` : '')
      } catch (error) {
        XMessage.error('网络异常，请重新训练')
        return router.back()
      }
    })
    .catch((res: any) => {
      XMessage.error('网络异常,请重新训练')
      return router.back()
    })
}

defineOptions({
  name: 'SentenceSort',
})

onMounted(() => {
  wordStore.changeAudioFlag(false)
  init()
  $XXL.setScreenOn(1)
})
</script>
<template>
  <UrmLoad v-if="showLoad" :duration="1" @loaded="onLoaded" />
  <div v-show="!showLoad" class="page">
    <div class="back" @click="clickBack">
      <Icon name="left_arrow" size="80"></Icon>
      <LineFont :text="titleData || '返回'" />
    </div>

    <div ref="topicListBorder" class="topicList-border">
      <div
        ref="topicListContent"
        class="topicList-content hidden_scroll"
        :style="{
          paddingTop: paddingTop,
        }"
      >
        <div ref="beforeTopicRef" class="beforeTopic">
          <TopicItem
            v-for="(item, index) in sentenceData.sentenceList.slice(0, currentNumber)"
            :key="item.sentenceId"
            v-model="item.onPlay"
            :isEnd="isEnd"
            :sentenceData="item"
            :onResult="onResult"
            :numData="{
              current: index,
              totol: sentenceData.sentenceList.length,
            }"
            @changeCollect="item.collect = $event"
            @plsySound="playSound"
            @clickWord="longTouch"
          ></TopicItem>
        </div>

        <div ref="currentTopicBox" class="currentTopic">
          <CurrentTopic
            ref="currentTopic"
            v-model="isEnd"
            :onResult="onResult"
            :sentenceData="sentenceData.sentenceList[currentNumber]"
            :currentSelectWordList="currentSelectWordList"
            :numData="{
              current: currentNumber,
              totol: sentenceData.sentenceList.length,
            }"
            @count="count"
            @changeCollect="sentenceData.sentenceList[currentNumber].collect = $event"
            @plsySound="playSound"
            @longTouch="longTouch"
          ></CurrentTopic>
        </div>
        <!-- <div  class="lock"></div> -->
      </div>
    </div>

    <div class="answer">
      <div
        class="top-user"
        :style="{ background: userInfo.sex === 1 ? figureBoy : figureGirl }"
      ></div>
      <div v-if="onResult" class="result">
        <Btn width="286" @click="goStatistics">统计</Btn>
      </div>
      <div v-else class="topic-answer-container">
        <div class="answer_box">
          <Answer
            ref="answer"
            :isEnd="isEnd"
            :sentenceData="sentenceData.sentenceList[currentNumber]"
            @click="clickAnswer"
            @longTouch="longTouch"
            @plsySound="playSound"
          ></Answer>
        </div>
        <div class="tools">
          <Tools v-if="!isEnd" @click="clickTools"></Tools>
        </div>
      </div>
    </div>

    <mj-dialog v-model="showDia" title="单词卡" :hide-footer="true" class="Dia">
      <WordCard
        :onResult="onResult"
        :isEnd="isEnd"
        :wordData="wordData"
        @changeWord="changeWord"
      ></WordCard>
    </mj-dialog>
  </div>
  <div id="x-audio-sentenceSort"></div>
</template>
<style lang="scss" scoped>
#x-audio-sentenceSort {
  position: absolute;
  z-index: -999;
  display: none;
  visibility: hidden;
  height: 0;
  width: 0;
}
.page {
  @include main_bg;
  padding-left: 56px;
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  column-gap: 64px;
  .back {
    cursor: pointer;
    position: absolute;
    top: 2.67vh;
    left: $space-6;
    z-index: 5;
    display: flex;
    justify-content: center;
    align-items: center;
    & > span {
      margin-left: $space-3;
    }
  }
  .answer {
    height: 91vh;
    width: 734px;
    padding-top: 10vh;

    position: relative;
    border: none;
    .top-user {
      width: 100%;
      height: 58.33vh;
    }
    .result {
      margin-top: 11.67vh;
      display: flex;
      justify-content: center;
    }
    .answer_box {
      position: absolute;
      bottom: 5.83vh;
      width: 100%;
    }
    .tools {
      position: absolute;
      bottom: -5.83vh;
      width: 100%;
    }
  }
  :deep(.Dia) {
    width: 1322px;
    .el-dialog__header {
      height: 7.33vh;
      .header {
        height: 7.33vh;
      }
    }
    .body {
      align-items: start;
      padding-left: 25px;
      overflow: scroll;
    }
    .content {
      height: auto !important;
    }
    .word_gist {
      padding-top: 2.92vh;
    }
  }
}
$list_h: 86vh;
.topicList-border {
  // height: 100%;
  margin-top: 10.83vh;
  height: $list_h;
  display: flex;
  overflow: hidden;
  align-items: flex-end;
}
.topicList-content {
  width: 1012px;
  max-height: $list_h;
  overflow-y: auto;
  @include hidden_scroll;
  &::before {
    pointer-events: none;
  }
  .topic-item {
    margin-bottom: 2.5vh;
  }
}
</style>
