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

NProgress.configure({ showSpinner: false })

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

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

  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)

    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        try {
          isRelogin.show = true
          // 获取用户信息
          const res = await store.dispatch('GetInfo')
          isRelogin.show = false

          // 生成可访问的路由表
          const accessRoutes = await store.dispatch('GenerateRoutes')

          // 动态添加可访问路由表
          router.addRoutes(accessRoutes)

          const group = res.deptList[0].label
          console.log('User group:', group)

          let redirectPath = '/'
          if (group.includes('维修')) {
            console.log('Redirecting to leader page')
            redirectPath = '/wx'

          } else if (group.includes('仓储')) {
            redirectPath = '/index'
          } else {
            redirectPath = '/leader'
          }
          toggleRouteVisibility(redirectPath,false);
          // 重定向到正确的页面
          next({ path: redirectPath, replace: true })
        } catch (error) {
          // 处理错误
          await store.dispatch('LogOut')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${encodeURIComponent(to.path)}`)
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
      NProgress.done()
    }
  }
})

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

