import React, { PureComponent } from 'react';
import RCTreeSelct, { SHOW_ALL, SHOW_PARENT, SHOW_CHILD } from 'rc-tree-select';
import PropTypes from 'prop-types';
import './tree.less';
import './select.less';
import './TreeSelect.scss';

const CHECKEDSTRATEGY = {
    all: SHOW_ALL,
    parent: SHOW_PARENT,
    child: SHOW_CHILD
};

class TreeSelect extends PureComponent {
    static propTypes = {
        value: PropTypes.arrayOf.isRequired,
        options: PropTypes.arrayOf.isRequired,
        onChange: PropTypes.func.isRequired,
        multiple: PropTypes.bool,
        showCheckedStrategy: PropTypes.string
    }

    static defaultProps = {
        multiple: false,
        showCheckedStrategy: "all"
    }
    
    constructor(props) {
        super(props);
        this.state = {};
    }

    handleChange = (value) => {
        const { onChange } = this.props;
        onChange(value);
    }

    renderSwitcherIcon = (nodeProps) => {
        const { isLeaf, loading, expanded } = nodeProps;
        if (loading) {
            return <i className="treeicon iconfont icon-loading" />
        }
        if (isLeaf) {
            return null;
        }
        return <i className={ `treeicon iconfont icon-caret-${expanded ? "down" : "right"}` } style={{ color: "#999"}}/>
    };

    render() {
        const { options, value, multiple, showCheckedStrategy } = this.props;
        if(options.length === 0) return null;
        return <RCTreeSelct 
            className="add-tree-select"
            prefixCls="neatui"
            icon={ false }
            showTreeIcon={ false }
            showCheckedStrategy={ CHECKEDSTRATEGY[showCheckedStrategy] }
            multiple={ multiple }
            allowClear
            treeData={ options || [] } 
            switcherIcon={(nodeProps) =>
                this.renderSwitcherIcon(nodeProps)
            }
            value={ value }
            onChange={ this.handleChange }
            treeCheckable={ multiple ? <span className="neatui-tree-checkbox-inner"></span> : false }
            inputIcon={ false }
            removeIcon={ <i className="treeicon iconfont icon-remove" />}
            clearIcon={ <i className="treeicon iconfont icon-remove" />}
            dropdownClassName="add-tree-select-dropdown"
        />
    }
}

export default TreeSelect;