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','/screen']

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

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title);
    if (to.path === '/login') {
      next({ path: '/screen' });
      NProgress.done();
    } else if (isWhiteList(to.path)) {
      next();
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true;
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false;
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            router.addRoutes(accessRoutes); // 动态添加路由
            next({ ...to, replace: true }); // 确保路由加载完成
          });
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err);
            next({ path: '/screen' });
          });
        });
      } else {
        next();
      }
    }
  } else {
    if (isWhiteList(to.path)) {
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
      NProgress.done();
    }
  }
});

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