import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var _jsxFileName = 'src/select/Select.jsx';
/**
 * Select.jsx
 *
 * @Author: jruif
 * @Date: 2018/1/21 上午10:12
 */

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TagsInput from './TagsInput';
import Icon from '../icon';
import DropdownMenu from '../dropdownMenu';
// import AutoComplete from '../autoComplete';
import Menu, { MenuItem } from '../menu';

/**
 * Select
 * */

var Select = function (_React$Component) {
    _inherits(Select, _React$Component);

    function Select(props, context) {
        _classCallCheck(this, Select);

        var _this = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props, context));

        _initialiseProps.call(_this);

        var options = props.options,
            defaultValue = props.defaultValue,
            children = props.children,
            multiple = props.multiple;

        options ? options.forEach(function (_ref, index) {
            var label = _ref.label,
                className = _ref.className,
                value = _ref.value,
                item = _objectWithoutProperties(_ref, ['label', 'className', 'value']);

            _this.valueToLabel[value] = label;
        }) : React.Children.forEach(children, function (child, index) {
            if (!React.isValidElement(child)) {
                return null;
            }
            _this.valueToLabel[child.props.value] = child.props.searchText || child.props.children;
        });

        var value = '';
        if (multiple && !Array.isArray(defaultValue)) {
            value = [defaultValue];
        } else {
            value = defaultValue;
        }
        _this.state = {
            value: value,
            width: 100,
            isOpen: false,
            search: props.multiple ? '' : _this.valueToLabel[props.defaultValue] || ''
        };
        _this.selectRootNode = null;
        return _this;
    }

    _createClass(Select, [{
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps(nextProps) {
            var _this2 = this;

            var _props = this.props,
                defaultValue = _props.defaultValue,
                children = _props.children,
                options = _props.options;

            if (children !== nextProps.children || options !== nextProps.options) {
                this.valueToLabel = {};
                nextProps.options ? nextProps.options.forEach(function (_ref2, index) {
                    var label = _ref2.label,
                        className = _ref2.className,
                        value = _ref2.value,
                        item = _objectWithoutProperties(_ref2, ['label', 'className', 'value']);

                    _this2.valueToLabel[value] = label;
                }) : React.Children.forEach(nextProps.children, function (child, index) {
                    if (!React.isValidElement(child)) {
                        return null;
                    }
                    _this2.valueToLabel[child.props.value] = child.props.searchText || child.props.children;
                });
                if (!nextProps.searchable && !nextProps.multiple) {
                    this.setState(function (state) {
                        return {
                            search: _this2.valueToLabel[state.value] || ''
                        };
                    });
                }
            }
            if (nextProps.defaultValue !== defaultValue) {
                var value = '';
                if (nextProps.multiple) {
                    if (!Array.isArray(nextProps.defaultValue)) {
                        value = [nextProps.defaultValue];
                    } else {
                        value = nextProps.defaultValue;
                    }
                    this.setState(function () {
                        return {
                            value: value,
                            search: ''
                        };
                    });
                } else {
                    value = nextProps.defaultValue;
                    this.setState({
                        value: value,
                        search: this.valueToLabel[value] || ''
                    });
                }
            }
        }
    }, {
        key: 'render',


        // handleOpen = () => {
        //     this.setState(state => ({
        //         isOpen: true,
        //     }));
        // };
        value: function render() {
            var _this3 = this,
                _classNames;

            var _props2 = this.props,
                prefixCls = _props2.prefixCls,
                className = _props2.className,
                children = _props2.children,
                readOnly = _props2.readOnly,
                defaultValue = _props2.defaultValue,
                placeholder = _props2.placeholder,
                filterable = _props2.filterable,
                style = _props2.style,
                disabled = _props2.disabled,
                propOptions = _props2.options,
                inputProps = _props2.inputProps,
                size = _props2.size,
                multiple = _props2.multiple,
                onChange = _props2.onChange,
                filter = _props2.filter,
                onSearch = _props2.onSearch,
                searchable = _props2.searchable,
                autoCalcWidth = _props2.autoCalcWidth,
                tagRender = _props2.tagRender,
                other = _objectWithoutProperties(_props2, ['prefixCls', 'className', 'children', 'readOnly', 'defaultValue', 'placeholder', 'filterable', 'style', 'disabled', 'options', 'inputProps', 'size', 'multiple', 'onChange', 'filter', 'onSearch', 'searchable', 'autoCalcWidth', 'tagRender']);

            var _state = this.state,
                width = _state.width,
                isOpen = _state.isOpen,
                value = _state.value,
                search = _state.search;

            var options = propOptions ? propOptions.map(function (_ref3, index) {
                var label = _ref3.label,
                    className = _ref3.className,
                    value = _ref3.value,
                    item = _objectWithoutProperties(_ref3, ['label', 'className', 'value']);

                return React.createElement(
                    MenuItem,
                    Object.assign({
                        value: value,
                        className: classNames(prefixCls + '-menu-item', className),
                        key: value || index
                    }, item, {
                        role: 'option', __source: {
                            fileName: _jsxFileName,
                            lineNumber: 291
                        },
                        __self: _this3
                    }),
                    label
                );
            }) : React.Children.map(children, function (child, index) {
                if (!React.isValidElement(child)) {
                    return null;
                }
                return React.cloneElement(child, {
                    key: child.props.value || index,
                    role: 'option'
                });
            });
            var filtered = searchable ? options.filter(function (option) {
                return filter(search, option.props.searchText || option.props.children, option.props.value);
            }) : options;
            var valueData = this.getTagData(options, value);
            return React.createElement(
                'div',
                { className: classNames(prefixCls, className), ref: this.selectRootNodeRef, __source: {
                        fileName: _jsxFileName,
                        lineNumber: 316
                    },
                    __self: this
                },
                React.createElement(
                    DropdownMenu,
                    {
                        anchorEl: React.createElement(TagsInput, {
                            'aria-haspopup': 'true',
                            role: 'button',
                            onTagDelete: this.tagFilter,
                            onChange: this.handleSearch,
                            searchText: search,
                            readOnly: !searchable || readOnly,
                            suffix: React.createElement(Icon, { type: 'down-arrow', className: prefixCls + '-icon', __source: {
                                    fileName: _jsxFileName,
                                    lineNumber: 326
                                },
                                __self: this
                            })
                            // onClick={this.handleOpen}
                            , tags: multiple ? value.filter(function (tag) {
                                return _this3.getTagData(options, tag);
                            }).map(function (tag) {
                                return _this3.getTagData(options, tag);
                            }) : [],
                            placeholder: valueData ? valueData.label : placeholder,
                            inputProps: inputProps,
                            className: classNames(prefixCls + '-input', (_classNames = {}, _defineProperty(_classNames, prefixCls + '-open', isOpen && !disabled), _defineProperty(_classNames, prefixCls + '-disabled', disabled), _defineProperty(_classNames, prefixCls + '-multiple', multiple), _classNames)),
                            tagRender: tagRender,
                            style: style,
                            disabled: disabled,
                            searchable: searchable,
                            size: size === 'base' ? 'medium' : size,
                            __source: {
                                fileName: _jsxFileName,
                                lineNumber: 319
                            },
                            __self: this
                        }),
                        trigger: multiple && searchable ? 'focus' : 'click',
                        disabled: disabled,
                        onOpenChange: this.getSelectWidth,
                        defaultIsOpen: isOpen,
                        noClose: multiple, __source: {
                            fileName: _jsxFileName,
                            lineNumber: 317
                        },
                        __self: this
                    },
                    React.createElement(
                        Menu,
                        Object.assign({}, other, {
                            selectable: true,
                            multiple: multiple,
                            onChange: this.handleChange,
                            className: classNames(prefixCls + '-menu'),
                            value: value,
                            role: 'listbox',
                            size: size === 'base' ? 'medium' : size,
                            style: autoCalcWidth ? { width: width } : {}, __source: {
                                fileName: _jsxFileName,
                                lineNumber: 354
                            },
                            __self: this
                        }),
                        filtered
                    )
                )
            );
        }
    }]);

    return Select;
}(React.Component);

