"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

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

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _tslib = require("tslib");

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

var _mobx = require("mobx");

var _mobxReact = require("mobx-react");

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

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _KeyCode = _interopRequireDefault(require("../../../lib/_util/KeyCode"));

var _enum = require("../../../lib/_util/enum");

var _DataSetComponent2 = _interopRequireDefault(require("../data-set/DataSetComponent"));

var _Select = _interopRequireDefault(require("../select/Select"));

var _NumberField = _interopRequireDefault(require("../number-field/NumberField"));

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

var _autobind = _interopRequireDefault(require("../_util/autobind"));

var _localeContext = require("../locale-context");

var _Pager = _interopRequireDefault(require("./Pager"));

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

var _enum2 = require("./enum");

var _enum3 = require("../text-field/enum");

var _QuickJumper = _interopRequireDefault(require("./QuickJumper"));

function defaultItemRender(page, type) {
  switch (type) {
    case 'first':
      return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "first_page"
      });

    case 'last':
      return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "last_page"
      });

    case 'prev':
      return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "navigate_before"
      });

    case 'next':
      return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "navigate_next"
      });

    case 'jump-prev':
    case 'jump-next':
      return '•••';

    default:
      return page;
  }
}

var Pagination = /*#__PURE__*/function (_DataSetComponent) {
  (0, _inherits2["default"])(Pagination, _DataSetComponent);

  var _super = (0, _createSuper2["default"])(Pagination);

  function Pagination() {
    (0, _classCallCheck2["default"])(this, Pagination);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(Pagination, [{
    key: "pageSize",
    get: function get() {
      var _this$observableProps = this.observableProps,
          dataSet = _this$observableProps.dataSet,
          pageSize = _this$observableProps.pageSize;

      if (dataSet) {
        return dataSet.pageSize;
      }

      return pageSize;
    }
  }, {
    key: "page",
    get: function get() {
      var _this$observableProps2 = this.observableProps,
          dataSet = _this$observableProps2.dataSet,
          page = _this$observableProps2.page;

      if (dataSet) {
        return dataSet.currentPage;
      }

      return page;
    }
  }, {
    key: "total",
    get: function get() {
      var _this$observableProps3 = this.observableProps,
          dataSet = _this$observableProps3.dataSet,
          total = _this$observableProps3.total;

      if (dataSet) {
        return dataSet.totalCount;
      }

      return total;
    }
  }, {
    key: "totalPage",
    get: function get() {
      var dataSet = this.observableProps.dataSet;
      var total = this.total,
          pageSize = this.pageSize;

      if (dataSet) {
        return dataSet.totalPage;
      }

      if (total !== undefined && pageSize !== undefined) {
        return Math.ceil(total / pageSize);
      }

      return 1;
    }
  }, {
    key: "next",
    get: function get() {
      var _this$total = this.total,
          total = _this$total === void 0 ? 0 : _this$total,
          pageSize = this.pageSize,
          page = this.page;
      return page < Math.floor((total - 1) / pageSize) + 1;
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      var globalPagination = this.getContextConfig('pagination');
      var pageSizeOptions = props.pageSizeOptions || globalPagination && globalPagination.pageSizeOptions || ['10', '20', '50', '100'];
      var maxPageSize = Math.max.apply(Math, [(0, _defaultTo["default"])('maxPageSize' in props ? props.maxPageSize : globalPagination && globalPagination.maxPageSize, 100)].concat((0, _toConsumableArray2["default"])(pageSizeOptions)));
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _get2["default"])((0, _getPrototypeOf2["default"])(Pagination.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        page: (0, _defaultTo["default"])('page' in props ? props.page : globalPagination && globalPagination.page, 1),
        pageSize: (0, _defaultTo["default"])('pageSize' in props ? props.pageSize : globalPagination && globalPagination.pageSize, 10),
        total: props.total,
        pageSizeOptions: pageSizeOptions,
        pageSizeEditable: 'pageSizeEditable' in props ? props.pageSizeEditable : globalPagination && globalPagination.pageSizeEditable,
        maxPageSize: maxPageSize
      });
    }
  }, {
    key: "handlePageSizeBeforeChange",
    value: function handlePageSizeBeforeChange(value) {
      if (value < 1 || value > this.observableProps.maxPageSize) {
        return false;
      }

      var dataSet = this.props.dataSet;

      if (dataSet) {
        return dataSet.modifiedCheck();
      }

      return true;
    }
  }, {
    key: "handlePageSizeChange",
    value: function handlePageSizeChange(value) {
      this.handleChange(this.page, Number(value));
    }
  }, {
    key: "handleChange",
    value: function () {
      var _handleChange = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(page, pageSize) {
        var _this = this;

        var _this$props, dataSet, onChange, _this$props$beforeCha, beforeChange;

        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$props = this.props, dataSet = _this$props.dataSet, onChange = _this$props.onChange, _this$props$beforeCha = _this$props.beforeChange, beforeChange = _this$props$beforeCha === void 0 ? _noop["default"] : _this$props$beforeCha;
                _context.t0 = this.pageSize !== pageSize;

                if (!_context.t0) {
                  _context.next = 7;
                  break;
                }

                _context.next = 5;
                return beforeChange(page, pageSize);

              case 5:
                _context.t1 = _context.sent;
                _context.t0 = _context.t1 !== false;

              case 7:
                if (!_context.t0) {
                  _context.next = 11;
                  break;
                }

                (0, _mobx.runInAction)(function () {
                  _this.observableProps.pageSize = pageSize;
                  _this.observableProps.page = 1;

                  if (dataSet) {
                    dataSet.pageSize = pageSize;
                    dataSet.currentPage = 1;
                    dataSet.query(1, undefined, true);
                  }
                });
                _context.next = 12;
                break;

              case 11:
                (0, _mobx.runInAction)(function () {
                  _this.observableProps.page = page;
                });

              case 12:
                if (onChange) {
                  onChange(page, pageSize);
                }

              case 13:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function handleChange(_x, _x2) {
        return _handleChange.apply(this, arguments);
      }

      return handleChange;
    }()
  }, {
    key: "handlePagerClick",
    value: function handlePagerClick(page) {
      this.jumpPage(page);
    }
  }, {
    key: "getValidValue",
    value: function getValidValue(value) {
      var page = this.page,
          totalPage = this.totalPage;
      value = Number(value);

      if (isNaN(value)) {
        value = page;
      }

      if (value > totalPage) {
        value = totalPage;
      }

      return value;
    }
  }, {
    key: "jumpPage",
    value: function () {
      var _jumpPage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(page) {
        var _this$props2, dataSet, _this$props2$beforeCh, beforeChange;

        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$props2 = this.props, dataSet = _this$props2.dataSet, _this$props2$beforeCh = _this$props2.beforeChange, beforeChange = _this$props2$beforeCh === void 0 ? _noop["default"] : _this$props2$beforeCh;
                _context2.next = 3;
                return beforeChange(page, this.pageSize);

              case 3:
                _context2.t0 = _context2.sent;

                if (!(_context2.t0 !== false)) {
                  _context2.next = 7;
                  break;
                }

                if (dataSet) {
                  dataSet.page(page);
                }

                this.handleChange(page, this.pageSize);

              case 7:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function jumpPage(_x3) {
        return _jumpPage.apply(this, arguments);
      }

      return jumpPage;
    }()
  }, {
    key: "handleJumpChange",
    value: function handleJumpChange(value) {
      var page = this.page,
          totalPage = this.totalPage,
          _this$props3 = this.props,
          showQuickJumper = _this$props3.showQuickJumper,
          simple = _this$props3.simple;
      value = Number(value);

      if (isNaN(value)) {
        value = page;
      }

      if (value > totalPage) {
        value = totalPage;
      }

      if (simple) {
        this.jumpPage(value);
      } else if (showQuickJumper) {
        if ((0, _isObject["default"])(showQuickJumper) && showQuickJumper.goButton) {
          this.pageInput = value;
        } else {
          this.jumpPage(value);
        }
      }
    }
  }, {
    key: "handleJumpGo",
    value: function handleJumpGo(e) {
      if (e.keyCode === _KeyCode["default"].ENTER || e.type === 'click') {
        var pageInput = this.pageInput;

        if (pageInput) {
          this.jumpPage(pageInput);
          this.pageInput = '';
        }
      }
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Pagination.prototype), "getOmitPropsKeys", this).call(this).concat(['total', 'page', 'pageSize', 'maxPageSize', 'pageSizeEditable', 'onChange', 'pageSizeOptions', 'itemRender', 'showSizeChanger', 'showQuickJumper', 'showSizeChangerLabel', 'showTotal', 'showPager', 'sizeChangerPosition', 'sizeChangerOptionRenderer', 'hideOnSinglePage', 'simple', 'quickJumperPosition']);
    }
  }, {
    key: "getOptions",
    value: function getOptions() {
      var Option = _Select["default"].Option;
      return this.observableProps.pageSizeOptions.map(function (option) {
        return /*#__PURE__*/_react["default"].createElement(Option, {
          key: option,
          value: option
        }, option);
      });
    }
  }, {
    key: "getPager",
    value: function getPager(page, type) {
      var active = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var disabledSender = arguments.length > 3 ? arguments[3] : undefined;
      var prefixCls = this.prefixCls,
          _this$props4 = this.props,
          _this$props4$itemRend = _this$props4.itemRender,
          itemRender = _this$props4$itemRend === void 0 ? defaultItemRender : _this$props4$itemRend,
          _this$props4$disabled = _this$props4.disabled,
          disabled = _this$props4$disabled === void 0 ? false : _this$props4$disabled;
      var disabledValue = disabledSender || disabled;
      var classNamePager = (0, _isString["default"])(type) ? "".concat(prefixCls, "-pager-").concat(type) : "";
      return /*#__PURE__*/_react["default"].createElement(_Pager["default"], {
        key: type === 'page' ? page : type,
        page: page,
        active: active,
        type: type,
        onClick: this.handlePagerClick,
        renderer: itemRender,
        disabled: disabledValue,
        className: "".concat(prefixCls, "-pager ").concat(classNamePager)
      });
    }
  }, {
    key: "renderPagers",
    value: function renderPagers(page) {
      var totalPage = this.totalPage;
      var bufferSize = 1;
      var pagerList = [];

      if (totalPage <= 3 + bufferSize * 2) {
        for (var i = 1; i <= totalPage; i += 1) {
          pagerList.push(this.getPager(i, 'page', page === i));
        }
      } else {
        var left = Math.max(1, page - bufferSize);
        var right = Math.min(totalPage, page + bufferSize);

        if (page - 1 <= bufferSize) {
          right = 1 + bufferSize * 2;
        }

        if (totalPage - page <= bufferSize) {
          left = totalPage - bufferSize * 2;
        }

        for (var _i = left; _i <= right; _i++) {
          pagerList.push(this.getPager(_i, 'page', page === _i));
        }

        if (page - 1 >= bufferSize * 2 && page !== 1 + 2) {
          pagerList.unshift(this.getPager(Math.max(page - 5, 1), 'jump-prev'));
        }

        if (totalPage - page >= bufferSize * 2 && page !== totalPage - 2) {
          pagerList.push(this.getPager(Math.min(page + 5, totalPage), 'jump-next'));
        }

        if (left !== 1) {
          pagerList.unshift(this.getPager(1, 'page', page === 1));
        }

        if (totalPage > 1 && right !== totalPage) {
          pagerList.push(this.getPager(totalPage, 'page', page === totalPage));
        }
      }

      return pagerList;
    }
  }, {
    key: "renderSizeChange",
    value: function renderSizeChange(pageSize) {
      var _this$props5 = this.props,
          showSizeChangerLabel = _this$props5.showSizeChangerLabel,
          showSizeChanger = _this$props5.showSizeChanger,
          sizeChangerOptionRenderer = _this$props5.sizeChangerOptionRenderer,
          disabled = _this$props5.disabled;

      if (showSizeChanger) {
        var pageSizeEditable = this.observableProps.pageSizeEditable;
        var prefixCls = this.prefixCls;

        var select = /*#__PURE__*/_react["default"].createElement(_Select["default"], {
          isFlat: true,
          searchable: false,
          key: "size-select",
          className: (0, _classnames["default"])("".concat(prefixCls, "-size-changer"), (0, _defineProperty2["default"])({}, "".concat(prefixCls, "-size-editable"), pageSizeEditable)),
          disabled: disabled,
          onBeforeChange: this.handlePageSizeBeforeChange,
          onChange: this.handlePageSizeChange,
          value: String(pageSize),
          clearButton: false,
          renderer: sizeChangerOptionRenderer,
          optionRenderer: sizeChangerOptionRenderer,
          combo: pageSizeEditable,
          restrict: "0-9",
          size: _enum.Size.small
        }, this.getOptions());

        return showSizeChangerLabel ? [/*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-perpage"),
          key: "size-info"
        }, (0, _localeContext.$l)('Pagination', 'records_per_page')), select] : select;
      }
    }
  }, {
    key: "renderTotal",
    value: function renderTotal(pageSize, page, total) {
      var prefixCls = this.prefixCls,
          showTotal = this.props.showTotal,
          dataSet = this.dataSet;
      var from = pageSize * (page - 1) + 1;
      var to = Math.min(pageSize * page, total);
      var counting = dataSet && dataSet.counting;

      if (typeof showTotal === 'function') {
        return /*#__PURE__*/_react["default"].createElement("span", {
          key: "total",
          className: "".concat(prefixCls, "-page-info")
        }, showTotal(total, [from, to], counting !== undefined));
      }

      return /*#__PURE__*/_react["default"].createElement("span", {
        key: "total",
        className: "".concat(prefixCls, "-page-info")
      }, from, " - ", to, " / ", counting ? '...' : total);
    }
    /**
     * 渲染快速跳至
     */

  }, {
    key: "renderQuickGo",
    value: function renderQuickGo() {
      var prefixCls = this.prefixCls,
          page = this.page;
      var _this$props6 = this.props,
          disabled = _this$props6.disabled,
          showQuickJumper = _this$props6.showQuickJumper;
      var gotoButton = null;

      if ((0, _isObject["default"])(showQuickJumper) && showQuickJumper.goButton) {
        var goButton = showQuickJumper.goButton;
        gotoButton = typeof goButton === 'boolean' ? /*#__PURE__*/_react["default"].createElement(_button["default"], {
          className: "".concat(prefixCls, "-go-button"),
          onClick: this.handleJumpGo,
          onKeyUp: this.handleJumpGo,
          disabled: disabled,
          size: _enum.Size.small
        }, (0, _localeContext.$l)('Pagination', 'jump_to_confirm')) : /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-go-button"),
          onClick: this.handleJumpGo,
          onKeyUp: this.handleJumpGo
        }, goButton);
      }

      return /*#__PURE__*/_react["default"].createElement(_QuickJumper["default"], {
        prefixCls: prefixCls,
        value: this.pageInput || page,
        onChange: this.handleJumpChange,
        disabled: disabled,
        gotoButton: gotoButton
      });
    }
  }, {
    key: "render",
    value: function render() {
      var total = this.total,
          pageSize = this.pageSize,
          page = this.page,
          _this$props7 = this.props,
          hideOnSinglePage = _this$props7.hideOnSinglePage,
          simple = _this$props7.simple,
          prefixCls = this.prefixCls;

      if (total === undefined || pageSize === undefined || page === undefined) {
        return null;
      }

      if (hideOnSinglePage === true && total <= pageSize) {
        return null;
      }

      var totalPage = this.totalPage,
          _this$props8 = this.props,
          children = _this$props8.children,
          sizeChangerPosition = _this$props8.sizeChangerPosition,
          showTotal = _this$props8.showTotal,
          showPager = _this$props8.showPager,
          showQuickJumper = _this$props8.showQuickJumper,
          quickJumperPosition = _this$props8.quickJumperPosition;
      var sizeChanger = this.renderSizeChange(pageSize);

      if (simple) {
        return /*#__PURE__*/_react["default"].createElement("nav", (0, _extends2["default"])({}, this.getMergedProps()), this.getPager(page - 1, 'prev', false, page === 1), /*#__PURE__*/_react["default"].createElement("li", {
          className: "".concat(prefixCls, "-simple-pager")
        }, /*#__PURE__*/_react["default"].createElement(_NumberField["default"], {
          value: page,
          min: 1,
          onChange: this.handleJumpChange,
          valueChangeAction: _enum3.ValueChangeAction.input,
          wait: 200
        }), /*#__PURE__*/_react["default"].createElement("span", null, "\uFF0F"), totalPage), this.getPager(page + 1, 'next', false, !this.next));
      }

      return /*#__PURE__*/_react["default"].createElement("nav", (0, _extends2["default"])({}, this.getMergedProps()), children, sizeChangerPosition === _enum2.SizeChangerPosition.left && sizeChanger, showQuickJumper && quickJumperPosition === _enum2.QuickJumperPosition.left && this.renderQuickGo(), showTotal && this.renderTotal(pageSize, page, total), this.getPager(1, 'first', false, page === 1), this.getPager(page - 1, 'prev', false, page === 1), showPager && this.renderPagers(page), this.getPager(page + 1, 'next', false, !this.next), this.getPager(totalPage, 'last', false, !this.next), sizeChangerPosition === _enum2.SizeChangerPosition.right && sizeChanger, showQuickJumper && quickJumperPosition === _enum2.QuickJumperPosition.right && this.renderQuickGo());
    }
  }]);
  return Pagination;
}(_DataSetComponent2["default"]);

