/**
 * @Description: 路由权限
 * @Author: zenghua.wang
 * @Date: 2022-01-26 22:04:31
 * @LastEditors: zenghua.wang
 * @LastEditTime: 2024-02-26 13:54:43
 */
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import router from '@/router';
import { useUserStore } from '@/store/modules/user';
import { usePermissionStore } from '@/store/modules/permission';

NProgress.configure({ showSpinner: false });

const { VITE_APP_TITLE } = import.meta.env;
const whiteList = [];
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (typeof to.meta.title === 'string') {
    document.title = `${VITE_APP_TITLE} | ` + to.meta.title;
  }

  const userStore = useUserStore();
  const hasToken = true; //userStore.hasToken();
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      try {
        const PermissionStore = usePermissionStore();
        if (!PermissionStore.routes.length) {
          const accessRoutes = await PermissionStore.generateRoutes(userStore.roles);
          accessRoutes.forEach((item) => router.addRoute(item));
          return next({ ...to, replace: true });
        } else {
          next();
        }
      } catch (error) {
        next(`/login?redirect=${to.path}`);
      }
    }
  } else {
    NProgress.done();
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

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