import type { Router } from 'vue-router'

import { saveScrollPosition } from './scrollStorage'
import { parseCode } from '@/utils/wxUtil'
import { useUserStore } from '@/stores'
import { finishPageProgress, startPageProgress } from '@/components/common/Progress/usePageProgress'

// 白名单
const WHITE_LIST: string[] = ['/aa']

export function registerRouterGuards(router: Router) {
  router.beforeEach(async (to, from) => {
    if (to.fullPath !== from.fullPath) {
      startPageProgress()
    }
    // 保存当前页面的滚动位置
    if (from.fullPath) {
      saveScrollPosition(from.fullPath, window.scrollY)
    }
    if (WHITE_LIST.includes(to.path)) {
      return true
    }

    const code = parseCode(to.fullPath)

    // code是否来自企业微信 1 不是 0 是 2 开发人员登录方式
    // const isCodeLogin = parseIsCodeLogin()
    // const cutEmail = parseIsCutEmail()
    const userStore = useUserStore()
    if (code) {
      // 如果有token 就不需要重新获取用户信息
      // if (!userStore.token || !userStore.refreshToken) {
      await userStore.getUserInfoByCode({
        code,
        isCodeLogin: 0,
      })
      // }
      return {
        path: to.path,
        replace: true,
      }
    } else {
      return true
    }
  })

  router.afterEach(() => {
    finishPageProgress()
  })

  router.onError(() => {
    finishPageProgress()
  })
}
