import { Table, TableProps, Tag } from "antd"
import React, { useContext, useEffect, useRef, useState } from "react"
import { DispatchContext } from ".";
import { Resizable } from "react-resizable";
import './index.less'

const ResizableHeader = (props: { [x: string]: any; onResize: any; width: any }) => {
    const { onResize, width, ...restProps } = props;
    if (!width) {
        return <th {...restProps} />
    }
    return <Resizable width={width} height={0} onResize={onResize} draggableOpts={{ enableUserSelectHack: false }}>
        <th {...restProps} />
    </Resizable>
}

const NewTable: React.FC<TableProps<any>> = ({ columns, pagination, ...props }) => {

    /************************************/
    const { total, page: current, pageSize, onPaginationChange, handelResize } = useContext(DispatchContext)!;
    let ww = document.body.clientWidth < 415
    const colsRef = useRef<any[]>([])
    const [cols, setCols] = useState<any>(columns)
    /************************************/

    const components = {
        header: {
            cell: ResizableHeader
        }
    }

    useEffect(() => {
        setCols(columns)
    }, [columns])

    const handleResize = (index: any) => (e: any, { size }: any) => {
        const nextColumns = [...cols]
        nextColumns[index] = {
            ...nextColumns[index],
            width: size.width
        }
        setCols(nextColumns)
        handelResize && handelResize(nextColumns)
    }
    colsRef.current = (cols || []).map((col: any, index: any) => ({
        ...col,
        onHeaderCell: (column: any) => ({
            width: column.width,
            onResize: handleResize(index)
        })
    }))

    return <div className='components-table-resizable-column'>
        <Table
            rowKey={(a: any) => (JSON.stringify(a?.id) || JSON.stringify(a?.key))}
            pagination={pagination ? {
                size: 'small',
                total,//总共多少条数据,服务器给,设置后分页自动计算页数
                current,//当前页数,需state控制配合翻页
                pageSize,
                defaultCurrent: 1,//默认初始的当前页数
                defaultPageSize: 20,//默认初始的每页条数
                pageSizeOptions: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true, //手动开启条数筛选器，默认超过50条开启
                onChange: onPaginationChange, //点击页码或条数筛选时触发获取当前页数和每页条数
                simple: ww ? true : false,//开启简单分页
                showLessItems: true
            } : false}
            components={components}
            columns={colsRef?.current}
            {...props}
        />
    </div>
}

export default React.memo(NewTable)