"use strict";

var __awaiter = this && this.__awaiter || function(thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))((function(resolve, reject) {
        function fulfilled(value) {
            try {
                step(generator.next(value));
            } catch (e) {
                reject(e);
            }
        }
        function rejected(value) {
            try {
                step(generator.throw(value));
            } catch (e) {
                reject(e);
            }
        }
        function step(result) {
            var value;
            result.done ? resolve(result.value) : (value = result.value, value instanceof P ? value : new P((function(resolve) {
                resolve(value);
            }))).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    }));
};

Object.defineProperty(exports, "__esModule", {
    value: !0
}), exports.listTableUpdateRecords = exports.listTableDeleteRecords = exports.listTableAddRecords = exports.listTableAddRecord = exports.sortRecords = exports.listTableChangeCellValuesByIds = exports.listTableChangeCellValues = exports.listTableChangeCellValue = void 0;

const compute_col_width_1 = require("../scenegraph/layout/compute-col-width"), compute_row_height_1 = require("../scenegraph/layout/compute-row-height"), helper_1 = require("../tools/helper"), util_1 = require("../tools/util"), TABLE_EVENT_TYPE_1 = require("./TABLE_EVENT_TYPE"), vutils_1 = require("@visactor/vutils");

function listTableChangeCellValue(col, row, value, workOnEditableCell, triggerEvent, table, silentChangeCellValuesEvent) {
    if (workOnEditableCell && table.isHasEditorDefine(col, row) || !1 === workOnEditableCell) {
        const recordShowIndex = table.getRecordShowIndexByCell(col, row), recordIndex = recordShowIndex >= 0 ? table.dataSource.getIndexKey(recordShowIndex) : void 0, {field: field} = table.internalProps.layoutMap.getBody(col, row), beforeChangeValue = table.getCellRawValue(col, row), oldValue = table.getCellOriginValue(col, row);
        table.isHeader(col, row) ? table.internalProps.layoutMap.updateColumnTitle(col, row, value) : table.dataSource.changeFieldValue(value, recordShowIndex, field, col, row, table);
        const range = table.getCellRange(col, row), aggregators = table.internalProps.layoutMap.getAggregatorsByCell(col, row);
        if (aggregators) {
            if (Array.isArray(aggregators)) for (let i = 0; i < (null == aggregators ? void 0 : aggregators.length); i++) aggregators[i].recalculate(); else aggregators.recalculate();
            const aggregatorCells = table.internalProps.layoutMap.getAggregatorCellAddress(range.start.col, range.start.row, range.end.col, range.end.row);
            for (let i = 0; i < aggregatorCells.length; i++) {
                const range = table.getCellRange(aggregatorCells[i].col, aggregatorCells[i].row);
                for (let sCol = range.start.col; sCol <= range.end.col; sCol++) for (let sRow = range.start.row; sRow <= range.end.row; sRow++) table.scenegraph.updateCellContent(sCol, sRow);
            }
        }
        for (let sCol = range.start.col; sCol <= range.end.col; sCol++) for (let sRow = range.start.row; sRow <= range.end.row; sRow++) table.scenegraph.updateCellContent(sCol, sRow);
        if ("adaptive" === table.widthMode || table.autoFillWidth && table.getAllColsWidth() <= table.tableNoFrameWidth) 0 === table.internalProps._widthResizedColMap.size && table.scenegraph.recalculateColWidths(); else if (!table.internalProps._widthResizedColMap.has(col)) {
            const oldWidth = table.getColWidth(col), newWidth = (0, compute_col_width_1.computeColWidth)(col, 0, table.rowCount - 1, table, !1);
            newWidth !== oldWidth && table.scenegraph.updateColWidth(col, newWidth - oldWidth);
        }
        if ("adaptive" === table.heightMode || table.autoFillHeight && table.getAllRowsHeight() <= table.tableNoFrameHeight) 0 === table.internalProps._heightResizedRowMap.size && table.scenegraph.recalculateRowHeights(); else if (table.isAutoRowHeight(row) && !table.internalProps._heightResizedRowMap.has(row)) {
            const oldHeight = table.getRowHeight(row), newHeight = (0, compute_row_height_1.computeRowHeight)(row, 0, table.colCount - 1, table);
            table.scenegraph.updateRowHeight(row, newHeight - oldHeight);
        }
        const changedValue = table.getCellOriginValue(col, row);
        if (oldValue !== changedValue && triggerEvent) {
            const changeValue = {
                col: col,
                row: row,
                recordIndex: recordIndex,
                field: field,
                rawValue: beforeChangeValue,
                currentValue: oldValue,
                changedValue: changedValue
            };
            table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.CHANGE_CELL_VALUE, changeValue), 
            silentChangeCellValuesEvent || table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.CHANGE_CELL_VALUES, {
                values: [ changeValue ]
            });
        }
        table.scenegraph.updateNextFrame();
    }
}