Select.displayName = 'NeatUI.Select';
Select.propTypes = {
    /**
     * 占位描述字段
     * */
    placeholder: PropTypes.string,
    /**
     * 预设值
     * */
    defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool, PropTypes.array]),
    /**
     * Select的选项
     * */
    options: PropTypes.array,
    /**
     * 是否禁止
     * */
    disabled: PropTypes.bool,
    /**
     * 是否过滤
     * */
    filterable: PropTypes.bool,
    /**
     * Select的ref函数，获取Select的dom元素
     * */
    selectRef: PropTypes.func,
    /**
     * 自定义样式
     * */
    style: PropTypes.object,
    /**
     * Select选项
     * */
    inputProps: PropTypes.object,
    /**
     * 是否多选
     * */
    multiple: PropTypes.bool,
    /**
     * 是否可搜索
     * */
    searchable: PropTypes.bool,
    /**
     * 是否根据输入项进行筛选
     * */
    filter: PropTypes.func,
    /**
     * 文本框值变化时回调
     * */
    onChange: PropTypes.func,
    /**
     * 选择框大小，默认medium，base同medium
     * */
    size: PropTypes.oneOf(['large', 'medium', 'small', 'base']), // base === medium
    /**
     * 是否自动计算宽度
     * */
    autoCalcWidth: PropTypes.bool,
    /**
     * 在change返回值中包含label
     * */
    hasLabelInChange: PropTypes.bool,
    /**
     * 多选标签渲染方法
     */
    tagRender: PropTypes.bool
};
Select.defaultProps = {
    multiple: false,
    searchable: false,
    prefixCls: 'ne-select',
    filterable: false,
    disabled: false,
    size: 'medium',
    autoCalcWidth: true,
    filter: function filter(search, value) {
        if (search === '') {
            return true;
        } else {
            return (value + '').includes(search);
        }
    }
};

