<template>
  <div :class="['g-container', 'page__container', { bg_snow: isFromTextBook }]">
    <div v-if="loaded" class="stage_pass">
      {{ stage }}
    </div>
    <div class="page__box">
      <div v-if="loaded" class="back-btn" @click="app.confirmExit"></div>
      <div v-if="showAgainLoad" class="backBtn" @click="() => $router.back()"></div>
      <div class="page__box__content">
        <div v-if="!loaded" class="page__box__load" @stopped="startgame">
          <template v-if="taskWords.length">
            <span class="page__box__load__title">本关单词</span>
            <div class="page__box__task">
              <SimpleTable
                :columns="[
                  {
                    label: '',
                    prop: 'tips',
                  },
                  {
                    label: '',
                    prop: 'value',
                  },
                ]"
                :tableData="taskWords"
                hideHead
              />
            </div>
          </template>
          <div v-if="showAgainLoad" class="beginBtn" @click="() => loadAgain()">重新加载</div>
          <div class="progress">
            <div
              :class="{
                'progress-fact': true,
                'progress-role-boy': userInfo.sex === 1,
                'progress-role-girl': userInfo.sex === 2,
              }"
            ></div>
          </div>
        </div>
        <template v-else>
          <!-- 进度条 -->
          <ProgressBar :rate="app.data.score"></ProgressBar>
          <SingleChoice
            :currentLevel="level.data.currentData"
            :isChanged="isChanged"
            :handle="{
              handleRight: level.right,
              handleError: level.error,
            }"
            @onTapEnlargeImg="tapEnlargeImg"
          />
          <TestBtn :handle="test"></TestBtn>
        </template>
      </div>
      <div
        v-if="level.data.result === question_wrong || showStatisticsBtn"
        class="next__btn pointer"
        @click="level.next()"
      >
        <img class="animate__animated animate__infinite animate__breath" :src="img_arrow" />
        <text>{{ isLast ? '统计' : '下一题' }}</text>
      </div>
    </div>
    <EnlargePicture
      v-if="showEnlarge"
      v-model="showEnlarge"
      :picture="level.data.currentData?.titlePicture"
    />
    <div id="learn-audio"></div>
  </div>
  <SuccessPop
    :levelTitle="stage"
    :status="successPop.status.value"
    v-bind="successProps"
    :nextLevelOpen="learnWordStore.nextLevel.levelId ? true : false"
    @exit="app.exit()"
    @next="app.next()"
    @again="app.again()"
  />
  <FailPop
    :levelTitle="stage"
    :status="FailedPop.status.value"
    v-bind="successProps"
    @exit="app.exit()"
    @again="app.again()"
  />

  <confirmPop v-model="confirmExitPop.status.value" :confirmCallBack="handleConfirm"></confirmPop>
  <PostLoad v-model="showLoad"></PostLoad>
</template>
<script setup lang="ts">
import type { Exercises } from './interface'

import ProgressBar from './components/ProgressBar.vue'
import SuccessPop from './components/SuccessPop.vue'
import FailPop from './components/FailPop.vue'
import SingleChoice from './components/SingleChoice.vue'
import confirmPop from '../hardMode/components/confirmPop.vue'
import TestBtn from './components/TestBtn.vue'
import useLoad from './hooks/useLoad'

import usePopup from './hooks/usePopup'
// import useSoundEffect from '@/hooks/useSoundEffect';
import { useLearnWordStore } from '@/stores/learnWord/useLearnWordStore'
import { XMessage } from '@/hooks'

import { userStore } from '@/stores/user'
import { getLevelName } from '@/utils/tool.ts'
import { getCache } from '@/utils/store'
import { useRoute, useRouter } from 'vue-router'
import useCommonAudio from '@/hooks/useCommonAudio'
import { question_right, question_wrong } from '..'
import learnWordApi from '@/api/subject/learnWord'
const showLoad = ref(false) // 最后统计加载页面
const showStatisticsBtn = ref(false) // 是否显示统计按钮

