'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _autoComplete = require('../auto-complete');

var _autoComplete2 = _interopRequireDefault(_autoComplete);

var _input = require('../input');

var _input2 = _interopRequireDefault(_input);

var _icon = require('../icon');

var _icon2 = _interopRequireDefault(_icon);

var _alert = require('../alert');

var _alert2 = _interopRequireDefault(_alert);

var _button = require('../button');

var _button2 = _interopRequireDefault(_button);

var _index = require('../page-point/index');

var _index2 = _interopRequireDefault(_index);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var Option = _autoComplete2['default'].Option;
var Group = _input2['default'].Group;
var regKey = _index2['default'].pagePointConfig.regKey;
/**
 * 搜索框。根据用户在input中输入的内容，调用外部的接口获取AutoComplete数据。
 * 并且把用户最终的选择通过callback传递到外部组件中。
 */

var SearchInput = function (_Component) {
    (0, _inherits3['default'])(SearchInput, _Component);

    function SearchInput(props) {
        (0, _classCallCheck3['default'])(this, SearchInput);

        var _this = (0, _possibleConstructorReturn3['default'])(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 = _react2['default'].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 _react2['default'].createElement(_alert2['default'], { '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;
    }

    (0, _createClass3['default'])(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 = (0, _defineProperty3['default'])({}, 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
            }, (0, _defineProperty3['default'])(_inputProps, regKey, dataRegId), (0, _defineProperty3['default'])(_inputProps, 'size', size), (0, _defineProperty3['default'])(_inputProps, 'suffix', suffix), (0, _defineProperty3['default'])(_inputProps, 'disabled', disabled), (0, _defineProperty3['default'])(_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, _react2['default'].createElement(_icon2['default'], { '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, _react2['default'].createElement(_icon2['default'], { key: 'extra-info', className: 'extra-icon', onClick: this.toggleTipText, type: loading ? "loading" : "exclamation-circle-o" }));
            }
            return _react2['default'].createElement(
                'div',
                { 'data-spm': 'Xiala' },
                _react2['default'].createElement(
                    Group,
                    { compact: true, size: 'large' },
                    prefix,
                    _react2['default'].createElement(
                        _autoComplete2['default'],
                        props,
                        _react2['default'].createElement(_input2['default'], inputProps)
                    ),
                    _react2['default'].createElement(
                        _button2['default'],
                        (0, _extends3['default'])({ '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 (0, _extends3['default'])((0, _extends3['default'])({}, state), { image: props.injectImage });
        }
    }]);
    return SearchInput;
}(_react.Component);

exports['default'] = SearchInput;
module.exports = exports['default'];