import React, { useState, useEffect } from 'react';
import { Layout, Spin } from 'antd';
import { Outlet, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setMenuRouter, setOperationPermissionsList } from '@/store/modules/user';

import UserInfo from './components/userinfo';
import UserMenu from './components/menu';
import BreadCrumbMenu from './components/breadMenu';

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

const { Header, Content, Footer } = Layout;

const LayoutComponent = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [menuList, setMenuList] = useState([]);
  const [menuRole, setMenuRole] = useState([]);
  const [isSSOToken, setIsSSOToken] = useState(false);

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

  useEffect(() => {
    (async () => {
      await getSSOToken();
      await getMenu();
    })();
  }, []);
  useEffect(() => {
    if (menuRole.length > 0 && location.pathname === '/') {
      setLoading(true);
      setTimeout(() => {
        if (menuRole.length) {
          navigate(menuRole[0].front_url);
        }
        setLoading(false);
      }, 1000);
    }
  }, [location.pathname, menuRole]);

  return (
    <Layout className='layout-container'>
      <Spin spinning={loading}>
        <Header className='layout-header'>
          <div className='header-logo'>
            <img src={logo} alt='logo' />
            <span></span>
          </div>
          <UserMenu menuList={menuList} />
          {
            menuList && menuList.length && (<UserInfo />)
          }
        </Header>
        <Content className='layout-content'>
          <div className='crumb'>
            <BreadCrumbMenu />
          </div>
          <div className='content-sandbox'>
            <div className='content-pro' style={{ padding: 20 }}>
              <Outlet aa={2} />
            </div>
          </div>
        </Content>
      </Spin>
    </Layout>
  );
};

export default LayoutComponent;
