const modules = import.meta.glob('/src/pages/**/*.vue') // 匹配pages下所有vue文件，默认懒加载模式

const loadComponent = component => {
  return modules[`/src/pages${component}/index.vue`] // 进行动态导入
}

const changeMenu = list => {
  return list.map(item => ({
    ...item,
    component: loadComponent(item.component),
    redirect: item.children ? item.redirect : null,
    children:
      item.children && item.children.length ? changeMenu(item.children) : null
  }))
}
const keepAliveRoutes = ['projectStore']
const getRedirect = (obj) => {
  if (obj.name !== 'home' && obj.level === 1 && obj.children?.length) {
    if (obj.children[0]?.children?.filter(i => i.menuType === 'MENU')?.length) {
      return obj.path + '/' + obj.children[0].path + '/' + obj.children[0].children[0].path
    } else {
      return obj.path + '/' + obj.children[0].path
    }
  } else {
    return undefined
  }
}
export const generateRoute = menus => {
  // 动态添加路由
  return changeMenu(menus)
}

export const treeMap = obj => {
  const haveChildren = Array.isArray(obj.children) && obj.children.length
  return {
    path: obj.path,
    name: obj.name,
    component: obj.component,
    redirect: getRedirect(obj),
    meta: {
      topMenu: obj.topMenu,
      activeMenu: obj.activeMenu,
      title: obj.title,
      activeIcon: obj.icon,
      uIcon: 'un' + obj.icon,
      hidden: obj.hidden === 1,
      isShowTag: obj.isShowTag === 1,
      menuType: obj.menuType,
      keepAlive: keepAliveRoutes.includes(obj.name)
    },
    children: haveChildren ? obj.children.map(item => treeMap(item)) : null
  }
}
