import { EnumStorageKey } from '@/enum'
import { useAuth } from '@/hooks/useAuth'
import { getQueryVariable } from '@/utils/location'
import { getSession } from '@/utils/storage'
import { DONT_NEED_WECHAT_AUTH_PATHS } from '@/constants/index'
import { getToken } from '@/utils/user'

const { codeExchangeToken, oauth2Verify, utdExchangeToken } = useAuth()

/** 路由守卫 -- 处理用户权限 */
export function helperHandleAuth(router: any) {
  router.beforeEach(async (to: any, from: any, next: any) => {
    document.title = to.meta.title || '晓得'

    if (DONT_NEED_WECHAT_AUTH_PATHS.includes(to.path)) {
      next()
    }
    else if (!getToken()) {
      // 如果没有token，就得重新获取code，然后获取userInfo&token
      if (getQueryVariable('code')) {
        try {
          // 如果有code，用code直接获取userInfo，code获取结果可能会失败，
          const result = await codeExchangeToken()
          if (result) {
            next()
            // window.location.reload();
          }
          else {
            // oauth2Verify();
          }
        }
        catch (error) {
          // catch 继续二次捕捉失败的情况
          oauth2Verify()
        }
      }
      else {
        console.log('没有code')
        // 如果没有code，那就重新去获取code
        oauth2Verify()
      }
    }
    else {
      if (getSession(EnumStorageKey.temporary) && !getQueryVariable('code')) {
        // 回到了授权页
        // getWxConfig(true)
      }
      next()
    }
  })
}

export function helperHandleAuthTemp(router: any) {
  router.beforeEach(async (to: any, from: any, next: any) => {
    if (DONT_NEED_WECHAT_AUTH_PATHS.includes(to.path)) {
      next()
    }
    else if (!getToken()) {
      const utd = getQueryVariable('utd')
      if (utd) {
        const res = await utdExchangeToken()
        console.log(res, 'res')
      }
      else {
        // next
      }
    }
    else {
      next()
    }
  })
}
