import type { Router } from 'vue-router'

import { saveScrollPosition } from './scrollStorage'
import { parseCode } from '@/utils/wxUtil'
import { useUserStore } from '@/stores'

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

export function registerRouterGuards(router: Router) {
  router.beforeEach(async (to, from) => {
    // console.log('to', to)
    // console.log('from', from)
    // 保存当前页面的滚动位置
    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()
    // console.log(code, isCodeLogin, cutEmail)
    const userStore = useUserStore()
    if (code) {
      // 如果有token 就不需要重新获取用户信息
      // console.log('userStore.token', userStore.token)
      // if (!userStore.token || !userStore.refreshToken) {
      // console.log('code', code)
      await userStore.getUserInfoByCode({
        code,
        isCodeLogin: 0,
      })
      // }
      return {
        path: to.path,
        replace: true,
      }
    } else {
      return true
    }
  })
}
