import { LocalStorage, Notify } from 'quasar';
import { loginApi } from 'src/api/login/loginApi';
import { Router } from 'vue-router';

export const layouts = import.meta.glob('../../layouts/**/*.vue');
export const getLayouts = (layout: string) => {
  console.log(layout);
  return layouts['../../' + layout];
};
export const componets = import.meta.glob('../../pages/**/*.vue');
export const getComponent = (component: string) => {
  return componets['../../' + component];
};

//动态路由解析
export const routeConfig = (
  routerInfo: menuType,
  router: Router,
  fRouterName: string
) => {
  if (fRouterName) {
    router.addRoute(fRouterName, {
      path: routerInfo.path,
      name: routerInfo.name,
      redirect: routerInfo.redirect,
      meta: {
        title: routerInfo.menuName, // 导航 title
        icon: routerInfo.icon // [非必须] 导航 icon
      },
      component: getComponent(routerInfo.component),
      children: []
    });
  }
  if (routerInfo.children && routerInfo.children.length >= 1) {
    routerInfo.children.forEach((item) => {
      routeConfig(item, router, routerInfo.path);
    });
  } else {
    return;
  }
};

// 路由解析并添加
const menuAnalysis = (menuData: menuType, router: any) => {
  router.addRoute('index', {
    path: menuData.path,
    name: menuData.name,
    redirect: menuData.redirect,
    meta: {
      title: menuData.menuName, // 导航 title
      icon: menuData.icon // [非必须] 导航 icon
    },
    component: getLayouts(menuData.component)
  });
  if (!menuData.children) {
    return;
  }
  menuData.children.forEach((item: menuType) => {
    routeConfig(item, router, menuData.name);
  });
  LocalStorage.set('menuInfo', menuData);
};

export const getMenus = (router: Router) => {
  let menuData: any = {};
  //console.log(LocalStorage.remove('menuInfo'));
  //判断本地是否有路由数据，若无则从后台获取

  if (!LocalStorage.has('menuInfo')) {
    return loginApi.getMenus().then((res: any) => {
      if (!res) {
        Notify.create({
          message: '菜单获取失败',
          color: 'negative',
          icon: 'close'
        });
        return;
      } else {
        menuData = res;
        // console.log(menuData);
        menuAnalysis(menuData, router);
      }
    });
  } else {
    return new Promise(() => {
      menuData = LocalStorage.getItem('menuInfo');
      menuAnalysis(menuData, router);
    });
  }
};
