'use client';
import React, { useEffect, useState } from 'react';
import { RowTable } from './RowTable';
import { useStickyLefts } from './useStickyLeft';
import { PHXClientQueryV3 } from '../Func/GRPC/PHXGrpcClientV3';
import { PHXSkeleton } from '../Skeleton';
import { classNames } from '../types';
import { PHXEmptyRecord } from '../EmptyRecord';
import { PHXEmptySearch } from '../EmptySearch';
export 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] = useState(true);
    const [dataTableQuery, setDataTableQuery] = useState([]);
    const { lefts, refs } = 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 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);
        }
    };
    useEffect(() => {
        queryData();
    }, []);
    useEffect(() => {
        if (filterLoading) {
            queryData();
        }
    }, [list]);
    return (React.createElement(React.Fragment, null, isMainLoading ? (React.createElement(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.createElement(React.Fragment, null,
        React.createElement("div", { className: 'mt-3 rounded-lg bg-white shadow ring-1 ring-black ring-opacity-5' },
            React.createElement("div", { className: 'flex flex-col' }, dataTableQuery.length > 0 ? (React.createElement("div", null, !isMainLoading ? (React.createElement("div", { className: 'overflow-x-auto rounded-lg' },
                React.createElement("div", { className: classNames('min-w-full align-middle shadow ring-black ring-opacity-5') },
                    React.createElement("div", { className: classNames('relative overflow-auto ') },
                        React.createElement("table", { className: 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.createElement("thead", null,
                                React.createElement("tr", null, thHeader.map((item, index) => index === 0 ? (React.createElement("th", { key: index, 
                                    // @ts-ignore
                                    ref: (el) => (refs.current[0] = el), className: 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.createElement("th", { key: index, 
                                    // @ts-ignore
                                    ref: (el) => (refs.current[index] = el), className: 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.createElement("tbody", { className: 'divide-y divide-gray-200' },
                                React.createElement(React.Fragment, null, !thHeaderVertical || !isCellRendering ? (React.createElement(React.Fragment, null, dataTableQuery.map((item, itemIndex) => (React.createElement("tr", { key: item.id }, thBody.map((_, bodyIndex) => (React.createElement(React.Fragment, null,
                                    React.createElement(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.createElement(React.Fragment, null, thHeaderVertical.map((item, index) => {
                                    var _a, _b, _c, _d;
                                    return (React.createElement("tr", { key: index, className: 'hover:cursor-default' },
                                        item.parent_name && (React.createElement("td", { className: 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.createElement("td", { className: 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.createElement("div", { className: 'flex flex-col justify-center px-2 py-2' }, item.component ? (React.createElement(React.Fragment, null, item.component)) : (React.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.createElement(React.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.createElement("td", { key: indexChunk + 1, className: 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.createElement(React.Fragment, null, [...Array(cellNumberInRow - ((_d = dataTableQuery[index]) === null || _d === void 0 ? void 0 : _d.length))].map((_, indexArr) => (React.createElement("td", { key: indexArr + 1, className: 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.createElement("td", { key: indexArr + 1, className: classNames('px-3 py-2 text-xs text-[#616161]', border && 'border-r border-t ') }, "Ch\u01B0a c\u00F3 d\u1EEF li\u1EC7u"))))));
                                })))))))))) : (React.createElement(PHXEmptySearch, null)))) : (React.createElement(PHXEmptyRecord, null))))))));
}
//# sourceMappingURL=TableVertical.js.map