<template>
  <div :class="[dynamicBg, 'g-container', isBook ? 'bg_snow' : '']">
    <div ref="page" class="level__page hidden_scroll">
      <level-list
        :key="aniKey"
        :lastOpenLevel="state.lastOpenLevel as any"
        :list="state.currentList"
      ></level-list>
    </div>
    <div class="interactive__page">
      <div class="full-w-h">
        <div class="back-btn" @click="router.back()"></div>
      </div>
      <div>
        <div v-if="!isBook" class="data__list">
          <data-bar
            :data="getListStars"
            :count="getAllLevelStars"
            progerssColor="#FFF01F"
            iconName="icon_star"
          ></data-bar>
          <data-bar
            :data="gameInfo.data.knowWordCount"
            :count="gameInfo.data.levelWordCount"
            progerssColor="#FFF01F"
            iconName="icon_shu"
          ></data-bar>
          <data-bar
            :data="gameInfo.data.spellWordCount"
            :count="gameInfo.data.levelWordCount"
            progerssColor="#99D609"
            iconName="icon_ping"
          ></data-bar>
        </div>
        <div v-else class="bookTitle">{{ bookTitle }}</div>
      </div>
      <div class="full-w-h pointer-auto flex-r">
        <div v-if="!isBook" class="flex-center selectBtns">
          <Select
            v-model="gameModeValue"
            :select-list="MODE_LIST"
            @selectChange="gameMode.change($event.value)"
          ></Select>
          <Select
            v-model="selectedCpn.data.value"
            :select-list="selectedCpn.data.list"
            @selectChange="selectedCpn.change($event.value)"
          ></Select>
          <div class="t-icon" @click="isShowIllustrate = true">
            <img class="full-w-h scaleToFill" :src="Question_fill" />
          </div>
        </div>
      </div>
      <div class="full-w-h">
        <!-- <div v-if="!isBook" class="btn__rank">
                    <div
                        class="trophy__box pointer pointer-auto"
                        @click="router.push('/subject/learnWord/word-table')"
                    >
                        <img class="icon" :src="icon_word" />
                    </div>
                    <div class="btn__rank__text">
                        <text>单词本</text>
                    </div>
                </div> -->
      </div>
      <div></div>
      <div class="full-w-h flex-r">
        <div v-if="!isBook" class="list_mode_box">
          <div class="btn_switchStar pointer-auto">
            <img class="full-w-h" :src="btn_switchStar" />
            <div
              :class="{
                switch__box: true,
                active: state.hasFilteredNotFull,
              }"
              @click="switchFilter"
            ></div>
          </div>
        </div>
      </div>
      <div></div>
      <div class="btn__start pointer pointer-auto" @click="enterLevel">
        <img class="full-w-h" :src="bg_popup" />
      </div>
    </div>
    <div v-show="isLoading" class="loading">
      <img :src="getLoading(userInfo.sex || 1)" />

      <!-- <text calss="loading_text">正在加载中</text> -->
    </div>
    <div v-show="isShowIllustrate" class="popup">
      <div class="popup_content">
        <img class="full-w-h" :src="popup" />
        <div class="close-btn pointer" @click="isShowIllustrate = false"></div>
      </div>
    </div>
  </div>

  <!-- <Medal :medalList="medalList" /> -->
</template>

<script lang="ts" setup>
import type { LevelDataItem } from './interface/index'

import LevelList from './components/LevelList.vue'
import learnWordApi from '@/api/subject/learnWord'
import type { Stage, UniSelectItem } from './interface'
import { userStore } from '@/stores/user'
import { useLearnWordStore } from '@/stores/learnWord/useLearnWordStore'
import DataBar from './components/DataBar.vue'
import { XMessage } from '@/hooks'
import { setCache, getCache } from '@/utils/store'
import { useRouter, useRoute } from 'vue-router'

import Select from './components/Select.vue'
import type { IModelItem } from './components/medal.vue'

