import { useState, useEffect, Suspense } from 'react'
import { Layout, Flex } from 'antd'
import { Outlet, Link } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { setMenuRouter, setOperationPermissionsList } from '@/store/modules/user'

import Menu from './components/menu'
import Message from './components/message'
import User from './components/user'
import Logout from './components/logout'
import Breadcrumb from './components/breadcrumb'

import './index.less'
import logo from '@/assets/images/logo.png'
import { getMenuList, checkSSOLogin } from './request'
import { generateToAntdMenus } from '@/utils/breadCrumb'

const { Header, Content } = Layout

function generateMenus(items = [], maxLevel = 2, level = 1) {
  return items.map((item) => {
    const children = level < maxLevel && item.childs ? generateMenus(item.childs, maxLevel, level + 1) : null
    return { key: item.id + '', path: item.front_url, label: <Link to={item.front_url}>{item.name}</Link>, children }
  })
}

export default function AppLayout() {
  const dispatch = useDispatch()
  const [menuList, setMenuList] = useState([])

  const getSSOToken = async () => {
    const data = await checkSSOLogin()
    if (data && data.token) {
      localStorage.setItem('kiwi.token', data.token)
    }
  }
  // 获取菜单
  const getMenu = async () => {
    // 获取菜单内容
    const { data, operation_permissions_list } = await getMenuList()
    if (data && data.length) {
      const menus = generateToAntdMenus(data, 'name', 'front_url', 'childs', 1)
      setMenuList(generateMenus(data))
      dispatch(setMenuRouter(menus))
    }
    // 获取操作权限内容
    if (operation_permissions_list && operation_permissions_list.length) {
      dispatch(setOperationPermissionsList(operation_permissions_list))
    }
  }

  useEffect(() => {
    ;(async () => {
      await getSSOToken()
      await getMenu()
    })()
  }, [])

  return (
    <Layout className="layout-container">
      <div className="layout-sticky">
        <Header className="layout-header">
          <div className="header-logo">
            <Link to="/">
              <img src={logo} />
            </Link>
          </div>
          <Menu menuList={menuList}></Menu>
          {menuList.length ? (
            <Flex align="center" gap="small">
              <Message></Message>
              <User></User>
              <Logout></Logout>
            </Flex>
          ) : null}
        </Header>
        <Breadcrumb menuList={menuList}></Breadcrumb>
      </div>
      <Content className="layout-content">
        <Suspense>
          <Outlet />
        </Suspense>
      </Content>
    </Layout>
  )
}
