"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _configProvider = _interopRequireDefault(require("../config-provider"));

var _icon = _interopRequireDefault(require("../icon"));

var _button = _interopRequireDefault(require("../button"));

var _dropdown = _interopRequireDefault(require("../dropdown"));

var _menu = _interopRequireDefault(require("../menu"));

var _input = _interopRequireDefault(require("../input"));

var _select = _interopRequireDefault(require("../select"));

var _util = require("../util");

var _zhCn = _interopRequireDefault(require("../locale/zh-cn.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Option = _select["default"].Option;

var noop = function noop() {};
/**
 * Pagination
 */


var Pagination =
/*#__PURE__*/
function (_Component) {
  _inherits(Pagination, _Component);

  function Pagination(_props, context) {
    var _this;

    _classCallCheck(this, Pagination);

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

    _defineProperty(_assertThisInitialized(_this), "correctCurrent", function (currentPage, total, currentPageSize) {
      var totalPage = _this.getTotalPage(total, currentPageSize);

      return currentPage > totalPage ? totalPage : currentPage;
    });

    _defineProperty(_assertThisInitialized(_this), "getTotalPage", function (total, currentPageSize) {
      var totalPage = Math.ceil(total / currentPageSize);
      return totalPage <= 0 ? 1 : totalPage;
    });

    _defineProperty(_assertThisInitialized(_this), "onJump", function (e) {
      var total = _this.props.total;
      var _this$state = _this.state,
          current = _this$state.current,
          currentPageSize = _this$state.currentPageSize;

      var totalPage = _this.getTotalPage(total, currentPageSize);

      var value = parseInt(_this.inputValue, 10);

      if (typeof value === 'number' && value >= 1 && value <= totalPage && value !== current) {
        _this.onPageItemClick(value, e);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onPageItemClick", function (page, e) {
      if (!('current' in _this.props)) {
        _this.setState({
          current: page
        }, function () {
          _this.props.onChange(page, e);
        });
      } else {
        _this.props.onChange(page, e);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onInputChange", function (value) {
      _this.inputValue = value;
    });

    _defineProperty(_assertThisInitialized(_this), "onSelectSize", function (pageSize) {
      var newState = {
        currentPageSize: pageSize
      };

      var totalPage = _this.getTotalPage(_this.props.total, pageSize);

      if (_this.state.current > totalPage) {
        newState.current = totalPage;
      }

      _this.setState(newState);

      _this.props.onPageSizeChange(pageSize);
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageTotal", function () {
      var _this$props = _this.props,
          prefix = _this$props.prefix,
          total = _this$props.total,
          totalRender = _this$props.totalRender;
      var _this$state2 = _this.state,
          currentPageSize = _this$state2.currentPageSize,
          current = _this$state2.current;
      var range = [(current - 1) * currentPageSize + 1, current * currentPageSize];
      return _react["default"].createElement("div", {
        className: "".concat(prefix, "pagination-total")
      }, totalRender(total, range));
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageItem", function (index) {
      var _cx;

      var _this$props2 = _this.props,
          prefix = _this$props2.prefix,
          total = _this$props2.total,
          pageSize = _this$props2.pageSize,
          locale = _this$props2.locale;
      var current = _this.state.current;

      var totalPage = _this.getTotalPage(total, pageSize);

      var isCurrent = parseInt(index, 10) === current;
      var props = {
        className: (0, _classnames["default"])((_cx = {}, _defineProperty(_cx, "".concat(prefix, "pagination-item"), true), _defineProperty(_cx, "".concat(prefix, "current"), isCurrent), _cx)),
        onClick: isCurrent ? noop : _this.onPageItemClick.bind(_assertThisInitialized(_this), index)
      };
      return _react["default"].createElement("div", _extends({
        "aria-label": _util.str.template(locale.total, {
          current: index,
          total: totalPage
        })
      }, props, {
        key: index
      }), index);
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageFirst", function (current) {
      var _cx2;

      var _this$props3 = _this.props,
          prefix = _this$props3.prefix,
          locale = _this$props3.locale;
      var isFirst = current <= 1;
      var props = {
        className: (0, _classnames["default"])((_cx2 = {}, _defineProperty(_cx2, "".concat(prefix, "pagination-item"), true), _defineProperty(_cx2, "".concat(prefix, "pagination-item-disabled"), isFirst), _defineProperty(_cx2, "".concat(prefix, "prev"), true), _cx2)),
        onClick: isFirst ? null : _this.onPageItemClick.bind(_assertThisInitialized(_this), current - 1)
      };
      return _react["default"].createElement(_icon["default"], _extends({
        type: "chevron-left-s"
      }, props, {
        "aria-label": _util.str.template(locale.labelPrev, {
          current: current
        })
      }));
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageLast", function (current, totalPage) {
      var _cx3;

      var _this$props4 = _this.props,
          prefix = _this$props4.prefix,
          locale = _this$props4.locale;
      var isLast = current >= totalPage;
      var props = {
        className: (0, _classnames["default"])((_cx3 = {}, _defineProperty(_cx3, "".concat(prefix, "pagination-item"), true), _defineProperty(_cx3, "".concat(prefix, "pagination-item-disabled"), isLast), _defineProperty(_cx3, "".concat(prefix, "next"), true), _cx3)),
        onClick: isLast ? null : _this.onPageItemClick.bind(_assertThisInitialized(_this), current + 1)
      };
      return _react["default"].createElement(_icon["default"], _extends({
        type: "chevron-right-s"
      }, props, {
        "aria-label": _util.str.template(locale.labelNext, {
          current: current
        })
      }));
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageEllipsis", function (idx) {
      var prefix = _this.props.prefix;
      return _react["default"].createElement(_icon["default"], {
        type: "more",
        className: "".concat(prefix, "pagination-ellipsis"),
        key: "ellipsis-".concat(idx)
      });
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageJump", function () {
      var _this$props5 = _this.props,
          prefix = _this$props5.prefix,
          locale = _this$props5.locale;
      /* eslint-disable react/jsx-key */

      return [_react["default"].createElement("span", {
        className: "".concat(prefix, "pagination-jump-text")
      }, locale.goTo), _react["default"].createElement(_input["default"], {
        size: "xs",
        className: "".concat(prefix, "pagination-jump-input"),
        type: "text",
        "aria-label": locale.inputAriaLabel,
        onChange: _this.onInputChange,
        onKeyDown: function onKeyDown(e) {
          if (e.keyCode === _util.KEYCODE.ENTER) {
            _this.onJump(e);
          }
        }
      }), _react["default"].createElement("span", {
        className: "".concat(prefix, "pagination-jump-text")
      }, locale.page)];
      /* eslint-enable react/jsx-key */
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageDisplay", function (current, totalPage) {
      var prefix = _this.props.prefix;
      var menu = [];

      for (var i = 1; i <= totalPage; i++) {
        menu.push(_react["default"].createElement(_menu["default"].Item, {
          key: i
        }, i));
      }

      return _react["default"].createElement("span", {
        className: "".concat(prefix, "pagination-display")
      }, _react["default"].createElement(_dropdown["default"], {
        trigger: _react["default"].createElement(_button["default"], {
          type: "secondary"
        }, "".concat(current, "/").concat(totalPage)),
        triggerType: "click"
      }, _react["default"].createElement(_menu["default"], {
        style: {
          maxHeight: 152,
          overflow: 'auto'
        },
        selectMode: "single",
        selectedKeys: "".concat(current),
        onSelect: function onSelect(selectedKeys) {
          _this.onPageItemClick(+selectedKeys[0]);
        }
      }, menu)));
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageList", function (current, totalPage) {
      var _this$props6 = _this.props,
          prefix = _this$props6.prefix,
          pageShowCount = _this$props6.pageShowCount;
      var pages = [];

      if (totalPage <= pageShowCount) {
        for (var i = 1; i <= totalPage; i++) {
          pages.push(_this.renderPageItem(i));
        }
      } else {
        // 除去第一页，最后一页以及当前页，剩下的页数
        var othersCount = pageShowCount - 3;
        var halfCount = parseInt(othersCount / 2, 10);
        var start;
        var end;
        pages.push(_this.renderPageItem(1));
        start = current - halfCount;
        end = current + halfCount;

        if (start <= 1) {
          start = 2;
          end = start + othersCount;
        }

        if (start > 2) {
          pages.push(_this.renderPageEllipsis(1));
        }

        if (end >= totalPage - 1) {
          end = totalPage - 1;
          start = totalPage - 1 - othersCount;
        }

        for (var j = start; j <= end; j++) {
          pages.push(_this.renderPageItem(j));
        }

        if (end < totalPage - 1) {
          pages.push(_this.renderPageEllipsis(2));
        }

        pages.push(_this.renderPageItem(totalPage));
      }

      return _react["default"].createElement("div", {
        className: "".concat(prefix, "pagination-list")
      }, pages);
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageSizeSelector", function () {
      var _this$props7 = _this.props,
          prefix = _this$props7.prefix,
          pageSizeSelector = _this$props7.pageSizeSelector;

      switch (pageSizeSelector) {
        case 'dropdown':
          return _react["default"].createElement("div", {
            className: "".concat(prefix, "pagination-size-selector")
          }, _this.renderPageSizeDropdown());

        default:
          return null;
      }
    });

    _defineProperty(_assertThisInitialized(_this), "renderPageSizeDropdown", function () {
      var _this$props8 = _this.props,
          prefix = _this$props8.prefix,
          pageSizeList = _this$props8.pageSizeList,
          selectPopupContiner = _this$props8.selectPopupContiner,
          locale = _this$props8.locale,
          popupProps = _this$props8.popupProps;
      var currentPageSize = _this.state.currentPageSize;
      return _react["default"].createElement(_select["default"], {
        size: "xs",
        className: "".concat(prefix, "pagination-size-selector-dropdown"),
        popupClassName: "".concat(prefix, "pagination-size-selector-popup"),
        popupContainer: selectPopupContiner,
        popupProps: popupProps,
        "aria-label": locale.selectAriaLabel,
        autoWidth: true,
        value: currentPageSize,
        valueRender: function valueRender(item) {
          return _react["default"].createElement("span", {
            className: "".concat(prefix, "pagination-size-selector-dropdown-value-text")
          }, "".concat(item.value, " ").concat(locale.pageSize));
        },
        onChange: _this.onSelectSize
      }, pageSizeList.map(function (item, index) {
        var label;
        var pageSize;

        if (item.value) {
          // {label: '', value: 5}
          label = item.label;
          pageSize = item.value;
        } else {
          // number
          label = pageSize = item;
        }

        return _react["default"].createElement(Option, {
          key: index,
          value: pageSize
        }, label);
      }));
    });

    var _current = _props.current,
        defaultCurrent = _props.defaultCurrent,
        _total = _props.total,
        _pageSize = _props.pageSize;
    _this.state = {
      current: _this.correctCurrent(_current || defaultCurrent, _total, _pageSize),
      currentPageSize: _pageSize
    };
    return _this;
  }

  _createClass(Pagination, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var current = nextProps.current,
          total = nextProps.total,
          pageSize = nextProps.pageSize;
      var st = {};
      var newCurrent = this.correctCurrent(current || this.state.current, total, pageSize);

      if (this.state.current !== newCurrent) {
        st.current = newCurrent;
      }

      if (this.state.currentPageSize !== pageSize) {
        st.currentPageSize = pageSize;
      }

      if (Object.keys(st).length) {
        this.setState(st);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _cx4,
          _this2 = this;

      /* eslint-disable no-unused-vars */
      var _this$props9 = this.props,
          prefix = _this$props9.prefix,
          pure = _this$props9.pure,
          rtl = _this$props9.rtl,
          type = _this$props9.type,
          className = _this$props9.className,
          total = _this$props9.total,
          totalRender = _this$props9.totalRender,
          pageSize = _this$props9.pageSize,
          pageSizeSelector = _this$props9.pageSizeSelector,
          pageSizeList = _this$props9.pageSizeList,
          onPageSizeChange = _this$props9.onPageSizeChange,
          hideOnlyOnePage = _this$props9.hideOnlyOnePage,
          showJump = _this$props9.showJump,
          locale = _this$props9.locale,
          current = _this$props9.current,
          defaultCurrent = _this$props9.defaultCurrent,
          pageShowCount = _this$props9.pageShowCount,
          onChange = _this$props9.onChange,
          selectPopupContiner = _this$props9.selectPopupContiner,
          popupProps = _this$props9.popupProps,
          others = _objectWithoutProperties(_this$props9, ["prefix", "pure", "rtl", "type", "className", "total", "totalRender", "pageSize", "pageSizeSelector", "pageSizeList", "onPageSizeChange", "hideOnlyOnePage", "showJump", "locale", "current", "defaultCurrent", "pageShowCount", "onChange", "selectPopupContiner", "popupProps"]);
      /* eslint-enable */


      var _this$state3 = this.state,
          currentPage = _this$state3.current,
          currentPageSize = _this$state3.currentPageSize;
      var totalPage = this.getTotalPage(total, currentPageSize);
      var pageFirst = this.renderPageFirst(currentPage);
      var pageLast = this.renderPageLast(currentPage, totalPage);
      var sizeSelector = this.renderPageSizeSelector();
      var classes = (0, _classnames["default"])((_cx4 = {}, _defineProperty(_cx4, "".concat(prefix, "pagination"), true), _defineProperty(_cx4, "".concat(prefix).concat(type), type), _defineProperty(_cx4, "".concat(prefix, "hide"), totalPage <= 1 && hideOnlyOnePage), _defineProperty(_cx4, className, !!className), _cx4));

      if (rtl) {
        others.dir = 'rtl';
      }

      var buildComponent = function buildComponent() {
        for (var _len = arguments.length, coms = new Array(_len), _key = 0; _key < _len; _key++) {
          coms[_key] = arguments[_key];
        }

        return _react["default"].createElement("div", _extends({
          className: classes
        }, _util.obj.pickAttrs(others)), totalRender ? _this2.renderPageTotal() : null, _react["default"].createElement("div", {
          className: "".concat(prefix, "pagination-pages")
        }, coms.map(function (com, index) {
          return com && _react["default"].cloneElement(com, {
            key: index
          });
        })));
      };

      switch (type) {
        case 'simple':
          {
            var pageDisplay = this.renderPageDisplay(currentPage, totalPage);
            return buildComponent(pageFirst, pageDisplay, pageLast);
          }

        case 'normal':
          {
            var pageList = this.renderPageList(currentPage, totalPage);
            var pageJump = showJump && total > pageSize * pageShowCount ? this.renderPageJump(currentPage, totalPage) : [];
            return buildComponent.apply(void 0, [pageFirst, pageList, pageLast, sizeSelector].concat(_toConsumableArray(pageJump)));
          }

        default:
          return null;
      }
    }
  }]);

  return Pagination;
}(_react.Component);

_defineProperty(Pagination, "displayName", 'Pagination');

_defineProperty(Pagination, "propTypes", {
  prefix: _propTypes["default"].string,
  pure: _propTypes["default"].bool,
  rtl: _propTypes["default"].bool,
  className: _propTypes["default"].string,

  /**
   * 自定义国际化文案对象
   */
  locale: _propTypes["default"].object,

  /**
   * 分页组件类型
   */
  type: _propTypes["default"].oneOf(['normal', 'simple']),

  /**
   * （受控）当前页码
   */
  current: _propTypes["default"].number,

  /**
   * （非受控）初始页码
   */
  defaultCurrent: _propTypes["default"].number,

  /**
   * 页码发生改变时的回调函数
   * @param {Number} current 改变后的页码数
   * @param {Object} e 点击事件对象
   */
  onChange: _propTypes["default"].func,

  /**
   * 总记录数
   */
  total: _propTypes["default"].number,

  /**
   * 总数的渲染函数
   * @param {Number} total 总数
   * @param {Array} range 当前数据在总数中的区间
   */
  totalRender: _propTypes["default"].func,

  /**
   * 页码显示的数量，更多的使用...代替
   */
  pageShowCount: _propTypes["default"].number,

  /**
   * 一页中的记录数
   */
  pageSize: _propTypes["default"].number,

  /**
   * 每页显示选择器类型
   */
  pageSizeSelector: _propTypes["default"].oneOf([false, 'dropdown']),

  /**
   * 每页显示选择器可选值
   */
  pageSizeList: _propTypes["default"].oneOfType([_propTypes["default"].arrayOf(_propTypes["default"].number), _propTypes["default"].arrayOf(_propTypes["default"].shape({
    label: _propTypes["default"].string,
    value: _propTypes["default"].number
  }))]),

  /**
   * 每页显示记录数量改变时的回调函数
   * @param {Number} pageSize 改变后的每页显示记录数
   */
  onPageSizeChange: _propTypes["default"].func,

  /**
   * 当分页数为1时，是否隐藏分页器
   */
  hideOnlyOnePage: _propTypes["default"].bool,

  /**
   * type 设置为 normal 时，在页码数超过5页后，会显示跳转输入框与按钮，当设置 showJump 为 false 时，不再显示该跳转区域
   */
  showJump: _propTypes["default"].bool,
  selectPopupContiner: _propTypes["default"].func,

  /**
   * 弹层组件属性，透传给Popup
   */
  popupProps: _propTypes["default"].object
});

_defineProperty(Pagination, "defaultProps", {
  prefix: 'next-',
  pure: false,
  rtl: false,
  locale: _zhCn["default"].Pagination,
  type: 'normal',
  defaultCurrent: 1,
  onChange: noop,
  pageSize: 10,
  pageSizeSelector: false,
  pageSizeList: [5, 10, 20],
  onPageSizeChange: noop,
  total: 100,
  pageShowCount: 5,
  hideOnlyOnePage: false,
  showJump: true,
  selectPopupContiner: function selectPopupContiner(node) {
    return node.parentNode;
  }
});

var _default = _configProvider["default"].config(Pagination);

exports["default"] = _default;