import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import useSettingsStore from '@/store/modules/settings'
import useUserStore from "@/store/modules/user.js";

NProgress.configure({ showSpinner: false })

const whiteList = [
  '/login',
  '/register',
  '/index',
  '/computingResource/resourceList',
  '/industryApplications/index',
  '/industryApplications/detail',
  '/componentServices/componentServicesList',
  '/componentServices/detail',
  '/partnership/partnershipList',
  '/information/informationDetail',
  '/information/informationList',
  '/marketplace/ai',
  '/marketplace/ai/detail',
  '/marketplace/ai/orderConfirm',
]

router.beforeEach((to, from, next) => {
  NProgress.start()

  // 设置页面标题
  to.meta.title && useSettingsStore().setTitle(to.meta.title)

  // 1. 判断是否在白名单中
  if (whiteList.includes(to.path)) {
    // 白名单路由直接放行，不需要检查token
    next()
    NProgress.done()
    return
  }

  // 2. 非白名单路由，检查是否登录
  const hasToken = getToken()
  if (!hasToken) {
    // 未登录访问非白名单路由，重定向到登录页
    next(`/login?redirect=${to.fullPath}`)
    NProgress.done()
    return
  } else {
    useUserStore().getInfo().then(res => {
    })
  }

  // 3. 已登录访问非白名单路由，直接放行（不做权限检查）
  if (to.path === '/login') {
    // 已登录但访问登录页，重定向到首页
    next({ path: '/' })
    NProgress.done()
  } else {
    next()
    NProgress.done()
  }
})

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