var _excluded = ["value", "onChange", "page", "pageSize"];
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
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; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
import React, { useCallback, useEffect, useMemo, useState } from 'react';
// import { ArrowLeft, ArrowRight } from "@pisell/icon/es";
import ArrowRight from '@pisell/icon/es/ArrowRight';
import ArrowLeft from '@pisell/icon/es/ArrowLeft';
import { Pagination as OriginPagination } from 'antd';
import classNames from 'classnames';
import "./index.less";
import { locales as utilsLocales } from '@pisell/utils';
import { getText } from "../../locales";
import useIsMobileTable from "../table/hooks/useIsMobileTable";
/** 优先 utils；若 utils 返回 key（未命中）则用 materials RecordBoard 再回退 table-pagination-* */
function getPaginationText(key) {
  var _getText;
  var fullKey = "pisell2.salesManagement.pagination.".concat(key);
  var fromUtils = utilsLocales.getText(fullKey);
  if (fromUtils !== fullKey) return fromUtils;
  return (_getText = getText(fullKey)) !== null && _getText !== void 0 ? _getText : getText("table-pagination-".concat(key));
}

/**
 * antd Pagination 的 showTotal(total, range) 中 range 为本页条目序号区间 [start, end]，
 * 不是页码。未受控时用 range 与 pageSize 推算当前页。
 */