const sound = useCommonAudio(true)
const route = useRoute()
const router = useRouter()
const OSS_URL = import.meta.env.VITE_OSS_URL
const userInfo = userStore().userInfo

const img_arrow = `${OSS_URL}/xuexiaole_clinet/normalMode/arrow.png`
const boy_run = `url(${OSS_URL}/xuexiaole_clinet/learnWord/boy_run.gif) center/100% no-repeat`
const girl_run = `url(${OSS_URL}/xuexiaole_clinet/learnWord/girl_run.gif) center/100% no-repeat`
const back_btn = `url(${OSS_URL}/xuexiaole_clinet/normalMode/back_btn.png)`

const showCountDown = ref(true)
// const sound = useSoundEffect();
const learnWordStore = useLearnWordStore()
const stage = ref('') // 阶段
const isFromTextBook = ref(false)
const isChanged = ref(false) // 是否第一轮与第二轮交换
provide('isFromTextBook', isFromTextBook)
/* 闯关成功弹窗 */
const successPop = usePopup()
const successProps = reactive({
  breakThrough: false,
  breakTimeStr: '0',
  levelNum: '0',
  proportion: '0',
  simpleScore: 0,
  nextLevelId: '',
  simpleStar: 0,
  statList: [],
  exp: 0,
})
const showEnlarge = ref(false)
// 图片放大
function tapEnlargeImg() {
  showEnlarge.value = true
}

/* 失败弹窗 */
const FailedPop = usePopup()

/* 确认退出弹窗 */
const confirmExitPop = usePopup()
let urlQuery = reactive<anyObj>({})
const taskWords = ref([])
const isLast = computed(
  () => round.data.index === round.data.length - 1 && level.data.index === level.data.length - 1,
)
const { loadProgress, loaded, showAgainLoad, loadAgain, init } = useLoad()

function handleConfirm() {
  successPop.close()
  FailedPop.close()
}

function startgame() {
  showCountDown.value = false
  app.data.state = 'running'
}

