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

import { __extends, __assign } from 'tslib';
import { BaseSelection } from './Selection.js';
import { noop, resolveVariable, themeable, localeable, uncontrollable } from 'amis-core';
import React__default from 'react';
import Checkbox from './Checkbox.js';
import VirtualList from './virtual-list/index.js';
import isEqual from 'lodash/isEqual';
import forEach from 'lodash/forEach';
import AutoSizer from './virtual-list/AutoSizer.js';

var TableSelection = /** @class */ (function (_super) {
    __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 = 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 (React__default.createElement(React__default.Fragment, null,
            React__default.createElement("thead", null,
                React__default.createElement("tr", null,
                    multiple && Array.isArray(options) && options.length ? (React__default.createElement("th", { className: cx('Table-checkCell') },
                        React__default.createElement(Checkbox, { 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 (React__default.createElement("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 (React__default.createElement("tr", { style: styles !== null && styles !== void 0 ? styles : {}, key: rowIndex, 
            /** 被ResultTableList引用，如果设置click事件，会导致错误删除结果列表的内容，先加一个开关判断 */
            onClick: resultMode
                ? 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 ? (React__default.createElement("td", { className: cx('Table-checkCell'), key: "checkbox", onClick: function (e) {
                    e.stopPropagation();
                    _this.toggleOption(option);
                } },
                React__default.createElement(Checkbox, { size: "sm", checked: checked, disabled: disabled, testIdBuilder: itemTIB }))) : null,
            columns.map(function (column, colIndex) { return (React__default.createElement("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 = BaseSelection.value2array(value, options, option2value);
        return (React__default.createElement("tbody", null, Array.isArray(options) && options.length ? (options.map(function (option, rowIndex) {
            return _this.renderTr({ option: option, rowIndex: rowIndex, valueArray: valueArray, columns: columns });
        })) : (React__default.createElement("tr", null,
            React__default.createElement("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(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 = 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 = startIndex; index <= stopIndex; index++) {
                var option = options[index];
                if (!option) {
                    break;
                }
                trs.push(this.renderTr({
                    option: option,
                    rowIndex: index,
                    valueArray: valueArray,
                    columns: columns,
                    styles: {
                        height: "".concat(itemHeight, "px")
                    }
                }));
            }
            tableList = (React__default.createElement("table", { className: cx('Table-table'), style: {
                    marginTop: (startIndex || 0) * itemHeight + 'px'
                } },
                this.state.colsWidth.length ? (React__default.createElement("colgroup", null, this.state.colsWidth.map(function (colWidth, index) { return (React__default.createElement("col", { style: { width: "".concat(colWidth, "px") }, key: "col-".concat(index) })); }))) : null,
                React__default.createElement("tbody", null, trs)));
        }
        return (React__default.createElement("div", { className: cx('Table-content', 'is-virtual') },
            React__default.createElement("table", { className: cx('Table-table'), ref: this.tableHeadRef.bind(this) }, this.renderTHead()),
            React__default.createElement("div", { className: cx('Table-content-virtual') },
                React__default.createElement(AutoSizer, { minHeight: virtualListHeight, onResize: this.handleVirtualTableResize.bind(this) }, function (_a) {
                    var height = _a.height;
                    return (React__default.createElement(VirtualList, { onItemsRendered: function (res) {
                            if (!isEqual(_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 (__assign(__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()) : (React__default.createElement("div", { className: cx('Table-content') },
            React__default.createElement("table", { className: cx('Table-table') },
                this.renderTHead(),
                this.renderTBody())));
        return React__default.createElement("div", { className: cx('TableSelection', className) }, table);
    };
    TableSelection.defaultProps = __assign(__assign({}, BaseSelection.defaultProps), { cellRender: function (column, option, colIndex, rowIndex) { return React__default.createElement("span", null, resolveVariable(column.name, option)); } });
    return TableSelection;
}(BaseSelection));
var TableCheckboxes = themeable(localeable(uncontrollable(TableSelection, {
    value: 'onChange'
})));

export { TableSelection, TableCheckboxes as default };
