import {Input, Button, Table, Modal, Select} from 'antd';
import React, {PureComponent} from 'react';
import * as api from "../../services/api";
import PropTypes from 'prop-types';

/**w
 *
 * @desc    antd table 组件自带的 api 都可以直接使用
 *          Ptable 中 dataSource使用自身 state 对象。不可设置
 *          demo   LaborBasic.js
 * @param   {String} url  使用 /services/api.js 中的接口函数
 * @param   {Boolean} forceUpdate  父组件 强制刷新子组件
 * @param   {obj}  pageParm  分页请求参数，改变该参数，可以重新请求。
 * @param   {func} dateChange(data)  分页请求回来的数据，这里可以读取。
 * @param   {Boolean,func} 如果只传入 showTotal ，默认展示 总共${total}记录 。
 *            如果设置 showTotal 为 callback(total) ,callback返回一个自定义字符串。
 *            例如：showTotal={total=>`自定义${total}`}
 * @return
 */

export default class PTable extends PureComponent {
  state = {
    url: this.props.url,
    pageParm: {...this.props.pageParm},
    pageParmCache: {...this.props.pageParm},
    dataSource: [],
    pagination: {
      defaultPageSize: this.props.pageParm.pageSize ? parseInt(this.props.pageParm.pageSize) : 10,
      showQuickJumper: true,
      pageSizeOptions: ["5", "10", "15", "25", "50"],
      showSizeChanger: true,
      onChange: this.onPaginationChange,
      onShowSizeChange: this.onPaginationShowSizeChange,
      showTotal: this.showTotal,
      ...this.props.pagination
    },
    loading: false
  }

  static propTypes = {
    url: PropTypes.string.isRequired,
    pageParm:PropTypes.object.isRequired,
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.state.url == "" && console.log("请设置接口请求地址 url");
    this.state.pageParm == "" && console.log("请设置分页请求变量 pageParm");
    //请求分页信息
    this.state.url != "" && this.state.pageParm != "" && this.ajaxRequest();

    if (this.props.update) {
      this.props.update(ajaxRequest);
    }
  }

  componentWillReceiveProps = (nextProps) => {
    Object.keys(nextProps).map(val => {
      if (val in this.state) {
        this.setState({[val]: nextProps[val]});
      }
    });

    if (nextProps.forceUpdate) {
      /* let pageParmCache = {...this.state.pageParmCache};
       let pagination = {...this.state.pagination};
       pagination.current = parseInt(pageParmCache.pageNumber);
       pagination.pageSize = parseInt(pageParmCache.pageSize);

       this.setState({pageParm: pageParmCache, pagination});
       this.ajaxRequest(pageParmCache);*/

      //重新刷新的数据，默认从第一页开始
      this.ajaxRequest(nextProps.pageParm,1);
    } else {
      Object.keys(nextProps.pageParm).find(val => {
        nextProps.pageParm[val] != this.props.pageParm[val] && this.ajaxRequest(nextProps.pageParm);
        return nextProps.pageParm[val] != this.props.pageParm[val];
      });

    }


  }


  /******************************ajax请求******************************/

  ajaxRequest = (ajaxPara = this.state.pageParm,current='') => {
    //根据父组件的url parm 请求数据
    const {url, pagination} = this.state;
    // const pageParm = ajaxPara;
    let pageParm = ajaxPara;
    pageParm.pageNumber= current!==''?current:pageParm.pageNumber;
    api[url](pageParm).then((data) => {
      if(!data.data) return;  //防止接口返回null
      //[特殊情况],如果数据返回回来不止只有列表数组数据,自己拼接渲染数据
      if(this.props.renderDataParam){
        data.data={
          ...data.data,
          data:data.data[this.props.renderDataParam].data,
          pageNumber: data.data[this.props.renderDataParam].pageNumber,
          pageSize: data.data[this.props.renderDataParam].pageSize,
          total: data.data[this.props.renderDataParam].total,
          totalPage: data.data[this.props.renderDataParam].totalPage
        }
      }
      // 过滤数据
      if(this.props.filterData) {
        data.data.data = this.props.filterData(data.data.data);
      }
      const { pageNumber, pageSize } = data.data;
      let dataSource = [...data.data.data].map((val, key) => ({
        ...val, ...{key: key},
        number: (pageNumber - 1) * pageSize + key + 1  //序号显示
      }));
      let pagination = {...pagination};
      pagination.total = data.data.total;
      pagination.current = current!==''? current : parseInt(pageParm.pageNumber);
      this.setState({dataSource, pagination, loading: false});
      let props = this.props || {};
      ("dateChange" in this.props) && this.props.dateChange(data.data);
    }, (err) => {
      console.log(err);
      ("dateChange" in this.props) && this.props.dateChange(err);
    });
  }

  /******************************相关事件******************************/
  showTotal = (total) => {
    if ("showTotal" in this.props) {
      // addOption   设置为 true 的时候，默认增加"全部选项
      if (Object.prototype.toString.call(this.props.showTotal) == "[object Boolean]") {
        if (this.props.showTotal) {
          return `总共${total}记录`
        }
      }
      //如果 addOption 为 object 配置对象，则默认添加
      if (Object.prototype.toString.call(this.props.showTotal) == "[object Function]") {
        return this.props.showTotal(total);
      }
    } else {
      return ""
    }

  }
  //页码变化
  onPaginationChange = (page, pageSize) => {
    const pageParm = this.state.pageParm;
    pageParm.pageNumber = page;
    pageParm.current = page;
    this.setState({loading: true, pageParm}, () => {
      this.ajaxRequest();
    });
    let props = this.props || {};
    ("pagination" in this.props) && ("onChange" in this.props.pagination) && this.props.pagination.onChange(page, pageSize);
  }
  //页面记录数显示变化
  onPaginationShowSizeChange = (current, size) => {
    const pageParm = this.state.pageParm;
    const pagination = {...this.state.pagination};

    pageParm.pageSize = size;
    pageParm.pageNumber = 1;

    pagination.current = 1;
    this.setState({loading: true, pageParm, pagination}, () => {
      this.ajaxRequest(pageParm);
    });

    let props = this.props || {};
    ("pagination" in this.props) && ("onShowSizeChange" in this.props.pagination) && this.props.pagination.onShowSizeChange(current, size);
  }

  /******************************render******************************/

  render() {
    //防止自定义 page change 方法覆盖
    let pagination = {...this.state.pagination};
    pagination.onChange = this.onPaginationChange;
    pagination.onShowSizeChange = this.onPaginationShowSizeChange;

    let newProps = {...this.props, ...{pagination}};
    //数据使用自身请求
    // ("dataSource" in newProps) && (delete newProps.dataSource);
    return (
      <div>
        {newProps.dataSource}
        <Table
          dataSource={this.state.dataSource}
          // loading={this.state.loading}
          {...newProps}
        />
      </div>
    );
  }
}


