import React from 'react'
import { Table } from 'antd'
import './tableView.less'

class TableView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            columnWidth: 200,
            tableScrollHeight: 0,
        };
    }

    componentDidMount() {
        const { viewRef } = this.props;
        this.onTableLayoutChange();
        this[viewRef].addEventListener('resize', this.onTableLayoutChange);
    }

    componentWillUnmount() {
        const { viewRef } = this.props;
        this[viewRef].removeEventListener('resize', this.onTableLayoutChange);
    }

    onTableLayoutChange = () => {
        this.setState(this.getTableLayout());
    }

    getTableLayout = () => {
        const { chartOption, viewRef, onPageSizeChange } = this.props;
        let bodyRef = this[viewRef];
        const containerHeight = bodyRef.offsetHeight;
        const tableEl = bodyRef.getElementsByClassName('table-view')[0];
        let obj = {};
        if(tableEl) {
            let tableScrollHeight = containerHeight - 40 - 24 - 8 * 2;
            let pageSize = ~~(tableScrollHeight/38) + 1;
            obj = {
                tableScrollHeight
            }
            if(typeof onPageSizeChange === 'function' && pageSize !== chartOption.pageSize) {
                // 在报表中的dataView第一次数据请求在此发起
                onPageSizeChange(1, pageSize)
            }
        }
        return obj;
    }

    render() {
        const { viewRef, columns, dataSource, styleConfig, pagination } = this.props;
        const { columnWidth, tableScrollHeight } = this.state;

        const { bordered } = (styleConfig || {});

        return (<div style={{ height: '100%' }} ref={node => this[viewRef] = node }>
            <Table
                className='table-view'
                columns={columns ? columns.map((c, i) => {
                    let obj = { ...c };
                    if(i !== columns.length - 1) {
                        obj.onCell = () => {
                            return {
                                style: {
                                    whiteSpace: 'nowrap',
                                    maxWidth: columnWidth + 'px',
                                }
                            }
                        };
                        obj.width = columnWidth
                    }
                    return obj; 
                }) : []}
                dataSource={dataSource || []}
                size='small'
                bordered={bordered}
                scroll={{
                    x: columns ? columns.length * columnWidth : 0,
                    y: tableScrollHeight
                }}
                pagination={pagination}
            />
        </div>);
    }
}

export default TableView;