function listTableChangeCellValues(startCol, startRow, values, workOnEditableCell, triggerEvent, table, silentChangeCellValuesEvent) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, (function*() {
        const changedCellResults = [];
        let pasteColEnd = startCol, pasteRowEnd = startRow;
        const beforeChangeValues = [], oldValues = [];
        let cellUpdateType;
        for (let i = 0; i < values.length && !(startRow + i > table.rowCount - 1); i++) {
            const rowValues = values[i], rawRowValues = [], oldRowValues = [];
            beforeChangeValues.push(rawRowValues), oldValues.push(oldRowValues);
            for (let j = 0; j < rowValues.length && !(startCol + j > table.colCount - 1); j++) {
                cellUpdateType = getCellUpdateType(startCol + j, startRow + i, table, cellUpdateType);
                const beforeChangeValue = table.getCellRawValue(startCol + j, startRow + i);
                rawRowValues.push(beforeChangeValue);
                const oldValue = table.getCellOriginValue(startCol + j, startRow + i);
                oldRowValues.push(oldValue);
            }
        }
        const resultChangeValues = [];
        for (let i = 0; i < values.length && !(startRow + i > table.rowCount - 1); i++) {
            changedCellResults[i] = [], pasteRowEnd = startRow + i;
            const rowValues = values[i];
            let thisRowPasteColEnd = startCol;
            for (let j = 0; j < rowValues.length && !(startCol + j > table.colCount - 1); j++) {
                thisRowPasteColEnd = startCol + j;
                let isCanChange = !1;
                if (!1 === workOnEditableCell) isCanChange = !0; else if (table.isHasEditorDefine(startCol + j, startRow + i)) {
                    const editor = table.getEditor(startCol + j, startRow + i), oldValue = oldValues[i][j], value = rowValues[j], maybePromiseOrValue = null === (_b = null === (_a = null == editor ? void 0 : editor.validateValue) || void 0 === _a ? void 0 : _a.call(editor, value, oldValue, {
                        col: startCol + j,
                        row: startRow + i
                    }, table)) || void 0 === _b || _b;
                    if ((0, helper_1.isPromise)(maybePromiseOrValue)) {
                        const validateResult = yield maybePromiseOrValue;
                        isCanChange = !0 === validateResult || "validate-exit" === validateResult || "validate-not-exit" === validateResult;
                    } else isCanChange = !0 === maybePromiseOrValue || "validate-exit" === maybePromiseOrValue || "validate-not-exit" === maybePromiseOrValue;
                }
                if (isCanChange) {
                    changedCellResults[i][j] = !0;
                    const value = rowValues[j], recordShowIndex = table.getRecordShowIndexByCell(startCol + j, startRow + i), recordIndex = recordShowIndex >= 0 ? table.dataSource.getIndexKey(recordShowIndex) : void 0, {field: field} = table.internalProps.layoutMap.getBody(startCol + j, startRow + i), beforeChangeValue = beforeChangeValues[i][j], oldValue = oldValues[i][j];
                    table.isHeader(startCol + j, startRow + i) ? table.internalProps.layoutMap.updateColumnTitle(startCol + j, startRow + i, value) : table.dataSource.changeFieldValue(value, recordShowIndex, field, startCol + j, startRow + i, table);
                    const changedValue = table.getCellOriginValue(startCol + j, startRow + i);
                    if (oldValue !== changedValue && triggerEvent) {
                        const changeValue = {
                            col: startCol + j,
                            row: startRow + i,
                            recordIndex: recordIndex,
                            field: field,
                            rawValue: beforeChangeValue,
                            currentValue: oldValue,
                            changedValue: changedValue
                        };
                        table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.CHANGE_CELL_VALUE, changeValue), 
                        resultChangeValues.push(changeValue);
                    }
                } else changedCellResults[i][j] = !1;
            }
            pasteColEnd = Math.max(pasteColEnd, thisRowPasteColEnd);
        }
        silentChangeCellValuesEvent || table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.CHANGE_CELL_VALUES, {
            values: resultChangeValues
        });
        const startRange = table.getCellRange(startCol, startRow), range = table.getCellRange(pasteColEnd, pasteRowEnd), aggregators = table.internalProps.layoutMap.getAggregatorsByCellRange(startRange.start.col, startRange.start.row, range.end.col, range.end.row);
        if (aggregators) {
            for (let i = 0; i < (null == aggregators ? void 0 : aggregators.length); i++) aggregators[i].recalculate();
            if ("normal" === cellUpdateType) {
                const aggregatorCells = table.internalProps.layoutMap.getAggregatorCellAddress(startRange.start.col, startRange.start.row, range.end.col, range.end.row);
                for (let i = 0; i < aggregatorCells.length; i++) {
                    const range = table.getCellRange(aggregatorCells[i].col, aggregatorCells[i].row);
                    for (let sCol = range.start.col; sCol <= range.end.col; sCol++) for (let sRow = range.start.row; sRow <= range.end.row; sRow++) table.scenegraph.updateCellContent(sCol, sRow);
                }
            }
        }
        if ("group" === cellUpdateType && table.dataSource.updateRecordsForGroup([], []), 
        "sort" === cellUpdateType || "group" === cellUpdateType) return table.dataSource.sortedIndexMap.clear(), 
        sortRecords(table), table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(), changedCellResults;
        for (let sCol = startRange.start.col; sCol <= range.end.col; sCol++) for (let sRow = startRange.start.row; sRow <= range.end.row; sRow++) table.scenegraph.updateCellContent(sCol, sRow);
        if ("adaptive" === table.widthMode || table.autoFillWidth && table.getAllColsWidth() <= table.tableNoFrameWidth) 0 === table.internalProps._widthResizedColMap.size && table.scenegraph.recalculateColWidths(); else for (let sCol = startCol; sCol <= range.end.col; sCol++) if (!table.internalProps._widthResizedColMap.has(sCol)) {
            const oldWidth = table.getColWidth(sCol), newWidth = (0, compute_col_width_1.computeColWidth)(sCol, 0, table.rowCount - 1, table, !1);
            newWidth !== oldWidth && table.scenegraph.updateColWidth(sCol, newWidth - oldWidth);
        }
        if ("adaptive" === table.heightMode || table.autoFillHeight && table.getAllRowsHeight() <= table.tableNoFrameHeight) table.scenegraph.recalculateRowHeights(); else if (table.isAutoRowHeight(startRow)) {
            const rows = [], deltaYs = [];
            for (let sRow = startRow; sRow <= range.end.row; sRow++) if (table.rowHeightsMap.get(sRow)) {
                const oldHeight = table.getRowHeight(sRow), newHeight = (0, compute_row_height_1.computeRowHeight)(sRow, 0, table.colCount - 1, table);
                rows.push(sRow), deltaYs.push(newHeight - oldHeight);
            }
            table.scenegraph.updateRowsHeight(rows, deltaYs);
        }
        return table.scenegraph.updateNextFrame(), changedCellResults;
    }));
}

