import React, {useRef, useState, useEffect} from 'react';
import BasicTable from "@wisdom-components/basictable";
import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';
import {VariableSizeGrid as Grid} from 'react-window';
import './VirtualTable.less';

const VirtualTable = (props) => {
    const TABLE_ROW_HEIGHT = 40;
    const {columns, scroll} = props;
    const [tableWidth, setTableWidth] = useState(0);
    const widthColumnCount = columns.filter(({width}) => !width).length;
    const totalWidth = columns.reduce((final, curr) => {
        return final += (curr.width ?? 0)
    }, 0);
    const mergedColumns = columns.map((column) => {
        if (totalWidth < tableWidth) {
            return {
                ...column,
                width: Math.floor(tableWidth / totalWidth * column.width),
            };
        }
        if (column.width) {
            return column;
        }
        return {
            ...column,
            width: Math.floor(tableWidth / widthColumnCount),
        };
    });
    const gridRef = useRef();
    const [connectObject] = useState(() => {
        const obj = {};
        Object.defineProperty(obj, 'scrollLeft', {
            get: () => {
                if (gridRef.current) {
                    return gridRef.current?.state?.scrollLeft;
                }
                return null;
            },
            set: (scrollLeft) => {
                if (gridRef.current) {
                    gridRef.current.scrollTo({
                        scrollLeft,
                    });
                }
            },
        });
        return obj;
    });
    const resetVirtualGrid = () => {
        gridRef.current?.resetAfterIndices({
            columnIndex: 0,
            shouldForceUpdate: true,
        });
    };
    useEffect(() => resetVirtualGrid, [tableWidth, props.dataSource]);
    const renderVirtualList = (rawData, {scrollbarSize, ref, onScroll}) => {
        ref.current = connectObject;
        const totalHeight = rawData.length * TABLE_ROW_HEIGHT;

        return (
            <Grid
                ref={gridRef}
                className="virtual-grid"
                columnCount={mergedColumns.length}
                columnWidth={(index) => {
                    const {width} = mergedColumns[index];
                    return totalHeight > scroll.y && index === mergedColumns.length - 1
                        ? width - scrollbarSize - 1
                        : width;
                }}
                height={scroll.y}
                rowCount={rawData.length}
                rowHeight={() => TABLE_ROW_HEIGHT}
                width={tableWidth}
                // width={'100%'}
                onScroll={({scrollLeft}) => {
                    onScroll({
                        scrollLeft,
                    });
                }}
            >
                {({columnIndex, rowIndex, style}) => (
                    <div
                        className={classNames('virtual-table-cell', {
                            'virtual-table-cell-last': columnIndex === mergedColumns.length - 1,
                        })}
                        style={style}
                    >
                        {rawData[rowIndex][mergedColumns[columnIndex].dataIndex]}
                    </div>
                )}
            </Grid>
        );
    };
    return (
        <ResizeObserver
            onResize={({width}) => {
                setTableWidth(width);
            }}
        >
            <BasicTable
                {...props}
                size={'small'}
                // className="virtual-table"
                columns={mergedColumns}
                pagination={false}
                components={{
                    body: renderVirtualList,
                }}
            />
        </ResizeObserver>
    );
};
export default VirtualTable;