import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Scrollbars } from 'amos-framework';
import imgStatic from 'CONSTS/imgStatic';

class GroupListPaginate extends Component {

  static propTypes = {
    pageSize: PropTypes.number,
    onChangePage: PropTypes.func,
    groupBy: PropTypes.func,
    renderItem: PropTypes.func,
    data: PropTypes.array
  };

  static defaultProps = {
    pageSize: 10,
    renderItem(){},
    data: [],
    onChangePage(){},
    groupBy(){}
  };

  constructor(props) {
    super(props);
    this.state = {
      pageSize: props.pageSize,
      page: 0,
      tip: undefined
    };
  }


  onChangePage = () => {
    const { page } = this.state;
    this.setState({ tip: 'running' }, () => this.props.onChangePage(page + 1));
  }

  onScrollFrame = (e) => {
    if (e && e.top === 1) {
      !this.state.tip && this.state.tip !== 'running' && this.onChangePage();
    }
  }

  setData = (d, parent) => {
    let { data } = this.props;
    let { tip } = this.state;
    const { content, totalPages, number } = d || {};
    if (number === 0) {
      data = content;
    } else {
      if (content.length > 0) {
        data.push(...content);
      }
    }
    if (totalPages === (number + 1)) {
      tip = 'finsh';
    } else {
      tip = undefined;
    }
    this.setState({ tip, page: number });
    if (number === 0) {
      this.scroll.scrollToTop();
    }
    parent.setState({ data });
  }

  setPage = (page) => {
    this.setState({ page });
  }

  render() {
    const { renderItem, data, groupBy } = this.props;
    const { tip } = this.state;
    let flag = '';
    data.map(e => {
      const data = groupBy(e);
      if (flag !== data) {
        e.groupByValue = data;
        flag = data;
      } else {
        e.groupByValue = undefined;
      }
    });
    return (
      <Scrollbars
        ref={node => this.scroll = node}
        onScrollFrame={this.onScrollFrame}
      >
        <div className="list-paginate datapane-list-content" ref={node => this.node = node}>
          {
            data.map(e => renderItem(e))
          }
          {
            !tip && data.lengt > 0 && <Button className="list-paginate-more" onClick={this.onChangePage}>
                加载更多
            </Button>
          }
          {
            tip === 'finsh' && <span  className="list-paginate-nomore" ><img src={imgStatic.datapane.noMore} alt="" />没有更多了</span>
          }
          {
            tip === 'running' && <span  className="list-paginate-loading" >
              <img src={imgStatic.datapane.loading} alt="" />
              <p>加载中</p>
            </span>
          }
        </div>
      </Scrollbars>
    );
  }
}

export default GroupListPaginate;