function listTableChangeCellValuesByIds(ranges, value, workOnEditableCell, triggerEvent, table, silentChangeCellValuesEvent) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, (function*() {
        const resultChangeValues = [], processed = new Set, nextValue = null != value ? value : "";
        for (let i = 0; i < (null !== (_a = null == ranges ? void 0 : ranges.length) && void 0 !== _a ? _a : 0); i++) {
            const range = ranges[i], startCol = Math.min(range.start.col, range.end.col), endCol = Math.max(range.start.col, range.end.col), startRow = Math.min(range.start.row, range.end.row), endRow = Math.max(range.start.row, range.end.row);
            if (startCol > endCol || startRow > endRow) continue;
            const values = [], oldValues = [];
            for (let row = startRow; row <= endRow; row++) {
                const rowValues = [], rowOldValues = [];
                for (let col = startCol; col <= endCol; col++) rowValues.push(nextValue), rowOldValues.push(table.getCellOriginValue(col, row));
                values.push(rowValues), oldValues.push(rowOldValues);
            }
            const changedCellResults = yield listTableChangeCellValues(startCol, startRow, values, workOnEditableCell, triggerEvent, table, !0);
            for (let r = 0; r < values.length; r++) for (let c = 0; c < values[r].length; c++) {
                const col = startCol + c, row = startRow + r, key = `${col},${row}`;
                if (processed.has(key)) continue;
                if (processed.add(key), !triggerEvent || !(null === (_b = null == changedCellResults ? void 0 : changedCellResults[r]) || void 0 === _b ? void 0 : _b[c])) continue;
                const oldValue = oldValues[r][c], changedValue = table.getCellOriginValue(col, row);
                if (oldValue === changedValue) continue;
                const recordShowIndex = table.getRecordShowIndexByCell(col, row), recordIndex = recordShowIndex >= 0 ? table.dataSource.getIndexKey(recordShowIndex) : void 0, {field: field} = table.internalProps.layoutMap.getBody(col, row);
                resultChangeValues.push({
                    col: col,
                    row: row,
                    recordIndex: recordIndex,
                    field: field,
                    rawValue: oldValue,
                    currentValue: oldValue,
                    changedValue: changedValue
                });
            }
        }
        !silentChangeCellValuesEvent && triggerEvent && table.fireListeners(TABLE_EVENT_TYPE_1.TABLE_EVENT_TYPE.CHANGE_CELL_VALUES, {
            values: resultChangeValues
        });
    }));
}

