import React, { PureComponent } from 'react';
import { Table, Pagination } from 'antd';
import { Resizable } from "react-resizable";
import { is } from 'immutable';
import { getTableWidth } from 'jad-tool';


type TableProps = {
    columns: Object[],
    dataSource: Object[],
    [propName: string]: any;
}
type PaginationProps = {
    current: number,
    total: number,
    pageSize: number,
}
type PageProps = {
    pagination?: PaginationProps,
    [propName: string]: any;
}
type ExtraFunsProps = {
    [propName: string]: Function;
}


let isResizeStoped = false; //为了阻止在onResizeStop后，触发click 排序


const ResizeableTitle = props => {
    const { onResize, onResizeStop, width, ...restProps } = props;
    if (!width) {
        return <th {...restProps} />;
    }
    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            onResizeStop={(e, { size }) => isResizeStoped = onResizeStop(e, { size })}
            onClick={() => {
                //为了阻止在onResizeStop(onMouseUp)后，触发click 排序
                if (!isResizeStoped) restProps.onClick && restProps.onClick()
                else {
                    isResizeStoped = false
                    return false
                }
            }}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};




class ResizeTable extends PureComponent<{                                //这个其实可以不用了.这里暂时
    resizeTableCache?: {
        [propName: string]: number;
    },
    tableProps: TableProps;
    paginationProps: PageProps;
    extraFuns?: ExtraFunsProps;
    onGetResizeTableCache:()=>Promise<any>
    onSetResizeTableCache:(params:any)=>Promise<any>
    onRemoveResizeTableCache:(params:any)=>Promise<any>
}>{
    state: {
        columns: any[],
        resizeColumns:any[]
    };
    components = {
        header: {
            cell: ResizeableTitle
        }
    };
    constructor(props){
        super(props);
        this.state = {
            columns: [...props.tableProps.columns],
            resizeColumns:[]
        };
    }

    async componentDidMount() {
        const { onGetResizeTableCache } = this.props as any;
        await onGetResizeTableCache() // 缓存resize width
        this.computeResize()
    }
    UNSAFE_componentWillReceiveProps(nextProps) {
        if (!is(nextProps.tableProps.columns, this.props.tableProps.columns)) {
            this.setState({
                columns: [...nextProps.tableProps.columns]
            },()=>this.computeResize())
        }
    }


    handleResize = index => (e, { size }) => {
        window.event ? window.event.cancelBubble = true : e.stopPropagation();
        this.setState((state, props) => {
            const nextColumns = [...state['columns']];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width
            };
            return { columns: nextColumns };
        },()=>this.computeResize(true));
    };
    handleResizeStop = (index, col) => (e, { size }) => {
        window.event ? window.event.cancelBubble = true : e.stopPropagation();
        const { onSetResizeTableCache } = this.props as any
        onSetResizeTableCache({ [col['dataIndex']]: size['width'] }) // 缓存resize width
        return true
    }
    computeResize = (isMove?)=>{
        const { extraFuns,resizeTableCache } = this.props;
        let { columns } = this.state;
        let resizeColumns = columns.map((col:any, index) => {
            const width = isMove?
                                ( col.width ):
                                ( resizeTableCache && resizeTableCache[col.dataIndex]? 
                                    resizeTableCache[col.dataIndex] : col['width'] )
            return ({
                ...col,
                onHeaderCell: column => ({
                    fixed: column.fixed,
                    onResize: this.handleResize(index),
                    onResizeStop: this.handleResizeStop(index, col),
                    width,
                }),
                ...(extraFuns && extraFuns['toEditCell'] && extraFuns['toEditCell'](col)), // 额外函数，处理 onCell
                width,
            })
        });
        this.setState({
            resizeColumns
        })
    }
    


    //对外api
    resetTableWidth = async () => {
        const { onRemoveResizeTableCache } = this.props as any
        await onRemoveResizeTableCache()
        this.setState({
            columns: [...this.props.tableProps.columns],
            resizeColumns:[]
        },()=>this.computeResize())
    }



    render() {
        const { tableProps, paginationProps: { pagination, ...restPaginationProps } , extraFuns} = this.props;
        let { resizeColumns } = this.state;
        return (
            <div id='components-table-resizable-column'>
                <Table
                    bordered
                    pagination={false}
                    scroll={{ x: getTableWidth(resizeColumns), y: `calc(100vh - 235px)` }}
                    {...tableProps}
                    components={{
                        ...this.components,
                        ...tableProps['components'], // 兼容可编辑表格body等, 注意不要覆盖 this.components 的resize
                    }}
                    columns={resizeColumns} // 这个放在最后，是避免被restTableProps中的columns覆盖
                />
                {pagination && <Pagination
                    className={'jad-pagination-to-table'}
                    pageSizeOptions={['10', '20', '50', '100']}
                    showSizeChanger
                    showQuickJumper
                    current={pagination.current}
                    total={pagination.total}
                    pageSize={pagination.pageSize}
                    showTotal={() => `总计:${pagination.total}条记录`}
                    {...restPaginationProps}
                />}
            </div>
        );
    }
}

export default ResizeTable;
