<template>
  <div :class="['g-container', 'page__container', { bg_snow: isFromTextBook }]">
    <div v-if="loaded" class="stage_pass">
      {{ stage }}
    </div>
    <div id="hardModeBox" 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="propsNum.score" mode="hard"></ProgressBar>
          <hard-round-1
            :currentLevel="level.data.currentData"
            :handleRight="level.next"
            @handleOpenMask="handleOpenMask"
            @onCloseDetailPop="wordDetailPop.open()"
            @onTapEnlargeImg="tapEnlargeImg"
          ></hard-round-1>
        </template>
      </div>
      <div
        v-if="(showNext && loaded) || showStatisticsBtn"
        class="next__btn animate__slideInLeft pointer"
        @click="level.next()"
      >
        <img class="animate__animated animate__infinite animate__breath" :src="img_arrow" />

        <span>{{ level.data.index === level.data.length - 1 ? '统计' : '下一题' }}</span>
      </div>
      <TestBtn :handle="test"></TestBtn>
    </div>
    <div v-if="showMaskRef" class="mask">
      <div class="content">{{ toastText }}</div>
    </div>
    <EnlargePicture
      v-if="showEnlarge"
      v-model="showEnlarge"
      :picture="level.data.currentData?.titlePicture"
    />
    <div id="learn-audio"></div>
  </div>
  <PostLoad v-model="showLoad"></PostLoad>
  <SuccessPop
    :status="successPop.status.value"
    :levelTitle="stage"
    :pictureList="pictureList"
    v-bind="popProps"
    :nextLevelOpen="learnWordStore.nextLevel.levelId ? true : false"
    @exit="app.exit()"
    @next="app.next()"
    @again="app.again()"
  />
  <FailPop
    :levelTitle="stage"
    :status="FailedPop.status.value"
    v-bind="popProps"
    @exit="app.exit()"
    @again="app.again()"
  />

  <confirmPop v-model="confirmExitPop.status.value" :confirmCallBack="handleConfirm"></confirmPop>

  <!-- <van-popup
        v-model:show="showPop"
        class="pop__wrapper_box"
        :is-mask-click="false"
        position="bottom"
        :animation="false"
    >
        <div class="pop__wrapper">
            <div class="pop__container">
                <wordUnderstand
                    :id="level.data.currentData.wordId"
                    :searchKey="level.data.currentData.spell"
                />
            </div>
            <div class="btn_next pointer" @click="wordDetailPop.close">
                <text class="t-icon t-icon-a-Group48097752 icon-name"></text>
                <text class="text">下一题</text>
            </div>
        </div>
    </van-popup> -->
</template>
<script setup lang="ts">
import type { Level } from './interface'
import SuccessPop from './components/SuccessPop.vue'
import FailPop from './components/FailPop.vue'
import HardRound1 from './components/HardRound-1.vue'
import confirmPop from './components/confirmPop.vue'
import ProgressBar from '../normalMode/components/ProgressBar.vue'
import TestBtn from '../normalMode/components/TestBtn.vue'
import useLoad from '../normalMode/hooks/useLoad'
import usePopup from './hooks/usePopup'
import { useHardModeStore, useLearnWordStore } from '@/stores/learnWord/useLearnWordStore'
import { getLevelName } from '@/utils/tool.ts'
import { useAnswer, totalData, clear } from './hooks/useAnswer'
import { provide } from 'vue'
import { userStore } from '@/stores/user'
import router from '@/router'
import { getCache } from '@/utils/store'
import { useRoute } from 'vue-router'
import { XMessage } from '@/hooks'
import learnWordApi from '@/api/subject/learnWord'

const route = useRoute()
const OSS_URL = import.meta.env.VITE_OSS_URL
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 userInfo = userStore().userInfo
const stage = ref('') // 阶段
// const sound = useSoundEffect();
const propsNum = useHardModeStore()
const learnWordStore = useLearnWordStore()
const showCountDown = ref(true)
const showMaskRef = ref(false)
const timeRef = ref(0)
const pictureList = ref([] as any[])
const isFromTextBook = ref(false)
const taskWords = ref([])

const showLoad = ref(false) // 最后统计加载页面
const showStatisticsBtn = ref(false) // 是否显示统计按钮
const currentLevel = computed(() => {
  return level.data.currentData
})

let urlQuery = reactive<anyObj>({})

const { loadProgress, loaded, loadAgain, showAgainLoad, init } = useLoad()
provide('pictureList', pictureList)
provide('isFromTextBook', isFromTextBook)

const showEnlarge = ref(false)
// 图片放大
function tapEnlargeImg() {
  showEnlarge.value = true
}

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