const app = {
  data: reactive({
    lib: [] as Array<Array<Exercises>>, // 题库
    score: 0,
    star: 0,
    usedTime: 0,
    startTime: 0,
    state: 'init',
  }),
  totalData: [] as anyObj[],
  async getTopic(levelId: string, isFirst: number) {
    try {
      if (!levelId) return
      const res = await learnWordApi.getSimpleTopic(levelId, { isHead: isFirst })
      if (res.data.code === 200) {
        const data = res.data.data
        if (data[0].find((item: any) => item.titleType === 2)) {
          isChanged.value = true
        }

        taskWords.value = data[0][0].optionList

        stage.value =
          data[0][0].stageName +
          '-' +
          getLevelName(data[0][0].levelType) +
          '-' +
          '第' +
          data[0][0].levelNum +
          '关'
        let imgs = []
        for (let i of data) {
          for (let j of i) {
            j.titlePicture && imgs.push(j.titlePicture)
          }
        }

        init(imgs)
        app.setLib(res.data.data)
      }
    } catch (err) {
      // uni.navigateBack();
    }
  },
  setLib(list: Array<Array<Exercises>>) {
    const _this = app.data
    _this.lib = list

    if (list.length) {
      round.init()
      _this.startTime = new Date().getTime()
      _this.usedTime = 0
    }
    app.data.score = 0
  },
  over() {
    const _this = app.data
    showLoad.value = true
    showStatisticsBtn.value = false

    learnWordApi
      .postSimpleRecord({
        costTime: _this.usedTime,
        levelId: route.query.levelId,
        score: app.data.score,
        sessionId: level.data.currentData.sessionId,
        star: app.data.star,
        checkUnFullStart: learnWordStore.hasFilteredNotFull,
        levelType: 1,
        // levelNum: stage.value[stage.value.length - 2],
        levelNum: isNaN(Number(stage.value[stage.value.length - 3]))
          ? stage.value[stage.value.length - 2]
          : stage.value.slice(stage.value.length - 3, stage.value.length - 1),
        stageId: getCache('stage'),
        recordList: app.totalData,
      })
      .then((res: any) => {
        const toolObj: anyObj = {}
        app.totalData.forEach((item: anyObj) => {
          if (toolObj[item.wordId]) {
            toolObj[item.wordId].push(item.result)
          } else {
            toolObj[item.wordId] = [item.result]
          }
        })
        res.data.data.statList.forEach((item: anyObj) => {
          item.resultStr = toolObj[item.wordId].join()
        })
        Object.assign(successProps, res.data.data)
        successProps.levelNum = res.data.data.statList[0].levelNum
        learnWordStore.refreshLevelList = true
        learnWordStore.refreshTodayTask = true
        learnWordStore.refreshTextBookList = true

        if (successProps.simpleStar > 0) {
          successPop.open()
        } else {
          FailedPop.open()
        }
        app.totalData = []
      })
      .catch(() => {
        XMessage.error('网络不稳定，请再次点击统计。')
        showStatisticsBtn.value = true
      })
      .finally(() => {
        showLoad.value = false
      })
  },
  exit() {
    // const pages = getCurrentPages();
    sound.play('click.wav')
    router.back()

    /*
        if (pages?.length > 1) {
        } else {
            // uni.redirectTo({
            //     url: '/pages/learnWord/index',
            // });
        }
        */
  },
  confirmExit() {
    confirmExitPop.open()
    sound.play('click.wav')
  },
  async next() {
    // 进入下一关
    level.data.result = question_right

    if (learnWordStore.nextLevel.type === 1) {
      router.replace(`/subject/learnWord/normalMode?levelId=${learnWordStore.nextLevel.levelId}`)
    } else {
      router.replace(`/subject/learnWord/hardMode?levelId=${learnWordStore.nextLevel.levelId}`)
    }
    learnWordStore.currentLevelIndex++
    successPop.close()
  },
  async again() {
    app.totalData = []
    /* 重来 */
    await app.getTopic(urlQuery.levelId, urlQuery.first)
    FailedPop.close()
    successPop.close()
    level.data.result = question_right
  },
}

/* round对象，控制第几轮 */
const round = {
  data: reactive({
    index: 0,
    length: 4,
    currentRound: [] as Array<Exercises>,
  }),
  init() {
    const _this = round.data
    _this.index = 0
    _this.length = app.data.lib.length
    _this.currentRound = app.data.lib[0]
    if (_this.currentRound.length) {
      level.init()
    }
  },
  next() {
    const _this = round.data

    // 进入下一轮
    if (_this.index < _this.length - 1) {
      _this.index++
      _this.currentRound = app.data.lib[_this.index]
      level.init()
      isChanged.value = false
    } else {
      // 结束
      app.over()
    }
  },
}

