import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

// 标记路由是否已经添加，防止重复添加
let routesAdded = false

// 重置路由添加标记的函数
export const resetRoutesAdded = () => {
  routesAdded = false
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false
          // 只有在路由未添加时才生成和添加路由
          if (!routesAdded) {
            store.dispatch('GenerateRoutes').then(routes => {
              console.log('首次添加路由:', routes)
              router.addRoutes(routes.asyncRoutes) // 动态添加可访问路由表
              router.addRoutes(routes.rewriteRoutes) // 添加静态菜单路由
              routesAdded = true // 标记路由已添加
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          } else {
            next()
          }
        }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
      } else {
        // 用户已登录且有角色信息
        if (!routesAdded && store.getters.sidebarRouters.length === 0) {
          // 路由未添加且没有菜单数据，需要生成路由
          console.log('用户已登录但路由未添加，生成路由')
          store.dispatch('GenerateRoutes').then(routes => {
            console.log('路由守卫中添加路由:', routes)
            router.addRoutes(routes.asyncRoutes) // 动态添加可访问路由表
            router.addRoutes(routes.rewriteRoutes) // 添加静态菜单路由
            routesAdded = true // 标记路由已添加
            next({ ...to, replace: true })
          }).catch(err => {
            console.error('生成路由失败:', err)
            next()
          })
        } else {
          // 路由已添加，直接跳转
          next()
        }
      }
    }
  } else {
    // 没有token，重置路由添加标记
    routesAdded = false
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

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