import React from 'react';
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from 'antd';
import useUserModel from '@/store/user';
import { getMenuItems } from '@/routes/menus';
import { getAuthedRoutes } from '@/routes/permissions';

const menuStyle = { height: '100%' };

export default (props) => {
  const { theme } = props;
  const navigate = useNavigate();
  const location = useLocation();
  const [user] = useUserModel(s => s.user);

  const [openKeys, setOpenKeys] = React.useState([]);

  // 用户改变, 菜单改变
  const items = React.useMemo(() => {
    return getMenuItems(getAuthedRoutes());
  }, [user]);

  const selectedKeys = [location.pathname];

  // 只执行一次, 不需要监控 selectedKeys
  React.useEffect(() => {
    const keys = selectedKeys.reduce((acc, item) => {
      const arr = item.split('/').reduce((acc2, it) => {
        const last = acc2[acc2.length - 1];
        const path = [last, it].join('/').replace(/\/\//g, '/');
        
        return acc2.concat(path);
      }, []);

      return acc.concat(arr);
    }, []);

    setOpenKeys(keys);
  }, []);

  const onClick = ({ key }) => {
    if (key.startsWith('http')) {
      const a = document.createElement('a');
      a.target = '_blank';
      a.href = key;
      a.click();
    } else {
      navigate(key);
    }
  }
  return (
    <Menu
      mode='inline'
      style={menuStyle}
      theme={theme}
      items={items}
      selectedKeys={selectedKeys}
      openKeys={openKeys}
      onClick={onClick}
      onOpenChange={setOpenKeys}
    />
  )
}