const OSS_URL = import.meta.env.VITE_OSS_URL
const bg_popup = `${OSS_URL}/xuexiaole_clinet/learnWord/btn_start.png`
const btn_switchStar = `${OSS_URL}/xuexiaole_clinet/learnWord/btn_switchStar.png`
const Question_fill = `${OSS_URL}/xuexiaole_clinet/learnWord/Question_fill.png`
const popup = `${OSS_URL}/xuexiaole_clinet/learnWord/popup.png`
const back_btn = `url(${OSS_URL}/xuexiaole_clinet/normalMode/back_btn.png)`
const check_5 = `url(${OSS_URL}/xuexiaole_clinet/normalMode/check_5.png)`
const p_bg_land = `url(${OSS_URL}/xuexiaole_clinet/learnWord/bg_land.svg)`
const p_bg_sea = `url(${OSS_URL}/xuexiaole_clinet/learnWord/bg_sea.svg)`
const p_bg_sky = `url(${OSS_URL}/xuexiaole_clinet/learnWord/bg_sky.svg)`

const router = useRouter()
const route = useRoute()
const userInfo = userStore().userInfo
const state = useLearnWordStore()
const isLoading = ref(true)
const medalList = ref<IModelItem[]>([])
const isShowIllustrate = ref(false)
const isBook = ref(false)
const bookTitle = ref('')
const urlQuery = ref()
provide('isBook', isBook)

function getLoading(type: number) {
  return `${OSS_URL}/xuexiaole_clinet/learnWord/loading${type}.gif`
}
function navTo(url: string) {
  // uni.navigateTo({
  //     url: url,
  // });
  // sound.play('click.wav');
}

/* 下拉框组件 */
const selectedCpn = {
  data: reactive({
    value: '',
    list: [] as Array<UniSelectItem>,
  }),
  init() {
    const stageId = getCache('stage')
    if (stageId && typeof stageId === 'string') {
      selectedCpn.data.value = stageId
    } else {
      setCache('stage', this.data.list[0].value)
      selectedCpn.data.value = this.data.list[0].value
    }
  },
  async change(value: string) {
    const _this = selectedCpn
    _this.data.value = value
    setCache('stage', value)
    await getBaseInfo()
  },
}

const MODE_LIST = [
  {
    label: '入门',
    value: 1,
  },
  {
    label: '进阶',
    value: 2,
  },
  {
    label: '混合',
    value: 3,
  },
]

const queryLevel = route.query.level
const gameModeValue = ref(1)
const aniKey = ref(1)
const gameMode = {
  data: ref(1),
  init() {
    const mode = queryLevel || getCache('mode')

    if (mode) {
      gameModeValue.value = Number(mode)
      this.data.value = Number(mode)
      state.listType = Number(mode)
    } else {
      gameModeValue.value = 1
      this.data.value = 1
      state.listType = 1
      setCache('mode', 1)
    }
  },
  async change(value: number) {
    if (value === this.data.value) return
    this.data.value = value
    state.listType = value
    aniKey.value++
    setCache('mode', this.data.value)
    this.switchList()
  },
  switchList() {
    switch (this.data.value) {
      case 1:
        // 入门模式列表
        state.currentTypeList = state.levelList.filter(item => item.type === 1)
        break
      case 2:
        // 进阶模式列表
        state.currentTypeList = state.levelList.filter(item => item.type === 2)
        break
      case 3:
        state.currentTypeList = state.levelList
        break
      default:
        state.currentTypeList = state.levelList
        break
    }
    this.filterNotFull()
  },
  filterNotFull() {
    nextTick(() => {
      if (state.hasFilteredNotFull) {
        // 未满星关卡列表
        state.currentList = state.currentTypeList
          .filter(
            (item: LevelDataItem) =>
              (item.type === 1 && item.star < 3) || (item.type === 2 && item.star < 2),
          )
          .map((item, index) => {
            item.index = index
            return item
          })
      } else {
        state.currentList = state.currentTypeList.map((item, index) => {
          item.index = index
          return item
        })
      }
    })
  },
}

