"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const vue_1 = require("vue");
const seemly_1 = require("seemly");
const vueuc_1 = require("vueuc");
const cssr_1 = require("../../../_utils/cssr");
const _internal_1 = require("../../../_internal");
const _utils_1 = require("../../../_utils");
const interface_1 = require("../interface");
const utils_1 = require("../utils");
const Cell_1 = __importDefault(require("./Cell"));
const ExpandTrigger_1 = __importDefault(require("./ExpandTrigger"));
const BodyCheckbox_1 = __importDefault(require("./BodyCheckbox"));
const Header_1 = __importDefault(require("./Header"));
function flatten(rows, expandedRowKeys) {
    const fRows = [];
    function traverse(rs) {
        rs.forEach((r) => {
            if (r.children && expandedRowKeys.has(r.key)) {
                fRows.push(r);
                traverse(r.children);
            }
            else {
                fRows.push(r);
            }
        });
    }
    traverse(rows);
    return fRows;
}
const VirtualListItemWrapper = (0, vue_1.defineComponent)({
    props: {
        clsPrefix: {
            type: String,
            required: true
        },
        id: {
            type: String,
            required: true
        },
        cols: {
            type: Array,
            required: true
        },
        onMouseenter: Function,
        onMouseleave: Function
    },
    render() {
        const { clsPrefix, id, cols, onMouseenter, onMouseleave } = this;
        return ((0, vue_1.h)("table", { style: { tableLayout: 'fixed' }, class: `${clsPrefix}-data-table-table`, onMouseenter: onMouseenter, onMouseleave: onMouseleave },
            (0, vue_1.h)("colgroup", null, cols.map((col) => ((0, vue_1.h)("col", { key: col.key, style: col.style })))),
            (0, vue_1.h)("tbody", { "data-n-id": id, class: `${clsPrefix}-data-table-tbody` }, this.$slots)));
    }
});
exports.default = (0, vue_1.defineComponent)({
    name: 'DataTableBody',
    props: {
        onResize: Function,
        showHeader: Boolean,
        flexHeight: Boolean
    },
    setup(props) {
        const { mergedExpandedRowKeysRef, mergedClsPrefixRef, mergedThemeRef, scrollXRef, colsRef, paginatedDataRef, rawPaginatedDataRef, fixedColumnLeftMapRef, fixedColumnRightMapRef, mergedCurrentPageRef, rowClassNameRef, leftActiveFixedColKeyRef, rightActiveFixedColKeyRef, renderExpandRef, hoverKeyRef, summaryRef, mergedSortStateRef, virtualScrollRef, componentId, scrollPartRef, mergedTableLayoutRef, hasChildrenRef, firstContentfulColIndexRef, indentRef, rowPropsRef, maxHeightRef, setHeaderScrollLeft, doUpdateExpandedRowKeys, handleTableBodyScroll, doCheck, doUncheck
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         } = (0, vue_1.inject)(interface_1.dataTableInjectionKey);
        const scrollbarInstRef = (0, vue_1.ref)(null);
        const virtualListRef = (0, vue_1.ref)(null);
        let lastSelectedKey = '';
        const mergedExpandedRowKeySetRef = (0, vue_1.computed)(() => {
            return new Set(mergedExpandedRowKeysRef.value);
        });
        function handleCheckboxUpdateChecked(tmNode, checked, shiftKey) {
            if (shiftKey) {
                const lastIndex = paginatedDataRef.value.findIndex((item) => item.key === lastSelectedKey);
                if (lastIndex !== -1) {
                    const currentIndex = paginatedDataRef.value.findIndex((item) => item.key === tmNode.key);
                    const start = Math.min(lastIndex, currentIndex);
                    const end = Math.max(lastIndex, currentIndex);
                    const rowKeysToCheck = [];
                    paginatedDataRef.value.slice(start, end + 1).forEach((r) => {
                        if (!r.disabled) {
                            rowKeysToCheck.push(r.key);
                        }
                    });
                    if (checked) {
                        doCheck(rowKeysToCheck);
                    }
                    else {
                        doUncheck(rowKeysToCheck);
                    }
                    lastSelectedKey = tmNode.key;
                    return;
                }
            }
            if (checked) {
                doCheck(tmNode.key);
            }
            else {
                doUncheck(tmNode.key);
            }
            lastSelectedKey = tmNode.key;
        }
        function getScrollContainer() {
            if (virtualScrollRef.value) {
                return virtualListContainer();
            }
            const { value } = scrollbarInstRef;
            if (value)
                return value.containerRef;
            return null;
        }
        function handleUpdateExpanded(key) {
            const { value: mergedExpandedRowKeys } = mergedExpandedRowKeysRef;
            const index = mergedExpandedRowKeys.indexOf(key);
            const nextExpandedKeys = Array.from(mergedExpandedRowKeys);
            if (~index) {
                nextExpandedKeys.splice(index, 1);
            }
            else {
                nextExpandedKeys.push(key);
            }
            doUpdateExpandedRowKeys(nextExpandedKeys);
        }
        function handleMouseleaveTable() {
            hoverKeyRef.value = null;
        }
        function handleMouseenterTable() {
            scrollPartRef.value = 'body';
        }
        function virtualListContainer() {
            const { value } = virtualListRef;
            return value === null || value === void 0 ? void 0 : value.listElRef;
        }
        function virtualListContent() {
            const { value } = virtualListRef;
            return value === null || value === void 0 ? void 0 : value.itemsElRef;
        }
        function handleVirtualListScroll(e) {
            var _a;
            handleTableBodyScroll(e);
            (_a = scrollbarInstRef.value) === null || _a === void 0 ? void 0 : _a.sync();
        }
        function handleVirtualListResize(e) {
            var _a;
            const { onResize } = props;
            if (onResize)
                onResize(e);
            (_a = scrollbarInstRef.value) === null || _a === void 0 ? void 0 : _a.sync();
        }
        const exposedMethods = {
            getScrollContainer
        };
        // manually control shadow style to avoid rerender
        const style = (0, cssr_1.c)([
            ({ props: cProps }) => (0, cssr_1.c)([
                cProps.leftActiveFixedColKey === null
                    ? null
                    : (0, cssr_1.c)(`[data-n-id="${cProps.componentId}"] [data-col-key="${cProps.leftActiveFixedColKey}"]::after`, {
                        boxShadow: 'var(--box-shadow-after)'
                    }),
                cProps.rightActiveFixedColKey === null
                    ? null
                    : (0, cssr_1.c)(`[data-n-id="${cProps.componentId}"] [data-col-key="${cProps.rightActiveFixedColKey}"]::before`, {
                        boxShadow: 'var(--box-shadow-before)'
                    })
            ])
        ]);
        let fixedStyleMounted = false;
        (0, vue_1.watchEffect)(() => {
            const { value: leftActiveFixedColKey } = leftActiveFixedColKeyRef;
            const { value: rightActiveFixedColKey } = rightActiveFixedColKeyRef;
            if (!fixedStyleMounted &&
                leftActiveFixedColKey === null &&
                rightActiveFixedColKey === null) {
                return;
            }
            style.mount({
                id: `n-${componentId}`,
                force: true,
                props: {
                    leftActiveFixedColKey,
                    rightActiveFixedColKey,
                    componentId
                }
            });
            fixedStyleMounted = true;
        });
        (0, vue_1.onUnmounted)(() => {
            style.unmount({
                id: `n-${componentId}`
            });
        });
        return Object.assign({ componentId,
            scrollbarInstRef,
            virtualListRef, summary: summaryRef, mergedClsPrefix: mergedClsPrefixRef, mergedTheme: mergedThemeRef, scrollX: scrollXRef, cols: colsRef, paginatedData: paginatedDataRef, rawPaginatedData: rawPaginatedDataRef, fixedColumnLeftMap: fixedColumnLeftMapRef, fixedColumnRightMap: fixedColumnRightMapRef, currentPage: mergedCurrentPageRef, rowClassName: rowClassNameRef, renderExpand: renderExpandRef, mergedExpandedRowKeySet: mergedExpandedRowKeySetRef, hoverKey: hoverKeyRef, mergedSortState: mergedSortStateRef, virtualScroll: virtualScrollRef, mergedTableLayout: mergedTableLayoutRef, hasChildren: hasChildrenRef, firstContentfulColIndex: firstContentfulColIndexRef, indent: indentRef, rowProps: rowPropsRef, maxHeight: maxHeightRef, setHeaderScrollLeft,
            handleMouseenterTable,
            handleVirtualListScroll,
            handleVirtualListResize,
            handleMouseleaveTable,
            virtualListContainer,
            virtualListContent,
            handleTableBodyScroll,
            handleCheckboxUpdateChecked,
            handleUpdateExpanded }, exposedMethods);
    },
    render() {
        const { mergedTheme, scrollX, mergedClsPrefix, virtualScroll, maxHeight, mergedTableLayout, flexHeight, onResize, setHeaderScrollLeft } = this;
        const scrollable = scrollX !== undefined || maxHeight !== undefined || flexHeight;
        // For a basic table with auto layout whose content may overflow we will
        // make it scrollable, which differs from browser's native behavior.
        // For native behavior, see
        // https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout
        const isBasicAutoLayout = !scrollable && mergedTableLayout === 'auto';
        const xScrollable = scrollX !== undefined || isBasicAutoLayout;
        const contentStyle = {
            minWidth: (0, _utils_1.formatLength)(scrollX) || '100%'
        };
        if (scrollX)
            contentStyle.width = '100%';
        return ((0, vue_1.h)(_internal_1.NScrollbar, { ref: "scrollbarInstRef", scrollable: scrollable || isBasicAutoLayout, class: `${mergedClsPrefix}-data-table-base-table-body`, theme: mergedTheme.peers.Scrollbar, themeOverrides: mergedTheme.peerOverrides.Scrollbar, contentStyle: contentStyle, container: virtualScroll ? this.virtualListContainer : undefined, content: virtualScroll ? this.virtualListContent : undefined, horizontalRailStyle: { zIndex: 3 }, verticalRailStyle: { zIndex: 3 }, xScrollable: xScrollable, onScroll: virtualScroll ? undefined : this.handleTableBodyScroll, internalOnUpdateScrollLeft: setHeaderScrollLeft, onResize: onResize }, {
            default: () => {
                // coordinate to pass if there are cells that cross row & col
                const cordToPass = {};
                // coordinate to related hover keys
                const cordKey = {};
                const { cols, paginatedData, mergedTheme, fixedColumnLeftMap, fixedColumnRightMap, currentPage, rowClassName, mergedSortState, mergedExpandedRowKeySet, componentId, showHeader, hasChildren, firstContentfulColIndex, rowProps, handleMouseenterTable, handleMouseleaveTable, renderExpand, summary, handleCheckboxUpdateChecked, handleUpdateExpanded } = this;
                const { length: colCount } = cols;
                const rowIndexToKey = {};
                paginatedData.forEach((tmNode, rowIndex) => {
                    rowIndexToKey[rowIndex] = tmNode.key;
                });
                let mergedData;
                // if there is children in data, we should expand mergedData first
                const mergedPaginationData = hasChildren
                    ? flatten(paginatedData, mergedExpandedRowKeySet)
                    : paginatedData;
                if (summary) {
                    const summaryRows = summary(this.rawPaginatedData);
                    if (Array.isArray(summaryRows)) {
                        mergedData = [
                            ...mergedPaginationData,
                            ...summaryRows.map((row, i) => ({
                                summary: true,
                                rawNode: row,
                                key: `__n_summary__${i}`,
                                disabled: true
                            }))
                        ];
                    }
                    else {
                        mergedData = [
                            ...mergedPaginationData,
                            {
                                summary: true,
                                rawNode: summaryRows,
                                key: '__n_summary__',
                                disabled: true
                            }
                        ];
                    }
                }
                else {
                    mergedData = mergedPaginationData;
                }
                const indentStyle = hasChildren
                    ? { width: (0, seemly_1.pxfy)(this.indent) }
                    : undefined;
                const { length: rowCount } = mergedData;
                const renderRow = (rowInfo, rowIndex, isVirtual) => {
                    if ('isExpandedRow' in rowInfo) {
                        const { tmNode: { key, rawNode } } = rowInfo;
                        return ((0, vue_1.h)("tr", { class: `${mergedClsPrefix}-data-table-tr`, key: `${key}__expand` },
                            (0, vue_1.h)("td", { class: [
                                    `${mergedClsPrefix}-data-table-td`,
                                    `${mergedClsPrefix}-data-table-td--last-col`,
                                    rowIndex + 1 === rowCount &&
                                        `${mergedClsPrefix}-data-table-td--last-row`
                                ], colspan: colCount }, renderExpand(rawNode, rowIndex))));
                    }
                    const { rawNode: rowData, key: rowKey } = rowInfo;
                    const isSummary = 'summary' in rowInfo;
                    const expanded = mergedExpandedRowKeySet.has(rowInfo.key);
                    const props = rowProps ? rowProps(rowData, rowIndex) : undefined;
                    const mergedRowClassName = typeof rowClassName === 'string'
                        ? rowClassName
                        : (0, utils_1.createRowClassName)(rowData, rowIndex, rowClassName);
                    const row = ((0, vue_1.h)("tr", Object.assign({ onMouseenter: () => {
                            this.hoverKey = rowKey;
                        }, key: rowKey, class: [
                            `${mergedClsPrefix}-data-table-tr`,
                            mergedRowClassName
                        ] }, props), cols.map((col, colIndex) => {
                        var _a, _b, _c, _d, _e;
                        if (!isVirtual && rowIndex in cordToPass) {
                            const cordOfRowToPass = cordToPass[rowIndex];
                            const indexInCordOfRowToPass = cordOfRowToPass.indexOf(colIndex);
                            if (~indexInCordOfRowToPass) {
                                cordOfRowToPass.splice(indexInCordOfRowToPass, 1);
                                return null;
                            }
                        }
                        // TODO: Simplify row calculation
                        const { column } = col;
                        const colKey = (0, utils_1.getColKey)(col);
                        const { rowSpan, colSpan } = column;
                        const mergedColSpan = isSummary
                            ? ((_a = rowInfo.rawNode[colKey]) === null || _a === void 0 ? void 0 : _a.colSpan) || 1 // optional for #1276
                            : colSpan
                                ? colSpan(rowData, rowIndex)
                                : 1;
                        const mergedRowSpan = isSummary
                            ? ((_b = rowInfo.rawNode[colKey]) === null || _b === void 0 ? void 0 : _b.rowSpan) || 1 // optional for #1276
                            : rowSpan
                                ? rowSpan(rowData, rowIndex)
                                : 1;
                        const isLastCol = colIndex + mergedColSpan === colCount;
                        const isLastRow = rowIndex + mergedRowSpan === rowCount;
                        const isCrossRowTd = mergedRowSpan > 1;
                        if (isCrossRowTd) {
                            cordKey[rowIndex] = {
                                [colIndex]: []
                            };
                        }
                        if (mergedColSpan > 1 || isCrossRowTd) {
                            for (let i = rowIndex; i < rowIndex + mergedRowSpan; ++i) {
                                if (isCrossRowTd) {
                                    cordKey[rowIndex][colIndex].push(rowIndexToKey[i]);
                                }
                                for (let j = colIndex; j < colIndex + mergedColSpan; ++j) {
                                    if (i === rowIndex && j === colIndex)
                                        continue;
                                    if (!(i in cordToPass)) {
                                        cordToPass[i] = [j];
                                    }
                                    else {
                                        cordToPass[i].push(j);
                                    }
                                }
                            }
                        }
                        const hoverKey = isCrossRowTd ? this.hoverKey : null;
                        const { ellipsis } = column;
                        return ((0, vue_1.h)("td", { key: colKey, style: {
                                textAlign: column.align || undefined,
                                left: (0, seemly_1.pxfy)((_c = fixedColumnLeftMap[colKey]) === null || _c === void 0 ? void 0 : _c.start),
                                right: (0, seemly_1.pxfy)((_d = fixedColumnRightMap[colKey]) === null || _d === void 0 ? void 0 : _d.start)
                            }, colspan: mergedColSpan, rowspan: isVirtual ? undefined : mergedRowSpan, "data-col-key": colKey, class: [
                                `${mergedClsPrefix}-data-table-td`,
                                column.className,
                                isSummary &&
                                    `${mergedClsPrefix}-data-table-td--summary`,
                                ((hoverKey !== null &&
                                    cordKey[rowIndex][colIndex].includes(hoverKey)) ||
                                    (0, utils_1.isColumnSorting)(column, mergedSortState)) &&
                                    `${mergedClsPrefix}-data-table-td--hover`,
                                column.fixed &&
                                    `${mergedClsPrefix}-data-table-td--fixed-${column.fixed}`,
                                column.align &&
                                    `${mergedClsPrefix}-data-table-td--${column.align}-align`,
                                {
                                    [`${mergedClsPrefix}-data-table-td--ellipsis`]: ellipsis === true ||
                                        // don't add ellipsis class if tooltip exists
                                        (ellipsis && !ellipsis.tooltip),
                                    [`${mergedClsPrefix}-data-table-td--selection`]: column.type === 'selection',
                                    [`${mergedClsPrefix}-data-table-td--expand`]: column.type === 'expand',
                                    [`${mergedClsPrefix}-data-table-td--last-col`]: isLastCol,
                                    [`${mergedClsPrefix}-data-table-td--last-row`]: isLastRow
                                }
                            ] },
                            hasChildren && colIndex === firstContentfulColIndex
                                ? [
                                    (0, seemly_1.repeat)(isSummary ? 0 : rowInfo.level, (0, vue_1.h)("div", { class: `${mergedClsPrefix}-data-table-indent`, style: indentStyle })),
                                    isSummary || !rowInfo.children ? ((0, vue_1.h)("div", { class: `${mergedClsPrefix}-data-table-expand-placeholder` })) : ((0, vue_1.h)(ExpandTrigger_1.default, { class: `${mergedClsPrefix}-data-table-expand-trigger`, clsPrefix: mergedClsPrefix, expanded: expanded, onClick: () => {
                                            handleUpdateExpanded(rowKey);
                                        } }))
                                ]
                                : null,
                            column.type === 'selection' ? (!isSummary ? ((0, vue_1.h)(BodyCheckbox_1.default, { key: currentPage, rowKey: rowKey, disabled: rowInfo.disabled, onUpdateChecked: (checked, e) => handleCheckboxUpdateChecked(rowInfo, checked, e.shiftKey) })) : null) : column.type === 'expand' ? (!isSummary ? (!column.expandable ||
                                ((_e = column.expandable) === null || _e === void 0 ? void 0 : _e.call(column, rowData, rowIndex)) ? ((0, vue_1.h)(ExpandTrigger_1.default, { clsPrefix: mergedClsPrefix, expanded: expanded, onClick: () => handleUpdateExpanded(rowKey) })) : null) : null) : ((0, vue_1.h)(Cell_1.default, { index: rowIndex, row: rowData, column: column, isSummary: isSummary, mergedTheme: mergedTheme }))));
                    })));
                    return row;
                };
                // Tile the data of the expanded row
                const displayedData = [];
                mergedData.forEach((rowInfo) => {
                    if (renderExpand && mergedExpandedRowKeySet.has(rowInfo.key)) {
                        displayedData.push(rowInfo, {
                            isExpandedRow: true,
                            key: rowInfo.key,
                            tmNode: rowInfo
                        });
                    }
                    else {
                        displayedData.push(rowInfo);
                    }
                });
                if (!virtualScroll) {
                    return ((0, vue_1.h)("table", { class: `${mergedClsPrefix}-data-table-table`, onMouseleave: handleMouseleaveTable, onMouseenter: handleMouseenterTable, style: {
                            tableLayout: this.mergedTableLayout
                        } },
                        (0, vue_1.h)("colgroup", null, cols.map((col) => ((0, vue_1.h)("col", { key: col.key, style: col.style })))),
                        showHeader ? (0, vue_1.h)(Header_1.default, { discrete: false }) : null,
                        (0, vue_1.h)("tbody", { "data-n-id": componentId, class: `${mergedClsPrefix}-data-table-tbody` }, displayedData.map((rowInfo, rowIndex) => {
                            return renderRow(rowInfo, rowIndex, false);
                        }))));
                }
                else {
                    return ((0, vue_1.h)(vueuc_1.VirtualList, { ref: "virtualListRef", items: displayedData, itemSize: 28, visibleItemsTag: VirtualListItemWrapper, visibleItemsProps: {
                            clsPrefix: mergedClsPrefix,
                            id: componentId,
                            cols,
                            onMouseenter: handleMouseenterTable,
                            onMouseleave: handleMouseleaveTable
                        }, showScrollbar: false, onResize: this.handleVirtualListResize, onScroll: this.handleVirtualListScroll, itemsStyle: contentStyle, itemResizable: true }, {
                        default: ({ item, index }) => renderRow(item, index, true)
                    }));
                }
            }
        }));
    }
});
