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

class ListPaginate extends Component {

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

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

  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;
    }
    if (number === 0) {
      this.scroll.scrollToTop();
    }
    this.setState({ tip, page: number });
    parent.setState({ data });
  }

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

  render() {
    const { renderItem, data } = this.props;
    const { tip } = this.state;
    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.length > 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 ListPaginate;