function switchFilter() {
  state.hasFilteredNotFull = !state.hasFilteredNotFull
  gameMode.filterNotFull()
}

const PAGE_STATE = ref('init')

/* 根据不同的关卡和难度显示不同的背景图 */
const dynamicBg = computed(() => {
  if (PAGE_STATE.value === 'init') {
    const bgi = getCache('learnWordBgi')
    if (bgi) {
      if (bgi === 'bg_land_easy' || bgi === 'bg_land_hard') {
        return 'bg_land'
      } else if (bgi === 'bg_sea_easy' || bgi === 'bg_sea_hard') {
        return 'bg_sea'
      } else if (bgi === 'bg_space_easy' || bgi === 'bg_space_hard') {
        return 'bg_sky'
      }
      return bgi
    } else {
      setCache('learnWordBgi', 'bg_land')
      return 'bg_land'
    }
  }

  const mode = gameMode.data.value
  let map = 'land'
  if (mode === 1) {
    map = 'land'
  } else if (mode === 2) {
    map = 'sea'
  } else if (mode === 3) {
    map = 'sky'
  }

  const newBgi = `bg_${map}`
  setCache('learnWordBgi', newBgi)
  return newBgi
})

/* 信息栏和关卡列表 */
const gameInfo = {
  data: reactive({
    allStarCount: 0,
    knowWordCount: 0,
    spellWordCount: 0,
    levelWordCount: 0,
  }),
}

/* 进入关卡 */
function enterLevel() {
  if (!state.lastOpenLevel) {
    return XMessage.error('暂无关卡')
  }
  let levelId = state.lastOpenLevel.levelId
  let routePath = 'normalMode'

  if (state.lastOpenLevel.type === 2) {
    routePath = 'hardMode'
  }

  state.currentLevelIndex =
    state.lastOpenLevel.index || state.currentList.findIndex(item => item.levelId === levelId)
  router.push(
    `/subject/learnWord/${routePath}?levelId=${levelId}&first=${state.currentLevelIndex === 0 ? 1 : 0}`,
  )
}

const getListStars = computed(() => state.currentList.reduce((acc, cur) => acc + cur.star, 0))

const getAllLevelStars = computed(() => {
  let count: number
  switch (gameMode.data.value) {
    case 1:
      count = state.currentList.length * 3
      break
    case 2:
      count = state.currentList.length * 2
      break
    case 3:
      count = state.currentList.reduce((acc, cur) => (cur.type === 1 ? acc + 3 : acc + 2), 0)
      break
    default:
      count = 0
      break
  }
  return count
})

async function scrollList() {
  await nextTick()
  page.value.scrollTop = 0 // 必须清空一次滚动条高度
  await nextTick()
  const windowHeight = window.innerHeight
  const data = document.querySelector('.isLastUnlock')?.getBoundingClientRect()
  if (!data) {
    page.value.scrollTop = page.value.scrollHeight
    return
  }
  if (state.hasFilteredNotFull) {
    page.value.scrollTop = page.value.scrollHeight
  } else {
    page.value.scrollTop = data?.top - (windowHeight + data.height) / 4
  }
}

async function getBaseInfo() {
  try {
    const stageId = selectedCpn.data.value
    if (stageId) {
      isLoading.value = true
      await loadBg()
      /* 获取基本信息 */
      const res = await learnWordApi.getMixIntrudeIndex(stageId.toString())
      if (res.data.code === 200) {
        Object.assign(gameInfo.data, res.data.data)
        state.levelList = res.data.data.levelList
        state.showTestButton = res.data.data.showTestButton
        medalList.value = res.data.data.unCheckMedal
        gameMode.switchList()
      }
    }
  } catch (err) {
    console.log(err)
  } finally {
    isLoading.value = false
  }
}

const page = ref()