function resolveCurrentPage(props, range, pageSize) {
  var _props$current;
  var fromProps = (_props$current = props.current) !== null && _props$current !== void 0 ? _props$current : props.defaultCurrent;
  if (typeof fromProps === 'number' && fromProps >= 1) {
    return fromProps;
  }
  var start = range[0];
  if (start == null || start < 1 || pageSize < 1) {
    return 1;
  }
  return Math.floor((start - 1) / pageSize) + 1;
}
var Pagination = function Pagination(props) {
  var show = useMemo(function () {
    return Object.keys(props).length;
  }, [props]);
  var isMiniPagination = useIsMobileTable();
  var itemRenderFn = useMemo(function () {
    var prevText = getPaginationText('previous');
    var nextText = getPaginationText('next');
    return function (_, type, originalElement) {
      if (type === 'prev') {
        return /*#__PURE__*/React.createElement("div", {
          className: classNames('paginator-page-btn', 'left')
        }, /*#__PURE__*/React.createElement(ArrowLeft, {
          className: 'paginator-page-btn-left-icon'
        }), /*#__PURE__*/React.createElement("span", {
          className: 'paginator-page-btn-text'
        }, prevText));
      }
      if (type === 'next') {
        return /*#__PURE__*/React.createElement("div", {
          className: classNames('paginator-page-btn', 'right')
        }, /*#__PURE__*/React.createElement("span", {
          className: 'paginator-page-btn-text'
        }, nextText), /*#__PURE__*/React.createElement(ArrowRight, {
          className: 'paginator-page-btn-right-icon'
        }));
      }
      return originalElement;
    };
  }, []);
  var showTotalDefault = useCallback(function (totalRecords, range) {
    var _ref, _props$pageSize;
    var pageSize = (_ref = (_props$pageSize = props.pageSize) !== null && _props$pageSize !== void 0 ? _props$pageSize : props.defaultPageSize) !== null && _ref !== void 0 ? _ref : 10;
    var currentPage = resolveCurrentPage(props, range, pageSize);
    var totalPages = totalRecords <= 0 ? 1 : Math.max(1, Math.ceil(totalRecords / pageSize));
    var showTotalFn = getPaginationText('showTotal');
    if (typeof showTotalFn === 'function') {
      return showTotalFn(currentPage, totalPages);
    }
    return "Page ".concat(currentPage, " of ").concat(totalPages);
  }, [props.current, props.defaultCurrent, props.pageSize, props.defaultPageSize]);
  var effectiveConfig = useMemo(function () {
    return {
      className: 'materials-grid-paginator',
      defaultCurrent: 1,
      showTotal: showTotalDefault,
      itemRender: itemRenderFn,
      responsive: true,
      size: 'small'
    };
  }, [itemRenderFn, showTotalDefault]);
  var content = useMemo(function () {
    if (!show) {
      return null;
    }
    var Com = OriginPagination;
    if (isMiniPagination) {
      Com = MiniPagination;
    }
    return /*#__PURE__*/React.createElement(Com, _extends({}, effectiveConfig, props));
  }, [show, effectiveConfig, props, isMiniPagination]);
  return content;
};
export var paginationConfig = {
  className: 'materials-grid-paginator',
  defaultCurrent: 1,
  /** 无 props 上下文时仅能根据 total + range 近似推算（见 resolveCurrentPage） */
  showTotal: function showTotal(totalRecords, range) {
    var pageSize = 10;
    var currentPage = resolveCurrentPage({
      pageSize: pageSize
    }, range, pageSize);
    var totalPages = totalRecords <= 0 ? 1 : Math.max(1, Math.ceil(totalRecords / pageSize));
    var fn = getPaginationText('showTotal');
    if (typeof fn === 'function') {
      return fn(currentPage, totalPages);
    }
    return "Page ".concat(currentPage, " of ").concat(totalPages);
  },
  responsive: true,
  size: 'small'
};
export default Pagination;
var MiniPagination = function MiniPagination(props) {
  var _props$current2 = props.current,
    current = _props$current2 === void 0 ? 1 : _props$current2,
    _props$pageSize2 = props.pageSize,
    pageSize = _props$pageSize2 === void 0 ? 10 : _props$pageSize2,
    _props$total = props.total,
    total = _props$total === void 0 ? 0 : _props$total;

  // 最大翻页
  var MAX = useMemo(function () {
    return Math.ceil(total / pageSize);
  }, [total, pageSize]);

  // 最小翻页
  var MIN = useMemo(function () {
    return 1;
  }, []);

  /**
   * @title: 翻页回调
   * @description:
   * @param {*} type
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2023-07-20 17:02
   */
  var onChange = function onChange(type) {
    var currentPage = current;
    if (type === 'prev') {
      currentPage = current - 1;
    }
    if (type === 'next') {
      currentPage = current + 1;
    }
    props.onChange && props.onChange(currentPage, pageSize || 10);
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "materials-grid-paginator"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode-pagination-prev",
    onClick: function onClick() {
      if (current <= MIN) {
        return;
      }
      onChange('prev');
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('paginator-page-btn', 'left')
  }, /*#__PURE__*/React.createElement(ArrowLeft, {
    className: 'paginator-page-btn-left-icon'
  }))), /*#__PURE__*/React.createElement("div", {
    className: "materials-grid-paginator-center"
  }, /*#__PURE__*/React.createElement("span", {
    className: "materials-grid-paginator-center-text"
  }, function () {
    var totalFn = getPaginationText('total');
    return typeof totalFn === 'function' ? totalFn(current, MAX) : "".concat(current, " / ").concat(MAX);
  }())), /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode-pagination-next",
    onClick: function onClick() {
      if (current >= MAX) {
        return;
      }
      onChange('next');
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('paginator-page-btn', 'right')
  }, /*#__PURE__*/React.createElement(ArrowRight, {
    className: 'paginator-page-btn-right-icon'
  }))));
};
export var FormPagination = function FormPagination(_ref2) {
  var _ref2$value = _ref2.value,
    value = _ref2$value === void 0 ? {} : _ref2$value,
    onChange = _ref2.onChange,
    page = _ref2.page,
    pageSize = _ref2.pageSize,
    other = _objectWithoutProperties(_ref2, _excluded);
  var _useState = useState(page || 1),
    _useState2 = _slicedToArray(_useState, 2),
    _p = _useState2[0],
    _setP = _useState2[1];
  var _useState3 = useState(pageSize || 10),
    _useState4 = _slicedToArray(_useState3, 2),
    _ps = _useState4[0],
    _setPs = _useState4[1];
  var _onChange = function _onChange(p, ps) {
    onChange && onChange({
      page: ps === _ps ? p : 1,
      size: ps
    });
  };
  useEffect(function () {
    var _page = (value === null || value === void 0 ? void 0 : value.page) || page || 1;
    var _size = (value === null || value === void 0 ? void 0 : value.size) || pageSize || 10;
    _setP(_page);
    _setPs(_size);
  }, [value, page, pageSize]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Pagination, _extends({}, other, {
    pageSize: _ps,
    current: _p,
    onChange: _onChange,
    onShowSizeChange: _onChange
  })));
};