/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

'use strict';

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

var tslib = require('tslib');
var React = require('react');
var isInteger = require('lodash/isInteger');
var debounce = require('lodash/debounce');
var moment = require('moment');
var amisCore = require('amis-core');
var icons = require('./icons.js');
var chain = require('lodash/chain');
var Input = require('./Input.js');
var Spinner = require('./Spinner.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var isInteger__default = /*#__PURE__*/_interopDefaultLegacy(isInteger);
var debounce__default = /*#__PURE__*/_interopDefaultLegacy(debounce);
var moment__default = /*#__PURE__*/_interopDefaultLegacy(moment);
var chain__default = /*#__PURE__*/_interopDefaultLegacy(chain);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var historyDefaultOptions = {
    enable: false,
    key: 'amis:search_history',
    limit: 5,
    dropdownClassName: ''
};
var SearchBox = /** @class */ (function (_super) {
    tslib.__extends(SearchBox, _super);
    function SearchBox() {
        var _this = this;
        var _a;
        _this = _super.apply(this, tslib.__spreadArray([], tslib.__read(arguments), false)) || this;
        _this.inputRef = React__default["default"].createRef();
        _this.state = {
            isHistoryOpened: false,
            isFocused: false,
            inputValue: (_a = _this.props.value) !== null && _a !== void 0 ? _a : '',
            historyRecords: _this.getHistoryRecords()
        };
        _this.lazyEmitSearch = debounce__default["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, clearAndSubmit = _a.clearAndSubmit, onChange = _a.onChange;
        this.setState({ inputValue: '' }, function () {
            onChange === null || onChange === void 0 ? void 0 : onChange('');
            if (clearAndSubmit === true || searchImediately) {
                _this.lazyEmitSearch();
            }
        });
    };
    SearchBox.prototype.handleFocus = function () {
        var _a, _b;
        var enable = this.getHistoryOptions().enable;
        this.setState({ isFocused: true, isHistoryOpened: enable });
        (_b = (_a = this.props).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    SearchBox.prototype.handleBlur = function (e) {
        var _a, _b;
        this.setState({ isFocused: false, isHistoryOpened: false });
        (_b = (_a = this.props).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    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) && isInteger__default["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 chain__default["default"](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 = chain__default["default"](tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(datasource), false), [
                { value: value, timestamp: moment__default["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, classPrefix = _a.classPrefix, active = _a.active, name = _a.name, className = _a.className, style = _a.style, disabled = _a.disabled, placeholder = _a.placeholder, mini = _a.mini, enhance = _a.enhance, clearable = _a.clearable, mobileUI = _a.mobileUI, __ = _a.translate, loading = _a.loading, loadingConfig = _a.loadingConfig, testIdBuilder = _a.testIdBuilder;
        var _b = this.state, isFocused = _b.isFocused, inputValue = _b.inputValue;
        var enable = this.getHistoryOptions().enable;
        return (_J$X_("div", tslib.__assign({ className: cx('SearchBox', enhance && 'SearchBox--enhance', !!isHistoryMode ? '' : className, disabled ? 'is-disabled' : '', isFocused ? 'is-focused' : '', !mini || active ? 'is-active' : '', { 'is-history': enable }, { 'is-mobile': mobileUI }), style: style }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getTestId()),
            _J$X_(Input["default"], { name: name, ref: this.inputRef, disabled: disabled, placeholder: __(placeholder || 'placeholder.enter'), value: inputValue !== null && inputValue !== void 0 ? inputValue : '', autoComplete: "off", onFocus: this.handleFocus, onBlur: this.handleBlur, onChange: this.handleChange, onKeyDown: this.handleKeyDown, testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('input') }),
            !mini && clearable && inputValue && !disabled ? (_J$X_("div", tslib.__assign({ className: cx('SearchBox-clearable'), onClick: this.handleClear }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('clear').getTestId()),
                _J$X_(icons.Icon, { icon: "input-clear", className: "icon" }))) : null,
            !mini ? (_J$X_("a", tslib.__assign({ className: cx('SearchBox-searchBtn', {
                    'SearchBox-searchBtn--loading': loading
                }), onClick: this.handleSearch }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('search').getTestId()), loading ? (_J$X_(Spinner["default"], { classnames: cx, classPrefix: classPrefix, className: cx('SearchBox-spinner'), spinnerClassName: cx('SearchBox-spinner-icon'), disabled: disabled, size: "sm", icon: "loading-outline", loadingConfig: loadingConfig })) : (_J$X_(icons.Icon, { icon: "search", className: "icon" })))) : active ? (_J$X_("a", { className: cx('SearchBox-cancelBtn'), onClick: this.handleCancel },
                _J$X_(icons.Icon, { icon: "close", className: "icon" }))) : (_J$X_("a", { className: cx('SearchBox-activeBtn'), onClick: this.handleActive },
                _J$X_(icons.Icon, { icon: "search", className: "icon" })))));
    };
    SearchBox.prototype.renderTag = function (item, index) {
        var _this = this;
        var cx = this.props.classnames;
        return (_J$X_("span", { className: cx('Tag', 'SearchBox-history-tag'), key: index },
            _J$X_("span", { className: cx('SearchBox-history-tag-text'), onMouseDown: function (e) {
                    e.preventDefault();
                    _this.handleHistoryRecordSelect(item);
                } }, item.value),
            _J$X_("span", { className: cx("SearchBox-history-tag-close"), onMouseDown: function (e) {
                    e.preventDefault();
                    _this.removeHistoryRecord(item);
                } },
                _J$X_(icons.Icon, { icon: "close", className: "icon" }))));
    };
    SearchBox.prototype.renderHitoryMode = function () {
        var _this = this;
        var _a = this.props, cx = _a.classnames, __ = _a.translate, className = _a.className, style = _a.style;
        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 (_J$X_("div", { id: "searchbox-history", className: cx('SearchBox-history', className), style: style },
            this.renderInput(true),
            _J$X_("div", { className: cx('SearchBox-history-dropdown', dropdownClassName, {
                    'is-active': showDropdown
                }) },
                _J$X_("header", null,
                    _J$X_("h4", null, __('searchHistory')),
                    _J$X_("a", { onMouseDown: function (e) {
                            e.preventDefault();
                            _this.clearHistoryRecords();
                        } }, __('clear'))),
                _J$X_("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();
    };
    SearchBox.defaultProps = {
        mini: true,
        enhance: false,
        clearable: false,
        searchImediately: true,
        history: historyDefaultOptions,
        clearAndSubmit: false
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleActive", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleCancel", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleSearch", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleKeyDown", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleClear", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleFocus", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SearchBox.prototype, "handleBlur", null);
    return SearchBox;
}(React__default["default"].Component));
var SearchBox$1 = amisCore.themeable(amisCore.localeable(amisCore.uncontrollable(SearchBox, {
    active: 'onActiveChange',
    value: 'onChange'
})));

exports.SearchBox = SearchBox;
exports["default"] = SearchBox$1;