function loadBg() {
  return new Promise((resolve, reject) => {
    // const img = new Image();

    // img.src = `${OSS_URL}/xuexiaole_clinet/learnWord/${dynamicBg.value}.png`;
    // console.log('img.src', img.src);

    // img.addEventListener('load', () => {
    //     resolve(true);
    // });
    // img.addEventListener('error', () => {
    //     reject(new Error('背景图加载失败'));
    // });
    resolve(true)
  })
}

const currentListWarcher = watch(
  () => state.currentList,
  () => {
    scrollList()
  },
)

function getBookDetail(options: anyObj) {
  if (options?.textBookId) {
    isBook.value = true
    learnWordApi
      .getMixIntrudeIndexFromTextBookId(options.textBookId, { grasp: options.grasp })
      .then((res: any) => {
        if (res.data.code === 200) {
          Object.assign(gameInfo.data, res.data)
          state.showTestButton = res.data.data.showTestButton
          medalList.value = res.data.data.unCheckMedal
          state.levelList = res.data.data.levelList
          state.currentTypeList = res.data.data.levelList
          state.currentList = res.data.data.levelList
          PAGE_STATE.value = 'inited'
        }
      })
      .finally(() => {
        isLoading.value = false
        PAGE_STATE.value = 'inited'
      })
    bookTitle.value = `${options?.stage} ${options?.version} ${options?.textBook}`
  } else {
    isBook.value = false
  }
}

defineOptions({
  name: 'LearnWord',
})

onMounted(() => {
  if (route.query.textBookId) {
    urlQuery.value = route.query

    getBookDetail(route.query)
  }
  // isBook.value = false;
  const stageId = getCache('stage')
  if (
    PAGE_STATE.value !== 'init' &&
    stageId &&
    stageId !== selectedCpn.data.value &&
    !isBook.value
  ) {
    selectedCpn.data.value = stageId
    nextTick(() => {
      getBaseInfo()
    })
  }
  /* 答题获得结果返回后刷新 */
  if (state.refreshLevelList) {
    state.refreshLevelList = false
    if (isBook.value) {
      learnWordApi
        .getMixIntrudeIndexFromTextBookId(urlQuery.value?.textBookId, {
          grasp: urlQuery.value?.grasp,
        })
        .then((res: any) => {
          if (res.data.code === 200) {
            Object.assign(gameInfo.data, res.data.data)
            state.showTestButton = res.data.data.showTestButton
            medalList.value = res.data.data.unCheckMedal
            state.levelList = res.data.data.levelList
            state.currentTypeList = res.data.data.levelList
            state.currentList = res.data.data.levelList
          }
        })
        .finally(() => {
          isLoading.value = false
        })
    } else {
      getBaseInfo()
    }
  } else {
    if (PAGE_STATE.value === 'init') return
    scrollList()
  }
})

onMounted(() => {
  // TODO 临时改为70

  if (!isBook.value) {
    /* 初始化下拉框 */
    learnWordApi
      .getStageList({
        current: 1,
        size: 70,
        status: 0,
      })
      .then((res: any) => {
        res.data.data.rows.forEach((item: Stage) => {
          /* 修改数据格式 */
          selectedCpn.data.list.push({
            label: item.name,
            value: item.id,
          })
        })
        state.stageList = selectedCpn.data.list
        PAGE_STATE.value = 'inited'

        nextTick(() => {
          selectedCpn.init()
          gameMode.init()
          getBaseInfo()
        })
      })
  }
})
</script>
<style lang="scss">
.full-w-h {
  width: 100%;
  height: 100%;
}
.flex-r {
  display: flex;
  justify-content: flex-end;
}
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

<style lang="scss" scoped>
.back-btn {
  width: 10vh;
  height: 10vh;
  background-image: v-bind(back_btn);
  background-repeat: no-repeat;
  background-size: cover;
  pointer-events: auto;
  cursor: pointer;
}
.loading {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fffef5;
  display: flex;
  flex-direction: column;
  align-items: center;
  // .loading_text {
  //     font-size: 32px;
  // }

  image {
    width: 33.33vh;
    height: 33.33vh;
  }
}