function getCellUpdateType(col, row, table, oldCellUpdateType) {
    if ("group" === oldCellUpdateType) return oldCellUpdateType;
    if ("sort" === oldCellUpdateType && !table.internalProps.groupBy) return oldCellUpdateType;
    let cellUpdateType = "normal";
    if (table.internalProps.groupBy) cellUpdateType = "group"; else if (!table.isHeader(col, row) && table.dataSource.lastOrderField) {
        table.getBodyField(col, row) === table.dataSource.lastOrderField && (cellUpdateType = "sort");
    }
    return cellUpdateType;
}

function sortRecords(table) {
    let sortState = table.sortState;
    sortState = !sortState || Array.isArray(sortState) ? sortState : [ sortState ], 
    sortState && (sortState = sortState.map((item => {
        var _a;
        return item.orderFn = null !== (_a = table._getSortFuncFromHeaderOption(void 0, item.field)) && void 0 !== _a ? _a : util_1.defaultOrderFn, 
        item;
    })), table.dataSource.sort(sortState));
}

function listTableAddRecord(record, recordIndex, table) {
    var _a, _b, _c, _d, _e, _f;
    try {
        if (!record) return !1;
        if (table.internalProps.groupBy) null === (_b = (_a = table.dataSource).addRecordsForGroup) || void 0 === _b || _b.call(_a, [ record ], recordIndex), 
        table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if ("tree" === table.dataSource.rowHierarchyType) null === (_d = (_c = table.dataSource).addRecordsForTree) || void 0 === _d || _d.call(_c, [ record ], recordIndex), 
        adjustCheckBoxStateMapWithAddRecordIndex(table, recordIndex, 1), table.refreshRowColCount(), 
        table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if (table.sortState) {
            !!(null === (_e = table.options) || void 0 === _e ? void 0 : _e.syncRecordOperationsToSourceRecords) ? table.dataSource.addRecord(record, table.dataSource.records.length, !0) : table.dataSource.addRecordForSorted(record), 
            table.stateManager.checkedState.clear(), sortRecords(table), table.refreshRowColCount(), 
            table.scenegraph.clearCells(), table.scenegraph.createSceneGraph();
        } else {
            (void 0 === recordIndex || recordIndex > table.dataSource.sourceLength) && (recordIndex = table.dataSource.sourceLength);
            const headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, syncToOriginalRecords = !!(null === (_f = table.options) || void 0 === _f ? void 0 : _f.syncRecordOperationsToSourceRecords);
            if (table.dataSource.addRecord(record, recordIndex, syncToOriginalRecords), adjustCheckBoxStateMapWithAddRecordIndex(table, recordIndex, 1), 
            syncToOriginalRecords) return table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), 
            table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(), !0;
            const oldRowCount = table.rowCount;
            if (table.refreshRowColCount(), 0 === table.scenegraph.proxy.totalActualBodyRowCount) return table.scenegraph.clearCells(), 
            table.scenegraph.createSceneGraph(), !0;
            const newRowCount = table.transpose ? table.colCount : table.rowCount;
            if (table.pagination) {
                const {perPageCount: perPageCount, currentPage: currentPage} = table.pagination, endIndex = perPageCount * (currentPage || 0) + perPageCount;
                if (recordIndex < endIndex) if (recordIndex < endIndex - perPageCount) table.scenegraph.clearCells(), 
                table.scenegraph.createSceneGraph(); else {
                    const rowNum = recordIndex - (endIndex - perPageCount) + headerCount;
                    if (oldRowCount - headerCount === table.pagination.perPageCount) {
                        const updateRows = [];
                        for (let row = rowNum; row < newRowCount; row++) table.transpose ? updateRows.push({
                            col: row,
                            row: 0
                        }) : updateRows.push({
                            col: 0,
                            row: row
                        });
                        table.transpose ? table.scenegraph.updateCol([], [], updateRows) : table.scenegraph.updateRow([], [], updateRows);
                    } else {
                        const addRows = [];
                        for (let row = rowNum; row < Math.min(newRowCount, rowNum + 1); row++) table.transpose ? addRows.push({
                            col: row,
                            row: 0
                        }) : addRows.push({
                            col: 0,
                            row: row
                        });
                        table.transpose ? table.scenegraph.updateCol([], addRows, []) : table.scenegraph.updateRow([], addRows, []);
                    }
                }
            } else {
                const addRows = [];
                for (let row = recordIndex + headerCount; row < recordIndex + headerCount + 1; row++) table.transpose ? addRows.push({
                    col: row,
                    row: 0
                }) : addRows.push({
                    col: 0,
                    row: row
                });
                const updateRows = [], topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, bottomAggregationCount = table.internalProps.layoutMap.hasAggregationOnBottomCount;
                for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                for (let row = (table.transpose ? table.colCount : table.rowCount) - bottomAggregationCount; row < (table.transpose ? table.colCount : table.rowCount); row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                table.transpose ? table.scenegraph.updateCol([], addRows, []) : table.scenegraph.updateRow([], addRows, []);
            }
        }
        return !0;
    } catch (error) {
        return !1;
    }
}

