import React, { Component, Suspense, lazy } from 'react';
import { useRoutes } from "react-router-dom";

const routes = [
  {
    path: '/login',
    auth: false,
    component: lazy(() => import('../pages/login'))
  },
  {
    path: '/',
    auth: false,
    component: lazy(() => import('../pages/home')),
    children: [
      {
        path: '/wjjr',
        auth: false,
        component: lazy(() => import('../pages/sjjr/wjjr'))
      },
      {
        path: '*',
        auth: false,
        component: lazy(() => import('../pages/404.js'))
      }
    ]
  },
  {
    path: '*',
    auth: false,
    component: lazy(() => import('../pages/404.js'))
  }
]

//根据路径获取路由
const checkAuth = (routers, path) => {
  for (const data of routers) {
    if (data.path == path) return data
    if (data.children) {
      const res = checkAuth(data.children, path)
      if (res) return res
    }
  }
  return null
}

const checkRouterAuth = (path) => {
  let auth = null
  auth = checkAuth(routes, path)
  return auth
}

// 路由处理方式
const generateRouter = (routers) => {
  return routers.map((item) => {
    if (item.children) {
      item.children = generateRouter(item.children)
    }
    item.element = <Suspense fallback={<div>loading...</div>}>
      <item.component />
    </Suspense>
    return item
  })
}

const Router = () => useRoutes(generateRouter(routes))

export { Router, checkRouterAuth }