import React, { ReactNode, useEffect, useRef, useState } from 'react'
import { Table, Tag, message } from 'antd';
import { Excle } from '@/utils/Excle'
import './index.less'
import { Resizable } from 'react-resizable'
import { SortOrder } from 'antd/lib/table/interface';

export interface DataType {
    key: React.Key;
    name: string;
    age: string;
    address: string;
}

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>
}
/**
 * https://ant-design.gitee.io/components/table-cn/#API
 */
interface Props {
    dataSource: any[],
    columns: any[],
    excle?: {
        fillName: string,//文件名称
        filter?: string[]//需要排除的数据,输入数据key
    },
    total?: number,
    current?: number,
    pageSize?: number,
    rowSelection?: any,//选择
    onRow?: {//行操作事件
        onClick?: (event?: any) => void, // 点击行
        onDoubleClick?: (event?: any) => void,
        onContextMenu?: (event?: any) => void,
        onMouseEnter?: (event?: any) => void, // 鼠标移入行
        onMouseLeave?: (event?: any) => void,
    }
    pageChange?: (page: number, pageSize?: number) => void,
    sizeChange?: (current: number, size?: number) => void,
    rowClassName?: string | ((record: any, index: any) => string),//样式
    expandedRowRender?: any,//子table
    scroll?: { x?: number, y?: number },
    summary?: (data: readonly any[]) => ReactNode,
    size?: 'small' | 'middle' | 'large',
    loading?: boolean,
    defaultPageSize?: 10 | 20 | 30 | 100,
    bordered?: boolean,
    columnWidth?: string | number
    onChange?: (pagination: any, filters: any, sorter: any) => void//服务端排序回调
    pagination?: boolean,
    showHeader?: boolean,
    hideOnSinglePage?: boolean,
    className?: string,
    handelResize?: (columns: any) => void//当表头被拖动改变宽度时回调设置对应的本地保存
    sortDirections?: SortOrder[],
    isShowTotal?: boolean,  // 是否展示总计
    myKey?: any,//自定义要用哪个值做key
}

function Tables(props: Props) {
    // //导出数据
    let { columns, dataSource, excle, total, handelResize, columnWidth, rowSelection, onRow, isShowTotal = true, hideOnSinglePage, className, expandedRowRender, scroll, summary, showHeader, bordered, size = 'small', onChange, sortDirections, pagination, myKey, ...prop } = props
    let handleExcle = () => {
        if (dataSource.length < 1) {
            message.error('请先搜索再导出');
            return
        }
        let thName: any = {};
        let obj = columns;
        obj.forEach((item: any) => {
            thName[item.key] = item.title
        })
        let fillName = excle?.fillName || ''
        let filter = excle?.filter || []
        Excle(thName, dataSource, fillName, filter)
    }
    let ww = document.body.clientWidth < 415
    // 拖动宽逻辑
    const [cols, setCols] = useState<any>(columns)
    const colsRef = useRef<any[]>([])
    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'>
        {
            excle && <Tag color='#f50' style={{ margin: '10px 0', float: 'right' }} onClick={handleExcle}><a>导出数据</a></Tag>
        }
        <Table
            components={components}
            columns={colsRef?.current}
            sortDirections={sortDirections || ['descend', 'ascend', null]}
            onChange={(pagination, filters, sorter) => {
                onChange && onChange(pagination, filters, sorter)
            }}
            bordered={bordered ? bordered : false}
            dataSource={dataSource}
            showHeader={showHeader}
            scroll={scroll ? { ...scroll, scrollToFirstRowOnChange: true } : undefined}
            size={size}
            rowKey={(a: any) => {
                if (myKey) {
                    return JSON.stringify(a[myKey])
                }
                return (JSON.stringify(a?.id) || JSON.stringify(a?.key))
            }}
            rowSelection={rowSelection ? rowSelection : undefined}
            onRow={record => {
                return {
                    onClick: onRow?.onClick && onRow?.onClick.bind('', record) || undefined,
                }
            }}
            summary={summary}
            className={className}
            expandable={expandedRowRender ? {
                defaultExpandedRowKeys: ['0'],
                expandRowByClick: false,
                columnWidth, 
                expandedRowRender: (data) => {
                    return expandedRowRender(data)
                }
            } : {}}
            pagination={
                {
                    total: total || 0,//总共多少条数据,服务器给,设置后分页自动计算页数
                    current: props.current,//当前页数,需state控制配合翻页
                    pageSize: props?.pageSize,
                    defaultCurrent: 1,//默认初始的当前页数
                    defaultPageSize: props?.defaultPageSize || 20,//默认初始的每页条数
                    pageSizeOptions: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                    showTotal: (total) => isShowTotal ? <Tag color="cyan">总共{total}数据</Tag> : null,
                    showSizeChanger: true, //手动开启条数筛选器，默认超过50条开启
                    // size:'small',//设置分页尺寸
                    //responsive:true,//当 size 未指定时，根据屏幕宽度自动调整尺寸
                    onChange: props.pageChange, //点击页码或条数筛选时触发获取当前页数和每页条数
                    onShowSizeChange: props.sizeChange,//点击条数筛选器触发
                    simple: ww ? true : false,//开启简单分页
                    hideOnSinglePage: hideOnSinglePage ? hideOnSinglePage : false,//只有一页数据隐藏分页
                    showLessItems: true
                }
            }
            {...prop}
        />
    </div>
}

export default Tables



