import _extends from "@babel/runtime/helpers/esm/extends";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";

/**
 * Pagination.jsx
 *
 * @Author: jruif
 * @Date: 2017/7/14 上午11:44
 */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Button from '../button';
import Input from '../input';
import scrollTo from '../util/scrollTo';
import Select from '../select';
/**
 * Pagination
 * */

var Pagination =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Pagination, _React$Component);

  _createClass(Pagination, null, [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      var newState = null;
      var current = props.current,
          pageSize = props.pageSize;

      if (current !== state.prevCurrent) {
        newState = {
          current: current,
          prevCurrent: current
        };
      }

      if (pageSize !== state.prevPageSize) {
        newState = Object.assign({}, newState, {
          pageSize: pageSize,
          prevPageSize: pageSize
        });
        var total = props.total,
            totalPage = props.totalPage;
        var totalNumber = 0;

        if (totalPage === 0) {
          if (total !== 0) {
            totalNumber = Math.ceil(total / pageSize);
          }
        } else {
          totalNumber = totalPage;
        }

        var maxPage = totalNumber;
        var currentPage = newState.current || state.current;
        newState.current = Math.min(currentPage, maxPage);
      }

      return newState;
    }
  }]);

  function Pagination(props) {
    var _this;

    _classCallCheck(this, Pagination);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Pagination).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "handleSizeChange", function (e, value) {
      var _this$props = _this.props,
          onChangePageSize = _this$props.onChangePageSize,
          onSizeChange = _this$props.onSizeChange;

      _this.setState(function (state) {
        var newState = {
          pageSize: value
        };

        var maxPage = _this.calcPage(value);

        var currentPage = state.current;
        newState.current = Math.min(currentPage, maxPage);
        return newState;
      });

      _this.scrollToTop();

      if (onSizeChange) onSizeChange(value);
      if (onChangePageSize) onChangePageSize(value);
    });

    _defineProperty(_assertThisInitialized(_this), "getTotalPage", function () {
      var _this$props2 = _this.props,
          total = _this$props2.total,
          pageSize = _this$props2.pageSize,
          totalPage = _this$props2.totalPage;
      return totalPage || Math.ceil(total / pageSize);
    });

    _defineProperty(_assertThisInitialized(_this), "handleInput", function (e) {
      var _this$props3 = _this.props,
          onChangePage = _this$props3.onChangePage,
          onInput = _this$props3.onInput;
      var target = e.target;
      var value = Number(target.value);

      var totalPage = _this.getTotalPage();

      var validValue = isNaN(value) || value < 1 ? '' : value > totalPage ? totalPage : value;

      _this.setState({
        inputPage: validValue
      });

      if (onChangePage) onChangePage(validValue);
      if (onInput) onInput(validValue);
    });

    _defineProperty(_assertThisInitialized(_this), "quickJumpPage", function () {
      var inputPage = _this.state.inputPage;

      if (inputPage > 0 && inputPage <= _this.getTotalPage()) {
        _this.jumpPage(inputPage);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "jumpPage", function (next) {
      var onChange = _this.props.onChange;

      _this.setState({
        current: next
      });

      _this.scrollToTop(function () {
        onChange && onChange(next);
      });
    });

    _defineProperty(_assertThisInitialized(_this), "scrollToTop", function (callback) {
      var _this$props4 = _this.props,
          scrollToTop = _this$props4.scrollToTop,
          scrollTime = _this$props4.scrollTime,
          tweenName = _this$props4.tweenName,
          scrollToValue = _this$props4.scrollToValue;

      if (scrollToTop) {
        var _window = window,
            pageYOffset = _window.pageYOffset;
        scrollTo(pageYOffset, scrollToValue, scrollTime, tweenName, function () {
          callback && callback();
        });
      } else {
        callback && callback();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "prev", function () {
      var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
      var current = _this.state.current;

      if (current > 1) {
        _this.jumpPage(current - page);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "next", function () {
      var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
      var current = _this.state.current;

      if (_this.calcPage() - current > 0) {
        _this.jumpPage(current + page);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "calcPage", function (p) {
      var size = p;
      var _this$props5 = _this.props,
          total = _this$props5.total,
          totalPage = _this$props5.totalPage;
      var pageSize = _this.state.pageSize;
      var totalNumber = 0; // 有默认值

      if (size == null) {
        size = pageSize;
      }

      if (totalPage === 0) {
        if (total !== 0) {
          totalNumber = Math.ceil(total / size);
        }
      } else {
        totalNumber = totalPage;
      }

      return totalNumber;
    });

    _defineProperty(_assertThisInitialized(_this), "renderPreBtn", function (index) {
      var _this$props6 = _this.props,
          buttonProps = _this$props6.buttonProps,
          prefixCls = _this$props6.prefixCls,
          size = _this$props6.size;
      var current = _this.state.current;
      var isCurrent = index === current;
      return React.createElement(Button, _extends({
        variant: "outlined",
        size: size
      }, buttonProps, {
        className: classNames(_defineProperty({}, "".concat(prefixCls, "-button-active"), isCurrent)),
        onClick: function onClick() {
          return _this.jumpPage(index);
        },
        color: isCurrent ? 'primary' : 'secondary'
      }), index);
    });

    var _current = props.current,
        _pageSize = props.pageSize;
    _this.state = {
      current: _current,
      prevCurrent: _current,
      pageSize: _pageSize,
      prevPageSize: _pageSize,
      inputPage: ''
    };
    return _this;
  }

  _createClass(Pagination, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props7 = this.props,
          total = _this$props7.total,
          totalPage = _this$props7.totalPage;
      var _this$props8 = this.props,
          showTotal = _this$props8.showTotal,
          showQuickJump = _this$props8.showQuickJump,
          showSelectPageSize = _this$props8.showSelectPageSize,
          prefixCls = _this$props8.prefixCls,
          showWhenOnlyOne = _this$props8.showWhenOnlyOne,
          size = _this$props8.size,
          buttonProps = _this$props8.buttonProps,
          prev = _this$props8.prev,
          next = _this$props8.next,
          className = _this$props8.className,
          showPer = _this$props8.showPer,
          compact = _this$props8.compact,
          isCompact = _this$props8.isCompact,
          pageSizeOptions = _this$props8.pageSizeOptions;
      var pageSize = this.state.pageSize;
      var _this$state = this.state,
          current = _this$state.current,
          inputPage = _this$state.inputPage;
      var elementPage = [];
      totalPage = Number(totalPage);
      total = Number(total);
      pageSize = Number(pageSize);

      if (totalPage === 0 && total === 0) {
        return null;
      }

      if (total !== 0) {
        // 默认值为0
        totalPage = Math.ceil(total / pageSize);
      }

      if (totalPage < 9) {
        for (var i = 0; i < totalPage; i++) {
          elementPage.push(React.createElement("li", {
            key: "page-".concat(i)
          }, this.renderPreBtn(i + 1)));
        }
      } else {
        var left = Math.max(1, current - 2);
        var right = Math.min(current + 2, totalPage);

        if (current - 1 <= 2) {
          right = 1 + 4;
        }

        if (totalPage - current <= 2) {
          left = totalPage - 4;
        }

        for (var _i = left; _i <= right; _i++) {
          elementPage.push(React.createElement("li", {
            key: "page-".concat(_i)
          }, this.renderPreBtn(_i)));
        }

        if (current - 1 >= 4) {
          elementPage.unshift(React.createElement("li", {
            key: "ellipsis-1"
          }, React.createElement(Button, _extends({
            variant: "outlined",
            className: classNames("".concat(prefixCls, "-ellipsis-prev"), _defineProperty({}, buttonProps.className, buttonProps.className)),
            size: size,
            onClick: function onClick() {
              return _this2.prev(4);
            }
          }, buttonProps), "...")));
        }

        if (totalPage - current >= 4) {
          elementPage.push(React.createElement("li", {
            key: "ellipsis-2"
          }, React.createElement(Button, _extends({
            variant: "outlined",
            className: classNames("".concat(prefixCls, "-ellipsis-next"), _defineProperty({}, buttonProps.className, buttonProps.className)),
            size: size,
            onClick: function onClick() {
              return _this2.next(4);
            }
          }, buttonProps), "...")));
        }

        if (left !== 1) {
          elementPage.unshift(React.createElement("li", {
            key: "page-first"
          }, this.renderPreBtn(1)));
        }

        if (right !== totalPage) {
          elementPage.push(React.createElement("li", {
            key: "page-last"
          }, this.renderPreBtn(totalPage)));
        }
      }

      var classes = classNames(prefixCls, className, "".concat(prefixCls, "-").concat(size), _defineProperty({}, "".concat(prefixCls, "-compact"), isCompact || compact));
      return this.calcPage() <= 1 && !showWhenOnlyOne ? null : React.createElement("ul", {
        className: classes
      }, React.createElement("li", {
        className: "".concat(prefixCls, "-previous")
      }, React.createElement(Button, _extends({
        variant: "outlined",
        onClick: function onClick() {
          return _this2.prev(1);
        },
        disabled: current <= 1,
        size: size
      }, buttonProps), prev)), showPer ? elementPage : null, React.createElement("li", {
        className: "".concat(prefixCls, "-next")
      }, React.createElement(Button, _extends({
        variant: "outlined",
        size: size,
        onClick: function onClick() {
          return _this2.next(1);
        },
        disabled: !(this.calcPage() - current > 0)
      }, buttonProps), next)), showSelectPageSize && React.createElement("li", null, React.createElement(Select, {
        className: "".concat(prefixCls, "-select"),
        defaultValue: pageSize,
        onChange: this.handleSizeChange,
        size: size,
        options: pageSizeOptions.map(function (val) {
          return {
            label: "".concat(val, "\u6761/\u9875"),
            value: val
          };
        })
      })), !!total && showTotal && React.createElement("li", null, React.createElement("span", {
        className: "".concat(prefixCls, "-total")
      }, "\u5171 ", total, " \u6761")), showQuickJump && React.createElement("li", {
        className: "".concat(prefixCls, "-number")
      }, "\u7B2C", React.createElement(Input, {
        size: size,
        className: "".concat(prefixCls, "-input"),
        type: "number",
        onChange: this.handleInput,
        value: inputPage
      }), "\u9875", React.createElement(Button, _extends({
        className: "".concat(prefixCls, "-jump"),
        size: size,
        onClick: this.quickJumpPage
      }, buttonProps), "\u8DF3\u8F6C")));
    }
  }]);

  return Pagination;
}(React.Component);

_defineProperty(Pagination, "propTypes", {
  /**
   * 数据总数，和totalPage二选一
   * */
  total: PropTypes.number,

  /**
   * 页数总数，和total二选一
   * */
  totalPage: PropTypes.number,

  /**
   * 每页大小
   * */
  pageSize: PropTypes.number,

  /**
   * 当前页码
   * */
  current: PropTypes.number,

  /**
   * 分页数组，例如：[10, 20, 40]
   * */
  pageSizeOptions: PropTypes.array,

  /**
   * 是否显示快速跳转
   * */
  showQuickJump: PropTypes.bool,

  /**
   * 是否显示每一页，为false的时候，只显示上下翻页按钮
   * */
  showPer: PropTypes.bool,

  /**
   * 是否数据总条数
   * */
  showTotal: PropTypes.bool,

  /**
   * 当只有一页的时候是否显示分页
   * */
  showWhenOnlyOne: PropTypes.bool,

  /**
   * 是否显示选择分页选择器
   * */
  showSelectPageSize: PropTypes.bool,

  /**
   * 是否显示为紧凑形式
   * */
  compact: PropTypes.bool,

  /**
   * 跳转页面，返回目标页码
   * */
  onChange: PropTypes.func,

  /**
   * 跳转输入框的change回调
   * */
  onInput: PropTypes.func,

  /**
   * 改变分页大小，返回改变后的数值
   * */
  onSizeChange: PropTypes.func,

  /**
   * 是否跳到页面顶部
   * */
  scrollToTop: PropTypes.bool,

  /**
   * 缓动动画名，参考：http://easings.net/zh-cn
   * */
  tweenName: PropTypes.string,

  /**
   * 滚动时间，单位是ms
   * */
  scrollTime: PropTypes.number,
  // 800秒

  /**
   * 滚动到某一点坐标
   * */
  scrollToValue: PropTypes.number,

  /**
   * 分页中所有按钮的属性，同Button组件
   * */
  buttonProps: PropTypes.object,

  /**
   * 优先级低于buttonProps.size
   * */
  size: PropTypes.oneOf(['small', 'medium', 'large']),

  /**
   * 前一页按钮
   * */
  prev: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),

  /**
   * 后一页按钮
   * */
  next: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),

  /**
   * 组件前缀，可用来重置样式
   * */
  prefixCls: PropTypes.string,

  /**
   * 分页样式类
   * */
  className: PropTypes.string
});

_defineProperty(Pagination, "defaultProps", {
  total: 0,
  totalPage: 0,
  pageSize: 10,
  current: 1,
  showPer: true,
  compact: false,
  showQuickJump: false,
  showTotal: false,
  showSelectPageSize: false,
  showWhenOnlyOne: false,
  prefixCls: 'ne-pagination',
  scrollToTop: true,
  scrollTime: 800,
  scrollToValue: 0,
  tweenName: 'easeOutQuint',
  size: 'medium',
  buttonProps: {},
  prev: '上一页',
  next: '下一页',
  pageSizeOptions: [10, 20, 50, 100]
});

export default Pagination;