import React from 'react';
import styles from './index.less';
import { CommonProps, CommonState } from './interface';
import Table from './Table';

class AirTable extends React.Component<CommonProps, CommonState> {
    static getDerivedStateFromProps(nextProps: CommonProps, prevState: CommonState) {
        const { columns, dataSource } = prevState;

        let nextState: CommonState = {
            ...prevState,
        };
        if (JSON.stringify(dataSource) !== JSON.stringify(nextProps.dataSource)) {
            nextState.dataSource = nextProps.dataSource;
        }
        if (JSON.stringify(columns) !== JSON.stringify(nextProps.columns)) {
            nextState.columns = nextProps.columns;
        }
        return nextState;
    }

    constructor(props: CommonProps) {
        super(props);
        const { columns, dataSource } = props;
        this.state = {
            columns,
            dataSource,
        };
    }

    onScroll = () => {
        const { onScroll } = this.props;
        if (typeof onScroll === 'function') {
            onScroll();
        }
    };

    render() {
        const { columns, dataSource } = this.state;
        const { rowStyle, rowClassName, distanceToLoad, emitChangeCell, bordered } = this.props;
        return (
            <div className={styles.container}>
                <div className={styles.tableContainer}>
                    <Table
                        columns={columns}
                        dataSource={dataSource}
                        onScroll={this.onScroll}
                        rowStyle={rowStyle}
                        rowClassName={rowClassName}
                        distanceToLoad={distanceToLoad}
                        emitChangeCell={emitChangeCell}
                        bordered={bordered}
                    />
                </div>
            </div>
        );
    }
}

export default AirTable;