Pagination.displayName = 'Pagination';
Pagination.defaultProps = {
  suffixCls: 'pagination',
  sizeChangerPosition: _enum2.SizeChangerPosition.left,
  quickJumperPosition: _enum2.QuickJumperPosition.right,
  sizeChangerOptionRenderer: function sizeChangerOptionRenderer(_ref) {
    var text = _ref.text;
    return text;
  },
  hideOnSinglePage: false,
  showSizeChanger: true,
  showQuickJumper: false,
  showSizeChangerLabel: true,
  showTotal: true,
  simple: false
};
(0, _tslib.__decorate)([_mobx.observable], Pagination.prototype, "pageInput", void 0);
(0, _tslib.__decorate)([_mobx.computed], Pagination.prototype, "pageSize", null);
(0, _tslib.__decorate)([_mobx.computed], Pagination.prototype, "page", null);
(0, _tslib.__decorate)([_mobx.computed], Pagination.prototype, "total", null);
(0, _tslib.__decorate)([_mobx.computed], Pagination.prototype, "totalPage", null);
(0, _tslib.__decorate)([_mobx.computed], Pagination.prototype, "next", null);
(0, _tslib.__decorate)([_autobind["default"]], Pagination.prototype, "handlePageSizeBeforeChange", null);
(0, _tslib.__decorate)([_autobind["default"]], Pagination.prototype, "handlePageSizeChange", null);
(0, _tslib.__decorate)([_autobind["default"]], Pagination.prototype, "handlePagerClick", null);
(0, _tslib.__decorate)([_autobind["default"]], Pagination.prototype, "handleJumpChange", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Pagination.prototype, "handleJumpGo", null);
(0, _tslib.__decorate)([_mobx.action], Pagination.prototype, "getOptions", null);
Pagination = (0, _tslib.__decorate)([_mobxReact.observer], Pagination);
var _default = Pagination;
exports["default"] = _default;
//# sourceMappingURL=Pagination.js.map
