import React, { forwardRef, useState, useImperativeHandle } from 'react';
import { Drawer } from 'antd';
import { history } from 'umi';
import _ from 'lodash';
import { MenuDataItem } from '../../typings';
import BaseMenu from '@ant-design/pro-layout/lib/components/SiderMenu/BaseMenu';
import MenuCounter from '@ant-design/pro-layout/lib/components/SiderMenu/Counter';
import styles from './index.less';
import { HTML_ID_LAYOUT_CONTENT } from '@/constant/ID';

declare type ExpandMenuProps = {
  menuData: MenuDataItem[];
  selectMenuKey: string[];
  onMenuSelect: Function;
};
export const MenuExpander: React.FC<ExpandMenuProps> = forwardRef(
  ({ menuData, selectMenuKey, onMenuSelect }, ref) => {
    const [visible, setVisible] = useState<boolean>(false);

    useImperativeHandle(ref, () => ({
      toggle() {
        setVisible((visible) => !visible);
      },
    }));

    return (
      <Drawer
        title="全部导航"
        visible={visible}
        maskClosable
        maskStyle={{ background: 'transparent' }}
        onClose={() => setVisible(false)}
        width={692}
        placement="left"
        style={{ position: 'absolute', left: 1, zIndex: 777 }}
        //@ts-ignore
        getContainer={() => document.getElementById(HTML_ID_LAYOUT_CONTENT)}
      >
        {visible && (
          <Menus
            menuData={menuData}
            selectMenuKey={selectMenuKey}
            onMenuSelect={onMenuSelect}
            onClose={() => setVisible(false)}
          />
        )}
      </Drawer>
    );
  },
);

declare type MenusProps = {
  menuData: MenuDataItem[];
  selectMenuKey: string[];
  onMenuSelect: Function;
  onClose: Function;
};
const Menus: React.FC<MenusProps> = ({
  menuData,
  selectMenuKey,
  onMenuSelect,
  onClose,
}) => {
  return (
    <MenuCounter.Provider>
      <div className={styles.expandMenu}>
        {_.map(menuData, (menu: MenuDataItem) => {
          return (
            <div className={styles.menuItem} key={menu.key}>
              <BaseMenu
                matchMenuKeys={[]}
                openKeys={[menu.key || '']}
                selectedKeys={selectMenuKey}
                menuData={[menu]}
                expandIcon={null}
                mode="inline"
                collapsed={false}
                menuItemRender={(item, dom) => (
                  <a
                    onClick={() => {
                      history.push(item.path || '/manage');
                      onClose();
                    }}
                  >
                    {dom}
                  </a>
                )}
                menuProps={{
                  mode: 'inline',
                  expandIcon: () => null,
                  //@ts-ignore
                  onSelect: onMenuSelect,
                }}
              />
            </div>
          );
        })}
      </div>
    </MenuCounter.Provider>
  );
};
