/** @format */

import * as React from 'react';
import {decodeBase64} from '../utils/base64';
import {useHistory} from 'react-router-dom';
import {Tabs} from 'antd';
import KeepAlive, {withAliveScope, useAliveController} from 'react-activation';

const {TabPane} = Tabs;
interface Iprops {
    complete: {[key: string]: string};
}
interface panesProps {
    path: string;
    search: string;
}
interface Istate {
    panes: panesProps[];
    activeKey: string;
}

const PathHistory: React.FC<Iprops> = props => {
    const history = useHistory();
    const location = history.location;
    const currentUrl = location.pathname;
    const search = location.search;
    const {complete} = props;
    const {drop, dropScope, clear, getCachingNodes} = useAliveController();

    const [state, setState] = React.useState<Istate>(() => {
        return {
            panes: [],
            activeKey: '',
        };
    });
    React.useEffect(() => {
        if (complete.hasOwnProperty(currentUrl)) {
            if (!state.panes.some(element => element.path + element.search === currentUrl + search)) {
                setState({
                    panes: state.panes.concat({
                        path: currentUrl,
                        search: search,
                    }),
                    activeKey: currentUrl + search,
                });
            } else {
                setState(preState => ({...preState, activeKey: currentUrl + search}));
            }
        }
    }, [currentUrl, JSON.stringify(complete)]);
    const onEdit = (targetKey: string | React.MouseEvent<HTMLElement>, action: 'add' | 'remove') => {
        if (action === 'remove') {
            remove(targetKey);
        }
    };
    //移除
    const remove = (targetKey: string | React.MouseEvent<HTMLElement>) => {
        let {activeKey, panes} = state;
        const allPanes = panes.filter(element => element.path + element.search !== targetKey);
        if (activeKey === currentUrl + search) {
            const removeIndex = panes.findIndex(element => {
                return element.path + element.search === targetKey;
            });
            const left = panes.slice(removeIndex + 1);
            if (left.length) {
                activeKey = panes[removeIndex + 1].path + panes[removeIndex + 1].search;
            } else {
                activeKey = panes[removeIndex - 1].path + panes[removeIndex - 1].search;
            }
        }
        setState(preState => ({...preState, panes: allPanes}));
        setTimeout(() => {
            dropScope(targetKey as string);
        }, 100);
        if (activeKey !== currentUrl + search) {
            handleChange(activeKey);
        }
    };
    //切换当前选中项
    const handleChange = (activeKey: string) => {
        setState(preState => ({...preState, activeKey}));
        history.push(activeKey);
    };
    return (
        <Tabs
            style={{backgroundColor: '#eee'}}
            hideAdd
            type='editable-card'
            activeKey={state.activeKey}
            onEdit={onEdit}
            onChange={handleChange}
        >
            {state.panes.map((element: panesProps) => {
                const name = decodeURIComponent(
                    new URLSearchParams(decodeBase64(element.search.slice(1))).get('name') || '',
                );
                const message = name ? `(${name})` : '';
                return (
                    <TabPane
                        closable={state.panes.length !== 1}
                        key={element.path + element.search}
                        tab={`${complete[element.path]}${message}`}
                    />
                );
            })}
        </Tabs>
    );
};
export default React.memo(PathHistory);
