import React from 'react';
import * as PropTypes from 'prop-types';
import styles from './index.less';
import { CommonProps, CommonState } from './interface';
import Table from './Table';
import Data from './data';

const {cols,list} = Data;
class AirTable extends React.Component<CommonProps, CommonState> {
    static propTypes = {
        dataSource: PropTypes.array,
        columns: PropTypes.array,
        tableId: PropTypes.number,
    };
    static defaultProps = {
        dataSource: list,
        columns: cols,
        tableId: 1,
    };

    static getDerivedStateFromProps(nextProps: CommonProps, prevState: CommonState) {
        const { prevProps } = prevState;

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

    constructor(props: CommonProps) {
        super(props);

        const { columns, dataSource, tableId } = props;

        this.state = {
            columns,
            dataSource,
            tableId,
            prevProps: props,
        };
    }
    render() {
        const { columns, dataSource, tableId } = this.state;
        return (
            <div className={styles.container}>
                <div className={styles.tableContainer}>
                    <Table columns={columns} dataSource={dataSource} tableId={tableId} />
                </div>
            </div>
        );
    }
}

export default AirTable;
