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

import { __extends, __read, __assign, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import { findDOMNode } from 'react-dom';
import Picker from './Picker.js';
import PopUp from './PopUp.js';
import { autobind, highlight } from 'amis-core';
import merge from 'lodash/merge';
import { matchSorter } from 'match-sorter';
import { value2array } from './Select.js';
import VirtualList from './virtual-list/index.js';
import Checkbox from './Checkbox.js';
import Input from './Input.js';
import { Icon } from './icons.js';

var SelectMobile = /** @class */ (function (_super) {
    __extends(SelectMobile, _super);
    function SelectMobile(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            selection: value2array(props.value, props),
            isFocused: false,
            inputValue: '',
            itemHeight: 32 /** Select选项高度保持一致 */
        };
        return _this;
    }
    SelectMobile.prototype.handleChange = function (_a) {
        var _b = __read(_a, 1), item = _b[0];
        var _c = this.props; _c.onChange; var multiple = _c.multiple; _c.simpleValue; var valueField = _c.valueField, options = _c.options;
        var selection = this.state.selection;
        // 单选是字符串
        var selectItem = options.find(function (option) {
            return multiple
                ? option[valueField] === item[valueField]
                : option[valueField] === item;
        });
        if (multiple) {
            var selectionValues = selection.map(function (item) { return item[valueField]; });
            selection = selection.concat();
            var idx = selectionValues.indexOf(selectItem === null || selectItem === void 0 ? void 0 : selectItem[valueField]);
            if (~idx) {
                selection.splice(idx, 1);
            }
            else {
                selectItem && selection.push(selectItem);
            }
            this.setState({
                selection: selection
            });
        }
        else {
            this.setState({
                selection: selectItem ? [selectItem] : []
            });
        }
    };
    SelectMobile.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); });
    };
    SelectMobile.prototype.getTarget = function () {
        if (!this.target) {
            this.target = findDOMNode(this);
        }
        return this.target;
    };
    SelectMobile.prototype.inputRef = function (ref) {
        this.input = ref;
    };
    SelectMobile.prototype.toggleCheckAll = function () {
        var _a = this.props, options = _a.options; _a.onChange; _a.simpleValue; var checkAllBySearch = _a.checkAllBySearch, labelField = _a.labelField, valueField = _a.valueField;
        var inputValue = this.state.inputValue;
        var selection = this.state.selection;
        var filtedOptions = inputValue && checkAllBySearch !== false
            ? matchSorter(options, inputValue, {
                keys: [labelField || 'label', valueField || 'value'],
                threshold: matchSorter.rankings.CONTAINS
            })
            : 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;
        this.setState({ selection: selection });
    };
    SelectMobile.prototype.handleAddClick = function () {
        var onAdd = this.props.onAdd;
        onAdd && onAdd();
    };
    SelectMobile.prototype.handleEditClick = function (e, item) {
        var onEdit = this.props.onEdit;
        e.preventDefault();
        e.stopPropagation();
        onEdit && onEdit(item);
    };
    SelectMobile.prototype.handleDeleteClick = function (e, item) {
        var onDelete = this.props.onDelete;
        e.preventDefault();
        e.stopPropagation();
        onDelete && onDelete(item);
    };
    SelectMobile.prototype.onFocus = function (e) {
        var simpleValue = this.props.simpleValue;
        var selection = this.state.selection;
        var value = simpleValue ? selection.map(function (item) { return item.value; }) : selection;
        this.props.disabled ||
            this.props.isOpen ||
            this.setState({
                isFocused: true
            }, this.focus);
        this.props.onFocus &&
            this.props.onFocus(__assign(__assign({}, e), { value: value }));
    };
    SelectMobile.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 }));
    };
    SelectMobile.prototype.focus = function () {
        this.input
            ? this.input.focus()
            : this.getTarget() && this.getTarget().focus();
    };
    SelectMobile.prototype.blur = function () {
        this.input
            ? this.input.blur()
            : this.getTarget() && this.getTarget().blur();
    };
    SelectMobile.prototype.clearSearchValue = function () {
        var loadOptions = this.props.loadOptions;
        this.setState({
            inputValue: ''
        }, function () { return loadOptions === null || loadOptions === void 0 ? void 0 : loadOptions(''); });
    };
    SelectMobile.prototype.onConfirm = function () {
        var _a, _b;
        var selection = this.state.selection;
        var _c = this.props, multiple = _c.multiple, onChange = _c.onChange, simpleValue = _c.simpleValue, valueField = _c.valueField, options = _c.options, loadOptions = _c.loadOptions, labelField = _c.labelField;
        if (multiple) {
            onChange(simpleValue ? selection.map(function (item) { return item[valueField]; }) : selection);
        }
        else {
            var inputValue = this.state.inputValue;
            var filtedOptions = (inputValue && !loadOptions
                ? matchSorter(options, inputValue, {
                    keys: [labelField || 'label', valueField || 'value'],
                    threshold: matchSorter.rankings.CONTAINS
                })
                : options.concat()).filter(function (option) { return !option.hidden && option.visible !== false; });
            // picker 打开未滑动时选中第一项
            if (!selection.length && filtedOptions.length) {
                onChange(simpleValue ? (_a = filtedOptions[0]) === null || _a === void 0 ? void 0 : _a[valueField] : filtedOptions[0]);
            }
            else {
                onChange(simpleValue ? (_b = selection[0]) === null || _b === void 0 ? void 0 : _b[valueField] : selection[0]);
            }
        }
    };
    SelectMobile.prototype.render = function () {
        var _this = this;
        var _a;
        var _b = this.props, popOverContainer = _b.popOverContainer, options = _b.options, valueField = _b.valueField, labelField = _b.labelField, noResultsText = _b.noResultsText, loadOptions = _b.loadOptions, multiple = _b.multiple, valuesNoWrap = _b.valuesNoWrap, cx = _b.classnames, checkAll = _b.checkAll, checkAllLabel = _b.checkAllLabel, checkAllBySearch = _b.checkAllBySearch, searchable = _b.searchable, disabled = _b.disabled, searchPromptText = _b.searchPromptText, visibleItemCount = _b.visibleItemCount, __ = _b.translate, hideSelected = _b.hideSelected, renderMenu = _b.renderMenu, _c = _b.virtualThreshold, virtualThreshold = _c === void 0 ? 100 : _c, isOpen = _b.isOpen, onClose = _b.onClose, getInputProps = _b.getInputProps, getItemProps = _b.getItemProps, selectedItem = _b.selectedItem;
        var selection = this.state.selection;
        var inputValue = this.state.inputValue;
        var checkedAll = false;
        var checkedPartial = false;
        var filtedOptions = (inputValue && isOpen && !loadOptions
            ? matchSorter(options, inputValue, {
                keys: [labelField || 'label', valueField || 'value'],
                threshold: matchSorter.rankings.CONTAINS
            })
            : options.concat()).filter(function (option) {
            return !option.hidden &&
                option.visible !== false &&
                option[labelField || 'label'];
        });
        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;
            }
            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-active': checked,
                    'is-mobile': true
                }) }), renderMenu ? (multiple ? (React__default.createElement(React__default.Fragment, null,
                React__default.createElement("div", { title: item[labelField], className: cx('Select-option-item-check'), onClick: function () { return !item.disabled && _this.handleChange([item]); } }, renderMenu(item, {
                    multiple: multiple,
                    checkAll: checkAll,
                    checked: checked,
                    onChange: function () { return _this.handleChange(item); },
                    inputValue: inputValue || '',
                    searchable: searchable,
                    index: index
                })),
                checked ? (React__default.createElement(Icon, { icon: "check", className: cx('Select-option-mcheck') })) : null)) : (renderMenu(item, {
                multiple: multiple,
                checkAll: checkAll,
                checked: checked,
                onChange: function () { return _this.handleChange(item); },
                inputValue: inputValue || '',
                searchable: searchable,
                index: index
            }))) : multiple ? (React__default.createElement(React__default.Fragment, null,
                React__default.createElement("div", { title: item[labelField], className: cx('Select-option-item-check'), onClick: function () { return !item.disabled && _this.handleChange([item]); } },
                    item.disabled
                        ? item[labelField]
                        : highlight(item[labelField], inputValue, cx('Select-option-hl')),
                    item.tip),
                checked ? (React__default.createElement(Icon, { icon: "check", className: cx('Select-option-mcheck') })) : null)) : (React__default.createElement("span", { className: cx('Select-option-content'), title: typeof item[labelField] === 'string' ? item[labelField] : '' },
                item.disabled
                    ? item[labelField]
                    : highlight(item[labelField], inputValue, cx('Select-option-hl')),
                item.tip))));
        };
        var searchInput = (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));
        var menu = (React__default.createElement("div", { className: cx('Select-menu', {
                'Select--longlist': enableVirtualRender,
                'is-mobile': true
            }) },
            searchable ? searchInput : null,
            multiple && valuesNoWrap ? (React__default.createElement("div", { className: cx('Select-option') },
                "\u5DF2\u9009\u62E9(",
                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,
            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 (React__default.createElement(PopUp, { className: cx("Select-popup"), container: popOverContainer, isShow: isOpen, showConfirm: true, onConfirm: this.onConfirm, onHide: onClose }, multiple ? (menu) : (React__default.createElement("div", { className: cx("Select-popup-inner") },
            searchable ? searchInput : null,
            React__default.createElement(Picker, { className: 'Select-picker', columns: {
                    options: filtedOptions,
                    optionRender: renderMenu
                }, highlightTxt: inputValue, onChange: function (item) { return _this.handleChange(item); }, showToolbar: false, labelField: labelField, valueField: valueField, itemHeight: 40, visibleItemCount: visibleItemCount, value: [(_a = selection[0]) === null || _a === void 0 ? void 0 : _a[valueField]] })))));
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "handleChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "handleInputChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "getTarget", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HTMLInputElement]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "inputRef", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "toggleCheckAll", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "handleAddClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "handleEditClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "handleDeleteClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "onFocus", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "onBlur", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "focus", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "clearSearchValue", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SelectMobile.prototype, "onConfirm", null);
    return SelectMobile;
}(React__default.Component));

export { SelectMobile as default };