/* level对象，控制当前轮次第几关 */
const level = {
  data: reactive({
    index: 0,
    length: 0,
    currentData: {} as Exercises,
    lib: [] as Array<Exercises>,
    result: '',
  }),
  init() {
    const _this = level.data
    _this.index = 0
    _this.lib = round.data.currentRound
    _this.currentData = _this.lib[_this.index]
    _this.length = _this.lib.length
    _this.result = ''
  },
  right(currentLevel: Exercises) {
    level.data.result = question_right
    app.data.usedTime += level.data.currentData.usedTime || 0
    app.data.score += level.data.currentData.score
    app.data.star = app.data.score < 60 ? 0 : app.data.score < 80 ? 1 : app.data.score < 100 ? 2 : 3
    try {
      const postData = {
        levelId: urlQuery.levelId,
        levelType: 1,
        result: 1,
        costTime: level.data.currentData.usedTime,
        round: round.data.index,
        score: level.data.currentData.score,
        sessionId: level.data.currentData.sessionId,
        wordId: level.data.currentData.wordId,
        meaningId: level.data.currentData.meaningId,
        titleFrom: level.data.currentData.titleFrom,
      }
      app.totalData.push(postData)
      learnWordApi.postWordRecord(postData).catch(err => {
        // level.data.result = '';
        learnWordApi.postWordRecord(postData).catch(err => {
          XMessage.error('当前网络异常')
        })
      })
    } catch (error) {
      console.error('postWordRecord相关错误', error)
    } finally {
      level.next()
    }
    return 1
  },
  error(currentLevel: Exercises) {
    level.data.result = question_wrong
    app.data.usedTime += level.data.currentData.usedTime || 0
    // return new Promise((resolve, reject) => {
    const postData = {
      levelId: urlQuery.levelId,
      levelType: 1,
      result: 0,
      costTime: level.data.currentData.usedTime,
      round: round.data.index,
      score: level.data.currentData.score,
      sessionId: level.data.currentData.sessionId,
      wordId: level.data.currentData.wordId,
      meaningId: level.data.currentData.meaningId,
      surrender: currentLevel.surrender,
      titleFrom: level.data.currentData.titleFrom,
    }
    app.totalData.push(postData)

    learnWordApi.postWordRecord(postData).catch(() => {
      // level.data.result = '';
      learnWordApi.postWordRecord(postData).catch(err => {
        XMessage.error('当前网络异常')
      })
    })
    // });
    return 1
  },
  next() {
    level.data.result = ''
    if (level.data.index < level.data.length - 1) {
      level.data.index++
      level.data.currentData = level.data.lib[level.data.index]
    } else {
      round.next()
    }
    const dom = document.querySelector('.page__content__right')
    if (dom) {
      dom.scrollTop = 0
    }
  },
}

const test = {
  a: function () {
    learnWordApi
      .simpleRecordTest({
        levelId: urlQuery.levelId,
        costTime: app.data.usedTime,
        sessionId: level.data.currentData.sessionId,
        testType: 0,
      })
      .then((res: any) => {
        Object.assign(successProps, res.data.data)
        successProps.levelNum = res.data.data.statList[0].levelNum

        if (successProps.simpleStar > 0) {
          successPop.open()
        } else {
          FailedPop.open()
        }
      })
  },
  b: function () {
    learnWordApi
      .simpleRecordTest({
        levelId: urlQuery.levelId,
        costTime: app.data.usedTime,
        sessionId: level.data.currentData.sessionId,
        testType: 1,
      })
      .then((res: any) => {
        Object.assign(successProps, res.data.data)
        successProps.levelNum = res.data.data.statList[0].levelNum

        if (successProps.simpleStar > 0) {
          successPop.open()
        } else {
          FailedPop.open()
        }
      })
  },
  c: function () {
    app.again()
    // app.data.state = 'init';
    // app.getTopic(urlQuery.levelId);
  },
}
defineOptions({
  name: 'NormalMode',
})

/* 获取题目 */

// function onLyInit() {
//     successPop.close();
//     setTimeout(() => {
//         onInit();
//     }, 0);
// }

async function onInit(id?: any) {
  await nextTick()
  app.data.state = 'init'
  if (route.query?.levelId) {
    urlQuery = route.query
    app.getTopic(id ? id : urlQuery.levelId, urlQuery.first)
  }
  if (route.query?.from && route.query.from === 'textbook') {
    isFromTextBook.value = true
  }
}

onMounted(() => {
  onInit()
})

watch(
  () => route.query.levelId,
  nv => {
    console.log('levelId变化')

    successPop.close()
    onInit()
  },
)

