/**
 * 侧边栏组件
 * User: bjyangxiuwu
 * Date: 2017/07/05
 * Time: 16:23
 */
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { Menu } from 'antd';
import { parseAuthSysData, isArray, getSearchParams, parseData2Url, setDefaultValue } from 'UTIL/util';
import './sidebar.scss';
import xhr from 'SERVICE/xhr';
import projectConfig from 'CONFIG/projectConfig.json';
import BaseComponent from '../../common/BaseComponent';

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

const { SubMenu, Item } = Menu;
const MenuItem = Item;

class Sidebar extends BaseComponent {
    static propTypes = {
        className: PropTypes.string
    };

    constructor(props) {
        super(props);
        this.env = localHost.indexOf(window.location.hostname) > -1 ? 'local.' : '';
        this.rootSubmenuKeys = this.props.routePaths.map(item => item.path);
        this.state = {
            menuCollapsed: false,
            currPath: this.getCurrPath(),
            routePaths: this.props.routePaths,
            openKeys: []
        };
    }

    componentWillMount() {
        if(!projectConfig.noAuth && this.env !== 'local.') this.getUserAuth();
        this.props.history.listen((location) => {
            this.setState({
                currPath: location.pathname
            })
        });
    }

    componentDidMount() {
        this.setState({
            openKeys: this.getDefaultOpenKeys(this.getCurrPath())
        })
    }

    getCurrPath = () => {
        if (projectConfig.router === "BrowserRouter") {
            return window.location.pathname || '/';
        }
        return this.props.history.location.pathname || '/';
    }

    changeRoute = (auth, routeParam, gloArr) => {
        const route = routeParam;
        for (let i = 0; i < route.length; i += 1) {
            const arr = [];
            if (route[i] && route[i].routes) {
                this.changeRoute(auth, route[i].routes, arr);
                route[i].routes = arr;
            }
            if ((route[i] && route[i].auth && auth.indexOf(route[i].auth) > -1) || route[i].passAuth) {
                if ((route[i].routes && route[i].routes.length > 0) || !route[i].routes) gloArr.push(route[i]);
            }
        }
    }

    getUserAuth = () => {
        const { url, method, isNeedLocationSearch, urlParams } = projectConfig[`${this.env}ajax`].auth;
        const allSearch = getSearchParams();
        const searchParams = {};
        if (isNeedLocationSearch && isArray(isNeedLocationSearch)) {
            for (let i = 0; i < isNeedLocationSearch.length; i += 1) {
                const key = isNeedLocationSearch[i];
                searchParams[key] = setDefaultValue(allSearch[key]);
            }
        }
        if (url && !projectConfig.noAuth && this.env !== 'local.') {
            xhr({
                url: parseData2Url({ ...searchParams }, url, '', urlParams).url,
                method: method || 'get',
                type: 'json'
            }).then((rs) => {
                if (rs[projectConfig.codeKey] === projectConfig.code || (projectConfig.isAuthSys && rs[projectConfig.codeKey] === 200)) {
                    const authRoutePaths = [];
                    const { routePaths } = this.state;
                    if (rs.data) {
                        let userAuth = rs.data.auth || [];
                        if (projectConfig.isAuthSys) {
                            userAuth = parseAuthSysData(rs.data);
                        }
                        this.changeRoute(userAuth, routePaths, authRoutePaths);
                        this.setState({
                            routePaths: authRoutePaths
                        });
                    }
                }
            });
        }
    };

    onChangeRoute = router => {
        this.props.history.push(router.item.props.value);
    };

    collapsed = () => {
        const { menuCollapsed } = this.state;
        this.setState({ menuCollapsed: !menuCollapsed });
    };

    handleKeyDown = () => { };

    getDefaultOpenKeys = (currPath) => {
        const mine = this;
        const { routePaths } = mine.state;
        for (let a = 0; a < routePaths.length; a += 1) {
            const levelOne = routePaths[a];
            for (let b = 0; levelOne.routes && b < levelOne.routes.length; b += 1) {
                const levelTwo = levelOne.routes[b];
                if (levelTwo.path === currPath) {
                    return [levelOne.path];
                }
                for (let c = 0; levelTwo.routes && c < levelTwo.routes.length; c += 1) {
                    const levelThree = levelTwo.routes[c];
                    if (levelThree.path === currPath) {
                        return [levelOne.path, levelTwo.path];
                    }
                }
            }
        }
        return [];
    };

