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

// import './style/amosGrid.scss';
import VagueTextFilter from './filter/VagueTextFilter';

const dataToTree = (dataList = []) => {
  let result = [];
  dataList.map(data => {
    data = data || {};
    let obj = data.object || {};
    data.id = data.value;
    data.companyName = obj.companyName;
    data.departmentName = obj.departmentName;
    data.description = obj.description;
    data.companyLevel = obj.companyLevel;
    if (data.children) {
      data.children = dataToTree(data.children);
    }
    result.push(data);
  });
  return result;
};
/**
 * 基础信息表格组件
 * @class SystemTableTree
 * @extends {Component}
 */
class SystemTableTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      localeUrl: props.url || '',
      selectedRowKeys: [], //表格选择的行key值集合
      selectedRows: [], //表格选择的行数据集合
      loading: false, //页面是否加载中,默认false
      dataList: [], //表格数据集合
      searchValue: '',
      value: '',
      size: 'middle', //表格大小
      filter: {}, //表格过滤条件
      showFilter: false,
      expandedKeys: [],
      defaultExpandedRowKeys: [],
      expandedRowKeys: undefined,
      otherFilter: props.otherFilter
    };
  }

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

  componentWillReceiveProps(nextProps) {
    if (nextProps.url !== this.props.url) {
      this.setState({ localeUrl: nextProps.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));
  };

  /**
   * 获取表格所有的外部按钮封装成数组
   */
  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 {dataList} = this.state;
    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 === '启用';
        }
      }
    });
    // let cloneTreeDaTe = this.clone(dataList);
    // filterTableData(cloneTreeDaTe,this.reload);
    this.setState({ filter: res }, this.reload);
    console.log('filter:res', this.state.filter);
  };

  /**
   * 深度拷贝函数
   */
  clone = origin => {
    let originProto = Object.getPrototypeOf(origin);
    return Object.assign(Object.create(originProto), origin);
  };

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

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

  render() {
    let { dataList, invokeFeDataFilter, vagueExtra } = this.props;
    const { loading, selectedRowKeys, size, expandedKeys } = this.state;
    dataToTree(dataList);
    Log.debug('SystemTable expandedKeys|dataList:', expandedKeys, dataList);
    let value = dataList[0] ? [dataList[0].key] : ['1'];

    const { columns, isChecked, operateCol } = this.props;
    //设置复选框参数
    let rowSelection = {
      selectedRowKeys: this.props.selectedRowKeys || selectedRowKeys,
      onChange: this.onSelectChange
    };
    //设置是否添加复选框
    rowSelection = isChecked ? rowSelection : undefined;
    //用于分页
    let pagination = false;

    //如果表格各行存在内部按钮，将各个按钮添加到表格列模型中
    if (operateCol) {
      columns[columns.length - 1].render = (text, record) => this.addOperateCol(text, record);
    }
    // let filterDisplay = {display:this.state.showFilter?'block':'none'};
    return (
      <div className="amos-grid-table">
        <div className="amos-grid-table-head">
          <div className="amos-grid-table-filter-btns">
            {this.getbtns()}
            {/*<MoreFilter filterSearchModel={columns} showFilter={this.state.showFilter} openFilter={this.openFilter} />*/}
            <VagueTextFilter filterSearchModel={columns} changeFilters={this.changeFilters} invokeFeDataFilter={invokeFeDataFilter} vagueExtra={vagueExtra} />
          </div>
          {/*<div className='amos-grid-table-filter' style={filterDisplay}>
            <AmosFilter filterSearchModel={columns} closeFilter={this.openFilter} changeFilters={this.changeFilters} />
          </div>*/}
        </div>
        <div className="amos-tree-table-body">
          <Table
            className="amos-table tree-table"
            defaultExpandedRowKeys={value}
            onExpand={this.onExpand}
            pagination={pagination}
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataList}
            size={size}
          />
        </div>
        {/*组织机构数据较多时，列表底下边的边框看不见bug修复*/}
        <div>
          <img src="" alt="" />
        </div>
      </div>
    );
  }
}

SystemTableTree.propTypes = {
  url: PropTypes.string, //请求表格数据的url不带参数的
  columns: PropTypes.array, //表格列模型
  getSelectedRows: PropTypes.func, //获取选择的行数据，用于各个具体的表格回调获取数据。
  operBtns: PropTypes.array, //表格外部操作按钮，如'新增'，'编辑'等
  isChecked: PropTypes.bool, //表格是否包含复选框
  operateCol: PropTypes.func, //表格内部操作按钮，如'查看详情'等
  dataList: PropTypes.array,
  invokeFeDataFilter: PropTypes.func, // 前端模糊匹配
  vagueExtra: PropTypes.any, // 模糊匹配组件额外条件
  selectedRowKeys: PropTypes.array,
  getTableDataAction: PropTypes.func,
  callBack: PropTypes.func, //获取表格刷新方法，用于各个具体的表格回调获取，方便各种操作后进行表格刷新。
  otherFilter: PropTypes.string //其他查询条件
};

SystemTableTree.defaultProps = {
  operBtns: [],
  columns: [],
  dataList: [],
  isChecked: true,
  otherFilter: ''
};

export default SystemTableTree;