// onActivated(() => {
//     if (!route.query.levelId) return;
//     successPop.close();
//     onInit();
// });
</script>
<style lang="scss" scoped>
.g-container {
  width: 100vw;
  height: 100%;
  padding: 9.17vh 160px;
  user-select: none;
  background-color: #dfdaf2;

  &.bg_snow {
    // background: url('~@/static/learnWord/bg_snow.png') center/ cover no-repeat;
  }

  .stage_pass {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    padding: 1.33vh 42.01px 1.67vh 42.01px;
    line-height: 5vh;
    font-family: $font-special;
    font-size: 3.33vh;
    border-radius: 0 0 2.5vh 2.5vh;
    border: 0.33vh solid #d9d163;
    background-color: #fff78c;
    color: #4f4c2b;
    box-sizing: border-box;
  }

  .page__box {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    position: relative;

    .page__box__load {
      height: 100%;
      display: flex;
      // flex-wrap: wrap;
      flex-direction: column;
      align-items: center;

      // justify-content: center;
      overflow-y: auto;
      overflow-x: hidden;
      .beginBtn {
        margin-top: 3.33vh;
        border: 0.33vh solid #d9d163;
        font-family: $font-special;
        font-size: 2.67vh;
        text-align: center;
        background-color: #fffef5;
        padding: 1.67vh;
        border-radius: 1.67vh;
        color: #6a3906;
        cursor: pointer;
      }

      .page__box__load__title {
        width: 100%;
        color: #fff01f;
        font-family: $font-special;
        font-size: 8vh;
        line-height: 8.67vh;
        text-align: center;
        -webkit-text-stroke: 4px #6a3906;
        margin-bottom: 2.67vh;
      }

      .page__box__task {
        min-width: 1100px;
        width: max-content;
        max-width: 80%;
        border: 0.33vh solid #d9d163;
        border-radius: 1.67vh;
        text-align: center;
        font-family: $font-special;
        font-size: 2.67vh;
        line-height: 4vh;

        :deep(td) {
          font-size: 2.67vh;
          padding: 3.33vh;
        }
      }
    }

    .page__box__content {
      position: absolute;
      width: 100%;
      height: 100%;
      padding: 3.33vh 0 0;
      border-radius: 3.33vh;
      border: 0.33vh solid #d9d163;
      box-sizing: border-box;
      background: #fffef5;
      z-index: 2;
      overflow: hidden;
      // opacity: 0;

      // 进度条
      .progress {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 1.67vh;
        border-top: 0.33vh solid #d9d163;
        margin-top: 8.33vh;

        .progress-fact {
          transition: width 0.3s linear;
          width: v-bind(loadProgress);
          height: 100%;
          background: hsl(56, 100%, 56%);
          position: relative;

          &::after {
            content: '';
            display: block;
            width: 100px;
            height: 8.33vh;
            position: absolute;
            top: -6.25vh;
            right: -50px;
            transform: rotateY(180deg);
          }
        }

        .progress-role-girl {
          &::after {
            // background: url('~@/static/gif/animate/girl_run.gif') center/100% no-repeat;
            background: v-bind(girl_run);
          }
        }

        .progress-role-boy {
          &::after {
            // background: url('~@/static/gif/animate/boy_run.gif') center/100% no-repeat;
            background: v-bind(boy_run);
          }
        }
      }
    }

    .next__btn {
      box-sizing: border-box;
      width: 12.08vh;
      height: 21.67vh;
      padding: 2vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      border: 0.33vh solid #d9d163;
      border-radius: 0 1.67vh 1.67vh 0;
      background-color: #fffbc2;
      z-index: 1;
      animation: slideInLeft 0.3s linear 0.6s forwards;

      img {
        width: 8vh;
        height: 8vh;
        // animation: heartBeat 0.8s linear 1.5s 3;
      }

      text {
        color: #d9d163;
        text-align: center;
        font-family: $font-text;
        font-size: 2vh;
        font-style: normal;
        font-weight: 500;
        line-height: 3vh;
        /* 150% */
      }
    }

    .back-btn,
    .backBtn {
      cursor: pointer;
      position: absolute;
      left: -60px;
      top: -5.17vh;
      z-index: 100;
      width: 10vh;
      height: 10vh;
      background-image: v-bind(back_btn);
      background-repeat: no-repeat;
      background-size: cover;
    }
  }
}

@keyframes slideInLeft {
  0% {
    right: 0;
  }

  100% {
    right: -11.75vh;
  }
}

@keyframes heartBeat {
  0% {
    transform: scale(1);
  }

  33% {
    transform: scale(1.1);
  }

  66% {
    transform: scale(0.9);
  }
}
</style>
