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

'use strict';

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

var tslib = require('tslib');
var amisCore = require('amis-core');
var React = require('react');
var reactHookForm = require('react-hook-form');
var useSubForm = require('../hooks/use-sub-form.js');
var Button = require('./Button.js');
var FormField = require('./FormField.js');
var icons = require('./icons.js');

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

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
function InputTable(_a) {
    var _this = this;
    var _b, _c;
    var control = _a.control, name = _a.name, wrap = _a.wrap, mode = _a.mode, label = _a.label, labelAlign = _a.labelAlign, labelClassName = _a.labelClassName, description = _a.description, fieldClassName = _a.fieldClassName, className = _a.className, __ = _a.translate, cx = _a.classnames, removable = _a.removable, columns = _a.columns, addable = _a.addable, addButtonText = _a.addButtonText, addButtonClassName = _a.addButtonClassName, addButtonProps = _a.addButtonProps, scaffold = _a.scaffold, minLength = _a.minLength, maxLength = _a.maxLength, isRequired = _a.isRequired, rules = _a.rules, tableClassName = _a.tableClassName, tableHeadClassName = _a.tableHeadClassName, tableBodyClassName = _a.tableBodyClassName, placeholder = _a.placeholder, scroll = _a.scroll, footer = _a.footer, onItemAdd = _a.onItemAdd;
    var enableScroll = (scroll === null || scroll === void 0 ? void 0 : scroll.y) != null;
    var tBodyRef = React__default["default"].useRef(null);
    var tableRef = React__default["default"].useRef(null);
    var subForms = React__default["default"].useRef({});
    var subFormRef = React__default["default"].useCallback(function (subform, id) {
        if (subform) {
            subForms.current[id] = subform;
        }
        else {
            delete subForms.current[id];
        }
    }, [subForms]);
    var popOverContainer = React__default["default"].useCallback(function () {
        return tBodyRef.current;
    }, [tBodyRef]);
    var finalRules = tslib.__assign({}, rules);
    if (isRequired) {
        finalRules.required = true;
    }
    if (minLength) {
        finalRules.minLength = minLength;
    }
    if (maxLength) {
        finalRules.maxLength = maxLength;
    }
    finalRules.validate = React__default["default"].useCallback(function (items) { return tslib.__awaiter(_this, void 0, void 0, function () {
        var map, result, _a, _b, key, valid, e_1_1;
        var e_1, _c;
        return tslib.__generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    map = subForms.current;
                    if (!(typeof (rules === null || rules === void 0 ? void 0 : rules.validate) === 'function')) return [3 /*break*/, 2];
                    return [4 /*yield*/, rules.validate(items)];
                case 1:
                    result = _d.sent();
                    if (result) {
                        return [2 /*return*/, result];
                    }
                    _d.label = 2;
                case 2:
                    _d.trys.push([2, 7, 8, 9]);
                    _a = tslib.__values(Object.keys(map)), _b = _a.next();
                    _d.label = 3;
                case 3:
                    if (!!_b.done) return [3 /*break*/, 6];
                    key = _b.value;
                    return [4 /*yield*/, (function (methods) {
                            return new Promise(function (resolve) {
                                methods.handleSubmit(function () { return resolve(true); }, function () { return resolve(false); })();
                            });
                        })(map[key])];
                case 4:
                    valid = _d.sent();
                    if (!valid) {
                        return [2 /*return*/, __('validateFailed')];
                    }
                    _d.label = 5;
                case 5:
                    _b = _a.next();
                    return [3 /*break*/, 3];
                case 6: return [3 /*break*/, 9];
                case 7:
                    e_1_1 = _d.sent();
                    e_1 = { error: e_1_1 };
                    return [3 /*break*/, 9];
                case 8:
                    try {
                        if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7 /*endfinally*/];
                case 9: return [2 /*return*/];
            }
        });
    }); }, [subForms]);
    var _d = reactHookForm.useFieldArray({
        control: control,
        name: name,
        rules: finalRules
    }), fields = _d.fields, append = _d.append; _d.update; var remove = _d.remove;
    if (!Array.isArray(columns)) {
        columns = [];
    }
    var errors = reactHookForm.useFormState({
        control: control
    }).errors;
    var _e = reactHookForm.useFormContext(); _e.trigger; var setValue = _e.setValue;
    // useFieldArray 的 update 会更新行 id，导致重新渲染
    // 正在编辑中的元素失去焦点，所以自己写一个
    var lightUpdate = React__default["default"].useCallback(function (index, value) {
        // const arr = control._getFieldArray(name);
        // arr[index] = {...value};
        // control._updateFieldArray(name, arr);
        // trigger(name);
        // control._subjects.watch.next({});
        setValue("".concat(name, ".").concat(index), value);
    }, [control]);
    function renderBody() {
        var handleItemAdd = function () {
            var values = tslib.__assign({}, scaffold);
            append(values);
            /** 开启滚动后新增元素定位到底部 */
            if (enableScroll && tableRef) {
                requestAnimationFrame(function () {
                    var _a, _b;
                    (_b = (_a = tableRef === null || tableRef === void 0 ? void 0 : tableRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, {
                        behavior: 'smooth',
                        block: 'end',
                        inline: 'nearest'
                    });
                });
            }
            onItemAdd === null || onItemAdd === void 0 ? void 0 : onItemAdd(values);
        };
        return (_J$X_("div", { className: cx("Table", "InputTable-UI", className) },
            _J$X_("div", { className: cx("Table-contentWrap", { 'is-fixed': enableScroll }), style: { maxHeight: enableScroll ? scroll.y : 'unset' }, ref: tBodyRef },
                _J$X_("div", { className: cx('Table-content') },
                    _J$X_("table", { className: cx("Table-table", tableClassName), ref: tableRef },
                        _J$X_("thead", { className: cx(tableHeadClassName) },
                            _J$X_("tr", null,
                                columns.map(function (item, index) { return (_J$X_("th", { key: index, className: item.className }, item.thRender ? item.thRender() : item.title)); }),
                                _J$X_("th", { key: "operation" }, __('Table.operation')))),
                        _J$X_("tbody", { className: cx(tableBodyClassName) }, fields.length ? (fields.map(function (field, index) { return (_J$X_("tr", { key: field.id },
                            _J$X_(InputTableRow, { key: "columns", control: control, update: lightUpdate, index: index, value: field, columns: columns, translate: __, classnames: cx, formRef: subFormRef, popOverContainer: popOverContainer }),
                            _J$X_("td", { key: "operation" },
                                _J$X_(Button["default"], { level: "link", key: "delete", disabled: removable === false ||
                                        !!(minLength && fields.length <= minLength), className: cx('Table-delBtn'), onClick: function () { return remove(index); } }, __('delete'))))); })) : (_J$X_("tr", null,
                            _J$X_("td", { colSpan: columns.length + 1 },
                                _J$X_(icons.Icon, { icon: "desk-empty", className: cx('Table-placeholder-empty-icon', 'icon') }), placeholder !== null && placeholder !== void 0 ? placeholder : __('placeholder.noData')))))))),
            addable !== false && (!maxLength || fields.length < maxLength) ? (_J$X_("div", { className: cx("InputTable-toolbar") },
                _J$X_(Button["default"], tslib.__assign({ className: cx(addButtonClassName), size: "sm" }, addButtonProps, { onClick: function () { return handleItemAdd(); } }),
                    _J$X_(icons.Icon, { icon: "plus", className: "icon" }),
                    _J$X_("span", null, __(addButtonText || 'add'))), footer === null || footer === void 0 ? void 0 :
                footer())) : null));
    }
    return wrap === false ? (renderBody()) : (_J$X_(FormField["default"], { className: fieldClassName, label: label, labelAlign: labelAlign, labelClassName: labelClassName, description: description, mode: mode, hasError: !!((_b = errors[name]) === null || _b === void 0 ? void 0 : _b.message), errors: (_c = errors[name]) === null || _c === void 0 ? void 0 : _c.message }, renderBody()));
}
var InputTableRow = React__default["default"].memo(function InputTableRow(_a) {
    var value = _a.value, columns = _a.columns, index = _a.index, translate = _a.translate, update = _a.update, formRef = _a.formRef; _a.classnames; var popOverContainer = _a.popOverContainer;
    var indexRef = React__default["default"].useRef(index);
    React__default["default"].useEffect(function () {
        indexRef.current = index;
    }, [index]);
    var methods = useSubForm["default"](value, translate, function (data) {
        return update(indexRef.current, data);
    });
    React__default["default"].useEffect(function () {
        formRef === null || formRef === void 0 ? void 0 : formRef(methods, value.id);
        return function () {
            formRef === null || formRef === void 0 ? void 0 : formRef(null, value.id);
        };
    }, [methods, value.id]);
    return (_J$X_(React__default["default"].Fragment, null, columns.map(function (item, colIndex) { return (_J$X_("td", { key: colIndex, className: item.className }, item.tdRender(tslib.__assign(tslib.__assign({}, methods), { popOverContainer: popOverContainer }), colIndex, index))); })));
});
var InputTable$1 = amisCore.themeable(amisCore.localeable(InputTable));

exports.InputTable = InputTable;
exports.InputTableRow = InputTableRow;
exports["default"] = InputTable$1;
