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

// import './style/table.scss';
import './style/amosGrid.scss';

/**
 * 基础信息表格组件
 * @class AmosGridTable
 * @extends {Component}
 */
class AmosGridTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],//表格选择的行key值集合
      selectedRows: [],//表格选择的行数据集合
      loading: false,//页面是否加载中,默认false
      dataList: [],//表格数据集合
      size: 'middle',//表格大小
      current: 1,//当前页初始索引0
      pageSize: 10,//当前页数据量
      filter: {},//表格过滤条件
      totals: 1,//所有数据总和
      showFilter: false,
      otherFilter: props.otherFilter
    };
  }

  /**
   * 初始获取表格数据
   */
  componentDidMount() {
    this.props.callBack(this.reload);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.url !== this.props.url){
      this.reload();
    }
    if (nextProps.otherFilter && nextProps.otherFilter !== this.props.otherFilter){
      this.setState({ otherFilter: nextProps.otherFilter }, this.reload);
    }
  }

  /**
   * 获取复选框选择的数据，并进行回调
   */
  onSelectChange = (selectedRowKeys,selectedRows) => {
    this.setState({
      selectedRowKeys,
      selectedRows
    },this.props.getSelectedRows(selectedRows,selectedRowKeys));
  }
  /**
   * 设置页面数据大小事件
   */
  onSizeChange = (current, pageSize) => {
    this.setState({ current, pageSize },this.reload);
  }
  /**
   * 设置当前页事件
   */
  onPaginationChange = (current) => {
    this.setState({ current },this.reload);
  }
  /**
   * 获取表格所有的外部按钮封装成数组
   */
  getbtns = () => {
    let btns = [];
    this.props.operBtns.map((btn,index)=>{
      btns.push(<div key={`btn${index}`} className='amos-grid-oper-btn'>{btn}</div>);
    });
    return btns;
  }
  /**
   * 获取表格数据的筛选条件，通过回调获得的，并通过该条件进行表格刷新获取
   */
  changeFilters = (obj) => {
    let newobj = obj;
    let res = {};
    let list = Object.keys(newobj);
    list.map(e=>{
      let varName = newobj[e];
      if (varName && varName !== ''){
        res[e] = varName;
        if (e === 'enabled'){
          res[e] = varName === '启用';
        }
      }
    });
    this.setState({ filter: res },this.reload);
  }

  openFilter = () => {
    let showFilter = this.state.showFilter;
    this.setState({ showFilter: !showFilter });
  }

  /**
   * 获取表格数据（刷新）
   */
  reload = () => {
    let { current,pageSize,filter,otherFilter } = this.state;
    this.props.getTableDataAction({ current: current - 1, pageSize },JSON.stringify(filter),otherFilter);
  }
  /**
   * 获取表格内部按钮
   */
  addOperateCol =(text,record) =>{
    const { operateCol } = this.props;
    let operBtns = operateCol(text,record);
    return (<div className='operation-buttons'>{operBtns}</div>);
  }

  showTotal = (total) => {
    return `共 ${total} 条`;
  }

  generateRowkey = (record, index) => {
    // return record.id ? record.id : UUID.uuidFast();
    return record.id ? record.id : index + (this.state.current - 1) * this.state.pageSize;
    // return index + (this.state.current - 1) * this.state.pageSize;
  }

  render() {
    const { loading, selectedRowKeys,size } = this.state;
    let { columns, isChecked, operateCol, isTreeTable, isPageable, pagination, dataList, totals } = this.props;
    //设置复选框参数
    let rowSelection = {
      selectedRowKeys: this.props.selectedRowKeys || selectedRowKeys,
      onChange: this.onSelectChange
    };
    //设置是否添加复选框
    rowSelection = isChecked ? rowSelection : undefined;

    //如果表格各行存在内部按钮，将各个按钮添加到表格列模型中
    if (operateCol){
      columns[columns.length - 1].render = (text,record) => this.addOperateCol(text,record);
    }
    let _tempPagination = pagination === false ? false : pagination || {
      size: 'small',
      total: totals,
      current: this.state.current,
      pageSize: this.state.pageSize,
      onShowSizeChange: this.onSizeChange,
      onChange: this.onPaginationChange,
      showSizeChanger: true,
      showTotal: this.showTotal
    };
    let bordered = true;
    // 当为true 或 undefined时则分页
    let _pagination = isPageable === false ?  false : _tempPagination;
    Log.info('the table has pagination', !!_pagination);
    return (
      <div>
        <div>
          <div>
            {
              this.getbtns()
            }
          </div>
        </div>
        <div style={{ marginTop: '10px' }} >
          <Table
            rowKey={isTreeTable ? 'key' : this.generateRowkey}
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataList}
            pagination={_pagination}
            size={size}
            bordered={bordered}
            scroll={{ y: 450 }}
          />
        </div>
      </div>
    );
  }
}

AmosGridTable.propTypes = {
  url: PropTypes.string,//请求表格数据的url不带参数的
  columns: PropTypes.array,//表格列模型
  getSelectedRows: PropTypes.func,//获取选择的行数据，用于各个具体的表格回调获取数据。
  operBtns: PropTypes.array,//表格外部操作按钮，如'新增'，'编辑'等
  isChecked: PropTypes.bool,//表格是否包含复选框
  operateCol: PropTypes.func,//表格内部操作按钮，如'查看详情'等
  callBack: PropTypes.func,//获取表格刷新方法，用于各个具体的表格回调获取，方便各种操作后进行表格刷新。
  otherFilter: PropTypes.string,//其他查询条件
  dataList: PropTypes.array,
  getTableDataAction: PropTypes.func,
  selectedRowKeys: PropTypes.array,
  totals: PropTypes.number,
  pagination: PropTypes.any, // 分页props, false时无分页
  isPageable: PropTypes.bool, // 是否分页: true 分页, false 不分页, 当为undefined时默认有分页
  isTreeTable: PropTypes.bool // 是否是treeTable 默认非
};

AmosGridTable.defaultProps = {
  operBtns: [],
  dataList: [],
  totals: 1,
  columns: [],
  isChecked: true,
  isTreeTable: false,
  otherFilter: ''
};

export default AmosGridTable;
