/**
 * 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 Sortable = require('sortablejs');
var ReactDOM = require('react-dom');
var cloneDeep = require('lodash/cloneDeep');
var amisCore = require('amis-core');
var icons = require('./icons.js');
var TransferSearch = require('./TransferSearch.js');
var index = require('./virtual-list/index.js');
var AutoSizer = require('./virtual-list/AutoSizer.js');

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

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var Sortable__default = /*#__PURE__*/_interopDefaultLegacy(Sortable);
var cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(cloneDeep);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var ResultList = /** @class */ (function (_super) {
    tslib.__extends(ResultList, _super);
    function ResultList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            searchResult: null
        };
        _this.id = amisCore.guid();
        _this.unmounted = false;
        return _this;
    }
    ResultList.itemRender = function (option, states) {
        var scopeLabel = option.scopeLabel || '';
        var label = option[(states === null || states === void 0 ? void 0 : states.labelField) || 'label'];
        var canScopeLabelTitle = typeof scopeLabel === 'string' || typeof scopeLabel === 'number';
        var canLabelTitle = typeof label === 'string' || typeof label === 'number';
        var title = canScopeLabelTitle && canLabelTitle ? "".concat(scopeLabel).concat(label) : '';
        var classnames = states.classnames;
        return (_J$X_("span", { title: title, className: classnames('Selection-ellipsis-line') },
            scopeLabel,
            label));
    };
    ResultList.prototype.componentDidMount = function () {
        this.props.sortable && this.initSortable();
    };
    ResultList.prototype.componentDidUpdate = function () {
        if (this.props.sortable) {
            this.sortable || this.initSortable();
        }
        else {
            this.desposeSortable();
        }
    };
    ResultList.prototype.componentWillUnmount = function () {
        this.desposeSortable();
        this.unmounted = true;
    };
    ResultList.prototype.domSearchRef = function (ref) {
        while (ref && ref.getWrappedInstance) {
            ref = ref.getWrappedInstance();
        }
        this.searchRef = ref;
    };
    ResultList.prototype.initSortable = function () {
        var _this = this;
        var ns = this.props.classPrefix;
        var dom = ReactDOM.findDOMNode(this);
        var container = dom.querySelector(".".concat(ns, "Selections-items"));
        if (!container) {
            return;
        }
        this.sortable = new Sortable__default["default"](container, {
            group: "selections-".concat(this.id),
            animation: 150,
            handle: ".".concat(ns, "Selections-dragbar"),
            ghostClass: "".concat(ns, "Selections-item--dragging"),
            onEnd: function (e) {
                var _b, _c;
                // 没有移动
                if (e.newIndex === e.oldIndex) {
                    return;
                }
                // 换回来
                var parent = e.to;
                if (e.oldIndex < parent.childNodes.length - 1) {
                    parent.insertBefore(e.item, parent.childNodes[e.oldIndex > e.newIndex ? e.oldIndex + 1 : e.oldIndex]);
                }
                else {
                    parent.appendChild(e.item);
                }
                var value = _this.props.value;
                if (!Array.isArray(value)) {
                    return;
                }
                var newValue = value.concat();
                newValue.splice(e.newIndex, 0, newValue.splice(e.oldIndex, 1)[0]);
                (_c = (_b = _this.props).onChange) === null || _c === void 0 ? void 0 : _c.call(_b, newValue);
            }
        });
    };
    ResultList.prototype.desposeSortable = function () {
        var _b;
        (_b = this.sortable) === null || _b === void 0 ? void 0 : _b.destroy();
        delete this.sortable;
    };
    ResultList.prototype.handleValueChange = function (index, value, name) {
        var _b;
        if (typeof name !== 'string') {
            return;
        }
        var _c = this.props, list = _c.value, onChange = _c.onChange;
        var result = Array.isArray(list) ? list.concat() : [];
        if (!result[index]) {
            return;
        }
        result.splice(index, 1, tslib.__assign(tslib.__assign({}, result[index]), (_b = {}, _b[name] = value, _b)));
        onChange === null || onChange === void 0 ? void 0 : onChange(result, true);
    };
    ResultList.prototype.search = function (inputValue) {
        var _b = this.props, onSearch = _b.onSearch, value = _b.value;
        var searchResult = (value || []).filter(function (item) { return onSearch && onSearch(inputValue, item); });
        this.setState({ searchResult: searchResult });
    };
    ResultList.prototype.clearSearch = function () {
        this.setState({ searchResult: null });
    };
    ResultList.prototype.clearInput = function () {
        var _b, _c;
        if (this.props.searchable) {
            (_c = (_b = this.searchRef) === null || _b === void 0 ? void 0 : _b.clearInput) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
        this.clearSearch();
    };
    // 删除项
    ResultList.prototype.handleCloseItem = function (e, option) {
        var _b = this.props, value = _b.value, onChange = _b.onChange, disabled = _b.disabled, searchable = _b.searchable, _c = _b.valueField, valueField = _c === void 0 ? 'value' : _c;
        if (disabled || option.disabled) {
            return;
        }
        var searchResult = this.state.searchResult;
        // 结果搜索
        if (searchable && searchResult) {
            // 删除普通值
            var valueArray = cloneDeep__default["default"](value) || [];
            var idx = valueArray.findIndex(function (item) { return item[valueField] === option[valueField]; });
            if (idx > -1) {
                valueArray.splice(idx, 1);
                onChange && onChange(valueArray);
            }
            // 删除搜索结果
            var searchIdx = parseInt(e.currentTarget.getAttribute('data-index'), 10);
            if (searchIdx > -1) {
                searchResult.splice(searchIdx, 1);
                this.setState({ searchResult: searchResult });
            }
        }
        // 没有搜索，走旧的删除方式
        else {
            var index = parseInt(e.currentTarget.getAttribute('data-index'), 10);
            var _d = this.props, value_1 = _d.value, onChange_1 = _d.onChange;
            if (!Array.isArray(value_1)) {
                return;
            }
            var newValue = value_1.concat();
            newValue.splice(index, 1);
            onChange_1 === null || onChange_1 === void 0 ? void 0 : onChange_1(newValue);
        }
    };
    ResultList.prototype.renderOption = function (option, index, value, styles) {
        var _this = this;
        if (styles === void 0) { styles = {}; }
        var _b = this.props, cx = _b.classnames, itemRender = _b.itemRender, disabled = _b.disabled, itemClassName = _b.itemClassName, sortable = _b.sortable, labelField = _b.labelField; _b.translate; var showInvalidMatch = _b.showInvalidMatch, testIdBuilder = _b.testIdBuilder;
        var itemTIB = testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("item-".concat(option.value || index));
        return (_J$X_("div", { style: styles, className: cx('Selections-item', itemClassName, option === null || option === void 0 ? void 0 : option.className), key: index },
            sortable && !disabled && value.length > 1 ? (_J$X_(icons.Icon, { className: cx('Selections-dragbar icon'), icon: "drag-bar" })) : null,
            _J$X_("label", { className: cx('Selections-label', {
                    'is-invalid': showInvalidMatch ? option === null || option === void 0 ? void 0 : option.__unmatched : false
                }) }, itemRender(option, {
                index: index,
                disabled: disabled,
                onChange: this.handleValueChange.bind(this, index),
                labelField: labelField,
                classnames: cx
            })),
            !disabled ? (_J$X_("a", tslib.__assign({ className: cx('Selections-delBtn'), "data-index": index, onClick: function (e) {
                    return _this.handleCloseItem(e, option);
                } }, itemTIB === null || itemTIB === void 0 ? void 0 : itemTIB.getChild('close').getTestId()),
                _J$X_(icons.Icon, { icon: "close", className: "icon" }))) : null));
    };
    ResultList.prototype.renderNormalList = function (value) {
        var _this = this;
        var _b = this.props, cx = _b.classnames, __ = _b.translate, placeholder = _b.placeholder, _c = _b.virtualThreshold, virtualThreshold = _c === void 0 ? 1000 : _c, _d = _b.itemHeight, itemHeight = _d === void 0 ? 30 : _d;
        return (_J$X_(React__default["default"].Fragment, null, Array.isArray(value) && value.length ? (_J$X_("div", { className: cx('Selections-items') }, value.length > virtualThreshold ? (_J$X_(AutoSizer["default"], null, function (_b) {
            var height = _b.height;
            return (_J$X_(index["default"], { height: height, itemCount: value.length, itemSize: itemHeight, renderItem: function (_b) {
                    var index = _b.index, style = _b.style;
                    var option = value[index];
                    if (!option) {
                        return null;
                    }
                    return _this.renderOption(option, index, value, tslib.__assign(tslib.__assign({}, style), { width: '100%' }));
                } }));
        })) : (value.map(function (option, index) {
            return _this.renderOption(option, index, value);
        })))) : (_J$X_("div", { className: cx('Selections-placeholder') }, __(placeholder)))));
    };
    ResultList.prototype.render = function () {
        var _b = this.props, cx = _b.classnames, className = _b.className, title = _b.title, searchable = _b.searchable, value = _b.value, __ = _b.translate, _c = _b.searchPlaceholder, searchPlaceholder = _c === void 0 ? __('Transfer.searchKeyword') : _c;
        var searchResult = this.state.searchResult;
        return (_J$X_("div", { className: cx('Selections', className) },
            title ? _J$X_("div", { className: cx('Selections-title') }, title) : null,
            searchable ? (_J$X_(TransferSearch["default"], { ref: this.domSearchRef, placeholder: searchPlaceholder, onSearch: this.search, onCancelSearch: this.clearSearch })) : null,
            this.renderNormalList(searchResult !== null ? searchResult : value)));
    };
    var _a;
    _a = ResultList;
    ResultList.defaultProps = {
        placeholder: 'placeholder.selectData',
        itemRender: _a.itemRender,
        searchPlaceholder: '',
        virtualThreshold: 100,
        itemHeight: 32
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], ResultList.prototype, "domSearchRef", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [String]),
        tslib.__metadata("design:returntype", void 0)
    ], ResultList.prototype, "search", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ResultList.prototype, "clearSearch", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ResultList.prototype, "clearInput", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object, Object]),
        tslib.__metadata("design:returntype", void 0)
    ], ResultList.prototype, "handleCloseItem", null);
    return ResultList;
}(React__default["default"].Component));
var ResultList$1 = amisCore.themeable(amisCore.localeable(ResultList));

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