import React from 'react'
import { Modal, Table } from 'antd'
import { connect } from 'dva'
import './dataPreview.less'

// const DataPreview = ({ visibleBox, hideBox, columns, dataSource }) => {
class DataPreview extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = {
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight
        };
    }

    componentDidMount() {
        const { byChart, dispatch, code } = this.props;
        window.addEventListener('resize', this.onWindowResize);
        dispatch({ type: 'dataList/remoteDataList', byChart, code });
    }

    componentWillUnmount() {
        const { dispatch } = this.props;
        window.removeEventListener('resize', this.onWindowResize);
        dispatch({ type: 'dataList/reset' });
    }

    onWindowResize = () => {
        this.setState({
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight
        });
    }

    render() {
        const { dataList, visibleBox, hideBox } = this.props;
        const { columns, dataSource } = dataList;
        const { screenWidth, screenHeight } = this.state;
        const tableBodyWidth = screenWidth * 0.8 - 10 - 10 - 18;
        const tableBodyHeight = screenHeight * 0.8 - 40 - 40 - 38;
        const tableRowHeight = 38;

        return <Modal
            className='datapreview'
            width='80%'
            height='80%'
            visible={visibleBox}
            footer={null}
            onCancel={hideBox}
            maskClosable={false}
        >
            <Table
                columns={columns.map(c => ({
                    ...c,
                    width: 200,
                }))}
                dataSource={dataSource.map((d, i) => ({
                    ...d,
                    key: i
                }))}
                size='small'
                pagination={{ defaultPageSize: Math.floor(tableBodyHeight/tableRowHeight) || 10 }}
                scroll={{ x: columns ? columns.length * 200 : tableBodyWidth, y: tableBodyHeight }}
            />
        </Modal>
    }
}

export default connect(({ present: { dataList } }) => ({ dataList }))(DataPreview);