import { lazy, Suspense } from 'react'
import { Navigate } from 'react-router-dom'
import { Spin } from 'antd'

/*** 实现路由懒加载* @param Comp 懒加载组件* @returns */
const lazyLoad = (Comp) => {
  return (
    <Suspense fallback={<Spin />}>
      <Comp />
    </Suspense>
  )
}

const Modules = import.meta.glob('../pages/**/*.jsx') // 在vite中必须这样动态引入所有组件地址
const lazyLoadModule = (moduleName) => {
  const Module = lazy(Modules[`../pages/${moduleName}.jsx`])

  return (
    <Suspense fallback={<Spin>Loading...</Spin>}>
      <Module></Module>
    </Suspense>
  )
}

const filterAsyncRouter = (menuData) => {
  let temp = []
  menuData.forEach((item) => {
    const route = {
      name: item.name,
      path: item.path,
      element: ''
    }
    route.element = lazyLoadModule(item.component) // 懒加载路由
    if (item.children) {
      route.children = filterAsyncRouter(item.children) // 如有有嵌套路由则递归加载
    }
    temp.push(route)
  })

  return temp
}

const authComponent = (Com) => {
  const token = localStorage.getItem('kiwi.token') || true
  return token ? lazyLoad(Com) : <Navigate to="/login" />
}

export { lazyLoad, lazyLoadModule, authComponent, filterAsyncRouter }
