"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SearchBox = void 0;
var tslib_1 = require("tslib");
var react_1 = (0, tslib_1.__importDefault)(require("react"));
var moment_1 = (0, tslib_1.__importDefault)(require("moment"));
var lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
var debounce_1 = (0, tslib_1.__importDefault)(require("lodash/debounce"));
var isInteger_1 = (0, tslib_1.__importDefault)(require("lodash/isInteger"));
var theme_1 = require("../theme");
var icons_1 = require("./icons");
var uncontrollable_1 = require("uncontrollable");
var helper_1 = require("../utils/helper");
var locale_1 = require("../locale");
var historyDefaultOptions = {
    enable: false,
    key: 'amis:search_history',
    limit: 5,
    dropdownClassName: ''
};
var SearchBox = /** @class */ (function (_super) {
    (0, tslib_1.__extends)(SearchBox, _super);
    function SearchBox() {
        var _a;
        var _this = _super.apply(this, arguments) || this;
        _this.inputRef = react_1.default.createRef();
        _this.state = {
            isHistoryOpened: false,
            isFocused: false,
            inputValue: (_a = _this.props.value) !== null && _a !== void 0 ? _a : '',
            historyRecords: _this.getHistoryRecords()
        };
        _this.lazyEmitSearch = (0, debounce_1.default)(function () {
            var _a;
            var onSearch = _this.props.onSearch;
            onSearch === null || onSearch === void 0 ? void 0 : onSearch((_a = _this.state.inputValue) !== null && _a !== void 0 ? _a : '');
        }, 250, {
            leading: false,
            trailing: true
        });
        return _this;
    }
    SearchBox.prototype.componentDidUpdate = function (prevProps) {
        var _a;
        if (prevProps.value !== this.props.value) {
            this.setState({ inputValue: (_a = this.props.value) !== null && _a !== void 0 ? _a : '' });
        }
    };
    SearchBox.prototype.componentWillUnmount = function () {
        this.lazyEmitSearch.cancel();
    };
    SearchBox.prototype.handleActive = function () {
        var _a;
        var onActiveChange = this.props.onActiveChange;
        onActiveChange === null || onActiveChange === void 0 ? void 0 : onActiveChange(true);
        (_a = this.inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    };
    SearchBox.prototype.handleCancel = function () {
        var _a = this.props, onActiveChange = _a.onActiveChange, onCancel = _a.onCancel, onChange = _a.onChange;
        onActiveChange === null || onActiveChange === void 0 ? void 0 : onActiveChange(false);
        onCancel === null || onCancel === void 0 ? void 0 : onCancel();
        this.setState({ inputValue: '' }, function () { return onChange === null || onChange === void 0 ? void 0 : onChange(''); });
    };
    SearchBox.prototype.handleChange = function (e) {
        var _this = this;
        var _a = this.props, searchImediately = _a.searchImediately, onChange = _a.onChange;
        var inputValue = e.currentTarget.value;
        this.setState({ inputValue: inputValue }, function () {
            onChange === null || onChange === void 0 ? void 0 : onChange(inputValue);
            searchImediately && _this.lazyEmitSearch();
        });
    };
    SearchBox.prototype.handleSearch = function () {
        var onSearch = this.props.onSearch;
        var inputValue = this.state.inputValue;
        var enable = this.getHistoryOptions().enable;
        if (enable) {
            this.insertHistoryRecord(inputValue);
            this.setState({ isFocused: false, isHistoryOpened: false });
        }
        onSearch === null || onSearch === void 0 ? void 0 : onSearch(inputValue || '');
    };
    SearchBox.prototype.handleKeyDown = function (e) {
        if (e.key === 'Enter') {
            this.handleSearch();
            e.preventDefault();
        }
    };
    SearchBox.prototype.handleClear = function () {
        var _this = this;
        var _a = this.props, searchImediately = _a.searchImediately, onChange = _a.onChange;
        this.setState({ inputValue: '' }, function () {
            onChange === null || onChange === void 0 ? void 0 : onChange('');
            searchImediately && _this.lazyEmitSearch();
        });
    };
    SearchBox.prototype.handleFocus = function () {
        var enable = this.getHistoryOptions().enable;
        this.setState({ isFocused: true, isHistoryOpened: enable });
    };
    SearchBox.prototype.handleBlur = function (e) {
        this.setState({ isFocused: false, isHistoryOpened: false });
    };
    SearchBox.prototype.handleHistoryRecordSelect = function (record) {
        var _this = this;
        this.setState({ inputValue: record.value, isHistoryOpened: false, isFocused: false }, function () { return _this.handleSearch(); });
    };
    /** 获取历史搜索配置 */
    SearchBox.prototype.getHistoryOptions = function () {
        var _a, _b;
        var history = this.props.history;
        var options = {
            enable: !!(history === null || history === void 0 ? void 0 : history.enable),
            key: (_a = history === null || history === void 0 ? void 0 : history.key) !== null && _a !== void 0 ? _a : historyDefaultOptions.key,
            limit: (history === null || history === void 0 ? void 0 : history.limit) && (0, isInteger_1.default)(history === null || history === void 0 ? void 0 : history.limit) && (history === null || history === void 0 ? void 0 : history.limit) > 0
                ? history === null || history === void 0 ? void 0 : history.limit
                : historyDefaultOptions.limit,
            dropdownClassName: (_b = history === null || history === void 0 ? void 0 : history.dropdownClassName) !== null && _b !== void 0 ? _b : ''
        };
        return options;
    };
    /** 获取历史记录 */
    SearchBox.prototype.getHistoryRecords = function () {
        var _a = this.getHistoryOptions(), key = _a.key, limit = _a.limit;
        try {
            var storageValues = localStorage.getItem(key);
            return lodash_1.default.chain(storageValues ? JSON.parse(storageValues) : [])
                .uniqBy('value')
                .orderBy(['timestamp'], ['desc'])
                .slice(0, limit)
                .value();
        }
        catch (_b) { }
        return [];
    };
    /** 清空历史记录 */
    SearchBox.prototype.clearHistoryRecords = function () {
        var key = this.getHistoryOptions().key;
        localStorage.removeItem(key);
        this.setState({ historyRecords: [] });
        return [];
    };
    /** 删除一条历史记录 */
    SearchBox.prototype.removeHistoryRecord = function (record) {
        var key = this.getHistoryOptions().key;
        var datasource = this.getHistoryRecords();
        var recordIndex = datasource.findIndex(function (item) { return item.value === record.value; });
        if (~recordIndex) {
            datasource.splice(recordIndex, 1);
            localStorage.setItem(key, JSON.stringify(datasource));
            this.setState({ historyRecords: datasource });
        }
        return datasource;
    };
    /** 新增一条历史记录 */
    SearchBox.prototype.insertHistoryRecord = function (value) {
        var datasource = this.getHistoryRecords();
        if (!value || datasource.find(function (item) { return item.value === value; })) {
            return datasource;
        }
        try {
            var _a = this.getHistoryOptions(), key = _a.key, limit = _a.limit;
            var newDatasource = lodash_1.default.chain((0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], datasource, true), [
                { value: value, timestamp: (0, moment_1.default)().unix() }
            ], false))
                .orderBy(['timestamp'], ['desc'])
                .slice(0, limit)
                .value();
            localStorage.setItem(key, JSON.stringify(newDatasource));
            this.setState({ historyRecords: newDatasource });
            return newDatasource;
        }
        catch (_b) { }
        return datasource;
    };
    SearchBox.prototype.renderInput = function (isHistoryMode) {
        var _a = this.props, cx = _a.classnames, active = _a.active, name = _a.name, className = _a.className, disabled = _a.disabled, placeholder = _a.placeholder, mini = _a.mini, enhance = _a.enhance, clearable = _a.clearable, __ = _a.translate;
        var _b = this.state, isFocused = _b.isFocused, inputValue = _b.inputValue;
        var enable = this.getHistoryOptions().enable;
        return (react_1.default.createElement("div", { className: cx('SearchBox', enhance && 'SearchBox--enhance', !!isHistoryMode ? '' : className, disabled ? 'is-disabled' : '', isFocused ? 'is-focused' : '', !mini || active ? 'is-active' : '', { 'is-history': enable }) },
            react_1.default.createElement("input", { name: name, ref: this.inputRef, onFocus: this.handleFocus, onBlur: this.handleBlur, onChange: this.handleChange, onKeyDown: this.handleKeyDown, value: inputValue !== null && inputValue !== void 0 ? inputValue : '', disabled: disabled, placeholder: __(placeholder || 'placeholder.enter'), autoComplete: "off" }),
            !mini && clearable && inputValue && !disabled ? (react_1.default.createElement("div", { className: cx('SearchBox-clearable'), onClick: this.handleClear },
                react_1.default.createElement(icons_1.Icon, { icon: "input-clear", className: "icon" }))) : null,
            !mini ? (react_1.default.createElement("a", { className: cx('SearchBox-searchBtn'), onClick: this.handleSearch },
                react_1.default.createElement(icons_1.Icon, { icon: "search", className: "icon" }))) : active ? (react_1.default.createElement("a", { className: cx('SearchBox-cancelBtn'), onClick: this.handleCancel },
                react_1.default.createElement(icons_1.Icon, { icon: "close", className: "icon" }))) : (react_1.default.createElement("a", { className: cx('SearchBox-activeBtn'), onClick: this.handleActive },
                react_1.default.createElement(icons_1.Icon, { icon: "search", className: "icon" })))));
    };
    SearchBox.prototype.renderTag = function (item, index) {
        var _this = this;
        var cx = this.props.classnames;
        return (react_1.default.createElement("span", { className: cx('Tag', 'SearchBox-history-tag'), key: index },
            react_1.default.createElement("span", { className: cx('SearchBox-history-tag-text'), onMouseDown: function (e) {
                    e.preventDefault();
                    _this.handleHistoryRecordSelect(item);
                } }, item.value),
            react_1.default.createElement("span", { className: cx("SearchBox-history-tag-close"), onMouseDown: function (e) {
                    e.preventDefault();
                    _this.removeHistoryRecord(item);
                } },
                react_1.default.createElement(icons_1.Icon, { icon: "close", className: "icon" }))));
    };
    SearchBox.prototype.renderHitoryMode = function () {
        var _this = this;
        var _a = this.props, cx = _a.classnames, __ = _a.translate, className = _a.className;
        var _b = this.state, isHistoryOpened = _b.isHistoryOpened, inputValue = _b.inputValue, historyRecords = _b.historyRecords;
        var dropdownClassName = this.getHistoryOptions().dropdownClassName;
        var showDropdown = isHistoryOpened && !inputValue && historyRecords.length > 0;
        return (react_1.default.createElement("div", { id: "searchbox-history", className: cx('SearchBox-history', className) },
            this.renderInput(true),
            react_1.default.createElement("div", { className: cx('SearchBox-history-dropdown', dropdownClassName, {
                    'is-active': showDropdown
                }) },
                react_1.default.createElement("header", null,
                    react_1.default.createElement("h4", null, __('searchHistory')),
                    react_1.default.createElement("a", { onMouseDown: function (e) {
                            e.preventDefault();
                            _this.clearHistoryRecords();
                        } }, __('clear'))),
                react_1.default.createElement("div", { className: cx('SearchBox-history-content') }, historyRecords.map(function (item, index) { return _this.renderTag(item, index); })))));
    };
    SearchBox.prototype.render = function () {
        var enable = this.getHistoryOptions().enable;
        return enable ? this.renderHitoryMode() : this.renderInput();
    };
    var _a, _b, _c;
    SearchBox.defaultProps = {
        mini: true,
        enhance: false,
        clearable: false,
        searchImediately: true,
        history: historyDefaultOptions
    };
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", []),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleActive", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", []),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleCancel", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", [typeof (_a = typeof react_1.default !== "undefined" && react_1.default.ChangeEvent) === "function" ? _a : Object]),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleChange", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", []),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleSearch", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", [typeof (_b = typeof react_1.default !== "undefined" && react_1.default.KeyboardEvent) === "function" ? _b : Object]),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleKeyDown", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", []),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleClear", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", []),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleFocus", null);
    (0, tslib_1.__decorate)([
        helper_1.autobind,
        (0, tslib_1.__metadata)("design:type", Function),
        (0, tslib_1.__metadata)("design:paramtypes", [typeof (_c = typeof react_1.default !== "undefined" && react_1.default.FocusEvent) === "function" ? _c : Object]),
        (0, tslib_1.__metadata)("design:returntype", void 0)
    ], SearchBox.prototype, "handleBlur", null);
    return SearchBox;
}(react_1.default.Component));
exports.SearchBox = SearchBox;
exports.default = (0, theme_1.themeable)((0, locale_1.localeable)((0, uncontrollable_1.uncontrollable)(SearchBox, {
    active: 'onActiveChange',
    value: 'onChange'
})));
//# sourceMappingURL=./components/SearchBox.js.map
