import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
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';
import React, { Component } from "react";
import AutoComplete from '../auto-complete';
import Input from '../input';
import Icon from '../icon';
import Alert from '../alert';
import Button from '../button';
import PagePoint from '../page-point/index';
var Option = AutoComplete.Option;
var Group = Input.Group;
var regKey = PagePoint.pagePointConfig.regKey;
/**
 * 搜索框。根据用户在input中输入的内容，调用外部的接口获取AutoComplete数据。
 * 并且把用户最终的选择通过callback传递到外部组件中。
 */

var SearchInput = function (_Component) {
    _inherits(SearchInput, _Component);

    function SearchInput(props) {
        _classCallCheck(this, SearchInput);

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

        _this.getInputText = function () {
            var label = _this.state.label;

            return label;
        };
        _this.handleInputBlur = function () {
            var onBlur = _this.props.onBlur;

            if (typeof onBlur === "function") {
                onBlur();
            }
        };
        _this.handleInputFocus = function () {
            var label = _this.state.label;
            var onFocus = _this.props.onFocus;

            if (typeof onFocus === "function") {
                onFocus();
            }
            _this.handleLabelChange(label);
        };
        _this.handleClickClearIcon = function () {
            _this.handleLabelChange("");
            _this.doRemoveImage();
            _this.input.focus();
        };
        _this.toggleTipText = function () {
            var tipText = _this.props.tipText;

            if (tipText && tipText.length > 0) {
                _this.setState(function (state) {
                    return {
                        showTips: !state.showTips
                    };
                });
            }
            // if (typeof e !== "undefined") {
            //   e.stopPropagation();
            // }
        };
        _this.handleLabelChange = function (v) {
            var value = v;
            if (typeof value === "undefined") {
                value = _this.searchLabel;
            }
            var searchPromise = _this.props.searchPromise;
            var showTips = _this.state.showTips;

            _this.searchLabel = value;
            if (typeof searchPromise === "function") {
                var fetchQuery = function fetchQuery() {
                    var searchLabel = _this.searchLabel;

                    if (value === searchLabel) {
                        searchPromise(value).then(function (res) {
                            var label = _this.searchLabel;
                            if (res.search === label) {
                                var dataSource = res.dataSource;

                                _this.setState({
                                    dataSource: dataSource,
                                    loading: false
                                });
                                if (showTips === true) {
                                    _this.toggleTipText();
                                }
                            }
                        });
                    }
                };
                if (typeof _this.timer !== "undefined") {
                    try {
                        clearTimeout(_this.timer);
                    } catch (e) {
                        // Something wrong here.
                    }
                }
                if (value && value.length > 0) {
                    _this.timer = setTimeout(fetchQuery, 500);
                } else {
                    fetchQuery();
                }
                _this.setState({
                    label: value,
                    loading: true
                });
            }
        };
        _this.doRemoveImage = function () {
            var onRemoveImage = _this.props.onRemoveImage;

            if (typeof onRemoveImage === "function") {
                onRemoveImage();
            }
        };
        _this.handleSelect = function (value) {
            var onSelect = _this.props.onSelect;

            if (typeof onSelect === "function") {
                var object = _this.dataProvider.get(value);
                onSelect(object);
            }
            _this.setState({
                label: value
            });
        };
        _this.handleConfirm = function () {
            var onSelect = _this.props.onSelect;

            if (typeof onSelect === "function") {
                var label = _this.state.label;

                onSelect(label);
            }
        };
        _this.defaultOptionRenderer = function (renderer) {
            return function (item) {
                var component = void 0;
                if (renderer) {
                    component = renderer(item);
                } else {
                    component = React.createElement(
                        Option,
                        { key: item.id, text: item.label },
                        item.label
                    );
                }
                _this.dataProvider.set(component.key, item);
                return component;
            };
        };
        _this.renderTipContent = function () {
            var showTips = _this.state.showTips;
            var tipText = _this.props.tipText;

            if (showTips && tipText && tipText.length > 0) {
                return React.createElement(Alert, { 'data-spm': 'Clstips', style: {
                        textAlign: "left",
                        position: "absolute",
                        zIndex: 2,
                        backgroundColor: "#fff"
                    }, className: 'extra-msg', afterClose: _this.toggleTipText, message: tipText, closable: true, type: 'info', showIcon: true });
            }
        };
        _this.dataProvider = new Map();
        _this.searchLabel = props.defaultValue;
        _this.state = {
            image: null,
            dataSource: [],
            label: props.defaultValue || "",
            loading: false,
            showTips: false
        };
        return _this;
    }

    _createClass(SearchInput, [{
        key: 'render',
        value: function render() {
            var _this2 = this,
                _inputProps;

            var _props = this.props,
                _props$prefix = _props.prefix,
                prefix = _props$prefix === undefined ? [] : _props$prefix,
                placeholder = _props.placeholder,
                optionRenderer = _props.optionRenderer,
                tipText = _props.tipText,
                enterButton = _props.enterButton,
                _props$disabled = _props.disabled,
                disabled = _props$disabled === undefined ? false : _props$disabled,
                size = _props.size,
                optionLabelProp = _props.optionLabelProp,
                _props$suffix = _props.suffix,
                suffix = _props$suffix === undefined ? [] : _props$suffix,
                buttonClassName = _props.buttonClassName,
                autocompleteClassName = _props.autocompleteClassName,
                dataRegId = _props[regKey];
            var _state = this.state,
                dataSource = _state.dataSource,
                label = _state.label,
                loading = _state.loading;

            var regKeyProp = _defineProperty({}, regKey, dataRegId);
            var image = this.state.image;

            if (image) {
                prefix.push(image);
            }
            var props = {
                value: label,
                onSelect: this.handleSelect,
                onSearch: this.handleLabelChange,
                onFocus: this.handleInputFocus,
                onBlur: this.handleInputBlur,
                optionLabelProp: optionLabelProp,
                className: autocompleteClassName,
                style: {
                    flex: 1
                },
                size: size,
                ref: function ref(input) {
                    _this2.input = input;
                },
                dataSource: []
            };
            this.dataProvider.clear();
            if (typeof optionRenderer === "function") {
                props.dataSource = dataSource.map(this.defaultOptionRenderer(optionRenderer));
            } else {
                props.dataSource = dataSource.map(this.defaultOptionRenderer(null));
            }
            var inputProps = (_inputProps = {
                placeholder: image ? "" : placeholder,
                value: disabled ? "" : label
            }, _defineProperty(_inputProps, regKey, dataRegId), _defineProperty(_inputProps, 'size', size), _defineProperty(_inputProps, 'suffix', suffix), _defineProperty(_inputProps, 'disabled', disabled), _defineProperty(_inputProps, 'onKeyDown', function onKeyDown(e) {
                var st = _this2.state;
                var lb = st.label;
                var img = st.image;
                if (img && lb.length < 1 && e.key === "Backspace") {
                    _this2.doRemoveImage();
                }
            }), _inputProps);
            if (label && label.length > 0 || image) {
                SearchInput.addSuffix(inputProps.suffix, React.createElement(Icon, { 'data-spm': 'Clear', key: 'extra-close', className: 'extra-icon show', onClick: this.handleClickClearIcon, type: 'close-circle', size: 'small' }));
            }
            if (loading || tipText) {
                SearchInput.addSuffix(inputProps.suffix, React.createElement(Icon, { key: 'extra-info', className: 'extra-icon', onClick: this.toggleTipText, type: loading ? "loading" : "exclamation-circle-o" }));
            }
            return React.createElement(
                'div',
                { 'data-spm': 'Xiala' },
                React.createElement(
                    Group,
                    { compact: true, size: 'large' },
                    prefix,
                    React.createElement(
                        AutoComplete,
                        props,
                        React.createElement(Input, inputProps)
                    ),
                    React.createElement(
                        Button,
                        _extends({ 'data-spm': 'Search', type: 'primary', size: size, className: buttonClassName, onClick: this.handleConfirm }, regKeyProp),
                        enterButton
                    )
                ),
                this.renderTipContent()
            );
        }
    }], [{
        key: 'addSuffix',
        value: function addSuffix(suffix, element) {
            if (!suffix.find(function (e) {
                return e.key === element.key;
            })) {
                suffix.push(element);
            }
        }
    }, {
        key: 'getDerivedStateFromProps',
        value: function getDerivedStateFromProps(props, state) {
            return _extends(_extends({}, state), { image: props.injectImage });
        }
    }]);

    return SearchInput;
}(Component);

export default SearchInput;