import { createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import routes from './module/base-routes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from "../store/user";

NProgress.configure({ showSpinner: false })

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

/**
 * Router 前置拦截
 *
 * 1.验证 token 存在, 并且有效, 否则 -> login.vue
 * 2.验证 permission 存在, 否则 -> 403.vue
 * 3.验证 router 是否存在, 否则 -> 404.vue
 *
 * @param to 目标
 * @param from 来至
 */
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start();

  const userStore = useUserStore();

  // 如果路由需要认证
  if(to.meta.requireAuth) {
    // 检查是否有token
    if (!userStore.token) {
      next({ path: '/login' });
      return;
    }

    // 检查当前访问的路由是否在用户权限范围内
    const currentPath = to.path;
    const menus = userStore.menus;
    
    // 递归检查路径是否在菜单中
    const checkPathInMenus = (menus: any[]): boolean => {
      for(const menu of menus) {
        if(menu.id === currentPath) {
          return true;
        }
        if(menu.children && menu.children.length > 0) {
          if(checkPathInMenus(menu.children)) {
            return true;
          }
        }
      }
      return false;
    }

    // 如果路径不在用户菜单中,跳转到403
    if(!checkPathInMenus(menus)) {
      next({ path: '/error/403' });
      return;
    }

    next();
  } else if(to.matched.length == 0) {
    next({path: '/error/404'})
  } else {
    next();
  }
})

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

export default router
