import { Table, Button } from 'amos-antd';
import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * 可编辑table
 *
 * @class CommonTable
 * @extends {Component}
 */
class CommonTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      selectedRowKeys: [],
      selectedRows: []
    };
  }
  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    const { tableData } = this.props;
    this.props.onChangeTableValues(tableData);
  };

  componentWillReceiveProps = nextProps => {
    if (nextProps.tableData) {
      const { tableData } = nextProps || {};
      this.setState({ data: tableData });
    }
  };

  onRowChanger = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  onDelClick = e => {
    let { data, selectedRows, selectedRowKeys } = this.state;
    for (let i = 0; i < selectedRows.length; i++) {
      data.splice(data.findIndex(item => item.orderNo === selectedRows[i].orderNo), 1);
    }
    for(let i = 0; i < data.length; i++){
      data[i].orderNo =  i;
    }
    this.setState({ data, selectedRows: [], selectedRowKeys: [] }, () => this.props.onChangeTableValues(data));
  };

  onAddClick = e => {
    let { data } = this.state;
    let maxNo = data.length;
    if (!maxNo) {
      maxNo = 0;
    }
    let row = new Object();
    row.orderNo = maxNo;
    data.push(row);
    this.setState({ data }, () => this.props.onChangeTableValues(data));
  };

  onDoubleClick = (record, event) => {
    const { data } = this.state;
    for (let i = 0; i < data.length; i++) {
      if (record.orderNo === data[i].orderNo) {
        data[i].edit = true;
      } else {
        data[i].edit = false;
      }
    }
    this.props.onChangeTableValues(data);
  };

  /**
   * 获取表格工具栏
   */
  getHeader = () => {
    return <div>
        <Button onClick={this.onAddClick} icon="add">
          添加
        </Button>
        <Button onClick={this.onDelClick} icon="remove">
          删除
        </Button>
      </div>;
  };

  /**
   * 获取表格表头
   */
  getTablecolumns = () => {
    const { columns } = this.props;
    return columns;
  };

  render() {
    let pagination = false;
    let { data, selectedRowKeys } = this.state;
    const rowSelection = {
      selections: {
        key: 'orderNo'
      },
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.onRowChanger(selectedRowKeys, selectedRows);
      }
    };

    return (
      <div>
        <Table
          rowSelection={rowSelection}
          columns={this.getTablecolumns()}
          dataSource={data}
          pagination={pagination}
          bordered
          title={() => this.getHeader()}
          onRowClick={this.onDoubleClick}
        />
      </div>
    );
  }
}

CommonTable.propTypes = {
  tableData: PropTypes.array,
  onChangeTableValues: PropTypes.func,
  columns: PropTypes.array
};

export default CommonTable;
