import React, { useEffect, useRef, useMemo, useState } from 'react';
import { Layout, Spin } from 'antd';
import { useLocation } from "react-router-dom";
import { useModel } from '@/store';
import { getItems } from '@/routes/menus';
import RequireLogin from './components/RequireLogin';
import SiderBar from './components/SiderBar';
import Header from './components/Header';
import Container from './components/Container';
import HtmlTitle from './components/HtmlTitle';
import useReady from './useReady';

import './style.less';

export default (props) => {
  const { theme } = useModel('system');
  const { user, setUser } = useModel('user');

  const allMenus = useMemo(() => getItems(), []);
  const [siderMenus, setSiderMenus] = useState([]);

  // 如果当前未登录, 跳转到登录页
  useReady({ user, setUser });

  const location = useLocation();

  const onSplitMenuChange = (key) => {
    const target = allMenus.filter(x => x.key === key)[0];
    if (target) {
      setSiderMenus(target.children || []);
    }
  }

  return (
    <Spin spinning={!user} size="large">
      <HtmlTitle />
      <RequireLogin>
        <Layout style={{ minHeight: '100vh' }}>
          <Header theme={theme} menus={allMenus} location={location} onMenuChange={onSplitMenuChange} />
          <Layout>
            <SiderBar theme={theme} menus={siderMenus} location={location} />
            <Container location={location} />
          </Layout>
        </Layout>
      </RequireLogin>
    </Spin>
  );
}