function listTableAddRecords(records, recordIndex, table) {
    var _a, _b, _c, _d, _e, _f;
    try {
        if (!records || 0 === records.length) return !1;
        if (table.internalProps.groupBy) null === (_b = (_a = table.dataSource).addRecordsForGroup) || void 0 === _b || _b.call(_a, records, recordIndex), 
        table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if ("tree" === table.dataSource.rowHierarchyType) null === (_d = (_c = table.dataSource).addRecordsForTree) || void 0 === _d || _d.call(_c, records, recordIndex), 
        adjustCheckBoxStateMapWithAddRecordIndex(table, recordIndex, records.length), table.refreshRowColCount(), 
        table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if (table.sortState) {
            !!(null === (_e = table.options) || void 0 === _e ? void 0 : _e.syncRecordOperationsToSourceRecords) ? table.dataSource.addRecords(records, table.dataSource.records.length, !0) : table.dataSource.addRecordsForSorted(records), 
            sortRecords(table), table.refreshRowColCount(), table.scenegraph.clearCells(), table.scenegraph.createSceneGraph();
        } else {
            void 0 === recordIndex || recordIndex > table.dataSource.sourceLength ? recordIndex = table.dataSource.sourceLength : recordIndex < 0 && (recordIndex = 0);
            const headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, syncToOriginalRecords = !!(null === (_f = table.options) || void 0 === _f ? void 0 : _f.syncRecordOperationsToSourceRecords);
            if (table.dataSource.addRecords(records, recordIndex, syncToOriginalRecords), adjustCheckBoxStateMapWithAddRecordIndex(table, recordIndex, records.length), 
            syncToOriginalRecords) return table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), 
            table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(), !0;
            const oldRowCount = table.transpose ? table.colCount : table.rowCount;
            if (table.refreshRowColCount(), 0 === table.scenegraph.proxy.totalActualBodyRowCount) return table.scenegraph.clearCells(), 
            table.scenegraph.createSceneGraph(), !0;
            const newRowCount = table.transpose ? table.colCount : table.rowCount;
            if (table.pagination) {
                const {perPageCount: perPageCount, currentPage: currentPage} = table.pagination, endIndex = perPageCount * (currentPage || 0) + perPageCount;
                if (recordIndex < endIndex) if (recordIndex < endIndex - perPageCount) table.scenegraph.clearCells(), 
                table.scenegraph.createSceneGraph(); else {
                    const rowNum = recordIndex - (endIndex - perPageCount) + headerCount;
                    if (oldRowCount - headerCount === table.pagination.perPageCount) {
                        const updateRows = [];
                        for (let row = rowNum; row < newRowCount; row++) table.transpose ? updateRows.push({
                            col: row,
                            row: 0
                        }) : updateRows.push({
                            col: 0,
                            row: row
                        });
                        table.transpose ? table.scenegraph.updateCol([], [], updateRows) : table.scenegraph.updateRow([], [], updateRows);
                    } else {
                        const addRows = [];
                        for (let row = rowNum; row < Math.min(newRowCount, rowNum + (Array.isArray(records) ? records.length : 1)); row++) table.transpose ? addRows.push({
                            col: row,
                            row: 0
                        }) : addRows.push({
                            col: 0,
                            row: row
                        });
                        table.transpose ? table.scenegraph.updateCol([], addRows, []) : table.scenegraph.updateRow([], addRows, []);
                    }
                }
            } else {
                const addRows = [];
                for (let row = recordIndex + headerCount; row < recordIndex + headerCount + (Array.isArray(records) ? records.length : 1); row++) table.transpose ? addRows.push({
                    col: row,
                    row: 0
                }) : addRows.push({
                    col: 0,
                    row: row
                });
                const topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, bottomAggregationCount = table.internalProps.layoutMap.hasAggregationOnBottomCount, updateRows = [];
                for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                for (let row = (table.transpose ? table.colCount : table.rowCount) - bottomAggregationCount; row < (table.transpose ? table.colCount : table.rowCount); row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                table.transpose ? table.scenegraph.updateCol([], addRows, updateRows) : table.scenegraph.updateRow([], addRows, updateRows);
            }
        }
        return !0;
    } catch (error) {
        return !1;
    }
}

