"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHXTableVertical = PHXTableVertical;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const RowTable_1 = require("./RowTable");
const useStickyLeft_1 = require("./useStickyLeft");
const PHXGrpcClientV3_1 = require("../Func/GRPC/PHXGrpcClientV3");
const Skeleton_1 = require("../Skeleton");
const types_1 = require("../types");
const EmptyRecord_1 = require("../EmptyRecord");
const EmptySearch_1 = require("../EmptySearch");
function PHXTableVertical({ border = false, cellNumberInRow = 0, filterLoading = false, isBulkAction, isCellRendering = false, list, setHeaderLoading, setSelectedCheckbox, sortFields, stickyColumnNumber = 0, thBody, thBodyComponent, thHeader, thHeaderComponent, thHeaderVertical, typeLoading = { type: 'table' }, groupData, selectedCheckbox, listVerticalRender, }) {
    const [isMainLoading, setIsMainLoading] = (0, react_1.useState)(true);
    const [dataTableQuery, setDataTableQuery] = (0, react_1.useState)([]);
    const { lefts, refs } = (0, useStickyLeft_1.useStickyLefts)(stickyColumnNumber, dataTableQuery);
    const headerEmptyLength = thHeader.filter((item) => !item).length;
    const bindDataToTable = (dataTable) => {
        let data = [...dataTable];
        if (isBulkAction === null || isBulkAction === void 0 ? void 0 : isBulkAction.enable) {
            // Thêm item mới vào đầu mảng với id duy nhất và các giá trị rỗng
            data = [{ id: 'bulk-action-checkbox', isBulkCheckbox: true }, ...data];
        }
        setDataTableQuery(data);
    };
    function getValueByPath(obj, path) {
        return path.split('.').reduce((acc, part) => acc === null || acc === void 0 ? void 0 : acc[part], obj);
    }
    const chunkArray = (arr, groupDataCell) => {
        const { key, mapping } = groupDataCell;
        const grouped = new Map();
        for (const item of arr) {
            const groupKey = item[key];
            if (!grouped.has(groupKey)) {
                grouped.set(groupKey, []);
            }
            grouped.get(groupKey).push(item);
        }
        const result = [];
        const data = [];
        let stillData = true;
        while (stillData) {
            const chunk = [];
            stillData = false;
            for (const mapKey of mapping) {
                const items = grouped.get(mapKey) || [];
                if (items.length > 0) {
                    chunk.push(items.shift());
                    stillData = true;
                }
                else {
                    chunk.push(null);
                }
            }
            if (stillData) {
                result.push(chunk);
                data.push(chunk);
            }
        }
        if (listVerticalRender && result.length > 0) {
            let number = 0;
            const valueListVertical = listVerticalRender.list.length;
            for (let i = 0; i < valueListVertical; ++i) {
                const item = data[number];
                const value = item && item.length > 0 ? getValueByPath(item[0], listVerticalRender.key) : null;
                if (value !== listVerticalRender.list[i].value) {
                    const emptyItems = new Array(listVerticalRender.list[i].totalRow).fill([]);
                    result.splice(number, 0, ...emptyItems);
                }
                else {
                    number += listVerticalRender.list[i].totalRow;
                }
            }
        }
        return result;
    };
    function sortByFields(array, fields) {
        return [...array].sort((a, b) => {
            for (const { direction, path } of fields) {
                const valueA = getValueByPath(a, path);
                const valueB = getValueByPath(b, path);
                if (valueA == null && valueB != null)
                    return 1;
                if (valueB == null && valueA != null)
                    return -1;
                if (valueA == null && valueB == null)
                    continue;
                if (valueA < valueB) {
                    return direction === 'asc' ? -1 : 1;
                }
                if (valueA > valueB) {
                    return direction === 'asc' ? 1 : -1;
                }
            }
            return 0;
        });
    }
    const queryData = async () => {
        setIsMainLoading(true);
        try {
            const data = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
                query: list.query,
            });
            const dataQuery = data === null || data === void 0 ? void 0 : data.data;
            if (!dataQuery)
                return;
            const dataTable = list.keyResult;
            if (isCellRendering && cellNumberInRow) {
                const dataWithSort = sortFields ? sortByFields(dataQuery[dataTable], sortFields) : dataQuery[dataTable];
                const chunkedData = chunkArray(dataWithSort, groupData);
                bindDataToTable(chunkedData);
            }
            else {
                bindDataToTable(dataQuery[dataTable]);
            }
            if (setHeaderLoading)
                setHeaderLoading();
            setIsMainLoading(false);
        }
        catch (e) {
            console.log(e);
        }
    };
    (0, react_1.useEffect)(() => {
        queryData();
    }, []);
    (0, react_1.useEffect)(() => {
        if (filterLoading) {
            queryData();
        }
    }, [list]);
    return (react_1.default.createElement(react_1.default.Fragment, null, isMainLoading ? (react_1.default.createElement(Skeleton_1.PHXSkeleton, { filterQty: typeLoading === null || typeLoading === void 0 ? void 0 : typeLoading.filterQty, reportQty: typeLoading === null || typeLoading === void 0 ? void 0 : typeLoading.reportQty, type: typeLoading.type })) : (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: 'mt-3 rounded-lg bg-white shadow ring-1 ring-black ring-opacity-5' },
            react_1.default.createElement("div", { className: 'flex flex-col' }, dataTableQuery.length > 0 ? (react_1.default.createElement("div", null, !isMainLoading ? (react_1.default.createElement("div", { className: 'overflow-x-auto rounded-lg' },
                react_1.default.createElement("div", { className: (0, types_1.classNames)('min-w-full align-middle shadow ring-black ring-opacity-5') },
                    react_1.default.createElement("div", { className: (0, types_1.classNames)('relative overflow-auto ') },
                        react_1.default.createElement("table", { className: (0, types_1.classNames)(
                            // @ts-ignore
                            thHeader.length < 5
                                ? 'min-w-full table-fixed border-separate border-spacing-0 divide-y divide-gray-300'
                                : 'min-w-full border-separate border-spacing-0 divide-y divide-gray-300') },
                            thHeaderComponent ? (thHeaderComponent) : (react_1.default.createElement("thead", null,
                                react_1.default.createElement("tr", null, thHeader.map((item, index) => index === 0 ? (react_1.default.createElement("th", { key: index, 
                                    // @ts-ignore
                                    ref: (el) => (refs.current[0] = el), className: (0, types_1.classNames)('rounded-tl-lg bg-white px-3 py-2 text-left align-top text-xs font-medium text-gray-800', item ? 'min-w-[160px] ' : 'min-w-12', stickyColumnNumber &&
                                        'sticky left-0 top-0 z-10 sm:drop-shadow-[4px_0_4px_rgba(0,0,0,0.1)]', stickyColumnNumber === 1 && 'drop-shadow-[4px_0_4px_rgba(0,0,0,0.1)]'), scope: 'col', style: stickyColumnNumber ? { left: lefts[0] } : {} }, item)) : (react_1.default.createElement("th", { key: index, 
                                    // @ts-ignore
                                    ref: (el) => (refs.current[index] = el), className: (0, types_1.classNames)('min-w-[135px] bg-white px-3 py-2 text-left align-top text-xs font-medium text-gray-800', index === thHeader.length - 1 && 'rounded-tr-lg', stickyColumnNumber &&
                                        index < stickyColumnNumber &&
                                        'sticky top-0 z-10 drop-shadow-[4px_0_4px_rgba(0,0,0,0.1)]', border && item && 'border-l'), scope: 'col', style: stickyColumnNumber && index < stickyColumnNumber ? { left: lefts[index] } : {} }, item)))))),
                            react_1.default.createElement("tbody", { className: 'divide-y divide-gray-200' },
                                react_1.default.createElement(react_1.default.Fragment, null, !thHeaderVertical || !isCellRendering ? (react_1.default.createElement(react_1.default.Fragment, null, dataTableQuery.map((item, itemIndex) => (react_1.default.createElement("tr", { key: item.id }, thBody.map((_, bodyIndex) => (react_1.default.createElement(react_1.default.Fragment, null,
                                    react_1.default.createElement(RowTable_1.RowTable, { key: bodyIndex, bodyIndex: bodyIndex, border: border, isBulkAction: isBulkAction, itemBody: item, itemIndex: itemIndex, lefts: lefts, refs: refs, setSelectedCheckbox: setSelectedCheckbox, stickyColumnNumber: stickyColumnNumber, thBody: thBody, thBodyComponent: thBodyComponent, thHeaderVertical: thHeaderVertical, selectedCheckbox: selectedCheckbox }))))))))) : (react_1.default.createElement(react_1.default.Fragment, null, thHeaderVertical.map((item, index) => {
                                    var _a, _b, _c, _d;
                                    return (react_1.default.createElement("tr", { key: index, className: 'hover:cursor-default' },
                                        item.parent_name && (react_1.default.createElement("td", { className: (0, types_1.classNames)('sticky top-0 z-10 whitespace-nowrap rounded-bl-lg border-r border-t bg-white px-2 text-xs font-semibold text-gray-900', (item === null || item === void 0 ? void 0 : item.className) ? item.className : ''), rowSpan: item.parent_row, style: { left: lefts[0] } }, item.parent_name)),
                                        react_1.default.createElement("td", { className: (0, types_1.classNames)('sticky top-0 !z-10 h-[83px] whitespace-nowrap border-t bg-white text-xs text-gray-900 drop-shadow-[4px_0_4px_rgba(0,0,0,0.1)]', (item === null || item === void 0 ? void 0 : item.className) ? item.className : ''), style: {
                                                left: thHeaderVertical.filter((header) => header.parent_name)
                                                    .length > 0
                                                    ? lefts[1]
                                                    : lefts[0],
                                            } },
                                            react_1.default.createElement("div", { className: 'flex flex-col justify-center px-2 py-2' }, item.component ? (react_1.default.createElement(react_1.default.Fragment, null, item.component)) : (react_1.default.createElement("p", { className: 'text-xs font-semibold text-gray-900' }, item.name)))),
                                        ((_a = dataTableQuery[index]) === null || _a === void 0 ? void 0 : _a.length) > 0 ? (react_1.default.createElement(react_1.default.Fragment, null, (_b = dataTableQuery[index]) === null || _b === void 0 ? void 0 :
                                            _b.map((itemChunk, indexChunk) => {
                                                const isFunctionRender = thBodyComponent
                                                    ? thBodyComponent[thHeader[indexChunk + headerEmptyLength]]
                                                    : undefined;
                                                return (react_1.default.createElement("td", { key: indexChunk + 1, className: (0, types_1.classNames)('z-10 border-l border-t px-3 py-2 text-xs text-gray-900') }, isFunctionRender ? isFunctionRender(itemChunk, itemChunk) : ''));
                                            }),
                                            ((_c = dataTableQuery[index]) === null || _c === void 0 ? void 0 : _c.length) < cellNumberInRow && (react_1.default.createElement(react_1.default.Fragment, null, [...Array(cellNumberInRow - ((_d = dataTableQuery[index]) === null || _d === void 0 ? void 0 : _d.length))].map((_, indexArr) => (react_1.default.createElement("td", { key: indexArr + 1, className: (0, types_1.classNames)(' px-3 py-2 text-xs text-[#616161]', border && 'border-r border-t ') }, "Ch\u01B0a c\u00F3 d\u1EEF li\u1EC7u"))))))) : ([...Array(cellNumberInRow)].map((_, indexArr) => (react_1.default.createElement("td", { key: indexArr + 1, className: (0, types_1.classNames)('px-3 py-2 text-xs text-[#616161]', border && 'border-r border-t ') }, "Ch\u01B0a c\u00F3 d\u1EEF li\u1EC7u"))))));
                                })))))))))) : (react_1.default.createElement(EmptySearch_1.PHXEmptySearch, null)))) : (react_1.default.createElement(EmptyRecord_1.PHXEmptyRecord, null))))))));
}
//# sourceMappingURL=TableVertical.js.map