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

'use strict';

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

var tslib = require('tslib');
var Selection = require('./Selection.js');
var amisCore = require('amis-core');
var React = require('react');
var Checkbox = require('./Checkbox.js');
var index = require('./virtual-list/index.js');
var isEqual = require('lodash/isEqual');
var forEach = require('lodash/forEach');
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 isEqual__default = /*#__PURE__*/_interopDefaultLegacy(isEqual);
var forEach__default = /*#__PURE__*/_interopDefaultLegacy(forEach);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var TableSelection = /** @class */ (function (_super) {
    tslib.__extends(TableSelection, _super);
    function TableSelection(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            rowRenderScope: null,
            colsWidth: [],
            tableWidth: 0
        };
        return _this;
    }
    TableSelection.prototype.getColumns = function () {
        var columns = this.props.columns;
        if (!Array.isArray(columns) || !columns.length) {
            columns = [{ label: 'Label', name: 'label' }];
        }
        return columns;
    };
    TableSelection.prototype.renderTHead = function () {
        var _a = this.props, options = _a.options, cx = _a.classnames, value = _a.value, disabled = _a.disabled, option2value = _a.option2value, multiple = _a.multiple, testIdBuilder = _a.testIdBuilder;
        var columns = this.getColumns();
        var valueArray = Selection.BaseSelection.value2array(value, options, option2value);
        var availableOptions = options.filter(function (option) { return !option.disabled; });
        var partialChecked = false;
        var allChecked = !!availableOptions.length;
        availableOptions.forEach(function (option) {
            var isIn = !!~valueArray.indexOf(option);
            if (isIn && !partialChecked) {
                partialChecked = true;
            }
            else if (!isIn && allChecked) {
                allChecked = false;
            }
        });
        return (_J$X_(React__default["default"].Fragment, null,
            _J$X_("thead", null,
                _J$X_("tr", null,
                    multiple && Array.isArray(options) && options.length ? (_J$X_("th", { className: cx('Table-checkCell') },
                        _J$X_(Checkbox["default"], { key: "checkbox", size: "sm", disabled: disabled, onChange: this.toggleAll, checked: partialChecked, partial: partialChecked && !allChecked, testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('check-all') }))) : null,
                    columns.map(function (column, index) { return (_J$X_("th", { key: index }, column.label)); })))));
    };
    TableSelection.prototype.renderTr = function (_a) {
        var _this = this;
        var option = _a.option, rowIndex = _a.rowIndex, valueArray = _a.valueArray, columns = _a.columns, styles = _a.styles;
        var _b = this.props, cx = _b.classnames, cellRender = _b.cellRender, disabled = _b.disabled, multiple = _b.multiple; _b.translate; var itemClassName = _b.itemClassName, resultMode = _b.resultMode, testIdBuilder = _b.testIdBuilder;
        var checked = valueArray.indexOf(option) !== -1;
        var itemTIB = testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("item-".concat(option.value || rowIndex));
        return (_J$X_("tr", { style: styles !== null && styles !== void 0 ? styles : {}, key: rowIndex, 
            /** 被ResultTableList引用，如果设置click事件，会导致错误删除结果列表的内容，先加一个开关判断 */
            onClick: resultMode
                ? amisCore.noop
                : function (e) { return e.defaultPrevented || _this.toggleOption(option); }, className: cx(itemClassName, option.className, disabled || option.disabled ? 'is-disabled' : '', !!~valueArray.indexOf(option) ? 'is-active' : '') },
            multiple ? (_J$X_("td", { className: cx('Table-checkCell'), key: "checkbox", onClick: function (e) {
                    e.stopPropagation();
                    _this.toggleOption(option);
                } },
                _J$X_(Checkbox["default"], { size: "sm", checked: checked, disabled: disabled, testIdBuilder: itemTIB }))) : null,
            columns.map(function (column, colIndex) { return (_J$X_("td", { key: colIndex }, cellRender(column, option, colIndex, rowIndex))); })));
    };
    TableSelection.prototype.renderTBody = function () {
        var _this = this;
        var _a = this.props, options = _a.options, placeholder = _a.placeholder, value = _a.value, option2value = _a.option2value, __ = _a.translate;
        var columns = this.getColumns();
        var valueArray = Selection.BaseSelection.value2array(value, options, option2value);
        return (_J$X_("tbody", null, Array.isArray(options) && options.length ? (options.map(function (option, rowIndex) {
            return _this.renderTr({ option: option, rowIndex: rowIndex, valueArray: valueArray, columns: columns });
        })) : (_J$X_("tr", null,
            _J$X_("td", { colSpan: columns.length }, __(placeholder))))));
    };
    TableSelection.prototype.tableHeadRef = function (ref) {
        ref && (this.ref = ref);
    };
    TableSelection.prototype.handleVirtualTableResize = function (_a) {
        var width = _a.width;
        if (width && width === this.state.width) {
            return;
        }
        var widths = {};
        this.ref &&
            forEach__default["default"](this.ref.querySelectorAll('thead>tr:last-child>th'), function (item, index) {
                widths[index] = item.getBoundingClientRect().width;
            });
        var colsWidth = [];
        Object.keys(widths)
            .filter(function (key) { return !isNaN(Number(key)); })
            .sort()
            .forEach(function (key) {
            colsWidth.push(widths[key]);
        });
        this.setState({ colsWidth: colsWidth, tableWidth: width });
    };
    TableSelection.prototype.renderVirtualTable = function () {
        var _this = this;
        var _a = this.props, options = _a.options, value = _a.value, cx = _a.classnames, option2value = _a.option2value; _a.translate; var _b = _a.itemHeight, itemHeight = _b === void 0 ? 30 : _b, virtualListHeight = _a.virtualListHeight;
        var columns = this.getColumns();
        var valueArray = Selection.BaseSelection.value2array(value, options, option2value);
        var _c = this.state.rowRenderScope || {}, _d = _c.startIndex, startIndex = _d === void 0 ? 0 : _d, _e = _c.stopIndex, stopIndex = _e === void 0 ? 10 : _e;
        var tableList = null;
        if (startIndex !== undefined && stopIndex !== undefined) {
            var trs = [];
            for (var index$1 = startIndex; index$1 <= stopIndex; index$1++) {
                var option = options[index$1];
                if (!option) {
                    break;
                }
                trs.push(this.renderTr({
                    option: option,
                    rowIndex: index$1,
                    valueArray: valueArray,
                    columns: columns,
                    styles: {
                        height: "".concat(itemHeight, "px")
                    }
                }));
            }
            tableList = (_J$X_("table", { className: cx('Table-table'), style: {
                    marginTop: (startIndex || 0) * itemHeight + 'px'
                } },
                this.state.colsWidth.length ? (_J$X_("colgroup", null, this.state.colsWidth.map(function (colWidth, index) { return (_J$X_("col", { style: { width: "".concat(colWidth, "px") }, key: "col-".concat(index) })); }))) : null,
                _J$X_("tbody", null, trs)));
        }
        return (_J$X_("div", { className: cx('Table-content', 'is-virtual') },
            _J$X_("table", { className: cx('Table-table'), ref: this.tableHeadRef.bind(this) }, this.renderTHead()),
            _J$X_("div", { className: cx('Table-content-virtual') },
                _J$X_(AutoSizer["default"], { minHeight: virtualListHeight, onResize: this.handleVirtualTableResize.bind(this) }, function (_a) {
                    var height = _a.height;
                    return (_J$X_(index["default"], { onItemsRendered: function (res) {
                            if (!isEqual__default["default"](_this.state.rowRenderScope, res)) {
                                // 需要延后执行，否则报 warning
                                setTimeout(function () {
                                    _this.setState({
                                        rowRenderScope: res
                                    });
                                });
                            }
                        }, height: height, itemCount: options.length, itemSize: itemHeight, WrapperComponent: "div", InnerComponent: "div", prefix: tableList, innerStyleFilter: function (styles) { return (tslib.__assign(tslib.__assign({}, styles), { position: 'absolute', top: 0, minWidth: undefined, width: '1px', visibility: 'hidden' })); }, renderItem: function () { return null; } }));
                }))));
    };
    TableSelection.prototype.render = function () {
        var _a = this.props, className = _a.className, cx = _a.classnames, options = _a.options, _b = _a.virtualThreshold, virtualThreshold = _b === void 0 ? 1000 : _b;
        var table = Array.isArray(options) && options.length > virtualThreshold ? (this.renderVirtualTable()) : (_J$X_("div", { className: cx('Table-content') },
            _J$X_("table", { className: cx('Table-table') },
                this.renderTHead(),
                this.renderTBody())));
        return _J$X_("div", { className: cx('TableSelection', className) }, table);
    };
    TableSelection.defaultProps = tslib.__assign(tslib.__assign({}, Selection.BaseSelection.defaultProps), { cellRender: function (column, option, colIndex, rowIndex) { return _J$X_("span", null, amisCore.resolveVariable(column.name, option)); } });
    return TableSelection;
}(Selection.BaseSelection));
var TableCheckboxes = amisCore.themeable(amisCore.localeable(amisCore.uncontrollable(TableSelection, {
    value: 'onChange'
})));

exports.TableSelection = TableSelection;
exports["default"] = TableCheckboxes;
