/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

import { __extends, __awaiter, __generator, __assign, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import isInteger from 'lodash/isInteger';
import { autobind, themeable, localeable } from 'amis-core';
import { Icon } from './icons.js';
import EnhancedSelect from './Select.js';

var Pagination = /** @class */ (function (_super) {
    __extends(Pagination, _super);
    function Pagination(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            pageNum: '',
            internalPageNum: '1',
            perPage: Number(_this.props.perPage)
        };
        _this.handlePageNumChange = _this.handlePageNumChange.bind(_this);
        _this.renderPageItem = _this.renderPageItem.bind(_this);
        _this.renderEllipsis = _this.renderEllipsis.bind(_this);
        _this.handlePageNums = _this.handlePageNums.bind(_this);
        return _this;
    }
    Pagination.prototype.componentDidUpdate = function (prevProps) {
        if (prevProps.perPage !== this.props.perPage) {
            var perPage = Number(this.props.perPage);
            this.setState({ perPage: isInteger(perPage) ? perPage : 10 });
        }
    };
    Pagination.prototype.componentWillReceiveProps = function (nextProps) {
        if (
        // 原本作用在simple上的样式和部分方法变成了normal的，这里需要重置内部状态
        this.props.mode !== 'simple' &&
            nextProps.activePage !== Number(this.state.internalPageNum)) {
            this.setState({ internalPageNum: String(nextProps.activePage) });
        }
    };
    Pagination.prototype.handlePageNumChange = function (page, perPage, dir) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, disabled, onPageChange, _page;
            return __generator(this, function (_b) {
                _a = this.props, disabled = _a.disabled, onPageChange = _a.onPageChange;
                _page = isNaN(Number(page)) || Number(page) < 1 ? 1 : page;
                if (disabled) {
                    return [2 /*return*/];
                }
                onPageChange === null || onPageChange === void 0 ? void 0 : onPageChange(_page, perPage, dir);
                return [2 /*return*/];
            });
        });
    };
    /**
     * 渲染每个页码li
     *
     * @param page 页码
     */
    Pagination.prototype.renderPageItem = function (page) {
        var _this = this;
        var _a = this.props, cx = _a.classnames, activePage = _a.activePage, testIdBuilder = _a.testIdBuilder;
        var perPage = this.state.perPage;
        return (React__default.createElement("li", { onClick: function () { return _this.handlePageNumChange(page, perPage); }, key: page, className: cx('Pagination-pager-item', {
                'is-active': page === activePage
            }) },
            React__default.createElement("a", __assign({ role: "button" }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("page-".concat(page)).getTestId()), page)));
    };
    /**
     * 渲染...
     *
     * @param key 类型 'prev-ellipsis' | 'next-ellipsis'
     * @param page 页码
     */
    Pagination.prototype.renderEllipsis = function (key) {
        var _this = this;
        var _a = this.props, cx = _a.classnames, activePage = _a.activePage, ellipsisPageGap = _a.ellipsisPageGap, testIdBuilder = _a.testIdBuilder;
        var perPage = this.state.perPage;
        var lastPage = this.getLastPage();
        var gap = isNaN(Number(ellipsisPageGap)) || Number(ellipsisPageGap) < 1
            ? 5
            : Number(ellipsisPageGap);
        var isPrevEllipsis = key === 'prev-ellipsis';
        var jumpContent = isPrevEllipsis ? (React__default.createElement(Icon, { icon: "arrow-double-left", className: "icon" })) : (React__default.createElement(Icon, { icon: "arrow-double-right", className: "icon" }));
        var jumpPage = isPrevEllipsis
            ? Math.max(1, activePage - gap)
            : Math.min(lastPage, activePage + gap);
        return (React__default.createElement("li", __assign({ key: key, className: cx('Pagination-ellipsis'), onClick: function (e) {
                return _this.handlePageNumChange(jumpPage, perPage, isPrevEllipsis ? 'backward' : 'forward');
            } }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild(key).getTestId()),
            React__default.createElement("a", { role: "button" }, "..."),
            React__default.createElement("span", { className: "icon" }, jumpContent)));
    };
    /**
     * 渲染器事件方法装饰器
     *
     * @param cur 当前页数
     * @param counts 总共页码按钮数
     * @param min 最小页码
     * @param max 最大页码
     */
    Pagination.prototype.handlePageNums = function (cur, counts, min, max) {
        var pageButtons = [];
        if (counts === 0) {
            return pageButtons;
        }
        var step = 0;
        var page = cur;
        while (true) {
            if (pageButtons.length >= counts) {
                return pageButtons;
            }
            if (cur - step < min && cur + step > max) {
                return pageButtons;
            }
            page = cur - step;
            if (pageButtons.length < counts && page >= min) {
                pageButtons.unshift(this.renderPageItem(page));
            }
            page = cur + step;
            if (step !== 0 && pageButtons.length < counts && page <= max) {
                pageButtons.push(this.renderPageItem(page));
            }
            step++;
        }
    };
    Pagination.prototype.getLastPage = function () {
        var _a = this.props, total = _a.total, lastPage = _a.lastPage, activePage = _a.activePage, hasNext = _a.hasNext;
        var perPage = this.state.perPage;
        // 输入total，重新计算lastPage
        if (total && perPage) {
            return Math.ceil(total / perPage);
        }
        if (lastPage) {
            return Number(lastPage);
        }
        if (hasNext) {
            return Number(activePage + 1);
        }
        return Number(activePage);
    };
    Pagination.prototype.handlePageChange = function (e) {
        var lastPage = this.getLastPage();
        var value = e.currentTarget.value;
        if (/^\d+$/.test(value) && parseInt(value, 10) > lastPage) {
            value = String(lastPage);
        }
        this.setState({ pageNum: value });
    };
    /**
     * 简洁模式input onChange/onKeyUp事件
     *
     * @param event
     */
    Pagination.prototype.handleSimpleKeyUp = function (e) {
        var lastPage = this.getLastPage();
        var key = e.key;
        var v = parseInt(e.currentTarget.value, 10);
        // handle keyboard up and down events value
        switch (key) {
            case "ArrowDown" /* KeyCode.DOWN */:
                v = isNaN(v) || v < 2 ? 1 : v - 1;
                break;
            case "ArrowUp" /* KeyCode.UP */:
                v = v + 1;
                break;
        }
        // validate inputvalue
        if (/^\d+$/.test(String(v)) && v >= lastPage) {
            v = lastPage;
        }
        this.setState({ internalPageNum: String(v) });
        // handle empty val
        if (!v) {
            this.setState({ internalPageNum: '' });
            return;
        }
        if (["ArrowUp" /* KeyCode.UP */, "ArrowDown" /* KeyCode.DOWN */, "Enter" /* KeyCode.ENTER */].includes(key)) {
            this.handlePageNumChange(v, this.props.perPage);
        }
    };
    /**
     * 简洁模式input onBlur事件
     */
    Pagination.prototype.handleSimpleBlur = function () {
        this.setState({ internalPageNum: String(this.props.activePage) });
    };
    Pagination.prototype.render = function () {
        var _this = this;
        var _a = this.props, layout = _a.layout, mode = _a.mode, activePage = _a.activePage, total = _a.total, showPerPage = _a.showPerPage, perPageAvailable = _a.perPageAvailable, cx = _a.classnames, showPageInput = _a.showPageInput, className = _a.className, style = _a.style, disabled = _a.disabled; _a.hasNext; var popOverContainer = _a.popOverContainer, popOverContainerSelector = _a.popOverContainerSelector, mobileUI = _a.mobileUI, size = _a.size, __ = _a.translate, buttonType = _a.buttonType, testIdBuilder = _a.testIdBuilder;
        var maxButtons = this.props.maxButtons;
        var _b = this.state, pageNum = _b.pageNum, perPage = _b.perPage, internalPageNum = _b.internalPageNum;
        var lastPage = this.getLastPage();
        var basePager = null;
        // 非简洁模式
        if ((mode !== 'simple' && mobileUI) || (mode === 'simple' && !mobileUI)) {
            basePager = (React__default.createElement("li", { className: cx('Pagination-simplego'), key: "simple-go" },
                React__default.createElement("input", __assign({ className: cx('Pagination-simplego-input'), key: "simple-input", type: "text", disabled: disabled, onChange: this.handleSimpleKeyUp, onKeyUp: this.handleSimpleKeyUp, onBlur: this.handleSimpleBlur, value: internalPageNum }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('simple-input').getTestId())),
                "/",
                React__default.createElement("span", { className: cx('Pagination-simplego-right'), key: "go-right" }, lastPage)));
            return (React__default.createElement("div", __assign({ className: cx('Pagination-wrap', "Pagination-wrap-size--".concat(size), 'Pagination-simple', { disabled: disabled }, className), style: style }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getTestId()),
                React__default.createElement("ul", { key: "pager-items", className: cx('Pagination', 'Pagination--sm', 'Pagination-pager-items', 'Pagination-item') },
                    React__default.createElement("li", { className: cx('Pagination-prev', {
                            'is-disabled': Number(internalPageNum) < 2
                        }), onClick: function (e) {
                            if (Number(internalPageNum) < 2) {
                                return e.preventDefault();
                            }
                            return _this.handlePageNumChange(activePage - 1, undefined, 'backward');
                        }, key: "prev" },
                        React__default.createElement("span", __assign({}, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("go-prev").getTestId()), buttonType === 'icon' ? (React__default.createElement(Icon, { icon: "left-arrow", className: "icon" })) : buttonType === 'text' ? ('上一页') : null)),
                    basePager,
                    React__default.createElement("li", { className: cx('Pagination-next', {
                            'is-disabled': Number(internalPageNum) >= lastPage
                        }), onClick: function (e) {
                            if (Number(internalPageNum) === lastPage) {
                                return e.preventDefault();
                            }
                            return _this.handlePageNumChange(activePage + 1, perPage, 'forward');
                        }, key: "next" },
                        React__default.createElement("span", __assign({}, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild("go-next").getTestId()), buttonType === 'icon' ? (React__default.createElement(Icon, { icon: "right-arrow", className: "icon" })) : buttonType === 'text' ? ('下一页') : null)))));
        }
        var pageButtons = [];
        var layoutList = Array.isArray(layout)
            ? layout
            : typeof layout === 'string'
                ? layout.split(',')
                : [];
        /** 分页组件至少要包含页码 */
        if (!layoutList.includes("pager" /* PaginationWidget.Pager */)) {
            layoutList.unshift("pager" /* PaginationWidget.Pager */);
        }
        /** 统一使用小写格式，外部属性case insensitive */
        layoutList = layoutList.map(function (widget) { return widget.trim().toLowerCase(); });
        /** 兼容showPageInput属性，默认展示跳转页面 */
        if (showPageInput && !layoutList.includes("go" /* PaginationWidget.Go */)) {
            layoutList.push("go" /* PaginationWidget.Go */);
        }
        if (showPerPage && !layoutList.includes("perpage" /* PaginationWidget.PerPage */)) {
            layoutList.unshift("perpage" /* PaginationWidget.PerPage */);
        }
        // 页码全部显示 [1, 2, 3, 4]
        if (lastPage <= maxButtons) {
            pageButtons = this.handlePageNums(activePage, maxButtons, 1, Math.min(maxButtons, lastPage));
        }
        //当前为1234页时， [1, 2, 3, 4, 5, ... 12]
        else if (activePage <= maxButtons - 3) {
            pageButtons = this.handlePageNums(activePage, maxButtons - 2, 1, Math.min(maxButtons - 2, lastPage));
            pageButtons.push(this.renderEllipsis('next-ellipsis'));
            pageButtons.push(this.renderPageItem(lastPage));
        }
        // [1, ..., 5, 6, 7, 8, 9]
        else if (activePage > lastPage - (maxButtons - 3)) {
            var min = lastPage - (maxButtons - 3);
            pageButtons = this.handlePageNums(activePage, maxButtons - 2, min, lastPage);
            pageButtons.unshift(this.renderEllipsis('prev-ellipsis'));
            pageButtons.unshift(this.renderPageItem(1));
        }
        // [1, ... 4, 5, 6, ... 10]
        else {
            pageButtons = this.handlePageNums(activePage, maxButtons - 2, 3, lastPage - 3);
            pageButtons.unshift(this.renderEllipsis('prev-ellipsis'));
            pageButtons.unshift(this.renderPageItem(1));
            pageButtons.push(this.renderEllipsis('next-ellipsis'));
            pageButtons.push(this.renderPageItem(lastPage));
        }
        pageButtons.unshift(React__default.createElement("li", { className: cx('Pagination-prev', {
                'is-disabled': activePage < 2
            }), onClick: function (e) {
                if (activePage < 2) {
                    return e.preventDefault();
                }
                return _this.handlePageNumChange(activePage - 1, perPage);
            }, key: "prev" },
            React__default.createElement("span", __assign({}, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('go-prev').getTestId()), buttonType === 'icon' ? (React__default.createElement(Icon, { icon: "left-arrow", className: "icon" })) : buttonType === 'text' ? ('上一页') : null)));
        pageButtons.push(React__default.createElement("li", { className: cx('Pagination-next', {
                'is-disabled': activePage === lastPage
            }), onClick: function (e) {
                if (activePage === lastPage) {
                    return e.preventDefault();
                }
                return _this.handlePageNumChange(activePage + 1, perPage);
            }, key: "next" },
            React__default.createElement("span", __assign({}, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('go-next').getTestId()), buttonType === 'icon' ? (React__default.createElement(Icon, { icon: "right-arrow", className: "icon" })) : buttonType === 'text' ? ('下一页') : null)));
        if (mobileUI) {
            pageButtons = [
                pageButtons[0],
                // this.renderPageItem(activePage),
                pageButtons[pageButtons.length - 1]
            ];
        }
        var go = mobileUI ? null : (React__default.createElement("div", { className: cx('Pagination-inputGroup Pagination-item'), key: "go" },
            React__default.createElement("span", { className: cx('Pagination-inputGroup-left'), key: "go-left" }, __('Pagination.goto')),
            React__default.createElement("input", __assign({ className: cx('Pagination-inputGroup-input'), key: "go-input", type: "text", disabled: disabled, onChange: this.handlePageChange, onFocus: function (e) { return e.currentTarget.select(); }, onKeyUp: function (e) {
                    var v = parseInt(e.currentTarget.value, 10);
                    if (!v || e.code != 'Enter') {
                        return;
                    }
                    _this.setState({ pageNum: '' });
                    _this.handlePageNumChange(v, perPage);
                }, value: pageNum }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('go-input').getTestId())),
            React__default.createElement("span", __assign({ className: cx('Pagination-inputGroup-right'), key: "go-right", onClick: function (e) {
                    if (!pageNum) {
                        return;
                    }
                    _this.setState({ pageNum: '' });
                    _this.handlePageNumChange(+pageNum, perPage);
                } }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('go').getTestId()), __('Pagination.go'))));
        var selection = perPageAvailable
            .filter(function (v) { return !!v; })
            .map(function (v) { return ({ label: __('Pagination.select', { count: v }), value: v }); });
        var perPageEle = mobileUI ? null : (React__default.createElement(EnhancedSelect, __assign({ key: "perpage", className: cx('Pagination-perpage', 'Pagination-item'), clearable: false, disabled: disabled, value: perPage, options: selection || [], popOverContainer: popOverContainer, popOverContainerSelector: popOverContainerSelector, onChange: function (p) {
                _this.setState({
                    perPage: p.value,
                    pageNum: ''
                });
                _this.handlePageNumChange(1, p.value);
            } }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('perpage').getTestId())));
        // total或者lastpage不存在，不渲染总数
        var totalPage = !(total || lastPage) || mobileUI ? null : (React__default.createElement("div", { className: cx('Pagination-total Pagination-item'), key: "total" }, total || total === 0
            ? __('Pagination.totalCount', { total: total })
            : __('Pagination.totalPage', { lastPage: lastPage })));
        return (React__default.createElement("div", __assign({ className: cx('Pagination-wrap', "Pagination-wrap-size--".concat(size), { disabled: disabled }, className) }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getTestId()), layoutList.map(function (layoutItem) {
            if (layoutItem === "pager" /* PaginationWidget.Pager */) {
                return (React__default.createElement("ul", { key: "pager-items", className: cx('Pagination', 'Pagination--sm', 'Pagination-item') }, pageButtons));
            }
            else if (layoutItem === "go" /* PaginationWidget.Go */) {
                return go;
            }
            else if (layoutItem === "perpage" /* PaginationWidget.PerPage */) {
                return perPageEle;
            }
            else if (layoutItem === "total" /* PaginationWidget.Total */) {
                return totalPage;
            }
            else {
                return null;
            }
        })));
    };
    Pagination.defaultProps = {
        layout: ["pager" /* PaginationWidget.Pager */],
        maxButtons: 5,
        mode: 'normal',
        activePage: 1,
        perPage: 10,
        perPageAvailable: [10, 20, 50, 100],
        ellipsisPageGap: 5,
        size: 'md',
        buttonType: 'icon'
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Pagination.prototype, "handlePageChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], Pagination.prototype, "handleSimpleKeyUp", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], Pagination.prototype, "handleSimpleBlur", null);
    return Pagination;
}(React__default.Component));
var Pagination$1 = themeable(localeable(Pagination));

export { Pagination, Pagination$1 as default };