function listTableDeleteRecords(recordIndexs, table) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    if ((null == recordIndexs ? void 0 : recordIndexs.length) > 0) if (table.internalProps.groupBy) null === (_b = (_a = table.dataSource).deleteRecordsForGroup) || void 0 === _b || _b.call(_a, recordIndexs), 
    table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
    table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if ("tree" === table.dataSource.rowHierarchyType) {
        const deletedRecordIndexs = null === (_d = (_c = table.dataSource).deleteRecordsForTree) || void 0 === _d ? void 0 : _d.call(_c, recordIndexs);
        if (0 === deletedRecordIndexs.length) return;
        for (let index = 0; index < deletedRecordIndexs.length; index++) adjustCheckBoxStateMapWithDeleteRecordIndex(table, deletedRecordIndexs[index], 1);
        table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
        table.scenegraph.clearCells(), table.scenegraph.createSceneGraph();
    } else if (table.sortState) {
        !!(null === (_e = table.options) || void 0 === _e ? void 0 : _e.syncRecordOperationsToSourceRecords) ? table.dataSource.deleteRecords(recordIndexs, !0) : table.dataSource.deleteRecordsForSorted(recordIndexs), 
        sortRecords(table), table.refreshRowColCount(), table.scenegraph.clearCells(), table.scenegraph.createSceneGraph();
    } else {
        const syncToOriginalRecords = !!(null === (_f = table.options) || void 0 === _f ? void 0 : _f.syncRecordOperationsToSourceRecords), deletedRecordIndexs = table.dataSource.deleteRecords(recordIndexs, syncToOriginalRecords);
        if (0 === deletedRecordIndexs.length) return;
        for (let index = 0; index < deletedRecordIndexs.length; index++) adjustCheckBoxStateMapWithDeleteRecordIndex(table, deletedRecordIndexs[index], 1);
        if (syncToOriginalRecords) return table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), 
        table.scenegraph.clearCells(), void table.scenegraph.createSceneGraph();
        const oldRowCount = table.transpose ? table.colCount : table.rowCount;
        table.refreshRowColCount();
        const newRowCount = table.transpose ? table.colCount : table.rowCount, recordIndexsMinToMax = deletedRecordIndexs.sort(((a, b) => a - b)), minRecordIndex = recordIndexsMinToMax[0];
        if (table.pagination) {
            const {perPageCount: perPageCount, currentPage: currentPage} = table.pagination, endIndex = perPageCount * (currentPage || 0) + perPageCount;
            if (minRecordIndex < endIndex) if (minRecordIndex < endIndex - perPageCount) table.scenegraph.clearCells(), 
            table.scenegraph.createSceneGraph(); else {
                const headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, updateRows = [], delRows = [];
                for (let row = minRecordIndex - (endIndex - perPageCount) + (table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount) + topAggregationCount; row < newRowCount; row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRows.push({
                    col: row,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: row
                });
                if (newRowCount < oldRowCount) for (let row = newRowCount; row < oldRowCount; row++) table.transpose ? delRows.push({
                    col: row,
                    row: 0
                }) : delRows.push({
                    col: 0,
                    row: row
                });
                null === (_g = table.reactCustomLayout) || void 0 === _g || _g.clearCache(), table.transpose ? table.scenegraph.updateCol(delRows, [], updateRows) : table.scenegraph.updateRow(delRows, [], updateRows), 
                null === (_h = table.reactCustomLayout) || void 0 === _h || _h.updateAllCustomCell();
            }
        } else {
            const delRows = [], headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, bottomAggregationCount = table.internalProps.layoutMap.hasAggregationOnBottomCount;
            for (let index = 0; index < recordIndexsMinToMax.length; index++) {
                const rowNum = recordIndexsMinToMax[index] + headerCount + topAggregationCount;
                table.transpose ? delRows.push({
                    col: rowNum,
                    row: 0
                }) : delRows.push({
                    col: 0,
                    row: rowNum
                });
            }
            const updateRows = [];
            for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRows.push({
                col: row,
                row: 0
            }) : updateRows.push({
                col: 0,
                row: row
            });
            for (let row = (table.transpose ? table.colCount : table.rowCount) - bottomAggregationCount; row < (table.transpose ? table.colCount : table.rowCount); row++) table.transpose ? updateRows.push({
                col: row,
                row: 0
            }) : updateRows.push({
                col: 0,
                row: row
            });
            null === (_j = table.reactCustomLayout) || void 0 === _j || _j.clearCache(), table.transpose ? table.scenegraph.updateCol(delRows, [], updateRows) : table.scenegraph.updateRow(delRows, [], updateRows), 
            null === (_k = table.reactCustomLayout) || void 0 === _k || _k.updateAllCustomCell();
        }
    }
}

