import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Table } from 'amos-antd';
import { tools } from '@gm/graphmod-utils';
import './table.scss';

/**
 * 清除表格中的空child
 * @param {*} data
 */
export const clearEmptyChild = (data = []) => {
  return tools.recursive(data).map(e => {
    if (!e.children || e.children.length === 0) {
      delete e.children;
    }
  });
};
/**
 * 公共树表格
 *
 * @class ComTreeTable
 * @extends {Component}
 */
class ComTreeTable extends Component {

  static propTypes = {
    className: PropTypes.string,
    rowKey: PropTypes.any,
    scroll: PropTypes.object,
    dataSource: PropTypes.array,
    columns: PropTypes.array,
    rowSelection: PropTypes.object
  };

  static defaultProps = {
    segName: 'seg',
    showSeg: true,
    dataSource: [],
    columns: [],
    total: 0,
    pagination: {}
  };

  constructor(props) {
    super(props);
    this.state = {
      height: 0
    };
  }

  componentDidMount() {
    this.onResize();
    window.addEventListener('resize', this.onResize);
  }

  componentDidUpdate(preProps) {
    if (preProps.dataSource.length !== this.props.dataSource.length) {
      this.onResize();
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onResize);
  }

  onResize = () => {
    const tableBody = this.table.getElementsByClassName('ant-table-tbody')[0];
    if (tableBody.scrollHeight > this.table.clientHeight) {
      // eslint-disable-next-line no-magic-numbers
      this.setState({ height: this.table.clientHeight - 30 });
    } else {
      this.setState({ height: 0 });
    }
  }


  render() {
    const { className, rowKey, dataSource, columns, scroll, rowSelection, ...other } = this.props;
    let _rowKey = rowKey;
    const { height } = this.state;
    return (
      <div className={classnames('eb-gridtable',className)} >
        <div ref={node => this.table = node} className="eb-gridtable-content">
          <Table
            columns={columns}
            rowKey={_rowKey}
            dataSource={[...dataSource]}
            pagination={false}
            scroll={scroll ? scroll : height ? { y: height } : undefined}
            rowSelection={rowSelection}
            {...other}
          />
        </div>
      </div>
    );
  }
}

export default ComTreeTable;
