import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
  Menu,
  RouteRecordStringComponent,
} from '@vben/types'

import { generateAccessible } from '@vben/access'
import { useUserStore } from '@vben/stores'

import { BasicLayout, IFrameView } from '#/layouts'

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue')

const getRoutes = (menus: Menu[]) => {
  if (!menus) return []
  for (const menu of menus) {
    if (menu.path?.length) continue
    // const path = menu.children[0]?.path as string
    // const secondSlashIndex = path.indexOf('/', 1)
    menu.path = menu.name
    // console.log(menu)
  }
  return _getRoutes(menus)
}

const _getRoutes = (menus: Menu[]) => {
  if (menus?.length === 0) return []
  const routes: RouteRecordStringComponent[] = []
  for (const menu of menus) {
    const route = {
      name: menu.name,
      meta: {
        title: menu.name,
        icon: menu.icon,
      },
      path: menu.path,
      component: menu.componentPath,
      children: getRoutes(menu.children),
    } as RouteRecordStringComponent
    routes.push(route)
  }
  return routes
}

const generateAccess = async (options: GenerateMenuAndRoutesOptions) => {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue')
  const { userInfo } = storeToRefs(useUserStore())

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  }
  // preferences.app.accessMode
  return await generateAccessible('mixed', {
    ...options,
    fetchMenuListAsync: async () => {
      return getRoutes(userInfo.value.menus)
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  })
}

export { generateAccess }