var _initialiseProps = function _initialiseProps() {
    var _this4 = this;

    this.valueToLabel = {};

    this.getSelectWidth = function (isOpen) {
        var _props3 = _this4.props,
            disabled = _props3.disabled,
            searchable = _props3.searchable,
            multiple = _props3.multiple,
            options = _props3.options;

        if (!isOpen || disabled) {
            _this4.setState({
                isOpen: false
            });
            if (searchable && !multiple) {
                setTimeout(function () {
                    _this4.setState(function (state) {
                        return {
                            search: _this4.getTagData(options, state.value).label
                        };
                    });
                }, 200);
            } else if (searchable) {
                setTimeout(function () {
                    _this4.setState(function (state) {
                        return {
                            search: ''
                        };
                    });
                }, 200);
            }
            return;
        }
        var newWidth = void 0;
        if (!_this4.selectRootNode) {
            newWidth = 100;
        } else {
            var _selectRootNode$getBo = _this4.selectRootNode.getBoundingClientRect(),
                width = _selectRootNode$getBo.width;

            newWidth = width;
        }
        if (searchable && !multiple) {
            _this4.setState(function (state) {
                return {
                    search: ''
                };
            });
        }
        _this4.setState(function () {
            return {
                width: newWidth,
                isOpen: true
            };
        });
    };

    this.handleChange = function (e, value, itemValue) {
        var _props4 = _this4.props,
            onChange = _props4.onChange,
            multiple = _props4.multiple,
            hasLabelInChange = _props4.hasLabelInChange,
            options = _props4.options;

        _this4.setState(function (state) {
            return {
                search: !multiple ? _this4.valueToLabel[value] : '',
                value: value
            };
        });
        onChange && onChange(hasLabelInChange ? options.find(function (item) {
            return item.value === value;
        }) : value, itemValue);
    };

    this.handleSearch = function (e, search) {
        _this4.setState({
            search: search
        });
        var onSearch = _this4.props.onSearch;

        onSearch && onSearch(e, search);
    };

    this.getTagData = function (options, value) {
        var target = _this4.valueToLabel[value];
        return target ? { label: target, value: value } : '';
    };

    this.tagFilter = function (tag) {
        _this4.setState(function (state) {
            return {
                value: state.value.filter(function (v) {
                    return v !== tag;
                })
            };
        });
        _this4.props.onChange && _this4.props.onChange(_this4.state.value.filter(function (v) {
            return v !== tag;
        }), tag);
    };

    this.selectRootNodeRef = function (el) {
        var selectRef = _this4.props.selectRef;

        _this4.selectRootNode = el;
        selectRef && selectRef(el);
    };
};

export default Select;