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 AmosFilter from './../filter/AmosFilter';
import SearchBtn from './../btns/SearchBtn';
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: props.defaultPageConfig ? props.defaultPageConfig.current : 1,//当前页初始索引0
      pageSize: props.defaultPageConfig ? props.defaultPageConfig.pageSize : 10,//当前页数据量
      filter: {},//表格过滤条件
      totals: 1,//所有数据总和
      showFilter: true,
      otherFilter: props.otherFilter,
      maxHeight: 450
    };
  }

  /**
   * 初始获取表格数据
   */
  componentDidMount() {
    this.props.callBack(this.reload);
    this.getHeightOffset();
    window.addEventListener('resize', this.onWindowResize);
  }

  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);
    }
  }

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

  onWindowResize = (e) => {
    this.getHeightOffset();
  }

  /**
   * 获取复选框选择的数据，并进行回调
   */
  onSelectChange = (selectedRowKeys,selectedRows) => {
    this.setState({
      selectedRowKeys,
      selectedRows
    },this.props.getSelectedRows(selectedRows,selectedRowKeys));
  }
  /**
   * 设置页面数据大小事件
   */
  onSizeChange = (current, pageSize) => {
    let { setPageConfig } = this.props;
    setPageConfig && setPageConfig({ current, pageSize });
    this.setState({ current, pageSize },this.reload);
  }
  /**
   * 设置当前页事件
   */
  onPaginationChange = (current) => {
    let { setPageConfig } = this.props;
    setPageConfig && setPageConfig({ current });
    this.setState({ current },this.reload);
  }
  /**
   * 获取表格所有的外部按钮封装成数组
   */
  getbtns = () => {
    let btns = [];
    return <div key={`btntool`} className='amos-grid-oper-btn'>{this.props.operBtns}</div>;
  }
  /**
   * 获取表格数据的筛选条件，通过回调获得的，并通过该条件进行表格刷新获取
   */
  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);
    this.getHeightOffset();
  }
  /**
   * 获取表格内部按钮
   */
  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.key ? record.key :  record.id ? record.id : index + (this.state.current - 1) * this.state.pageSize;
    // return index + (this.state.current - 1) * this.state.pageSize;
  }

  getHeightOffset = () => {
    let { getPanelHeight } = this.props;
    let height = getPanelHeight === undefined ? 450 : getPanelHeight();
    height && this.setState({ maxHeight: height });
  }

  isVisableSearch(columns){
    let list = columns;
    let res = false;
    list.map((e)=>{
      if (e.query){
        res = true;
        return true;
      }
    });
    return res;
  }

  render() {
    const { loading, selectedRowKeys,size,maxHeight } = this.state;
    let { columns, isChecked, operateCol, isTreeTable, isPageable, pagination, dataList, totals,rowClassName, onRowClick, onRowDoubleClick } = 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 tepmPage = Object.assign({
      size: 'small',
      total: totals,
      current: this.state.current,
      pageSize: this.state.pageSize,
      onShowSizeChange: this.onSizeChange,
      onChange: this.onPaginationChange,
      showSizeChanger: true,
      showTotal: this.showTotal
    },  pagination);
    let _tempPagination = isPageable === false ? false :tepmPage;
    let bordered = true;
    // 当为true 或 undefined时则分页
    let _pagination = isPageable === false ?  false : _tempPagination;
    let divStyle = this.state.showFilter ? 'other-table-bar' : 'table-bar';
    let display = this.state.showFilter ? 'block' : 'none';
    let searchStyle = { display };

    return (
      <div className='grid-content'>
        <div className='oper-bar'>
          <div className='amos-grid-oper-btns'>
            {
              this.getbtns()
            }
            {
              // flag ? <SearchBtn className='search-upordown-btn' onclick={this.openFilter} /> : ''
            }
          </div>
        </div>
        <div className={divStyle}>
          { onRowClick ?
            <Table
              title={() => (
                <div style={searchStyle}>
                  <AmosFilter filterSearchModel={columns} closeFilter={this.openFilter} changeFilters={this.changeFilters} />
                </div>
              )}
              rowKey={isTreeTable ? 'key' : this.generateRowkey}
              loading={loading}
              rowSelection={rowSelection}
              columns={columns}
              dataSource={dataList}
              pagination={_pagination}
              size={size}
              bordered={bordered}
              scroll={{ y: maxHeight }}
              rowClassName={rowClassName}
              onRowClick={onRowClick}
            /> :
            <Table
              title={() => (
                <div style={searchStyle}>
                  <AmosFilter filterSearchModel={columns} closeFilter={this.openFilter} changeFilters={this.changeFilters} />
                </div>
              )}
              rowKey={isTreeTable ? 'key' : this.generateRowkey}
              loading={loading}
              rowSelection={rowSelection}
              columns={columns}
              dataSource={dataList}
              pagination={_pagination}
              size={size}
              bordered={bordered}
              scroll={{ y: maxHeight }}
              rowClassName={rowClassName}
              onRowDoubleClick={onRowDoubleClick}
            />
          }
        </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 默认非
  rowClassName: PropTypes.func,
  setPageConfig: PropTypes.func, //把分页参数给父类
  defaultPageConfig: PropTypes.object, //父类默认分页参数
  getPanelHeight: PropTypes.func
};

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

export default AmosGridTable;
