import router from "@/framework/router";
import { RouteRecordRaw } from 'vue-router';
import pinia from "@/framework/store";
import { usePermissionStoreHook } from "@/framework/store/modules/permission";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度条

import { useRoutesStore } from "@/framework/store/modules/routes";
import { getSubSystemRouter } from "@/framework/router/dynamicRouter";
import { useUserStoreHook } from "@/framework/store/modules/user";
import { useSettingsStore } from "@/framework/store/modules/settings";

const userStore = useUserStoreHook()

const routesStore = useRoutesStore(pinia);

const permissionStore = usePermissionStoreHook();

const settingsStore = useSettingsStore(pinia);

const whiteList=['']  //白名单配置
/**白名单路由处理 */
function whiteListHandle(to,next){
  if (routesStore.hasRoutes) {
    next();
  } else {
    routesStore.routes = getSubSystemRouter()
    routesStore.hasRoutes = true
    getSubSystemRouter().forEach((route: RouteRecordRaw) => {
      router.addRoute(route);
    });
    
    next({ ...to, replace: true });
  }
}

/**开发环境路由处理 */
async function developmentRouterHandle(to,next){
  if (routesStore.hasRoutes) {
    next();
    return;
  }
  userStore.getInfo()// 获取登录用户信息
  //获取并设置业务域
  await permissionStore.setAndGetBusinessDomain().catch((error) => {
    console.error(error);
  });
  routesStore.routes = getSubSystemRouter()
  routesStore.hasRoutes = true
  getSubSystemRouter().forEach((route: RouteRecordRaw) => {
    router.addRoute(route);
  });
  next({ ...to, replace: true });
}

/**路由处理 */
async function routerHandle(to,next){
  if (routesStore.hasRoutes) {
    next()
    return false
  }
  try {
    userStore.getInfo()// 获取登录用户信息
    //获取并设置业务域
    await permissionStore.setAndGetBusinessDomain().catch((error) => {
      console.error(error);
    });
    const accessRoutes = await permissionStore.generateRoutes(getSubSystemRouter());
    accessRoutes.forEach((route: RouteRecordRaw) => {
      router.addRoute(route);
    });
    routesStore.routes = accessRoutes
    routesStore.hasRoutes = true
    next({ ...to, replace: true });
  } catch (error) {
    ElMessage({type: 'error',message: '无菜单权限，请重新登录' })
    // setTimeout(()=>{
    //   window.location.href = settingsStore.loginAddress
    // },2000)
  }

}
/**
 * 全局前置路由守卫,在即将进入路由回调会被触发
 * to 表示oruter即将进入的路由对象
 * from 表示当前即将离开的路由对象
 * next 通过该函数可以重新定义要跳转的路由路径。常用示例：next({ path: '/' }) 表示跳转到重定向页面
 */
router.beforeEach( (to, from, next) => {
  NProgress.start() //进度条
  /**白名单处理 */
  if(whiteList.includes(to.fullPath)){
    whiteListHandle(to,next) 
    return
  }
  /**路由处理 */
  if (import.meta.env.MODE === 'development') {
    developmentRouterHandle(to,next)
  } else {
    routerHandle(to,next)
  }

});
/**
 * 全局后置路由守卫
 */
router.afterEach(() => {
  NProgress.done();//进度条
});
