import React from 'react';
import { Select } from 'antd';
///下拉框的值带描述{id:'',desc:''}
class NewSelect extends React.Component {
    constructor(props) {
        super(props);
        const value = props.value || {};
        this.state = {
            id: value.id || '',
            desc: value.desc || ''
        }
    }
    static getDerivedStateFromProps(nextProps) {
        // Should be a controlled component.
        if ('value' in nextProps) {
            if (nextProps.value) {
                if (nextProps.value.id !== "" && !nextProps.value.desc) {
                    nextProps.children.find((value, index) => {
                        value.props.value === nextProps.value.id ? nextProps.value.desc = value.props.children : '';
                    });
                }
                return { ...nextProps.value };
            } else {
                return { id: '', desc: '' };
            }
        }
        return null;
    }
    onChange = (value, option) => {
        const obj = { id: value, desc: option.props.children }
        if (this.props.onSelectChange){
            this.props.onSelectChange(obj, option);
        }
        this.triggerChange(obj);
    }
    triggerChange = (changedValue) => {
        // Should provide an event to pass value to Form.
        const onChange = this.props.onChange;
        if (onChange) {
            onChange(Object.assign({}, this.state, changedValue));
        }
    }
    render() {
        const props = this.props;
        let newProps = {}
        for (let key in props) {
            if (key != 'value' && key != 'onChange') {
                newProps[key] = props[key];
            }
        }
        return (
            <Select value={this.state.id} onChange={this.onChange} {...newProps}>{this.props.children}</Select>
        );
    }
}
export default NewSelect;