function listTableUpdateRecords(records, recordIndexs, table) {
    var _a, _b, _c, _d, _e, _f;
    if ((null == recordIndexs ? void 0 : recordIndexs.length) > 0) if (table.internalProps.groupBy) null === (_b = (_a = table.dataSource).updateRecordsForGroup) || void 0 === _b || _b.call(_a, records, recordIndexs), 
    table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
    table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if ("tree" === table.dataSource.rowHierarchyType) null === (_d = (_c = table.dataSource).updateRecordsForTree) || void 0 === _d || _d.call(_c, records, recordIndexs), 
    table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), table.sortState && sortRecords(table), 
    table.scenegraph.clearCells(), table.scenegraph.createSceneGraph(); else if (table.sortState) {
        !!(null === (_e = table.options) || void 0 === _e ? void 0 : _e.syncRecordOperationsToSourceRecords) ? table.dataSource.updateRecords(records, recordIndexs, !0) : table.dataSource.updateRecordsForSorted(records, recordIndexs), 
        sortRecords(table), table.refreshRowColCount(), table.scenegraph.clearCells(), table.scenegraph.createSceneGraph();
    } else {
        const syncToOriginalRecords = !!(null === (_f = table.options) || void 0 === _f ? void 0 : _f.syncRecordOperationsToSourceRecords), updateRecordIndexs = table.dataSource.updateRecords(records, recordIndexs, syncToOriginalRecords);
        if (0 === updateRecordIndexs.length) return;
        if (syncToOriginalRecords) return table.refreshRowColCount(), table.internalProps.layoutMap.clearCellRangeMap(), 
        table.scenegraph.clearCells(), void table.scenegraph.createSceneGraph();
        const recordIndexsMinToMax = updateRecordIndexs.map((index => table.getBodyRowIndexByRecordIndex(index))).sort(((a, b) => a - b));
        if (table.pagination) {
            const {perPageCount: perPageCount, currentPage: currentPage} = table.pagination, headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, endIndex = perPageCount * (currentPage || 0) + perPageCount, updateRows = [];
            for (let index = 0; index < recordIndexsMinToMax.length; index++) {
                const recordIndex = recordIndexsMinToMax[index];
                if (recordIndex < endIndex && recordIndex >= endIndex - perPageCount) {
                    const rowNum = recordIndex - (endIndex - perPageCount) + (table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount) + topAggregationCount;
                    updateRows.push(rowNum);
                }
            }
            if (updateRows.length >= 1) {
                const updateRowCells = [];
                for (let index = 0; index < updateRows.length; index++) {
                    const updateRow = updateRows[index];
                    table.transpose ? updateRowCells.push({
                        col: updateRow,
                        row: 0
                    }) : updateRowCells.push({
                        col: 0,
                        row: updateRow
                    });
                }
                for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRowCells.push({
                    col: row,
                    row: 0
                }) : updateRowCells.push({
                    col: 0,
                    row: row
                });
                table.transpose ? table.scenegraph.updateCol([], [], updateRowCells) : table.scenegraph.updateRow([], [], updateRowCells);
            }
        } else {
            const updateRows = [], headerCount = table.transpose ? table.rowHeaderLevelCount : table.columnHeaderLevelCount, topAggregationCount = table.internalProps.layoutMap.hasAggregationOnTopCount, bottomAggregationCount = table.internalProps.layoutMap.hasAggregationOnBottomCount;
            for (let index = 0; index < recordIndexsMinToMax.length; index++) {
                const rowNum = recordIndexsMinToMax[index] + headerCount + topAggregationCount;
                table.transpose ? updateRows.push({
                    col: rowNum,
                    row: 0
                }) : updateRows.push({
                    col: 0,
                    row: rowNum
                });
            }
            for (let row = headerCount; row < headerCount + topAggregationCount; row++) table.transpose ? updateRows.push({
                col: row,
                row: 0
            }) : updateRows.push({
                col: 0,
                row: row
            });
            for (let row = (table.transpose ? table.colCount : table.rowCount) - bottomAggregationCount; row < (table.transpose ? table.colCount : table.rowCount); row++) table.transpose ? updateRows.push({
                col: row,
                row: 0
            }) : updateRows.push({
                col: 0,
                row: row
            });
            table.transpose ? table.scenegraph.updateCol([], [], updateRows) : table.scenegraph.updateRow([], [], updateRows);
        }
    }
}