/* 闯关成功弹窗 */
const successPop = usePopup()
const popProps = reactive({
  hardStar: 0,
  timeStr: '',
  bombCount: 0,
  glassCount: 0,
  nextLevelId: '',
  surrenderCount: 0,
  allRightCount: 0,
  rightRate: 0,
  statList: [],
  proportion: '',
  breakThrough: false,
  breakTimeStr: '',
  levelNum: '1',
  lottery: false,
  lotteryResultType: 0,
  lotteryResultCount: 0,
  exp: 0,
  diamond: 0,
})

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

/* 确认退出弹窗 */
const confirmExitPop = usePopup()
function handleConfirm() {
  successPop.close()
  FailedPop.close()
}

/* 单词详情弹窗 */
const showPop = ref(false)
const wordDetailPop = {
  open() {
    showPop.value = true
  },
  close() {
    showPop.value = false

    // sound.play('click.wav');
    level.next()
  },
}
const toastText = ref('已加入生词本')

const handleOpenMask = (val: boolean) => {
  toastText.value = val ? '已加入生词本' : '已从生词本移除'
  showMaskRef.value = true
  if (timeRef.value) {
    clearTimeout(timeRef.value)
  }
  timeRef.value = setTimeout(() => {
    showMaskRef.value = false
    clearTimeout(timeRef.value)
  }, 500)
}

const app = {
  data: reactive({
    lib: [] as Array<Level>, // 题库
    score: 0,
    startTime: 0,
    state: 'init',
  }),
  async getTopic(levelId: string, isFirst: number) {
    try {
      if (!levelId) return
      const res = await learnWordApi.getHardTopic(levelId, { isHead: isFirst })
      if (res.data.code === 200) {
        const data = res.data.data
        taskWords.value = data.hardTileList.map((i: any) => {
          pictureList.value.push({
            img: i.titlePicture || '',
            id: i.wordId,
          })

          return {
            tips: i.wordSpell,
            value: i.wordSimpleZnDesc,
          }
        })

        let imgs = []

        stage.value =
          data.hardTileList[0].stageName +
          '-' +
          getLevelName(data.hardTileList[0].levelType) +
          '-' +
          '第' +
          data.hardTileList[0].levelNum +
          '关'
        for (let i of data.hardTileList) {
          i.titlePicture && imgs.push(i.titlePicture)
        }
        imgs.push(
          `${OSS_URL}/xuexiaole_clinet/normalMode/props_bomb_gray.png`,
          `${OSS_URL}/xuexiaole_clinet/normalMode/props_glass_gray.png`,
        )
        init(imgs)

        app.setLib(res.data.data.hardTileList)
        app.data.score = propsNum.score = 0
        propsNum.bombNum = res.data.data.bomb
        propsNum.glassNum = res.data.data.glass
      } else {
        // uni.navigateBack();
        router.back()
      }
    } catch (err) {
      router.back()
      // uni.navigateBack();
    }
  },
  setLib(list: Array<Level>) {
    const _this = app.data
    _this.lib = list

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

    showStatisticsBtn.value = false

    learnWordApi
      .postHardRecord({
        costTime: propsNum.usedTime,
        levelId: route.query.levelId,
        score: propsNum.score,
        star: propsNum.score < 50 ? 0 : propsNum.score < 100 ? 1 : 2,
        sessionId: currentLevel.value.sessionId,
        checkUnFullStart: learnWordStore.hasFilteredNotFull,
        levelType: 2,
        // 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: totalData.value,
      })
      .then((res: any) => {
        const toolObj: anyObj = {}
        totalData.value.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(popProps, res.data.data)
        learnWordStore.refreshLevelList = true
        learnWordStore.refreshTodayTask = true
        learnWordStore.refreshTextBookList = true
        if (popProps.hardStar > 0) {
          successPop.open()
        } else {
          FailedPop.open()
        }
        clear()
      })
      .catch(() => {
        XMessage.error('网络不稳定，请再次点击统计。')
        showStatisticsBtn.value = true
      })
      .finally(() => {
        showLoad.value = false
      })
  },
  exit() {
    router.back()

    // const pages = getCurrentPages();
    // handleChangeNext();
    // if (pages.length > 1) {
    //     uni.navigateBack();
    // } else {
    //     uni.redirectTo({
    //         url: '/pages/learnWord/index',
    //     });
    // }
  },
  confirmExit() {
    confirmExitPop.open()
  },
  async next() {
    // 进入下一关

    // console.log('learnWordStore.nextLevel', learnWordStore.nextLevel)
    if (learnWordStore.nextLevel.type === 2) {
      router.replace(
        `/subject/learnWord/hardMode?levelId=${learnWordStore.nextLevel.levelId}&first=0`,
      )
    } else {
      router.replace(
        `/subject/learnWord/normalMode?levelId=${learnWordStore.nextLevel.levelId}&first=0`,
      )
    }
    // onInit(learnWordStore.nextLevel.levelId);
    handleChangeNext()
    successPop.close()
    clear()
    learnWordStore.currentLevelIndex++
    clearPopProps()
  },
  async again(id?: any) {
    clear()
    // sound.play('click.wav');
    handleChangeNext()
    /* 重来 */
    await app.getTopic(id ? id : urlQuery.levelId, urlQuery.first)
    FailedPop.close()
    successPop.close()
  },
}

