"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _components = require("@alicloudfe/components");
var _utils = require("@teamix/utils");
var _hooks = require("@teamix/hooks");
require("./index.scss");
var _excluded = ["className", "onChange", "total", "pageSize", "current", "pageSizeList", "pageSizeSelector", "onPageSizeChange", "responsivePaginationType", "useMaxData"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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; }
var _default = function _default(props) {
  var className = props.className,
    propsOnChange = props.onChange,
    total = props.total,
    pageSize = props.pageSize,
    current = props.current,
    pageSizeList = props.pageSizeList,
    pageSizeSelector = props.pageSizeSelector,
    onPageSizeChange = props.onPageSizeChange,
    responsivePaginationType = props.responsivePaginationType,
    useMaxData = props.useMaxData,
    otherProps = _objectWithoutProperties(props, _excluded);
  var basePrefix = (0, _utils.usePrefixCls)('', {
    base: true
  });
  var prefixCls = (0, _utils.usePrefixCls)('teamix-pro-pagination');
  var _useResponsiveProps = (0, _hooks.useResponsiveProps)([480, 590, 700], ['mini', 'small', 'simple', 'normal']),
    responsiveProps = _useResponsiveProps.responsiveProps,
    paginationWrapperRef = _useResponsiveProps.ref;
  (0, _react.useEffect)(function () {
    // size='mini' 模式下 current 受控
    if (responsiveProps === 'mini') {
      setCurrentPage(current);
    }
  }, [current]);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    visible = _useState2[0],
    setVisible = _useState2[1];
  var _useState3 = (0, _react.useState)(current),
    _useState4 = _slicedToArray(_useState3, 2),
    currentPage = _useState4[0],
    setCurrentPage = _useState4[1];
  var maxDataState = (0, _react.useMemo)(function () {
    return Math.ceil((total !== null && total !== void 0 ? total : 0) / (pageSize !== null && pageSize !== void 0 ? pageSize : 0)) > 100;
  }, [total, pageSize]);
  var commonPaginationProps = {
    className: className,
    onChange: propsOnChange,
    total: useMaxData && maxDataState ? (pageSize !== null && pageSize !== void 0 ? pageSize : 0) * 100 : total,
    pageSize: pageSize,
    current: current,
    shape: 'arrow-only',
    pageSizeList: pageSizeList,
    pageSizeSelector: pageSizeSelector,
    pageSizePosition: 'end',
    onPageSizeChange: onPageSizeChange,
    // pagination 的渲染函数
    pageNumberRender: function pageNumberRender(index) {
      if (useMaxData && maxDataState) {
        if (index === 100) {
          return '100+';
        }
        return index;
      }
      return index;
    }
  };
  // 获取总数
  var getTotalContent = (0, _react.useMemo)(function () {
    if (useMaxData && maxDataState) {
      return (0, _utils.getMessage)('total', {
        total: new Intl.NumberFormat().format((pageSize !== null && pageSize !== void 0 ? pageSize : 0) * 100) + '+'
      });
    }
    return (0, _utils.getMessage)('total', {
      total: new Intl.NumberFormat().format(total !== null && total !== void 0 ? total : 0)
    });
  }, [pageSize, total, maxDataState]);
  // 自定义总数，用于 small、mini
  var customTotalRender = function customTotalRender() {
    return /*#__PURE__*/_react.default.createElement(_components.Balloon, {
      visible: visible,
      closable: false,
      onVisibleChange: function onVisibleChange(visible) {
        return setVisible(visible);
      },
      align: "t",
      // triggerType="click"
      trigger: /*#__PURE__*/_react.default.createElement(_components.Button, {
        text: true,
        onMouseEnter: function onMouseEnter() {
          return setVisible(true);
        },
        style: {
          lineHeight: '18px'
        }
      }, getTotalContent)
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: prefixCls('custom-total-content')
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: "title"
    }, (0, _utils.getMessage)('pageSize')), /*#__PURE__*/_react.default.createElement(_components.Select, {
      className: prefixCls('custom-page-size-selector'),
      dataSource: pageSizeList,
      defaultValue: pageSize,
      followTrigger: true,
      menuProps: {
        hasSelectedIcon: false
      },
      onChange: function onChange(value) {
        setVisible(false);
        setCurrentPage(1);
        onPageSizeChange === null || onPageSizeChange === void 0 ? void 0 : onPageSizeChange(value);
      }
    })));
  };
  // 获取页总数
  function getTotalPage(total, currentPageSize) {
    var totalPage = Math.ceil(total / currentPageSize);
    return totalPage <= 0 ? 1 : totalPage;
  }
  // 自定义翻页，用于 mini
  var customJumpRender = function customJumpRender() {
    var handleInputChange = function handleInputChange(value, e) {
      setCurrentPage(value);
    };
    // 回车触发跳转
    var handleJump = function handleJump(e) {
      var totalPage = getTotalPage(total, pageSize);
      var value = Number(currentPage);
      if (isNaN(value)) {
        value = '';
      } else if (value < 1) {
        value = 1;
      } else if (value > totalPage) {
        value = totalPage;
      }
      if (value && value !== current) {
        setCurrentPage(value);
        propsOnChange === null || propsOnChange === void 0 ? void 0 : propsOnChange(value, e);
      }
    };
    var handlePrevClick = function handlePrevClick(e) {
      setCurrentPage(currentPage - 1);
      propsOnChange === null || propsOnChange === void 0 ? void 0 : propsOnChange(currentPage - 1, e);
    };
    var handleNextClick = function handleNextClick(e) {
      setCurrentPage(currentPage + 1);
      propsOnChange === null || propsOnChange === void 0 ? void 0 : propsOnChange(currentPage + 1, e);
    };
    return /*#__PURE__*/_react.default.createElement("div", {
      className: prefixCls('custom-jumper')
    }, /*#__PURE__*/_react.default.createElement(_components.Button, {
      className: basePrefix('prev', 'pagination-item'),
      onClick: handlePrevClick,
      disabled: Number(currentPage) <= 1
    }, /*#__PURE__*/_react.default.createElement(_components.Icon, {
      size: "small",
      type: "arrow-left"
    })), /*#__PURE__*/_react.default.createElement(_components.Input, {
      className: "jump-input",
      value: currentPage,
      onChange: handleInputChange,
      onKeyDown: function onKeyDown(e) {
        if (e.keyCode === 13) {
          handleJump(e);
        }
      }
    }), /*#__PURE__*/_react.default.createElement("div", {
      className: "total"
    }, /*#__PURE__*/_react.default.createElement("span", {
      style: {
        marginRight: 4
      }
    }, "/"), getTotalPage(total, pageSize)), /*#__PURE__*/_react.default.createElement(_components.Button, {
      className: basePrefix('next', 'pagination-item'),
      onClick: handleNextClick,
      //@ts-ignore
      disabled: total && Number(currentPage) >= getTotalPage(total, pageSize)
    }, /*#__PURE__*/_react.default.createElement(_components.Icon, {
      size: "small",
      type: "arrow-right"
    })));
  };
  var renderMiniPagination = function renderMiniPagination() {
    if (total && pageSize) {
      if (total / pageSize <= 2) {
        return /*#__PURE__*/_react.default.createElement(_components.Pagination, _objectSpread(_objectSpread({}, commonPaginationProps), {}, {
          type: "simple"
        }, otherProps));
      } else {
        return /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _utils.cls)(basePrefix('pagination'), prefixCls('custom-mini-pagination'))
        }, customTotalRender(), customJumpRender());
      }
    }
  };
  var renderPagination = function renderPagination() {
    switch (responsivePaginationType || responsiveProps) {
      case 'normal':
        return /*#__PURE__*/_react.default.createElement(_components.Pagination, _objectSpread(_objectSpread({}, commonPaginationProps), {}, {
          totalRender: function totalRender() {
            return getTotalContent;
          }
        }, otherProps));
      case 'simple':
        return /*#__PURE__*/_react.default.createElement(_components.Pagination, _objectSpread(_objectSpread({}, commonPaginationProps), {}, {
          pageShowCount: 3,
          totalRender: function totalRender() {
            return getTotalContent;
          }
        }, otherProps));
      case 'small':
        return /*#__PURE__*/_react.default.createElement(_components.Pagination, _objectSpread(_objectSpread({}, commonPaginationProps), {}, {
          pageShowCount: 3,
          pageSizeSelector: false,
          totalRender: function totalRender() {
            return customTotalRender();
          }
        }, otherProps));
      case 'mini':
        return renderMiniPagination();
      default:
        return /*#__PURE__*/_react.default.createElement(_components.Pagination, _objectSpread(_objectSpread({}, commonPaginationProps), otherProps));
    }
  };
  return (
    /*#__PURE__*/
    // 用于获取翻页器响应式 ref
    _react.default.createElement("div", {
      ref: paginationWrapperRef,
      className: prefixCls('wrapper')
    }, renderPagination())
  );
};
exports.default = _default;