/**
 * by 菲鸽 on 2024-03-06
 * 路由拦截，通常也是登录拦截
 * 可以设置路由白名单，或者黑名单，看业务需要选哪一个
 * 我这里应为大部分都可以随便进入，所以使用黑名单
 */
import { useUserStore } from '@/store'
import {
  getNotNeedLoginPages as _getNotNeedLoginPages,
  notNeedLoginPages as _notNeedLoginPages,
} from '@/utils'
import type { Router } from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: true, parent: '#app' })

export const loginRoute = '/pages/login/index'

export const isLogged = () => {
  const userStore = useUserStore()
  return userStore.isLogged
}

const isDev = import.meta.env.DEV

// 黑名单登录拦截器 - （适用于大部分页面不需要登录，少部分页面需要登录）
const navigateToInterceptor = {
  // 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同
  invoke({ url }: { url: string }) {
    // console.log(url) // /pages/route-interceptor/index?name=feige&age=30
    const path = url.split('?')[0]
    let notNeedLoginPages: string[] = []
    // 为了防止开发时出现BUG，这里每次都获取一下。生产环境可以移到函数外，性能更好
    if (isDev) {
      notNeedLoginPages = getNotNeedLoginPages()
    } else {
      notNeedLoginPages = _notNeedLoginPages
    }
    const isNeedLogin = notNeedLoginPages.includes(path)
    if (!isNeedLogin) {
      return true
    }
    const hasLogin = isLogged()
    if (hasLogin) {
      return true
    }
    // const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
    uni.navigateTo({ url: loginRoute })
    return false
  },
}

export const routeInterceptor = {
  install() {
    uni.addInterceptor('navigateTo', navigateToInterceptor)
    uni.addInterceptor('reLaunch', navigateToInterceptor)
    uni.addInterceptor('redirectTo', navigateToInterceptor)
  },
}

export const getNotNeedLoginPages = () => {
  let notNeedLoginPages: string[] = []
  if (isDev) {
    notNeedLoginPages = _getNotNeedLoginPages()
  } else {
    notNeedLoginPages = _notNeedLoginPages
  }
  return notNeedLoginPages
}

export const checkLoginUrl = (url: string) => {
  const path = url.split('?')[0]
  const isNotNeedLogin = getNotNeedLoginPages().includes(path.replace(/^pages/, '/pages'))
  return isNotNeedLogin
}

export const checkWithRedirectLogin = (url: string) => {
  const isNotNeedLogin = checkLoginUrl(url)
  if (!isNotNeedLogin) {
    return !isLogged()
  }
  return false
}

export const checkNotFound = (url: string) => {
  const isNotNeedLogin = checkLoginUrl(url)
  if (!isNotNeedLogin) {
    return !isLogged()
  }
  return false
}

export const routerBeforeEachConfig = (router: Router) => {
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (checkWithRedirectLogin(to.path)) {
      return next({
        path: loginRoute,
      })
    }
    const userStore = useUserStore()
    if (!userStore.userInfo && userStore.isLogged) {
      await userStore.loadUserInfo()
    }
    return next()
  })

  router.afterEach(() => {
    NProgress.done()
  })
}
