/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

import { __extends, __assign, __spreadArray, __read, __decorate, __metadata, __rest } from 'tslib';
import { normalizeNodePath, isObject, findTree, getOptionValueBindField, getOptionValue, labelToString, Overlay, PopOver, noop, ucFirst, autobind, uncontrollable, themeable, localeable, highlight } from 'amis-core';
import React__default from 'react';
import isInteger from 'lodash/isInteger';
import omit from 'lodash/omit';
import merge from 'lodash/merge';
import VirtualList from './virtual-list/index.js';
import TooltipWrapper from './TooltipWrapper.js';
import Downshift from 'downshift';
import { Icon } from './icons.js';
import { matchSorter } from 'match-sorter';
import isPlainObject from 'lodash/isPlainObject';
import { findDOMNode } from 'react-dom';
import Checkbox from './Checkbox.js';
import Input from './Input.js';
import Spinner from './Spinner.js';
import { withRemoteConfig } from './WithRemoteConfig.js';
import { PopOverContainer } from './PopOverContainer.js';
import SelectMobile from './SelectMobile.js';

/**
 * @file Select
 * @description
 * @author fex
 * @date 2017-11-07
 */
var defaultFilterOption = function (options, inputValue, option) {
    return matchSorter(options, inputValue, __assign({ threshold: matchSorter.rankings.CONTAINS }, option));
};
function value2array(value, props, enableNodePath) {
    if (enableNodePath === void 0) { enableNodePath = false; }
    var labelField = props.labelField, _a = props.valueField, valueField = _a === void 0 ? 'value' : _a, pathSeparator = props.pathSeparator, delimiter = props.delimiter, options = props.options, multi = props.multi, multiple = props.multiple;
    if (enableNodePath) {
        value = normalizeNodePath(value, enableNodePath, labelField, valueField, pathSeparator, delimiter).nodeValueArray;
    }
    if (multi || multiple) {
        if (typeof value === 'string') {
            value = value.split(delimiter || ',');
        }
        if (!Array.isArray(value)) {
            if (value === null || value === undefined) {
                return [];
            }
            value = [value];
        }
        return value
            .map(function (value) {
            return expandValue(value, options, valueField) ||
                (isObject(value) && value.hasOwnProperty(valueField)
                    ? value
                    : undefined);
        })
            .filter(function (item) { return item; });
    }
    else if (Array.isArray(value)) {
        value = value[0];
    }
    var expandedValue = expandValue(value, options, valueField);
    return expandedValue
        ? [expandedValue]
        : isObject(value) && value.hasOwnProperty(valueField || 'value')
            ? [value]
            : [];
}
function expandValue(value, options, valueField) {
    var _a;
    if (valueField === void 0) { valueField = 'value'; }
    var valueType = typeof value;
    if (valueType !== 'string' &&
        valueType !== 'number' &&
        valueType !== 'boolean' &&
        valueType !== 'object') {
        return value;
    }
    if (!options) {
        return null;
    }
    if (valueType === 'object' &&
        value &&
        value.hasOwnProperty(valueField || 'value')) {
        value = (_a = value[valueField || 'value']) !== null && _a !== void 0 ? _a : '';
    }
    return findTree(options, optionValueCompare(value, valueField || 'value'), {
        resolve: getOptionValueBindField(valueField),
        value: getOptionValue(value, valueField)
    });
}
function matchOptionValue(a, b, valueField) {
    if (valueField === void 0) { valueField = 'value'; }
    return isObject(a)
        ? a === b[valueField || 'value']
        : String(b[valueField || 'value']) === String(a);
}
function optionValueCompare(a, valueField) {
    if (valueField === void 0) { valueField = 'value'; }
    return function (b) { return matchOptionValue(a, b, valueField); };
}
function normalizeOptions(options, share, valueField) {
    if (share === void 0) { share = {
        values: [],
        options: []
    }; }
    if (valueField === void 0) { valueField = 'value'; }
    if (typeof options === 'string') {
        return options.split(',').map(function (item) {
            var idx = share.values.indexOf(item);
            if (~idx) {
                return share.options[idx];
            }
            var option = {
                label: item,
                value: item
            };
            share.values.push(option.value);
            share.options.push(option);
            return option;
        });
    }
    else if (Array.isArray(options) &&
        typeof options[0] === 'string') {
        return options.map(function (item) {
            var idx = share.values.indexOf(item);
            if (~idx) {
                return share.options[idx];
            }
            var option = {
                label: item,
                value: item
            };
            share.values.push(option.value);
            share.options.push(option);
            return option;
        });
    }
    else if (Array.isArray(options)) {
        return options.map(function (item) {
            var value = item && item[valueField];
            var idx = value !== undefined && !item.children
                ? share.values.indexOf(value)
                : -1;
            if (~idx) {
                return share.options[idx];
            }
            var option = __assign(__assign({}, item), { value: value });
            if (typeof option.children !== 'undefined') {
                option.children = normalizeOptions(option.children, share, valueField);
            }
            else if (value !== undefined) {
                share.values.push(value);
                share.options.push(option);
            }
            return option;
        });
    }
    else if (isPlainObject(options)) {
        return Object.keys(options).map(function (key) {
            var idx = share.values.indexOf(key);
            if (~idx) {
                return share.options[idx];
            }
            var option = {
                label: options[key],
                value: key
            };
            share.values.push(option.value);
            share.options.push(option);
            return option;
        });
    }
    return [];
}
var DownshiftChangeTypes = Downshift.stateChangeTypes;
var Select = /** @class */ (function (_super) {
    __extends(Select, _super);
    function Select(props) {
        var _this = _super.call(this, props) || this;
        _this.menu = React__default.createRef();
        _this.state = {
            isOpen: props.defaultOpen || false,
            isFocused: false,
            inputValue: '',
            highlightedIndex: -1,
            selection: value2array(props.value, props),
            itemHeight: 32 /** Select选项高度保持一致 */,
            pickerSelectItem: ''
        };
        return _this;
    }
    Select.prototype.componentDidMount = function () {
        var loadOptions = this.props.loadOptions;
        loadOptions && loadOptions('');
    };
    Select.prototype.componentDidUpdate = function (prevProps) {
        var props = this.props;
        var fn = noop;
        if (JSON.stringify(props.value) !== JSON.stringify(prevProps.value) ||
            JSON.stringify(props.options) !== JSON.stringify(prevProps.options)) {
            var selection = value2array(props.value, props);
            this.setState({
                selection: selection
            }, fn);
        }
    };
    Select.prototype.open = function () {
        var _this = this;
        var _a = this.props, disabled = _a.disabled, loading = _a.loading;
        if (disabled || loading) {
            return;
        }
        this.setState({
            isOpen: true,
            highlightedIndex: -1
        }, function () { return setTimeout(_this.focus, 500); });
    };
    Select.prototype.close = function () {
        this.setState({
            isOpen: false
        });
    };
    Select.prototype.confirm = function () {
        // @ts-ignore
        this.handleChange(this.state.pickerSelectItem);
        this.setState({
            isOpen: false
        });
    };
    Select.prototype.toggle = function (e) {
        var _this = this;
        var _a = this.props, disabled = _a.disabled, loading = _a.loading;
        if ((e &&
            this.menu.current &&
            this.menu.current.contains(e.target)) ||
            disabled ||
            loading) {
            return;
        }
        this.setState({
            isOpen: !this.state.isOpen,
            highlightedIndex: -1
        }, this.state.isOpen ? undefined : function () { return setTimeout(_this.focus, 500); });
    };
    Select.prototype.onFocus = function (e) {
        var _a = this.props, simpleValue = _a.simpleValue, disabled = _a.disabled, loading = _a.loading;
        var _b = this.state, selection = _b.selection, isOpen = _b.isOpen;
        var value = simpleValue ? selection.map(function (item) { return item.value; }) : selection;
        if (!disabled && !loading && !isOpen) {
            this.setState({ isFocused: true }, this.focus);
        }
        this.props.onFocus &&
            this.props.onFocus(__assign(__assign({}, e), { value: value }));
    };
    Select.prototype.onBlur = function (e) {
        var simpleValue = this.props.simpleValue;
        var selection = this.state.selection;
        var value = simpleValue ? selection.map(function (item) { return item.value; }) : selection;
        this.setState({
            isFocused: false
        });
        this.props.onBlur &&
            this.props.onBlur(__assign(__assign({}, e), { value: value }));
    };
    Select.prototype.focus = function () {
        this.input
            ? this.input.focus()
            : this.getTarget() && this.getTarget().focus();
    };
    Select.prototype.blur = function () {
        this.input
            ? this.input.blur()
            : this.getTarget() && this.getTarget().blur();
    };
    Select.prototype.getTarget = function () {
        if (!this.target) {
            this.target = findDOMNode(this);
        }
        return this.target;
    };
    Select.prototype.inputRef = function (ref) {
        this.input = ref;
    };
    Select.prototype.toggleCheckAll = function () {
        var _a = this.props, options = _a.options, onChange = _a.onChange, simpleValue = _a.simpleValue, checkAllBySearch = _a.checkAllBySearch, labelField = _a.labelField, valueField = _a.valueField, _b = _a.filterOption, filterOption = _b === void 0 ? defaultFilterOption : _b;
        var inputValue = this.state.inputValue;
        var selection = this.state.selection;
        var filtedOptions = inputValue && checkAllBySearch !== false
            ? filterOption(options, inputValue, {
                keys: [labelField || 'label', valueField || 'value']
            })
            : options.concat();
        var optionsValues = filtedOptions.map(function (option) { return option.value; });
        var selectionValues = selection.map(function (select) { return select.value; });
        var checkedAll = optionsValues.every(function (option) { return selectionValues.indexOf(option) > -1; });
        selection = checkedAll ? [] : filtedOptions;
        onChange(simpleValue ? selection.map(function (item) { return item.value; }) : selection);
    };
    Select.prototype.removeItem = function (index, e) {
        var _a = this.props, onChange = _a.onChange, simpleValue = _a.simpleValue, disabled = _a.disabled;
        if (disabled) {
            return;
        }
        var value = this.state.selection;
        e && e.stopPropagation();
        value = Array.isArray(value) ? value.concat() : [value];
        value.splice(index, 1);
        onChange(simpleValue ? value.map(function (item) { return item.value; }) : value);
    };
    Select.prototype.handleInputChange = function (evt) {
        var _this = this;
        var loadOptions = this.props.loadOptions;
        this.setState({
            inputValue: evt.currentTarget.value
        }, function () { return loadOptions && loadOptions(_this.state.inputValue); });
    };
    Select.prototype.handlePickerChange = function (selectItem, index, confirm) {
        if (!this.props.multiple) {
            selectItem = selectItem[0];
        }
        this.setState({
            pickerSelectItem: selectItem
        });
        // 直接选中选项
        if (confirm) {
            this.handleChange(selectItem);
        }
    };
    /**
     * DownShift中ESC按键动作会触发change事件，此时selectItem为null，需要单独处理，参考：
     * {@link https://github.com/downshift-js/downshift/issues/719 GitHub Issue #719}
     */
    Select.prototype.handleChange = function (selectItem) {
        var _a = this.props, onChange = _a.onChange, multiple = _a.multiple, simpleValue = _a.simpleValue, valueField = _a.valueField;
        var selection = this.state.selection;
        if (selectItem == null) {
            return;
        }
        if (multiple) {
            var selectionValues = selection.map(function (item) { return item[valueField]; });
            selection = selection.concat();
            var idx = selectionValues.indexOf(selectItem[valueField]);
            if (~idx) {
                selection.splice(idx, 1);
            }
            else {
                selection.push(selectItem);
            }
            onChange(simpleValue ? selection.map(function (item) { return item[valueField]; }) : selection);
        }
        else {
            // Downshift里面的判断修改后的值是否相等时，没有区分是否多选，且用的是！==，所以这里拦截一下
            (!selection.length ||
                selection[0][valueField] !== selectItem[valueField]) &&
                onChange(simpleValue ? selectItem[valueField] : selectItem);
        }
    };
    Select.prototype.handleStateChange = function (changes) {
        var _a = this.props, multiple = _a.multiple, checkAll = _a.checkAll;
        var update = {};
        switch (changes.type) {
            case DownshiftChangeTypes.keyDownEnter:
            case DownshiftChangeTypes.clickItem:
                update = __assign(__assign({}, update), { isOpen: multiple ? true : false, isFocused: multiple && checkAll ? true : false });
                break;
            case DownshiftChangeTypes.controlledPropUpdatedSelectedItem:
                break;
            case DownshiftChangeTypes.changeInput:
                update.highlightedIndex = 0;
                break;
            case DownshiftChangeTypes.keyDownArrowDown:
            case DownshiftChangeTypes.keyDownArrowUp:
            case DownshiftChangeTypes.itemMouseEnter:
                update = __assign(__assign({}, update), changes);
                break;
        }
        if (Object.keys(update).length) {
            this.setState(update);
        }
    };
    Select.prototype.handleKeyPress = function (e) {
        /**
         * 考虑到label/value中有空格的case
         * 这里使用组合键关闭 win：shift + space，mac：shift + space
         */
        if (e.key === ' ' && e.shiftKey) {
            this.toggle();
            e.preventDefault();
        }
    };
    Select.prototype.clearValue = function (e) {
        var onChange = this.props.onChange;
        e.preventDefault();
        e.stopPropagation();
        onChange(this.props.resetValue);
    };
    Select.prototype.clearSearchValue = function () {
        var loadOptions = this.props.loadOptions;
        this.setState({
            inputValue: ''
        }, function () { return loadOptions === null || loadOptions === void 0 ? void 0 : loadOptions(''); });
    };
    Select.prototype.handleAddClick = function () {
        var onAdd = this.props.onAdd;
        onAdd && onAdd();
    };
    Select.prototype.handleEditClick = function (e, item) {
        var onEdit = this.props.onEdit;
        e.preventDefault();
        e.stopPropagation();
        onEdit && onEdit(item);
    };
    Select.prototype.handleDeleteClick = function (e, item) {
        var onDelete = this.props.onDelete;
        e.preventDefault();
        e.stopPropagation();
        onDelete && onDelete(item);
    };
    Select.prototype.renderValue = function (_a) {
        var _b;
        var _this = this;
        _a.inputValue; _a.isOpen;
        var _c = this.props, cx = _c.classnames, multiple = _c.multiple, valuesNoWrap = _c.valuesNoWrap, placeholder = _c.placeholder, labelField = _c.labelField, disabled = _c.disabled, maxTagCount = _c.maxTagCount, overflowTagPopover = _c.overflowTagPopover, showInvalidMatch = _c.showInvalidMatch, renderValueLabel = _c.renderValueLabel, popOverContainer = _c.popOverContainer, __ = _c.translate;
        var selection = this.state.selection;
        var labelKey = labelField || 'label';
        if (!selection.length) {
            return (React__default.createElement("div", { key: "placeholder", className: cx('Select-placeholder') }, __(placeholder)));
        }
        if (multiple &&
            maxTagCount != null &&
            isInteger(Math.floor(maxTagCount)) &&
            Math.floor(maxTagCount) >= 0 &&
            Math.floor(maxTagCount) < selection.length) {
            var maxVisibleCount_1 = Math.floor(maxTagCount);
            var tooltipProps_1 = __assign({ placement: 'top', trigger: 'hover', showArrow: false, offset: [0, -10], tooltipClassName: cx('Select-overflow', overflowTagPopover === null || overflowTagPopover === void 0 ? void 0 : overflowTagPopover.tooltipClassName) }, omit(overflowTagPopover, ['children', 'content', 'tooltipClassName']));
            return __spreadArray(__spreadArray([], __read(selection.slice(0, maxVisibleCount_1)), false), [
                (_b = {}, _b[labelKey] = "+ ".concat(selection.length - maxVisibleCount_1, " ..."), _b)
            ], false).map(function (item, index) {
                var label = labelToString(item[labelKey]);
                if (index === maxVisibleCount_1) {
                    return (React__default.createElement(TooltipWrapper, { key: selection.length, container: popOverContainer, tooltip: __assign(__assign({}, tooltipProps_1), { children: function () { return (React__default.createElement("div", { className: cx('Select-overflow-wrapper') }, selection
                                .slice(maxVisibleCount_1, selection.length)
                                .map(function (item, index) {
                                var itemIndex = index + maxVisibleCount_1;
                                var label = labelToString(item[labelKey]);
                                return (React__default.createElement("div", { key: itemIndex, className: cx('Select-value', {
                                        'is-disabled': disabled,
                                        'is-invalid': showInvalidMatch
                                            ? item.__unmatched
                                            : false
                                    }) },
                                    React__default.createElement("span", { className: cx('Select-valueLabel') }, renderValueLabel
                                        ? renderValueLabel(item)
                                        : label),
                                    React__default.createElement("span", { className: cx('Select-valueIcon', {
                                            'is-disabled': disabled || item.disabled
                                        }), onClick: _this.removeItem.bind(_this, itemIndex) },
                                        React__default.createElement(Icon, { icon: "close", className: "icon" }))));
                            }))); } }) },
                        React__default.createElement("div", { className: cx('Select-value', {
                                'is-disabled': disabled,
                                'is-invalid': showInvalidMatch ? item.__unmatched : false
                            }), onClick: function (e) {
                                return e.stopPropagation();
                            } },
                            React__default.createElement("span", { className: cx('Select-valueLabel') }, renderValueLabel ? renderValueLabel(item) : label))));
                }
                return (React__default.createElement(TooltipWrapper, { container: popOverContainer, placement: 'top', tooltip: label, trigger: 'hover', key: index },
                    React__default.createElement("div", { className: cx('Select-value', {
                            'is-disabled': disabled,
                            'is-invalid': showInvalidMatch ? item.__unmatched : false
                        }) },
                        React__default.createElement("span", { className: cx('Select-valueLabel') }, renderValueLabel ? renderValueLabel(item) : label),
                        React__default.createElement("span", { className: cx('Select-valueIcon', {
                                'is-disabled': disabled || item.disabled
                            }), onClick: _this.removeItem.bind(_this, index) },
                            React__default.createElement(Icon, { icon: "close", className: "icon" })))));
            });
        }
        return selection.map(function (item, index) {
            var label = labelToString(item[labelKey]);
            if (!multiple) {
                return (React__default.createElement("div", { className: cx('Select-value', {
                        'is-disabled': disabled,
                        'is-invalid': showInvalidMatch ? item.__unmatched : false
                    }), key: index }, renderValueLabel ? renderValueLabel(item) : label));
            }
            return valuesNoWrap ? ("".concat(label).concat(index === selection.length - 1 ? '' : ' + ')) : (React__default.createElement(TooltipWrapper, { container: popOverContainer, placement: 'top', tooltip: label, trigger: 'hover', key: index },
                React__default.createElement("div", { className: cx('Select-value', {
                        'is-disabled': disabled,
                        'is-invalid': showInvalidMatch ? item.__unmatched : false
                    }) },
                    React__default.createElement("span", { className: cx('Select-valueLabel') }, renderValueLabel ? renderValueLabel(item) : label),
                    React__default.createElement("span", { className: cx('Select-valueIcon', {
                            'is-disabled': disabled || item.disabled
                        }), onClick: _this.removeItem.bind(_this, index) },
                        React__default.createElement(Icon, { icon: "close", className: "icon" })))));
        });
    };
    Select.prototype.renderOuter = function (_a) {
        var _this = this;
        var _b;
        var selectedItem = _a.selectedItem, getItemProps = _a.getItemProps, highlightedIndex = _a.highlightedIndex, inputValue = _a.inputValue, isOpen = _a.isOpen; _a.getToggleButtonProps; var getInputProps = _a.getInputProps;
        var _c = this.props, popOverContainer = _c.popOverContainer, options = _c.options, valueField = _c.valueField, labelField = _c.labelField, noResultsText = _c.noResultsText, loadOptions = _c.loadOptions, creatable = _c.creatable, multiple = _c.multiple, valuesNoWrap = _c.valuesNoWrap, cx = _c.classnames, popoverClassName = _c.popoverClassName, popOverContainerSelector = _c.popOverContainerSelector, checkAll = _c.checkAll, checkAllLabel = _c.checkAllLabel, checkAllBySearch = _c.checkAllBySearch, searchable = _c.searchable, createBtnLabel = _c.createBtnLabel, disabled = _c.disabled, searchPromptText = _c.searchPromptText, editable = _c.editable, removable = _c.removable, overlayPlacement = _c.overlayPlacement, __ = _c.translate, hideSelected = _c.hideSelected, renderMenu = _c.renderMenu; _c.mobileClassName; var _d = _c.virtualThreshold, virtualThreshold = _d === void 0 ? 100 : _d, mobileUI = _c.mobileUI, _e = _c.filterOption, filterOption = _e === void 0 ? defaultFilterOption : _e, overlay = _c.overlay, loading = _c.loading, testIdBuilder = _c.testIdBuilder;
        var selection = this.state.selection;
        var checkedAll = false;
        var checkedPartial = false;
        var filtedOptions = (inputValue && isOpen && !loadOptions
            ? filterOption(options, inputValue, {
                keys: [labelField || 'label', valueField || 'value']
            })
            : options.concat()).filter(function (option) { return !option.hidden && option.visible !== false; });
        var enableVirtualRender = filtedOptions.length && filtedOptions.length > virtualThreshold;
        var selectionValues = selection.map(function (select) { return select[valueField]; });
        if (multiple && checkAll) {
            var optionsValues = (checkAllBySearch !== false ? filtedOptions : options).map(function (option) { return option[valueField]; });
            checkedAll = optionsValues.every(function (option) { return selectionValues.indexOf(option) > -1; });
            checkedPartial = optionsValues.some(function (option) { return selectionValues.indexOf(option) > -1; });
        }
        // 用于虚拟渲染的每项高度
        var virtualItemHeight = this.props.itemHeight || this.state.itemHeight;
        // 渲染单个选项
        var renderItem = function (_a) {
            var index = _a.index, style = _a.style;
            var item = filtedOptions[index];
            if (!item) {
                return null;
            }
            var checked = selectedItem === item || !!~selectionValues.indexOf(item[valueField]);
            if (hideSelected && checked) {
                return null;
            }
            var label = labelToString(item[labelField]);
            var optTestIdBudr = testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("option-".concat(label || index));
            return (React__default.createElement("div", __assign({}, getItemProps({
                key: typeof item.value === 'string'
                    ? "".concat(item.label, "-").concat(item.value)
                    : index,
                index: index,
                item: item,
                disabled: item.disabled
            }), { style: merge(style, enableVirtualRender ? { width: '100%' } : {}), className: cx("Select-option", {
                    'is-disabled': item.disabled,
                    'is-highlight': highlightedIndex === index,
                    'is-active': checked
                }) }, optTestIdBudr === null || optTestIdBudr === void 0 ? void 0 : optTestIdBudr.getTestId()),
                renderMenu ? (multiple ? (React__default.createElement(Checkbox, { checked: checked, trueValue: item.value, onChange: function () {
                        _this.handleChange(item);
                    }, disabled: item.disabled, testIdBuilder: optTestIdBudr === null || optTestIdBudr === void 0 ? void 0 : optTestIdBudr.getChild('chekbx'), size: "sm" }, renderMenu(item, {
                    multiple: multiple,
                    checkAll: checkAll,
                    checked: checked,
                    onChange: function () { return _this.handleChange(item); },
                    inputValue: inputValue || '',
                    searchable: searchable,
                    index: index
                }))) : (renderMenu(item, {
                    multiple: multiple,
                    checkAll: checkAll,
                    checked: checked,
                    onChange: function () { return _this.handleChange(item); },
                    inputValue: inputValue || '',
                    searchable: searchable,
                    index: index
                }))) : multiple ? (React__default.createElement("div", { title: label, className: cx('Select-option-checkbox') },
                    React__default.createElement(Checkbox, { checked: checked, trueValue: item.value, onChange: function () {
                            _this.handleChange(item);
                        }, disabled: item.disabled, size: "sm" },
                        item.disabled
                            ? label
                            : highlight(label, inputValue, cx('Select-option-hl')),
                        item.tip ? React__default.createElement("span", null, item.tip) : null))) : (React__default.createElement("span", __assign({ className: cx('Select-option-content'), title: typeof label === 'string' ? label : '' }, optTestIdBudr === null || optTestIdBudr === void 0 ? void 0 : optTestIdBudr.getChild('content').getTestId()),
                    item.disabled
                        ? label
                        : highlight(label, inputValue, cx('Select-option-hl')),
                    item.tip ? React__default.createElement("span", null, item.tip) : null)),
                editable ? (React__default.createElement("a", { "data-tooltip": __('Select.edit'), "data-position": "left" },
                    React__default.createElement(Icon, { icon: "pencil", className: "icon", onClick: function (e) { return _this.handleEditClick(e, item); } }))) : null,
                removable ? (React__default.createElement("a", { "data-tooltip": __('Select.clear'), "data-position": "left" },
                    React__default.createElement(Icon, { icon: "close", className: "icon", onClick: function (e) { return _this.handleDeleteClick(e, item); } }))) : null));
        };
        var menu = (React__default.createElement("div", { ref: this.menu, className: cx('Select-menu', {
                'Select--longlist': enableVirtualRender,
                'is-mobile': mobileUI
            }) },
            searchable ? (React__default.createElement("div", { className: cx("Select-input", {
                    'is-focused': this.state.isFocused
                }) },
                React__default.createElement(Icon, { icon: "search", className: "icon" }),
                React__default.createElement(Input, __assign({}, getInputProps({
                    onFocus: this.onFocus,
                    onBlur: this.onBlur,
                    disabled: disabled,
                    placeholder: __(searchPromptText),
                    onChange: this.handleInputChange,
                    ref: this.inputRef
                }))),
                (inputValue === null || inputValue === void 0 ? void 0 : inputValue.length) ? (React__default.createElement("a", { onClick: this.clearSearchValue, className: cx('Select-clear') },
                    React__default.createElement(Icon, { icon: "close", className: "icon" }))) : null)) : null,
            loading ? (React__default.createElement("div", { className: cx('Select-noResult') }, __('loading'))) : (React__default.createElement(React__default.Fragment, null,
                multiple && valuesNoWrap ? (React__default.createElement("div", { className: cx('Select-option') },
                    __('Select.selected'),
                    "(",
                    selectionValues.length,
                    ")")) : null,
                multiple && checkAll && filtedOptions.length ? (React__default.createElement("div", { className: cx('Select-option') },
                    React__default.createElement(Checkbox, { checked: checkedPartial, partial: checkedPartial && !checkedAll, onChange: this.toggleCheckAll, size: "sm" }, __(checkAllLabel)))) : null,
                creatable && !disabled ? (React__default.createElement("a", { className: cx('Select-addBtn'), onClick: this.handleAddClick },
                    React__default.createElement(Icon, { icon: "plus", className: "icon" }),
                    __(createBtnLabel))) : null,
                filtedOptions.length ? (filtedOptions.length > virtualThreshold ? ( // 较多数据时才启用 virtuallist，避免滚动条问题
                React__default.createElement(VirtualList, { height: filtedOptions.length > 8
                        ? 266
                        : filtedOptions.length * virtualItemHeight, itemCount: filtedOptions.length, itemSize: virtualItemHeight, renderItem: renderItem })) : (filtedOptions.map(function (item, index) {
                    return renderItem({ index: index });
                }))) : (React__default.createElement("div", { className: cx('Select-noResult') }, __(noResultsText)))))));
        return mobileUI ? (React__default.createElement(SelectMobile, __assign({}, this.props, { highlightedIndex: highlightedIndex, isOpen: isOpen, getItemProps: getItemProps, getInputProps: getInputProps, selectedItem: selectedItem, onChange: function (selection) {
                _this.setState({
                    isOpen: false
                });
                _this.props.onChange(selection);
            }, onClose: this.close }))) : (React__default.createElement(Overlay, { container: popOverContainer || this.getTarget, containerSelector: popOverContainerSelector, target: this.getTarget, placement: overlayPlacement === 'auto'
                ? PopOverContainer.alignToPlacement(overlay)
                : overlayPlacement, show: true },
            React__default.createElement(PopOver, { overlay: true, className: cx('Select-popover', popoverClassName), style: {
                    width: (overlay &&
                        PopOverContainer.calcOverlayWidth(overlay, (_b = this.target) === null || _b === void 0 ? void 0 : _b.offsetWidth)) ||
                        (this.target ? this.target.offsetWidth : 'auto')
                }, onHide: this.close }, menu)));
    };
    Select.prototype.render = function () {
        var _this = this;
        var _a = this.props, cx = _a.classnames, multiple = _a.multiple, valuesNoWrap = _a.valuesNoWrap, searchable = _a.searchable, inline = _a.inline, block = _a.block, className = _a.className, value = _a.value, loading = _a.loading, clearable = _a.clearable, labelField = _a.labelField, disabled = _a.disabled; _a.checkAll; var borderMode = _a.borderMode, mobileUI = _a.mobileUI, hasError = _a.hasError, testIdBuilder = _a.testIdBuilder, loadingConfig = _a.loadingConfig, controlStyle = _a.controlStyle;
        var selection = this.state.selection;
        var inputValue = this.state.inputValue;
        var resetValue = this.props.resetValue;
        return (React__default.createElement(Downshift, { selectedItem: selection, highlightedIndex: this.state.highlightedIndex, isOpen: this.state.isOpen, inputValue: inputValue, onChange: 
            /*展示 Checkbox 的时候，会出发多次 onChange 原因待查*/
            multiple ? noop : this.handleChange, onStateChange: this.handleStateChange, itemToString: function (item) {
                return item ? "".concat(labelToString(item[labelField])) : '';
            } }, function (options) {
            var _a;
            var isOpen = options.isOpen;
            return (React__default.createElement("div", __assign({ tabIndex: disabled ? -1 : 0, onKeyPress: _this.handleKeyPress, onClick: _this.toggle, onFocus: _this.onFocus, onBlur: _this.onBlur }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getTestId(), { className: cx("Select", (_a = {},
                    _a["Select--multi"] = multiple,
                    _a["Select--inline"] = inline,
                    _a["Select--block"] = block,
                    _a["Select--searchable"] = searchable,
                    _a['is-opened'] = isOpen,
                    _a['is-focused'] = _this.state.isFocused,
                    _a['is-disabled'] = disabled || loading,
                    _a['is-mobile'] = mobileUI,
                    _a['is-error'] = hasError,
                    _a["Select--border".concat(ucFirst(borderMode))] = borderMode,
                    _a), className), "data-amis-name": _this.props.dataName, style: controlStyle }),
                React__default.createElement("div", { className: cx("Select-valueWrap", {
                        'Select-valuesNoWrap': valuesNoWrap
                    }) }, _this.renderValue(options)),
                clearable &&
                    !disabled &&
                    (Array.isArray(value)
                        ? value.length
                        : value != null && value !== resetValue) ? (React__default.createElement("a", __assign({ onClick: _this.clearValue, className: cx('Select-clear') }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('clear').getTestId()),
                    React__default.createElement(Icon, { icon: "input-clear", className: "icon" }))) : null,
                loading ? (React__default.createElement(Spinner, { show: true, icon: "reload", size: "sm", spinnerClassName: cx('Select-spinner'), loadingConfig: loadingConfig })) : null,
                React__default.createElement("span", __assign({ className: cx('Select-arrow') }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('arrow').getTestId()),
                    React__default.createElement(Icon, { icon: "right-arrow-bold", className: "icon" })),
                isOpen ? _this.renderOuter(options) : null));
        }));
    };
    Select.defaultProps = {
        multiple: false,
        clearable: true,
        creatable: false,
        showInvalidMatch: false,
        createBtnLabel: 'Select.createLabel',
        searchPromptText: 'Select.searchPromptText',
        loadingPlaceholder: 'loading',
        noResultsText: 'noResult',
        clearAllText: 'Select.clearAll',
        clearValueText: 'Select.clear',
        placeholder: 'Select.placeholder',
        valueField: 'value',
        labelField: 'label',
        resetValue: '',
        inline: false,
        disabled: false,
        checkAll: false,
        checkAllLabel: 'Select.checkAll',
        defaultCheckAll: false,
        overlayPlacement: 'auto',
        virtualThreshold: 100
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "open", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "close", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "confirm", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "toggle", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "onFocus", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "onBlur", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "focus", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "getTarget", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HTMLInputElement]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "inputRef", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "toggleCheckAll", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleInputChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object, Number, Boolean]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handlePickerChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleStateChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleKeyPress", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "clearValue", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "clearSearchValue", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleAddClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleEditClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], Select.prototype, "handleDeleteClick", null);
    return Select;
}(React__default.Component));
var methods = ['focus', 'blur'];
var EnhancedSelect = uncontrollable(themeable(localeable(Select, methods), methods), {
    value: 'onChange'
}, methods);
var SelectWithRemoteOptions = withRemoteConfig({
    adaptor: function (data) { return data.options || data.items || data.rows || data; },
    normalizeConfig: function (options, origin) {
        options = normalizeOptions(options);
        if (Array.isArray(options)) {
            return options.concat();
        }
        return origin;
    }
})(/** @class */ (function (_super) {
    __extends(class_1, _super);
    function class_1() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    class_1.prototype.render = function () {
        var _a = this.props, loading = _a.loading, config = _a.config; _a.deferLoad; _a.updateConfig; var rest = __rest(_a, ["loading", "config", "deferLoad", "updateConfig"]);
        return (React__default.createElement(EnhancedSelect, __assign({}, rest, { options: config || rest.options || [], loading: loading })));
    };
    return class_1;
}(React__default.Component)));

export { Select, SelectWithRemoteOptions, EnhancedSelect as default, defaultFilterOption, expandValue, matchOptionValue, normalizeOptions, optionValueCompare, value2array };
