import learnWordApi from '@/api/subject/learnWord'
import { useLearnWordStore } from '@/stores/learnWord/useLearnWordStore'
import { nextTick } from 'vue'
import { setCache, getCache } from '@/utils/store'
import { useRouter } from 'vue-router'
import router from '@/router'
import { XMessage } from '@/hooks'

export default function useNextStage() {
  // const router = useRouter();
  const state = useLearnWordStore()
  const curStageId = getCache('stage')
  const mode = Number(getCache('mode'))
  const nextStageIdx = state.stageList.findIndex(item => item.value === curStageId)

  if (nextStageIdx === state.stageList.length - 1) {
    return XMessage.error('暂无下一阶关卡')
  } else if (nextStageIdx > -1) {
    const nextStageId = state.stageList[nextStageIdx + 1].value
    learnWordApi.getMixIntrudeIndex(nextStageId).then(async (res: any) => {
      if (res.data.code === 200) {
        setCache('stage', nextStageId)
        state.levelList = res.data.data.levelList
        state.showTestButton = res.data.data.showTestButton
        state.refreshLevelList = true
        switch (mode) {
          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
        }

        await nextTick(() => {
          state.hasFilteredNotFull = false
          state.currentList = state.currentTypeList.map((item, index) => {
            item.index = index
            return item
          })
        })

        await nextTick(() => {
          if (!state.currentList.length) {
            return XMessage.error('暂无关卡')
          }
          const levelId = state.currentList[0].levelId
          let routePath = 'normalMode'

          if (mode === 2) {
            routePath = 'hardMode'
          }

          state.currentLevelIndex = 0
          router.replace(
            `/subject/learnWord/${routePath}?levelId=${levelId}&first=${state.currentLevelIndex === 0 ? 1 : 0}`,
          )
        })
      }
    })
  } else {
    return XMessage.error('出错啦~找不到下一阶')
  }
}