    onOpenChange = openKeys => {
        const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1 || (projectConfig.sidebar && projectConfig.sidebar.multiple)) {
            this.setState({ openKeys });
        } else {
            this.setState({
                openKeys: latestOpenKey ? [latestOpenKey] : [],
            });
        }
    };

    render() {
        const { className } = this.props;
        const { menuCollapsed, routePaths, currPath, openKeys } = this.state;
        return (
            <div
                className={classNames(className, 'sidebar', {
                    'sidebar-collapsed': menuCollapsed
                })}>
                <div className="menu-index-logo">
                    {projectConfig.logo ? <img className='logo-p' src={require('../../../assets/img/common/logo.png')} alt="logo" /> : ''}
                    <h1>{!menuCollapsed ? projectConfig.name : (projectConfig.name).substr(0, 2)}</h1>
                </div>
                <Menu
                    mode="inline"
                    theme="dark"
                    selectedKeys={[currPath]}
                    openKeys={openKeys}
                    inlineCollapsed={menuCollapsed}
                    onOpenChange={this.onOpenChange}
                    onClick={this.onChangeRoute}
                    className="sidebar-menu">
                    {
                        routePaths.filter(item => item.auth !== 'admin2root').map(
                            item => {
                                if (item.routes) {
                                    if (isArray(item.routes) && item.routes.length > 0) {
                                        return (
                                            <SubMenu
                                                title={<span>
                                                    {item.icon ? <img className="sidebar-icon-img" src={require(`./icons/${item.icon}.svg`)} alt={item.icon} /> : ''}
                                                    <span className={item.icon ? 'sidebar-icon-title' : ''}>{!menuCollapsed ? item.title : item.title.substr(0, 2)}</span>
                                                </span>}
                                                key={`${item.path}`}>
                                                {
                                                    item.routes.map(
                                                        sub => {
                                                            if (sub.routes && isArray(sub.routes) && sub.routes.length > 0) {
                                                                return (
                                                                    <SubMenu
                                                                        title={sub.title}
                                                                        key={`${sub.path}`}>
                                                                        {sub.routes.map(
                                                                            eSub => {
                                                                                    if (!eSub.hideOnSidebar) {
                                                                                        return (
                                                                                            <MenuItem
                                                                                                value={eSub.path}
                                                                                                key={`${eSub.path}`}>
                                                                                                {eSub.title}
                                                                                            </MenuItem>
                                                                                        );
                                                                                    }
                                                                                    return this.env === 'local.' ? (
                                                                                            <MenuItem
                                                                                                value={eSub.path}
                                                                                                key={`${eSub.path}`}>
                                                                                                {`(已隐藏)${eSub.title}`}
                                                                                            </MenuItem>
                                                                                        ) : null
                                                                                }
                                                                        )}
                                                                    </SubMenu>
                                                                )
                                                            }
                                                            if (!sub.hideOnSidebar) {
                                                                return (
                                                                    <MenuItem
                                                                        value={sub.path}
                                                                        key={`${sub.path}`}>
                                                                        {sub.title}
                                                                    </MenuItem>
                                                                );
                                                            }
                                                            return this.env === 'local.' ? (
                                                                    <MenuItem
                                                                        value={sub.path}
                                                                        key={`${sub.path}`}>
                                                                        {`(已隐藏)${sub.title}`}
                                                                    </MenuItem>
                                                                ) : null;
                                                        }
                                                    )
                                                }
                                            </SubMenu>
                                        );
                                    }
                                    return this.env === 'local.' ? (<SubMenu
                                        title={<span>(已隐藏)
                                            {item.icon ? <img className="sidebar-icon-img" src={require(`./icons/${item.icon}.svg`)} alt={item.icon} /> : ''}
                                            <span className={item.icon ? 'sidebar-icon-title' : ''}>{!menuCollapsed ? item.title : item.title.substr(0, 2)}</span>
                                        </span>}
                                        key={`${item.path}`}>
                                        </SubMenu>) : null;
                                }
                                
                                if (!item.hideOnSidebar) {
                                    return (
                                        <MenuItem value={item.path} key={item.path}>
                                            {item.title}
                                        </MenuItem>
                                    );
                                }
                                return this.env === 'local.' ? (
                                        <MenuItem value={item.path} key={item.path}>
                                            {`(已隐藏)${item.title}`}
                                        </MenuItem>
                                    ) : null;
                            }
                        )}
                </Menu>
                {
                    projectConfig.sidebar && projectConfig.sidebar.nocollapse ? '' : <span style={{ outlineColor: 'rgba(0, 0, 0, 0)' }} role="button" tabIndex="0" className="close" onClick={this.collapsed} onKeyDown={this.handleKeyDown}>
                        <img style={{ height: '35px' }} className='item-manage' src={require('./item-manage.svg')} alt="item-manage" />
                    </span>
                }
            </div>
        );
    }
}

export default Sidebar;
