/**
 * @desc 数据展示表格
 * @author denghuan
 */
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import classNames from 'classnames';
import { AgGridReact } from 'ag-grid-react';
import { assemblyTableProps } from './helper';
import useSortChanged from './hooks/sort-changed';
import useGridReady from './hooks/grid-ready';
export default function JXTable(props) {
    const { wrapClassName, columnDefs, gridOption, tableData, isLoading, onTableReady, onSortChanged, } = props;
    const tableInstance = useRef();
    // 窗口大小改变事件
    const windowResizeHandler = useCallback(() => {
        tableInstance.current && tableInstance.current.api.sizeColumnsToFit();
    }, [gridOption, columnDefs]);
    // 窗口移动副作用
    useEffect(() => {
        window.addEventListener('resize', windowResizeHandler);
        return () => {
            window.removeEventListener('resize', windowResizeHandler);
        };
    }, [gridOption, columnDefs]);
    // 表格数据变化副作用
    useEffect(() => {
        tableInstance.current && tableInstance.current.api.setRowData(tableData);
    }, [tableData]);
    // 表格加载状态副作用
    useEffect(() => {
        if (!tableInstance.current || !tableInstance.current.api)
            return;
        if (isLoading) {
            tableInstance.current.api.showLoadingOverlay();
        }
        else if (tableData.length > 0) {
            tableInstance.current.api.hideOverlay();
        }
        else {
            tableInstance.current.api.showNoRowsOverlay();
        }
    }, [isLoading]);
    const sortChanged = useSortChanged(onSortChanged);
    const gridReady = useGridReady(tableInstance, tableData, onTableReady);
    // 表格配置
    const tableConfig = useMemo(() => {
        return {
            props: {
                ...assemblyTableProps(props),
                onGridReady: gridReady,
                onSortChanged: sortChanged,
            },
        };
    }, [gridOption, isLoading, columnDefs, onTableReady, onSortChanged]);
    return (React.createElement("div", { className: classNames('data-table', 'data-table-with-operations', wrapClassName, 'ag-theme-alpine') },
        React.createElement(AgGridReact, { headerHeight: 32, domLayout: "autoHeight", ...tableConfig.props })));
}