function adjustCheckBoxStateMapWithDeleteRecordIndex(table, recordIndex, count) {
    const {checkedState: checkedState} = table.stateManager;
    if (checkedState) if ("tree" === table.dataSource.rowHierarchyType) {
        let toOperateIndexArr;
        toOperateIndexArr = (0, vutils_1.isNumber)(recordIndex) ? [ recordIndex ] : recordIndex;
        const toOperateIndexArrLength = toOperateIndexArr.length, targetResult = [];
        checkedState.forEach(((value, key) => {
            var _a;
            const keyArray = key.split(",");
            if (keyArray.length >= toOperateIndexArr.length) for (let i = 0; i < keyArray.length; i++) {
                const toOperateIndex = null !== (_a = toOperateIndexArr[i]) && void 0 !== _a ? _a : -1, keyIndex = Number(keyArray[i]);
                if (!(toOperateIndex === keyIndex && i < keyArray.length - 1)) {
                    if (toOperateIndex === keyIndex && i === keyArray.length - 1 || -1 === toOperateIndex) {
                        targetResult.push({
                            originKey: key,
                            value: value
                        });
                        break;
                    }
                    if (toOperateIndex < keyIndex && i === toOperateIndexArrLength - 1) {
                        keyArray[i] = (keyIndex - count).toString(), targetResult.push({
                            originKey: key,
                            targetKey: keyArray.toString(),
                            value: value
                        });
                        break;
                    }
                    break;
                }
            }
        })), targetResult.sort(((a, b) => {
            const aArray = a.originKey.split(","), bArray = b.originKey.split(","), aLength = aArray.length, bLength = bArray.length, minLength = Math.min(aLength, bLength);
            for (let i = 0; i < minLength; i++) {
                const aIndex = Number(aArray[i]), bIndex = Number(bArray[i]);
                if (aIndex !== bIndex) return aIndex - bIndex;
            }
            return aLength - bLength;
        })), targetResult.forEach((({originKey: originKey, targetKey: targetKey, value: value}) => {
            checkedState.delete(originKey), targetKey && checkedState.set(targetKey, value);
        }));
    } else {
        const toDelete = [], toUpdate = [];
        checkedState.forEach(((value, key) => {
            const dataIndex = Number(key);
            !isNaN(dataIndex) && dataIndex >= recordIndex && (dataIndex === recordIndex ? toDelete.push(key) : dataIndex > recordIndex && toUpdate.push({
                originKey: key,
                targetKey: (dataIndex - count).toString(),
                value: value
            }));
        })), toDelete.forEach((key => checkedState.delete(key))), toUpdate.forEach((({originKey: originKey, targetKey: targetKey, value: value}) => {
            checkedState.delete(originKey), checkedState.set(targetKey, value);
        }));
    }
}

function adjustCheckBoxStateMapWithAddRecordIndex(table, recordIndex, count) {
    const {checkedState: checkedState} = table.stateManager;
    if (checkedState) if ("tree" === table.dataSource.rowHierarchyType) {
        let toOperateIndexArr;
        toOperateIndexArr = (0, vutils_1.isNumber)(recordIndex) ? [ recordIndex ] : recordIndex;
        const toOperateIndexArrLength = toOperateIndexArr.length, targetResult = [];
        checkedState.forEach(((value, key) => {
            var _a;
            const keyArray = key.split(",");
            if (keyArray.length >= toOperateIndexArr.length) for (let i = 0; i < keyArray.length; i++) {
                const toOperateIndex = null !== (_a = toOperateIndexArr[i]) && void 0 !== _a ? _a : -1, keyIndex = Number(keyArray[i]);
                if (toOperateIndex === keyIndex && (i === keyArray.length - 1 || i === toOperateIndexArrLength - 1)) {
                    keyArray[i] = (keyIndex + count).toString(), targetResult.push({
                        originKey: key,
                        targetKey: keyArray.toString(),
                        value: value
                    });
                    break;
                }
                if (!(toOperateIndex === keyIndex && i < keyArray.length - 1)) {
                    if (toOperateIndex < keyIndex && i === toOperateIndexArrLength - 1) {
                        keyArray[i] = (keyIndex + count).toString(), targetResult.push({
                            originKey: key,
                            targetKey: keyArray.toString(),
                            value: value
                        });
                        break;
                    }
                    break;
                }
            }
        })), targetResult.sort(((a, b) => {
            const aArray = a.originKey.split(","), bArray = b.originKey.split(","), aLength = aArray.length, bLength = bArray.length, minLength = Math.min(aLength, bLength);
            for (let i = 0; i < minLength; i++) {
                const aIndex = Number(aArray[i]), bIndex = Number(bArray[i]);
                if (aIndex !== bIndex) return -aIndex + bIndex;
            }
            return -aLength + bLength;
        })), targetResult.forEach((({originKey: originKey, targetKey: targetKey, value: value}) => {
            checkedState.delete(originKey), targetKey && checkedState.set(targetKey, value);
        }));
    } else {
        for (let key = checkedState.size - 1; key >= recordIndex; key--) {
            const record = checkedState.get(key.toString());
            checkedState.delete(key.toString()), checkedState.set((key + count).toString(), record);
        }
    }
}

//# sourceMappingURL=record-helper.js.map
exports.listTableChangeCellValue = listTableChangeCellValue, exports.listTableChangeCellValues = listTableChangeCellValues, 
exports.listTableChangeCellValuesByIds = listTableChangeCellValuesByIds, exports.sortRecords = sortRecords, 
exports.listTableAddRecord = listTableAddRecord, exports.listTableAddRecords = listTableAddRecords, 
exports.listTableDeleteRecords = listTableDeleteRecords, exports.listTableUpdateRecords = listTableUpdateRecords;