.g-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #dfdaf2;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  user-select: none;
  overflow: hidden;

  .popup {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 10;
    // background: rgba($color: #000000, $alpha: 0.45);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    .popup_content {
      position: relative;
      width: 666px;
      height: 45.92vh;
      .close-btn {
        position: absolute;
        right: 0;
        top: 2.42vh;
        width: 48px;
        height: 4vh;
      }
    }
  }

  &.bg_land {
    background-image: v-bind(p_bg_land);
  }

  &.bg_sea {
    background-image: v-bind(p_bg_sea);
  }

  &.bg_sky {
    background-image: v-bind(p_bg_sky);
  }
  &.bg_snow {
    background-image: v-bind(p_bg_sea);
  }

  .level__page {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;

    position: relative;
    z-index: 1;
  }

  .interactive__page {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    padding: 1.5vh 52px 3.33vh 100px;
    display: grid;
    grid-template-columns: 441px 1fr 467px;
    grid-template-rows: 72px 1fr 140px;
    justify-items: center;
    align-items: center;
    pointer-events: none;
    /*
        & > div {
            width: 100%;
            height: 100%;
            background: #000;
        }
*/
    .bookTitle {
      position: relative;
      transform: translateY(10px);
      min-width: 540px;
      height: 8.5vh;
      background-image: url(https://xuexiaole-1313840333.cos.ap-guangzhou.myqcloud.com/xuexiaoleClient/box_title_center.png);
      background-size: contain;
      line-height: 8.5vh;
      text-align: center;
      font-family: $font-special;
      font-size: 2.67vh;
      font-weight: 400;
      letter-spacing: 0em;
      color: #6a3906;

      &::before {
        content: '';
        width: 7.08vh;
        height: 8.5vh;
        position: absolute;
        top: 0;
        left: 0;
        transform: translateX(-98%);
        background: url(https://xuexiaole-1313840333.cos.ap-guangzhou.myqcloud.com/xuexiaoleClient/box_title_left.png)
          center/100% no-repeat;
      }

      &::after {
        content: '';
        width: 7.08vh;
        height: 8.5vh;
        position: absolute;
        top: 0;
        right: 0;
        transform: translateX(98%);
        background: url(https://xuexiaole-1313840333.cos.ap-guangzhou.myqcloud.com/xuexiaoleClient/box_title_right.png)
          center/100% no-repeat;
      }
    }
    .pointer-auto {
      pointer-events: auto;
    }

    .data__list {
      display: flex;
      justify-content: center;
      align-content: center;
    }

    .selectBtns {
      position: relative;
      font-size: 0;
      .t-icon {
        margin-left: 9px;
        width: 3.33vh;
        height: 3.33vh;
        cursor: pointer;
        pointer-events: auto;
      }
      :deep(.select_num) {
        .uni-select__selector-scroll {
          max-height: 32.67vh;
        }
        .uni-scroll-view {
          max-height: 32.67vh;
          .uni-select__selector-item {
            margin-bottom: 1.67vh;
          }
        }
      }
    }

    .btn__rank {
      margin-top: 7vh;

      .trophy__box {
        width: 10vh;
        height: 10vh;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 0.33vh solid #fffef5;
        background: rgba(0, 0, 0, 0.35);
        backdrop-filter: blur(3px);
        border-radius: 50%;

        .icon {
          width: 6.67vh;
          height: 6.67vh;
        }
      }

      .btn__rank__text {
        box-sizing: content-box;
        position: relative;
        width: 120px;
        text-align: center;
        margin-top: -1.83vh;
        font-size: 0;
        z-index: 1;

        text {
          color: #fffef5;
          text-align: center;
          font-family: $font-special;
          font-size: 2.33vh;
          text-shadow:
            -2px -2px 0 #6a3906,
            2px -2px 0 #6a3906,
            -2px 2px 0 #6a3906,
            2px 2px 0 #6a3906;
          /* 设置描边效果 */
        }

        image {
          width: 6.83vh;
          height: 2.08vh;
        }
      }
    }
    .words-num__box {
      box-sizing: border-box;
      width: 232px;
      margin-top: 2vh;
      padding: 0.67vh 32px;
      border-radius: 0.83vh;
      background: rgba(0, 0, 0, 0.35);
      .words-num__title {
        color: #fffef2;
        font-family: $font-special;
        font-size: 2vh;
        text-shadow:
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000;
      }
      .words-num__value {
        color: #fff01f;
        font-family: $font-special;
        font-size: 2.33vh;
        text-shadow:
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000,
          0 0 4px #000;
      }
    }
    .list_mode_box {
      margin-top: 5.42vh;
      & > view {
        & + view {
          margin-top: 1.5vh;
        }
      }
    }

    .btn__start {
      width: 31.67vh;
      height: 8.33vh;
      align-self: flex-end;
    }

    .btn_switchStar {
      position: relative;
      width: 24.33vh;
      height: 5.33vh;
      .switch__box {
        width: 4vh;
        height: 4vh;
        position: absolute;
        right: 36px;
        top: 0.67vh;
        cursor: pointer;
        &.active {
          background: v-bind(check_5);
          background-size: contain;
        }
      }
    }

    .btn_mode {
      position: absolute;
      bottom: 0;
      .type_ {
        image {
          width: 21.33vh;
          height: 10.83vh;
        }
      }

      .type_1 {
        image {
          width: 14.83vh;
          height: 14.83vh;
        }
      }

      .type_2 {
        image {
          width: 14.83vh;
          height: 14.83vh;
        }
      }

      .type_3 {
        image {
          width: 178px;
          height: 14.83vh;
        }
      }
    }
  }
}

.uniSelect {
  flex-shrink: 0;

  &.uniSelect {
    margin-left: 32px;
  }

  :deep(.uni-select) {
    padding: 0.33vh 24px 0.33vh 40px;
    border: 0.33vh solid #fffef2;
    border-radius: 3vh;
    background: rgba(0, 0, 0, 0.35);
    // backdrop-filter: blur(3px);
    // width: 187px;
    height: 4.67vh;
  }

  :deep(.uni-icons) {
    color: #fffef2 !important;
    font-size: 2.67vh !important;
  }

  :deep(.uni-select__input-text) {
    font-size: 2.67vh;
    font-family: $font-text;
    color: #fff;
  }

  :deep(.uni-popper__arrow) {
    display: none;
  }

  :deep(.uni-select__selector) {
    border: 0.33vh solid #fffef2;
    border-radius: 1.67vh;
    background: rgba(0, 0, 0, 0.35);
    // backdrop-filter: blur(3px);
    color: #fffef2;
    padding: 0;
  }

  :deep(.uni-select__selector-item) {
    margin-bottom: 0.67vh;
    padding-left: 0;
    font-size: 2.67vh;
    text-align: center;

    &.selected {
      color: #fff01f;
    }
  }

  :deep(.uni-scroll-view) {
    max-height: 16vh;

    .uni-scroll-view-content {
      height: auto;
      padding: 1.33vh 0 1.33vh 24px;
    }

    ::-webkit-scrollbar {
      width: 12px;
      border-radius: 0 1.67vh 1.67vh 0 !important;
      background-color: rgba(0, 0, 0, 0.35);
    }

    ::-webkit-scrollbar-thumb {
      /* 滚动条里面小方块 */
      height: 2.5vh !important;
      border-radius: 0.5vh !important;
      background-color: #fff681 !important;
    }

    ::-webkit-scrollbar-track {
      /* 滚动条 */
      // border-radius: 0 7.81rpx 7.81rpx 0 !important;
    }

    .uni-select__selector-item {
      &:hover {
        color: #ffee1d;
        background-color: transparent;
      }
    }
  }
}
</style>