const level = {
  data: reactive<{
    index: number
    length: number
    result: string | null
    currentData: Level
  }>({
    index: 0,
    length: 0,
    result: null, // 答题结果
    currentData: {} as Level,
  }),
  init() {
    const _this = level.data
    _this.index = 0
    _this.length = app.data.lib.length
    _this.currentData = app.data.lib[_this.index]
  },
  next() {
    const _this = level.data
    if (_this.index < _this.length - 1) {
      onClickNextFlag.value++

      _this.index++
      _this.currentData = app.data.lib[_this.index]
    } else {
      app.over()
    }
  },
}
const { showNext, onClickNextFlag, handleChangeNext } = useAnswer(level.next, {})

const test = {
  a: function () {
    learnWordApi
      .hardRecordTest({
        levelId: urlQuery.levelId,
        costTime: propsNum.usedTime,
        sessionId: level.data.currentData.sessionId,
        testType: 0,
      })
      .then((res: any) => {
        Object.assign(popProps, res.data.data)

        if (popProps.hardStar > 0) {
          successPop.open()
        } else {
          FailedPop.open()
        }
      })
  },
  b: function () {
    learnWordApi
      .hardRecordTest({
        levelId: urlQuery.levelId,
        costTime: propsNum.usedTime,
        sessionId: level.data.currentData.sessionId,
        testType: 1,
      })
      .then((res: any) => {
        Object.assign(popProps, res.data.data)

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

function clearPopProps() {
  Object.assign(popProps, {
    hardStar: 0,
    timeStr: '',
    bombCount: 0,
    glassCount: 0,
    nextLevelId: '',
    surrenderCount: 0,
    allRightCount: 0,
    rightRate: 0,
    statList: [],
    proportion: '',
    breakThrough: false,
    breakTimeStr: '',
    levelNum: '1',
    lottery: false,
    lotteryResultType: 0,
    lotteryResultCount: 0,
    exp: 0,
  })
}

/* 获取题目 */

defineOptions({
  name: 'HardMode',
})

function onInit(id?: any) {
  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
  }
}
watch(
  () => route.query.levelId,
  nv => {
    console.log('levelId变化')
    successPop.close()
    onInit()
  },
)

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

onUnmounted(() => {
  // audio.destroy();
  clear()
})
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.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 42px 1.67vh 42px;
    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;
  }

  .mask {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;

    .content {
      width: 320px;
      height: 8vh;
      z-index: 999;
      border-radius: 1.67vh;
      border: 0.33vh solid var(--4, #ffd58c);
      background: var(--4, #fffaf2);
      box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.15);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--grey-1, rgba(0, 0, 0, 0.85));
      font-family: $font-text;
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      line-height: 4vh;
      /* 150% */
    }
  }

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

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

      .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;
          }
        }
      }
    }

    .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: $theme-color;
        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: v-bind(girl_run);
        }
      }

      .progress-role-boy {
        &::after {
          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;
      left: 100%;
      top: 50%;
      margin-top: -10.83vh;
      border: 0.33vh solid #d9d163;
      border-radius: 0 1.67vh 1.67vh 0;
      background-color: #fffbc2;
      z-index: 1;
      animation-delay: 2s;
      animation-duration: 0.5s;
      animation-fill-mode: both;

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

      span {
        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;
    }
  }
}

:deep(.pop__wrapper) {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 10vh 240px 0;
  border-radius: 3.33vh 3.33vh 0 0;
  border: 0.33vh solid #d9d163;
  background-color: #fffef5;

  .pop__container {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    overflow-x: hidden;
  }

  ::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
    color: transparent;
  }

  .btn_next {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);

    height: 6.67vh;
    width: 18vh;
    border: 0.33vh solid #d9d163;
    border-top: none;
    background-color: #fffbc2;
    border-radius: 0 0 1.67vh 1.67vh;

    display: flex;
    align-items: center;
    padding: 0 32px;

    .icon-name {
      width: 48px;
      height: 4vh;
      position: relative;
      display: inline-block;
    }

    .text {
      color: #ccc018;
      font-size: 2.67vh;
      font-weight: 500;
      flex: 1;
      display: flex;
      justify-content: center;
    }
  }
}

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

  100% {
    right: -141px;
  }
}

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

  33% {
    transform: scale(1.1);
  }

  66% {
    transform: scale(0.9);
  }
}

@keyframes flicker {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 1;
  }

  51% {
    opacity: 0;
  }

  100% {
    opacity: 0;
  }
}

.pop__wrapper_box {
  :deep([name='content']) {
    transform: none !important;
  }
}
</style>
