import {PureComponent} from 'react';
import {TreeSelect} from 'antd';

const {TreeNode} = TreeSelect;

class SelectOptionTree extends PureComponent {
    state = {
        value: undefined,
        treeData: this.props.treeData || []
    }

    constructor(props) {
        super(props);
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        if(undefined !== nextProps.value && nextProps.value !== this.props.value) {
            this.setState({value: nextProps.value});
        }
        if(undefined !== nextProps.treeData) {
            this.setState({treeData: nextProps.treeData});
        }
    }

    onSelect = (value) => {
        const {onChange} = this.props;

        if(onChange){
            onChange(value);
        }
    }

    onChangeValue = (value) => {
        const {onChange} = this.props;
        let values = '';

        if (undefined !== value) {
            values = value;
        }
        if(onChange){
            onChange(values);
        }
        this.setState({
            value: values
        })
    }

    renderTreeNodes = data =>
        Array.from(data).map(item => {
            const {type} = this.props;
            let val = item.value ? item.value : null;
            let title = `${item.title ? item.title : ''}[${val}]`;

            if (item.children?.length > 0) {
                item.disabled = type !== 'area';

                return (
                    <TreeNode title={title} key={val} value={val} disabled={item.disabled}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} title={title} key={val} value={val}/>;
        });

    render() {
        const { placeholder, disabled, selectWidth } = this.props;
        const { treeData, value } = this.state;

        return (
            <TreeSelect
                allowClear
                showSearch
                value={value}
                dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                style={{width: '100%'}}
                dropdownMatchSelectWidth={selectWidth ? selectWidth : 255}
                placeholder={placeholder ? placeholder : ''}
                disabled={disabled ? disabled : false}
                onSelect={this.onSelect}
                onChange={this.onChangeValue}
                treeLine
                treeNodeFilterProp="title"
            >
                {this.renderTreeNodes(treeData)}
            </TreeSelect>
        );
    }
}

export default SelectOptionTree;
