/** @format */
import * as React from 'react';
import {Menu} from 'antd';
import {ClickParam} from 'antd/es/menu';
import {useHistory, Link} from 'react-router-dom';
import useAccess from '../service/access';
import {routeProps} from '../router/permission';
const {SubMenu} = Menu;

const createMenuItem = (routes: any[], prefixPath = '') => {
    return routes.map((element: routeProps) => {
        if (!element.child.length) {
            return (
                <Menu.Item
                    key={prefixPath + element.path}
                    style={{display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}
                >
                    {element.Icon}
                    <Link to={prefixPath + element.path} onClick={event => event.preventDefault()}>
                        {element.name}
                    </Link>
                </Menu.Item>
            );
        }
        return (
            <SubMenu
                key={prefixPath + element.path}
                title={
                    <span>
                        {element.Icon}
                        <span>{element.name}</span>
                    </span>
                }
            >
                {createMenuItem(element.child, prefixPath + element.path)}
            </SubMenu>
        );
    });
};

const Slider: React.FunctionComponent<{collapsed?: boolean}> = props => {
    const history = useHistory();
    const [state, setState] = React.useState(() => {
        const currentPath = history.location.pathname;
        const secondPath = currentPath.split('/home')[1];
        const curretnPahtIndex = secondPath.indexOf('/', 1);
        const isThird = curretnPahtIndex !== -1;
        const openKeys = isThird ? ['/home' + secondPath.slice(0, curretnPahtIndex)] : [];
        const selectedKeys = isThird ? [history.location.pathname] : [currentPath];
        return {
            openKeys,
            selectedKeys,
        };
    });

    const [access] = useAccess();
    const handleToHref = (MenuItem: ClickParam) => {
        const hrefPathName = MenuItem.keyPath[0];
        if (history.location.pathname !== hrefPathName) {
            history.push(hrefPathName);
        }
    };
    // const onOpenChange = (openKeys: string[]) => {
    //     setState(preState => ({...preState, openKeys: openKeys.slice(openKeys.length - 1)}));
    // };
    return (
        <Menu
            mode='inline'
            theme='dark'
            defaultOpenKeys={state.openKeys}
            // onOpenChange={onOpenChange}
            defaultSelectedKeys={state.selectedKeys}
            onClick={handleToHref}
        >
            {createMenuItem(access.data, '/home')}
        </Menu>
    );
};
export default Slider;
