<?php
// 功能：后台共用的顶部导航搜索+分页功能
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

function getGlobalHeaderUI($current_page = 1, $posts_per_page = 30)
{
    ob_start();
?>


    <div class="search-bar" id="global-search-bar">
        <input type="search" id="admin-search-keyword" name="admin_search_keyword" placeholder="搜索内容..." autocomplete="new-password" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="search" data-lpignore="true" data-1p-ignore="true" readonly onfocus="this.removeAttribute('readonly')">
        <button id="search-button">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
        </button>
    </div>
    <!-- 加载动画 -->
    <div id="loading-spinner" class="loading-spinner">
        <div class="spinner-wrapper">
            <div class="spinner-outer"></div>
            <div class="spinner-inner"></div>
        </div>
    </div>
    <div id="top-page-control" class="top-page-control" data-rendered="1">
        <a href="#" class="tpc-btn disabled" data-action="first" title="首页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="11 17 6 12 11 7"></polyline>
                <polyline points="18 17 13 12 18 7"></polyline>
            </svg>
        </a>
        <a href="#" class="tpc-btn disabled" data-action="prev" title="上一页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="15 18 9 12 15 6"></polyline>
            </svg>
        </a>
        <span class="tpc-text-btn" id="tpc-page-btn">
            第<span id="tpc-page-num"><?php echo $current_page; ?></span>页
            <div class="tpc-menu" id="tpc-page-menu"></div>
        </span>
        <a href="#" class="tpc-btn disabled" data-action="next" title="下一页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="9 18 15 12 9 6"></polyline>
            </svg>
        </a>
        <a href="#" class="tpc-btn disabled" data-action="last" title="尾页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="13 17 18 12 13 7"></polyline>
                <polyline points="6 17 11 12 6 7"></polyline>
            </svg>
        </a>
        <span class="tpc-text-btn" id="tpc-size-btn">
            <span id="tpc-size-num"><?php echo $posts_per_page; ?></span>条/页
            <div class="tpc-menu" id="tpc-size-menu"></div>
        </span>
    </div>
    <!-- 手机端分页控件 -->
    <div class="mobile-pagination" id="mobile-pagination">
        <a href="#" class="tpc-btn disabled" data-action="prev" title="上一页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="15 18 9 12 15 6"></polyline>
            </svg>
        </a>
        <span class="tpc-text-btn" id="mobile-page-btn">
            <span id="mobile-page-num"><?php echo $current_page; ?></span>
        </span>
        <a href="#" class="tpc-btn disabled" data-action="next" title="下一页">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="9 18 15 12 9 6"></polyline>
            </svg>
        </a>
    </div>
<?php
    return ob_get_clean();
}
?>

<script>
    (function() {
        // JS 只负责初始化事件，不再动态插入 HTML
        function initUI() {
            if (document.getElementById('global-search-bar')) {
                initSearchEvents();
                if (typeof isPaginationSupported === 'function' && isPaginationSupported()) {
                    initHeaderPagination();
                }
            }
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initUI);
        } else {
            initUI();
        }

        window.addEventListener('resize', function() {
            const spinner = document.getElementById('loading-spinner');
            if (spinner && spinner.classList.contains('show')) {
                positionLoadingSpinner(spinner);
            }
        });

        document.addEventListener('sidebarToggled', function() {
            const spinner = document.getElementById('loading-spinner');
            if (spinner && spinner.classList.contains('show')) {
                setTimeout(function() {
                    positionLoadingSpinner(spinner);
                }, 20);
            }
        });
    })();
</script>

<!-- 搜索框CSS -->
<style>


    /* 手机端分页控件默认隐藏（只在手机端显示） */
    .mobile-pagination {
        display: none !important;
    }

    .search-bar {
        padding: 0;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
        display: inline-flex;
        align-items: center;
        margin-left: 10px;
        height: 32px;
        box-sizing: border-box;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
        transition: border-color 0.2s ease, box-shadow 0.2s ease;
    }

    .search-bar:focus-within {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.08), 0 1px 2px rgba(0, 0, 0, 0.02);
    }

    #admin-search-keyword {
        padding: 0 12px;
        border: none;
        border-radius: 8px 0 0 8px;
        background: transparent;
        font-size: 13px;
        width: 180px;
        height: 30px;
        line-height: 30px;
        outline: none;
        color: #334155;
        /* 隐藏浏览器默认的清除按钮 */
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
    }

    /* 针对不同浏览器的清除按钮样式 */
    #admin-search-keyword::-webkit-search-cancel-button {
        display: none;
    }

    #admin-search-keyword::-webkit-search-decoration {
        display: none;
    }

    #admin-search-keyword::-webkit-search-results-button {
        display: none;
    }

    #admin-search-keyword::-webkit-search-results-decoration {
        display: none;
    }

    #admin-search-keyword::-moz-search-cancel-button {
        display: none;
    }

    #admin-search-keyword::placeholder {
        color: #94a3b8;
    }

    #search-button {
        padding: 0 12px;
        background: transparent;
        color: #64748b;
        border: none;
        border-radius: 0 8px 8px 0;
        font-size: 13px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        border-left: 1px solid #e2e8f0;
        height: 30px;
        transition: all 0.2s ease;
    }

    #search-button:hover {
        color: var(--primary-color);
        background: rgba(124, 58, 237, 0.05);
    }

    @media (max-width: 1089px) {
        .header-content .search-bar {
            display: none !important;
        }
    }

    @media (max-width: 768px) {
        .header-content .search-bar {
            display: none !important;
        }
    }

    /* 头部区域保持默认位置，避免抖动 */
    .main-nav-area {
        margin-left: 0;
    }

    /* 顶部页面控制 - 默认显示 */
    .top-page-control {
        display: inline-flex !important;
        align-items: center !important;
        margin-left: 10px !important;
        gap: 5px !important;
        /* 默认隐藏，但占据空间，防止布局跳变 */
        opacity: 0 !important;
        visibility: hidden !important;
        pointer-events: none !important;
        transition: opacity 0.3s ease, visibility 0.3s ease !important;
    }

    /* 鼠标进入 header 或 导航区域时显示 */
    .header:hover .top-page-control:not(:empty),
    .main-nav-area:hover .top-page-control:not(:empty) {
        opacity: 1 !important;
        visibility: visible !important;
        pointer-events: auto !important;
    }

    /* 有内容时才应用样式，没内容（如 metrics）则完全不占空间 */
    .top-page-control:empty {
        display: none !important;
    }

    .top-page-control .tpc-btn {
        width: 30px !important;
        height: 30px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 6px !important;
        background: #fff !important;
        color: #64748b !important;
        transition: all 0.2s !important;
    }

    .top-page-control .tpc-text-btn {
        height: 30px !important;
        line-height: 28px !important;
        padding: 0 10px !important;
        font-size: 13px !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 6px !important;
        background: #fff !important;
        min-width: 85px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: space-between !important;
    }

    .top-page-control .tpc-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 30px;
        padding: 0;
        color: #64748b;
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
    }

    .top-page-control .tpc-btn svg {
        display: block;
        transition: transform 0.2s ease;
    }

    .top-page-control .tpc-btn:hover {
        color: var(--primary-color);
        border-color: var(--primary-color);
        background: #f5f3ff;
        box-shadow: 0 1px 3px rgba(124, 58, 237, 0.1);
    }

    .top-page-control .tpc-btn:hover svg {
        transform: scale(1.1);
    }

    .top-page-control .tpc-btn.disabled {
        color: #cbd5e1;
        background: #f1f5f9;
        border-color: #e2e8f0;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    .top-page-control .tpc-text-btn {
        display: inline-flex;
        align-items: center;
        height: 30px;
        padding: 0 12px;
        font-size: 13px;
        font-weight: 500;
        color: #475569;
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        cursor: pointer;
        width: 95px;
        min-width: 95px;
        justify-content: space-between;
        transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
        position: relative;
    }

    .top-page-control .tpc-text-btn:hover {
        border-color: var(--primary-color);
        color: var(--primary-color);
        background: #f5f3ff;
        box-shadow: 0 1px 3px rgba(124, 58, 237, 0.1);
    }

    .top-page-control .tpc-text-btn::after {
        content: '';
        width: 0;
        height: 0;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 4px solid currentColor;
        margin-left: 6px;
    }

    .top-page-control .tpc-menu {
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%) scale(0.95);
        margin-top: 8px;
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12), 0 4px 10px rgba(0, 0, 0, 0.08);
        min-width: 86.2px;
        max-height: 220px;
        overflow-y: auto;
        z-index: 1000;
        display: none;
        opacity: 0;
        transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        padding: 5px;
    }

    .top-page-control .tpc-menu.show {
        display: block;
        opacity: 1;
        transform: translateX(-50%) scale(1);
    }

    .top-page-control .tpc-menu-item {
        padding: 5px;
        font-size: 13px;
        color: #475569;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: center;
        border-radius: 4px;
        margin: 2px 0;
    }

    .top-page-control .tpc-menu-item:hover {
        background: linear-gradient(135deg, #f5f3ff 0%, #ede9fe 100%);
        color: var(--primary-color);
    }

    .top-page-control .tpc-menu-item.active {
        background: linear-gradient(135deg, rgba(124, 58, 237, 0.12) 0%, rgba(124, 58, 237, 0.08) 100%);
        color: var(--primary-color);
        font-weight: 600;
    }

    @media (max-width: 1089px) {
        .header-content .search-bar {
            display: none !important;
        }
    }

    @media (max-width: 768px) {
        .header-content .search-bar {
            display: none !important;
        }

        /* 手机端隐藏电脑版分页控件 */
        .top-page-control {
            display: none !important;
        }

        /* 手机端显示简易翻页按钮 */
        .mobile-pagination {
            display: flex !important;
            align-items: center !important;
            gap: 6px !important;
            margin-right: 4px !important;
            padding: 0 !important;
            border: 0 !important;
            border-radius: 0 !important;
            background: transparent !important;
            box-shadow: none !important;
        }

        .mobile-pagination .tpc-btn {
            width: 36px !important;
            height: 36px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            border: 1px solid #d6dde7 !important;
            border-radius: 999px !important;
            background: #ffffff !important;
            color: #334155 !important;
            transition: all 0.2s ease !important;
            text-decoration: none !important;
        }

        .mobile-pagination .tpc-btn svg {
            width: 14px !important;
            height: 14px !important;
            stroke-width: 2.4 !important;
        }

        .mobile-pagination .tpc-btn:hover {
            color: var(--primary-color) !important;
            border-color: var(--primary-color) !important;
            background: rgba(124, 58, 237, 0.1) !important;
        }

        .mobile-pagination .tpc-btn:active {
            transform: scale(0.97) !important;
        }

        .mobile-pagination .tpc-btn.disabled {
            color: #cbd5e1 !important;
            background: #f8fafc !important;
            border-color: #e5eaf1 !important;
            cursor: not-allowed !important;
            opacity: 0.8 !important;
        }

        .mobile-pagination .tpc-text-btn {
            height: 36px !important;
            line-height: 36px !important;
            min-width: 52px !important;
            padding: 0 12px !important;
            font-size: 13px !important;
            border: 1px solid #d6dde7 !important;
            border-radius: 999px !important;
            background: #f8fafc !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            color: #1e293b !important;
            font-weight: 700 !important;
            letter-spacing: 0.2px !important;
        }
    }

    /* 加载动画样式 - 双环旋转效果 */
    .loading-spinner {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.22s ease, visibility 0.22s ease;
        background: rgba(0, 0, 0, 0.8);
        /* 黑色透明背景 */
        width: 100px;
        height: 100px;
        border-radius: 8px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        will-change: opacity;
    }

    .loading-spinner.show {
        opacity: 1;
        visibility: visible;
    }

    .spinner-wrapper {
        position: relative;
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .spinner-outer {
        position: absolute;
        width: 100%;
        height: 100%;
        border: 4px solid rgba(255, 255, 255, 0.1);
        border-top-color: #ffffff;
        border-radius: 50%;
        animation: spin-clockwise 1.2s cubic-bezier(0.5, 0.1, 0.4, 0.9) infinite;
    }

    .spinner-inner {
        position: absolute;
        width: 30px;
        height: 30px;
        border: 3px solid rgba(255, 255, 255, 0.1);
        border-top-color: #ffffff;
        /* 白色环 */
        border-radius: 50%;
        animation: spin-counter-clockwise 1s cubic-bezier(0.5, 0.1, 0.4, 0.9) infinite;
    }

    @keyframes spin-clockwise {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }

    @keyframes spin-counter-clockwise {
        from {
            transform: rotate(360deg);
        }

        to {
            transform: rotate(0deg);
        }
    }
</style>

<!-- 搜索框JS -->
<script>
    // 加载动画控制函数
    function showLoading() {
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab') || 'metrics';
        // 排除 网站设置、导航管理、模板标签、后台首页 不需要加载动画的页面
        const excludedTabs = ['settings', 'navigation', 'generator', 'metrics'];
        if (excludedTabs.includes(tab)) return;

        const spinner = document.getElementById('loading-spinner');
        if (spinner) {
            positionLoadingSpinner(spinner);
            spinner.classList.add('show');
        }
    }

    function hideLoading() {
        const spinner = document.getElementById('loading-spinner');
        if (spinner) {
            spinner.classList.remove('show');
        }
    }

    function positionLoadingSpinner(spinner) {
        if (!spinner) return;
        const content = document.querySelector('.admin-content');
        if (!content) {
            spinner.style.left = '50%';
            spinner.style.top = '50%';
            return;
        }
        const rect = content.getBoundingClientRect();
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
        const visibleTop = Math.max(rect.top, 0);
        const visibleBottom = Math.min(rect.bottom, viewportHeight);
        const visibleHeight = Math.max(0, visibleBottom - visibleTop);
        const top = visibleHeight > 0 ? (visibleTop + visibleHeight / 2) : (rect.top + Math.max(rect.height, 0) / 2);
        const left = rect.left + Math.max(rect.width, 0) / 2;
        spinner.style.left = left + 'px';
        spinner.style.top = top + 'px';
    }

    function performSearch() {
        // 检查是否支持搜索
        if (typeof isSearchSupported === 'function' && !isSearchSupported()) {
            showToast('当前页面不支持搜索功能', 'warning');
            return;
        }

        // 显示加载动画
        showLoading();

        const urlParams = new URLSearchParams(window.location.search);
        let searchType = urlParams.get('tab') || 'metrics';
        // 检查是否直接访问Plugin.php文件
        const isPluginPage = window.location.pathname.includes('Plugin.php');
        if (isPluginPage) searchType = 'plugin';
        const searchQuery = document.getElementById('admin-search-keyword')?.value.trim();

        const validTypes = ['articles', 'adcategory', 'comments', 'users', 'reports', 'tagSearch', 'order', 'publish', 'plugin', 'CloudPlug', 'adgoods', 'generator', 'counter', 'template'];
        if (!validTypes.includes(searchType)) {
            showToast('当前页面不支持搜索', 'warning');
            return;
        }

        // 标签生成器页面使用前端搜索
        if (searchType === 'generator') {
            // 直接执行搜索逻辑
            const tagCards = document.querySelectorAll('.tag-card');
            if (tagCards.length > 0) {
                const searchTerm = searchQuery ? searchQuery.toLowerCase() : '';
                tagCards.forEach(card => {
                    const name = card.querySelector('.tag-name')?.textContent.toLowerCase() || '';
                    const code = card.querySelector('.tag-code')?.textContent.toLowerCase() || '';
                    card.style.display = (name.includes(searchTerm) || code.includes(searchTerm)) ? 'flex' : 'none';
                });

                const visibleTags = Array.from(tagCards).filter(card => card.style.display !== 'none');
                const noResults = document.querySelector('.no-search-results');
                if (noResults) {
                    noResults.style.display = visibleTags.length === 0 ? 'block' : 'none';
                }

                if (visibleTags.length > 0) {
                    tagCards.forEach(card => card.classList.remove('active'));
                    visibleTags[0].classList.add('active');
                    // 尝试调用 updateGeneratorByTag 函数更新生成器
                    if (typeof updateGeneratorByTag === 'function') {
                        updateGeneratorByTag(visibleTags[0].dataset.value);
                    }
                }
            }
            return;
        }

        // 更新 URL
        const newParams = new URLSearchParams(window.location.search);
        if (searchQuery) {
            newParams.set('search', searchQuery);
        } else {
            newParams.delete('search');
        }
        newParams.set('page', '1'); // 搜索时重置到第一页

        // 处理特殊的 tab 参数（如 tagSearch 的 &tag / &Search）
        let tabSuffix = '';
        if (searchType === 'tagSearch') {
            if (window.location.href.includes('&Search')) tabSuffix = '&Search';
            else if (window.location.href.includes('&tag')) tabSuffix = '&tag';
        } else if (searchType === 'plugin') {
            if (window.location.href.includes('&cloud')) tabSuffix = '&cloud';
            else if (window.location.href.includes('&installed')) tabSuffix = '&installed';
        }

        const newUrl = window.location.pathname + '?' + newParams.toString() + tabSuffix;
        window.history.pushState({}, document.title, newUrl);

        // 如果 HeaderPagination 已加载，直接触发 load
        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = 1;
            HeaderPagination.load();
            // 搜索完成后隐藏加载动画
            setTimeout(hideLoading, 500);
        } else {
            // 否则使用传统方式加载
            loadPageContent(newUrl);
            // 搜索完成后隐藏加载动画
            setTimeout(hideLoading, 500);
        }
    }

    function loadPluginSearchResults(searchQuery) {
        const pluginCards = document.querySelectorAll('.plugin-card');
        const searchTerm = searchQuery.toLowerCase().trim();
        pluginCards.forEach(card => {
            if (!searchTerm || card.querySelector('h3').textContent.toLowerCase().includes(searchTerm)) {
                card.style.display = '';
                card.classList.add('visible');
            } else {
                card.style.display = 'none';
                card.classList.remove('visible');
            }
        });
    }

    function initSearchEvents() {
        function debounce(fn, ms) {
            let timer = null;
            return function() {
                if (timer) clearTimeout(timer);
                const args = arguments;
                timer = setTimeout(function() {
                    fn.apply(null, args);
                }, ms);
            };
        }
        const searchButton = document.getElementById('search-button');
        if (searchButton) {
            searchButton.onclick = debounce(performSearch, 200);
        }
        const searchInput = document.getElementById('admin-search-keyword');
        if (searchInput) {
            const enterDebounce = debounce(performSearch, 150);
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    enterDebounce();
                }
            });
        }
    }

    window.formatDateYMD = function(input) {
        if (input === null || input === undefined || input === '') return '-';
        if (typeof input === 'string') {
            const m = input.match(/^(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})/);
            if (m) {
                const y = m[1];
                const mm = String(m[2]).padStart(2, '0');
                const dd = String(m[3]).padStart(2, '0');
                return y + '-' + mm + '-' + dd;
            }
        }
        const d = new Date(input);
        if (isNaN(d.getTime())) return '-';
        const y = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        return y + '-' + mm + '-' + dd;
    };

    // 顶部页面控制
    window.HeaderPagination = {
        initialized: false, // 标记是否已初始化
        state: {
            page: <?php echo isset($current_page) ? $current_page : 1; ?>,
            pageSize: <?php echo isset($posts_per_page) ? $posts_per_page : 30; ?>,
            totalPages: 1
        },
        cache: {
            page: null,
            pageSize: null,
            totalPages: null
        },
        loading: false,
        controller: null,
        lastTotalPages: 0,

        init: function() {
            if (this.initialized) return; // 防止重复初始化
            this.initialized = true;
            this.render();
            this.bindEvents();

            const urlParams = new URLSearchParams(window.location.search);
            let p = null,
                s = null;
            for (const [key] of urlParams.entries()) {
                const m = key.match(/^p(\d+)_s(\d+)/);
                if (m) {
                    p = parseInt(m[1]);
                    s = parseInt(m[2]);
                    break;
                }
            }
            if (urlParams.get('page')) p = parseInt(urlParams.get('page'));
            if (urlParams.get('posts_per_page')) s = parseInt(urlParams.get('posts_per_page'));

            if (p) this.state.page = p;
            if (s) this.state.pageSize = s;

            const tab = urlParams.get('tab') || 'metrics';
            const isPluginPage = window.location.pathname.includes('Plugin.php');
            if (tab === 'plugin' || tab === 'CloudPlug' || tab === 'template' || isPluginPage) {
                this.state.pageSize = 12;
            }

            this.updateUI();

            // metrics页面不需要分页功能，跳过加载
            if (tab !== 'metrics' && tab !== 'template') {
                this.load(true); // 初始加载，传入 true 表示是静默加载（检查缓存/DOM）
            }
        },

        // 核心加载函数
        load: function(isInitial = false) {
            const urlParams = new URLSearchParams(window.location.search);
            const tab = urlParams.get('tab') || 'metrics';
            const isPluginPage = window.location.pathname.includes('Plugin.php');

            // 初始加载优化：如果页面上已经有数据，且状态匹配，则跳过请求
            if (isInitial) {
                const hasData = (tab === 'articles' && document.querySelector('.admin-table.section-manage tbody tr')) ||
                    (tab === 'adcategory' && document.querySelector('.category-manage tbody tr')) ||
                    (tab === 'comments' && document.querySelector('.comment-manage tbody tr')) ||
                    (tab === 'publish' && document.querySelector('.publish-manage tbody tr')) ||
                    (tab === 'counter' && document.querySelector('.admin-table.counter-manage tbody tr')) ||
                    ((tab === 'plugin' || isPluginPage) && document.querySelectorAll('.plugin-card').length > 0) ||
                    (tab === 'template' && document.querySelectorAll('#template-list .plugin-card').length > 0);

                // 检测是否为iOS设备
                const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

                // 栏目页和评论页首屏由PHP已按当前URL状态输出，首刷直接复用，避免二次AJAX重绘闪烁
                if (!isIOS && (tab === 'adcategory' || tab === 'template' || tab === 'comments' || tab === 'plugin' || isPluginPage) && hasData) {
                    return;
                }
                if (!isIOS && hasData && this.cache.page === this.state.page && this.cache.pageSize === this.state.pageSize) {
                    return;
                }
            }

            if (this.loading) return;
            this.loading = true;

            // 显示加载动画
            showLoading();

            let apiUrl = '';
            let renderFn = null;

            if (tab === 'articles') {
                apiUrl = this._buildArticleApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderArticlesList === 'function' ? renderArticlesList : null;
            } else if (tab === 'adgoods') {
                apiUrl = this._buildGoodsApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderGoodsMainList === 'function' ? renderGoodsMainList : null;
            } else if (tab === 'comments') {
                apiUrl = this._buildCommentsApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderCommentsList === 'function' ? renderCommentsList : null;
            } else if (tab === 'reports') {
                apiUrl = this._buildReportsApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderReportsList === 'function' ? renderReportsList : null;
            } else if (tab === 'order') {
                apiUrl = this._buildOrdersApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderOrdersList === 'function' ? renderOrdersList : null;
            } else if (tab === 'publish') {
                apiUrl = this._buildPublishApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderPublishList === 'function' ? renderPublishList : null;
            } else if (tab === 'users') {
                apiUrl = this._buildUsersApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderUsersList === 'function' ? renderUsersList : null;
            } else if (tab === 'counter') {
                apiUrl = this._buildCounterApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderCounterList === 'function' ? renderCounterList : null;
            } else if (tab === 'tagSearch') {
                apiUrl = this._buildTagSearchApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderTagSearchList === 'function' ? renderTagSearchList : null;
            } else if (tab === 'adcategory') {
                apiUrl = this._buildCategoriesApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderCategoriesList === 'function' ? renderCategoriesList : null;
            } else if (tab === 'CloudPlug') {
                const search = urlParams.get('search') || '';
                apiUrl = '/admin/CloudPlug.php?action=get_cloud_plugins&page=' + this.state.page + '&page_size=' + this.state.pageSize + (search ? '&search=' + encodeURIComponent(search) : '');
            } else if (tab === 'template') {
                if (urlParams.get('cloud') !== null || window.location.href.includes('&cloud')) {
                    this.loading = false;
                    this.controller = null;
                    hideLoading();
                    return;
                }
                apiUrl = this._buildTemplateApiUrl(this.state.page, this.state.pageSize);
                renderFn = typeof renderTemplatesList === 'function' ? renderTemplatesList : null;
            } else if (tab === 'plugin' || isPluginPage) {
                const search = urlParams.get('search') || '';
                const isCloud = urlParams.get('cloud') !== null || window.location.href.includes('&cloud');
                if (isCloud) {
                    apiUrl = '/admin/CloudPlug.php?action=get_cloud_plugins&page=' + this.state.page + '&page_size=' + this.state.pageSize + (search ? '&search=' + encodeURIComponent(search) : '');
                } else {
                    const extType = urlParams.get('ext_type') || '';
                    const extCharge = urlParams.get('ext_charge') || '';
                    apiUrl = '/admin/Plugin.php?action=get_plugins&page=' + this.state.page + '&page_size=' + this.state.pageSize + (extType ? '&ext_type=' + encodeURIComponent(extType) : '') + (extCharge ? '&ext_charge=' + encodeURIComponent(extCharge) : '') + (search ? '&search=' + encodeURIComponent(search) : '');
                }
            }

            if (!apiUrl) {
                this.loading = false;
                hideLoading();
                return;
            }

            if (this.controller) this.controller.abort();
            this.controller = new AbortController();

            fetch(apiUrl, {
                    signal: this.controller.signal,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(d => {
                    const data = d.data || d;
                    const totalPages = parseInt(data.total_pages || (d.total ? Math.ceil(d.total / this.state.pageSize) : 1));

                    this.cache = {
                        page: this.state.page,
                        pageSize: this.state.pageSize,
                        totalPages
                    };

                    this.updateFromMainPagination(this.state.page, this.state.pageSize, totalPages);

                    if (tab === 'CloudPlug') {
                        if (window.CloudPlugUI && typeof window.CloudPlugUI.applyData === 'function') {
                            window.CloudPlugUI.applyData(data);
                        } else {
                            const listEl = document.getElementById('cp-list');
                            if (listEl) listEl.innerHTML = data.list_html || '';
                        }
                    } else if (tab === 'plugin' || isPluginPage) {
                        const urlParams = new URLSearchParams(window.location.search);
                        const isCloud = urlParams.get('cloud') !== null || window.location.href.includes('&cloud');
                        if (isCloud) {
                            if (window.CloudPlugUI && typeof window.CloudPlugUI.applyData === 'function') {
                                window.CloudPlugUI.applyData(data);
                            } else {
                                const listEl = document.getElementById('cp-list');
                                if (listEl) listEl.innerHTML = data.list_html || '';
                            }
                        } else {
                            if (typeof renderPluginsList === 'function') renderPluginsList(data.plugins || data);
                        }
                    } else if (renderFn) {
                        renderFn(data);
                    }

                    // 如果不是初始加载，更新 URL（静默更新）
                    if (!isInitial) {
                        const newUrl = this._buildCurrentPageUrl(tab, isPluginPage);
                        window.history.pushState({}, document.title, newUrl);
                    }

                    this.loading = false;
                    this.controller = null;
                    // 隐藏加载动画
                    hideLoading();
                })
                .catch(err => {
                    if (err.name !== 'AbortError') {
                        console.error('HeaderPagination load failed:', err);
                    }
                    this.loading = false;
                    this.controller = null;
                    // 隐藏加载动画
                    hideLoading();
                });
        },

        // 构建当前页面的完整 URL（包含搜索和分页参数）
        _buildCurrentPageUrl: function(tab, isPluginPage) {
            if (tab === 'articles') return this._buildArticlesUrl(this.state.page, this.state.pageSize);
            if (tab === 'adgoods') return this._buildAdgoodsUrl(this.state.page, this.state.pageSize);
            if (tab === 'comments') return this._buildCommentsUrl(this.state.page, this.state.pageSize);
            if (tab === 'reports') return this._buildReportsUrl(this.state.page, this.state.pageSize);
            if (tab === 'order') return this._buildOrderUrl(this.state.page, this.state.pageSize);
            if (tab === 'publish') return this._buildPublishUrl(this.state.page, this.state.pageSize);
            if (tab === 'users') return this._buildUsersUrl(this.state.page, this.state.pageSize);
            if (tab === 'counter') return this._buildCounterUrl(this.state.page, this.state.pageSize);
            if (tab === 'tagSearch') return this._buildTagSearchUrl(this.state.page, this.state.pageSize);
            if (tab === 'adcategory') return this._buildCategoriesUrl(this.state.page, this.state.pageSize);
            if (tab === 'CloudPlug') return this._buildCloudPlugUrl(this.state.page, this.state.pageSize);
            if (tab === 'template') return this._buildTemplateUrl(this.state.page, this.state.pageSize);
            if (tab === 'plugin' || isPluginPage) return this._buildPluginUrl(this.state.page, this.state.pageSize);
            return window.location.search;
        },


        render: function() {
            // 已经在 PHP 中预渲染，无需 JS 再次插入内容，只需确保 updateUI 正常
            const container = document.getElementById('top-page-control');
            if (!container) return;
            this.updateUI();
        },

        bindEvents: function() {
            const self = this;
            const container = document.getElementById('top-page-control');
            if (!container || container.dataset.bound === '1') return;
            const supported = typeof isPaginationSupported === 'function' ? isPaginationSupported() : true;

            // 翻页按钮
            container.querySelectorAll('.tpc-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (!supported) {
                        showToast('当前页面不支持分页功能', 'warning');
                        return;
                    }
                    const action = this.dataset.action;
                    if (action === 'first') self.goToPage(1);
                    else if (action === 'prev') self.goToPage(self.state.page - 1);
                    else if (action === 'next') self.goToPage(self.state.page + 1);
                    else if (action === 'last') self.goToPage(self.state.totalPages);
                });
            });

            // 手机端分页按钮
            const mobileContainer = document.getElementById('mobile-pagination');
            if (mobileContainer) {
                mobileContainer.querySelectorAll('.tpc-btn').forEach(btn => {
                    btn.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (!supported) {
                            showToast('当前页面不支持分页功能', 'warning');
                            return;
                        }
                        const action = this.dataset.action;
                        if (action === 'prev') self.goToPage(self.state.page - 1);
                        else if (action === 'next') self.goToPage(self.state.page + 1);
                    });
                });
            }

            // 页码菜单
            const pageBtn = container.querySelector('#tpc-page-btn');
            const pageMenu = container.querySelector('#tpc-page-menu');
            pageBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                if (!supported) {
                    showToast('当前页面不支持分页功能', 'warning');
                    return;
                }
                self.closeAllMenus();
                pageMenu.classList.toggle('show');
            });

            // 每页条数菜单
            const sizeBtn = container.querySelector('#tpc-size-btn');
            const sizeMenu = container.querySelector('#tpc-size-menu');
            sizeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                if (!supported) {
                    showToast('当前页面不支持分页功能', 'warning');
                    return;
                }
                self.closeAllMenus();
                sizeMenu.classList.toggle('show');
            });

            // 点击外部关闭菜单
            document.addEventListener('click', function() {
                self.closeAllMenus();
            });
            container.dataset.bound = '1';
        },

        closeAllMenus: function() {
            document.querySelectorAll('.tpc-menu').forEach(menu => {
                menu.classList.remove('show');
            });
        },

        goToPage: function(page) {
            if (page < 1 || page > this.state.totalPages) return;
            this.state.page = page;
            this.updateUI();
            this.load();
        },

        updateUI: function() {
            const self = this;
            const container = document.getElementById('top-page-control');
            if (!container) return;

            // 更新页码显示
            container.querySelector('#tpc-page-num').textContent = this.state.page;

            // 更新每页条数显示
            container.querySelector('#tpc-size-num').textContent = this.state.pageSize;

            // 更新按钮状态
            container.querySelectorAll('.tpc-btn').forEach(btn => {
                const action = btn.dataset.action;
                if (action === 'first' || action === 'prev') {
                    btn.classList.toggle('disabled', this.state.page === 1);
                } else if (action === 'next' || action === 'last') {
                    btn.classList.toggle('disabled', this.state.page === this.state.totalPages);
                }
            });

            // 更新手机端分页按钮状态
            const mobileContainer = document.getElementById('mobile-pagination');
            if (mobileContainer) {
                // 更新手机端页码显示
                const mobilePageNum = mobileContainer.querySelector('#mobile-page-num');
                if (mobilePageNum) {
                    mobilePageNum.textContent = this.state.page;
                }

                // 更新手机端按钮状态
                mobileContainer.querySelectorAll('.tpc-btn').forEach(btn => {
                    const action = btn.dataset.action;
                    if (action === 'prev') {
                        btn.classList.toggle('disabled', this.state.page === 1);
                    } else if (action === 'next') {
                        btn.classList.toggle('disabled', this.state.page === this.state.totalPages);
                    }
                });
            }

            const pageMenu = container.querySelector('#tpc-page-menu');
            const sizeMenu = container.querySelector('#tpc-size-menu');
            if (this.lastTotalPages !== this.state.totalPages || this.state.totalPages === 1) {
                let pageHtml = '';
                for (let i = 1; i <= this.state.totalPages; i++) {
                    pageHtml += `<div class="tpc-menu-item ${i === this.state.page ? 'active' : ''}" data-page="${i}">第${i}页</div>`;
                }
                pageMenu.innerHTML = pageHtml;
                pageMenu.querySelectorAll('.tpc-menu-item').forEach(item => {
                    item.addEventListener('click', function(e) {
                        e.stopPropagation();
                        self.goToPage(parseInt(this.dataset.page));
                    });
                });
                const tab = (new URLSearchParams(window.location.search)).get('tab') || 'metrics';
                // 检查是否直接访问Plugin.php文件
                const isPluginPage = window.location.pathname.includes('Plugin.php');
                const sizes = tab === 'plugin' || tab === 'CloudPlug' || isPluginPage ? [12, 24, 48, 96] : [30, 100, 200, 500];
                let sizeHtml = '';
                sizes.forEach(size => {
                    sizeHtml += `<div class="tpc-menu-item ${size === self.state.pageSize ? 'active' : ''}" data-size="${size}">${size}条/页</div>`;
                });
                sizeMenu.innerHTML = sizeHtml;
                sizeMenu.querySelectorAll('.tpc-menu-item').forEach(item => {
                    item.addEventListener('click', function(e) {
                        e.stopPropagation();
                        self.state.pageSize = parseInt(this.dataset.size);
                        self.state.page = 1;
                        self.updateUI();
                        self.load();
                    });
                });
                this.lastTotalPages = this.state.totalPages;
            } else {
                pageMenu.querySelectorAll('.tpc-menu-item').forEach(item => {
                    const p = parseInt(item.dataset.page);
                    item.classList.toggle('active', p === self.state.page);
                });
                sizeMenu.querySelectorAll('.tpc-menu-item').forEach(item => {
                    const s = parseInt(item.dataset.size);
                    item.classList.toggle('active', s === self.state.pageSize);
                });
            }
        },

        syncToMainPagination: function() {
            if (typeof PaginationManager !== 'undefined' && PaginationManager.state && PaginationManager.state.container) {
                PaginationManager.state.page = this.state.page;
                PaginationManager.state.pageSize = this.state.pageSize;
                PaginationManager.load();
            }
        },

        updateFromMainPagination: function(page, pageSize, totalPages) {
            const p = parseInt(page);
            const ps = parseInt(pageSize);
            const tp = parseInt(totalPages);
            if (ps && ps > 0) this.state.pageSize = ps;
            this.state.totalPages = tp && tp > 0 ? tp : 1;
            this.state.page = p && p > 0 ? Math.min(p, this.state.totalPages) : 1;
            this.lastTotalPages = 0; // 强制重新渲染菜单
            this.updateUI();
        },

        _buildArticleApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_articles&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            if (urlParams.get('category_id')) url += '&category_id=' + encodeURIComponent(urlParams.get('category_id'));
            if (urlParams.get('property_id')) url += '&property_id=' + encodeURIComponent(urlParams.get('property_id'));
            if (urlParams.get('template')) url += '&template=' + encodeURIComponent(urlParams.get('template'));
            for (const [key, value] of urlParams.entries()) {
                const cidMatch = key.match(/^cid(\d+)$/);
                if (cidMatch) {
                    url += '&category_id=' + encodeURIComponent(cidMatch[1]);
                    continue;
                }
                const pCidMatch = key.match(/^p\d+_s\d+_cid(\d+)$/);
                if (pCidMatch) {
                    url += '&category_id=' + encodeURIComponent(pCidMatch[1]);
                    continue;
                }
            }
            return url;
        },

        // 构建用户API请求URL
        _buildUsersApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_users&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            return url;
        },

        _buildCounterApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_counter&page=' + page + '&page_size=' + pageSize;
            const dateRange = urlParams.get('date_range');
            if (dateRange) url += '&date_range=' + encodeURIComponent(dateRange);
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            const sort = urlParams.get('sort');
            const order = urlParams.get('order');
            if (sort) url += '&sort=' + encodeURIComponent(sort);
            if (order) url += '&order=' + encodeURIComponent(order);
            return url;
        },

        _buildArticlesUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=articles&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildGoodsApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_goods&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            if (urlParams.get('category_id')) url += '&category_id=' + encodeURIComponent(urlParams.get('category_id'));
            return url;
        },

        _buildAdgoodsUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=adgoods&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildCounterUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=counter&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildCommentsApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_comments&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('status')) url += '&status=' + encodeURIComponent(urlParams.get('status'));
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            return url;
        },

        _buildCommentsUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=comments&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildReportsApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_reports&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('status')) url += '&status=' + encodeURIComponent(urlParams.get('status'));
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            return url;
        },

        _buildReportsUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=reports&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildOrdersApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_orders&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            if (urlParams.get('filter')) url += '&filter=' + encodeURIComponent(urlParams.get('filter'));
            if (urlParams.get('time_range')) url += '&time_range=' + encodeURIComponent(urlParams.get('time_range'));
            return url;
        },

        _buildOrderUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=order&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildPublishApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_publish&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('status')) url += '&status=' + encodeURIComponent(urlParams.get('status'));
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            return url;
        },

        _buildPublishUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=publish&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildTagSearchApiUrl: function(page, pageSize) {
            const hasSearchTab = window.location.href.includes('&Search');
            const action = hasSearchTab ? 'get_searches' : 'get_tags';
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=' + action + '&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            return url;
        },

        _buildTagSearchUrl: function(page, pageSize) {
            const hasSearchTab = window.location.href.includes('&Search');
            const tabArg = hasSearchTab ? '&Search' : '&tag';
            return '?tab=tagSearch' + tabArg + '&p' + page + '_s' + pageSize;
        },

        _buildTemplateApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/Template.php?action=get_templates&page=' + page + '&page_size=' + pageSize;
            const search = urlParams.get('search') || '';
            const charge = urlParams.get('charge') || '';
            if (search) url += '&search=' + encodeURIComponent(search);
            if (charge) url += '&charge=' + encodeURIComponent(charge);
            return url;
        },

        _buildTemplateUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=template&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        _buildPluginUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=plugin';

            // 检查是否已经有 cloud 或 installed 参数
            if (urlParams.get('cloud')) {
                url += '&cloud';
            } else if (urlParams.get('installed')) {
                url += '&installed';
            } else {
                // 如果都没有，默认添加 installed
                url += '&installed';
            }

            // 添加分页参数
            url += '&p' + page + '_s' + pageSize;

            // 保留其他参数
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && key !== 'cloud' && key !== 'installed' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }

            return url;
        },

        _buildCloudPlugUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=CloudPlug&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        },

        // 构建分类API请求URL
        _buildCategoriesApiUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '/admin/ajaxx.php?action=get_categories&page=' + page + '&page_size=' + pageSize;
            if (urlParams.get('search')) url += '&search=' + encodeURIComponent(urlParams.get('search'));
            if (urlParams.get('archiveid')) url += '&archiveid=' + encodeURIComponent(urlParams.get('archiveid'));
            return url;
        },

        // 构建分类页面URL
        _buildCategoriesUrl: function(page, pageSize) {
            const urlParams = new URLSearchParams(window.location.search);
            let url = '?tab=adcategory&p' + page + '_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab' && !key.match(/^p\d+_s\d+/) && key !== 'page' && key !== 'posts_per_page') {
                    url += '&' + key + '=' + encodeURIComponent(value);
                }
            }
            return url;
        }
    };

    function initHeaderPagination() {
        HeaderPagination.init();
    }
</script>

<!-- ==================== 后台搜索功能公共代码 ==================== -->





<!-- ==================== 后台分页公共代码 ==================== -->

<style>
    .pagination-container {
        margin-top: 20px;
        padding: 15px 0;
        border-top: 1px solid #e5e7eb;
    }

    .pagination-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }

    .pagination-buttons {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .pagination-page-numbers {
        display: flex;
        gap: 8px;
    }

    .pagination-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 36px;
        height: 36px;
        padding: 0 12px;
        font-size: 14px;
        color: #374151;
        background-color: #fff;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .pagination-btn:hover {
        color: var(--primary-color);
        border-color: var(--primary-color);
        background-color: #f3f4f6;
    }

    .pagination-btn.active {
        color: #fff;
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .pagination-btn.disabled {
        color: #9ca3af;
        background-color: #f3f4f6;
        border-color: #e5e7eb;
        cursor: not-allowed;
        pointer-events: none;
    }

    .pagination-select,
    .pagination-page-size {
        height: 36px;
        padding: 0 8px;
        font-size: 14px;
        color: #374151;
        background-color: #fff;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        cursor: pointer;
    }

    .pagination-page-size {
        width: 80px !important;
        min-width: 80px !important;
        max-width: 80px !important;
    }

    .pagination-settings {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 14px;
        color: #6b7280;
        white-space: nowrap;
    }

    @media (max-width: 768px) {
        .pagination-wrapper {
            flex-direction: column;
            align-items: flex-start;
        }

        .pagination-buttons {
            flex-wrap: wrap;
        }
    }
</style>

<!-- 分页HTML模板 -->
<script>
    // 检查当前页面是否支持搜索
    function isSearchSupported() {
        const tab = (new URLSearchParams(window.location.search)).get('tab') || 'metrics';
        // 检查是否直接访问Plugin.php文件
        const isPluginPage = window.location.pathname.includes('Plugin.php');
        if (isPluginPage) return true;
        return ['articles', 'adcategory', 'comments', 'users', 'reports', 'tagSearch', 'order', 'publish', 'plugin', 'CloudPlug', 'adgoods', 'generator', 'counter', 'template'].includes(tab);
    }

    // 检查当前页面是否支持分页
    function isPaginationSupported() {
        const tab = (new URLSearchParams(window.location.search)).get('tab') || 'metrics';
        // 检查是否直接访问Plugin.php文件
        const isPluginPage = window.location.pathname.includes('Plugin.php');
        if (isPluginPage) return true;
        // 所有后台管理页面都支持分页 UI 显示，保持一致性
        return true;
    }

    window.PaginationManager = {
        state: {
            page: 1,
            pageSize: 30,
            totalPages: 1,
            container: null,
            apiUrl: '',
            onLoad: null
        },

        init: function(options) {
            this.state.container = document.querySelector(options.container);
            if (!this.state.container) return;

            this.state.apiUrl = options.apiUrl || '';
            this.state.page = options.page || 1;
            this.state.pageSize = options.pageSize || 30;
            this.state.onLoad = options.onLoad || function() {};

            this.render();
            this.bindEvents();
            this.load();
        },

        render: function() {
            this.state.container.innerHTML = `
                    <div class="pagination-wrapper">
                        <div class="pagination-buttons">
                            <a href="#" class="pagination-btn pagination-first">首页</a>
                            <div class="pagination-page-numbers"></div>
                            <select class="pagination-select"><option value="">页码</option></select>
                            <a href="#" class="pagination-btn pagination-last">尾页</a>
                        </div>
                        <div class="pagination-settings">
                            <span>每页显示：</span>
                            <select class="pagination-page-size">
                                <option value="30">30条</option>
                                <option value="100">100条</option>
                                <option value="200">200条</option>
                                <option value="500">500条</option>
                                <option value="1000">1000条</option>
                            </select>
                        </div>
                    </div>`;
            this.state.container.querySelector('.pagination-page-size').value = this.state.pageSize;
        },

        bindEvents: function() {
            const self = this;
            const container = this.state.container;

            container.querySelector('.pagination-first').addEventListener('click', function(e) {
                e.preventDefault();
                if (self.state.page > 1) self.goToPage(1);
            });

            container.querySelector('.pagination-last').addEventListener('click', function(e) {
                e.preventDefault();
                if (self.state.page < self.state.totalPages) self.goToPage(self.state.totalPages);
            });

            container.querySelector('.pagination-select').addEventListener('change', function() {
                const page = parseInt(this.value);
                if (page && page !== self.state.page) self.goToPage(page);
            });

            container.querySelector('.pagination-page-size').addEventListener('change', function() {
                self.state.pageSize = parseInt(this.value);
                self.state.page = 1;
                self.load();
            });
        },

        goToPage: function(page) {
            if (page < 1 || page > this.state.totalPages) return;
            this.state.page = page;
            this.load();
        },

        load: function() {
            const self = this;
            const url = this.state.apiUrl + (this.state.apiUrl.indexOf('?') > -1 ? '&' : '?') +
                'page=' + this.state.page + '&page_size=' + this.state.pageSize;

            fetch(url)
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        // 统一处理分页数据
                        const pageData = data.data || data;
                        self.state.totalPages = pageData.total_pages || 1;

                        // 更新当前页码
                        self.state.page = pageData.current_page || 1;

                        self.updateUI();

                        // 调用页面特定的渲染函数
                        if (self.state.onLoad) {
                            self.state.onLoad(pageData);
                        }

                        // 同步到头部分页
                        if (typeof HeaderPagination !== 'undefined') {
                            // 确保HeaderPagination已经初始化
                            if (HeaderPagination.state) {
                                HeaderPagination.updateFromMainPagination(
                                    self.state.page,
                                    self.state.pageSize,
                                    self.state.totalPages
                                );
                            } else {
                                // 如果HeaderPagination还没有初始化，延迟后再尝试
                                setTimeout(() => {
                                    if (typeof HeaderPagination !== 'undefined' && HeaderPagination.state) {
                                        HeaderPagination.updateFromMainPagination(
                                            self.state.page,
                                            self.state.pageSize,
                                            self.state.totalPages
                                        );
                                    }
                                }, 100);
                            }
                        }
                    }
                })
                .catch(e => console.error('分页加载失败:', e));
        },

        updateUI: function() {
            const self = this;
            const container = this.state.container;
            const maxVisible = 5;
            let start = Math.max(1, this.state.page - Math.floor(maxVisible / 2));
            let end = Math.min(this.state.totalPages, start + maxVisible - 1);
            if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);

            let html = '';
            for (let i = start; i <= end; i++) {
                html += `<a href="#" class="pagination-btn page-number ${i === this.state.page ? 'active' : ''}" data-page="${i}">${i}</a>`;
            }
            const pageNumbers = container.querySelector('.pagination-page-numbers');
            pageNumbers.innerHTML = html;

            pageNumbers.querySelectorAll('.page-number').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    self.goToPage(parseInt(btn.dataset.page));
                });
            });

            let options = '<option value="">页码</option>';
            for (let i = 1; i <= this.state.totalPages; i++) {
                options += `<option value="${i}" ${i === this.state.page ? 'selected' : ''}>第${i}页</option>`;
            }
            container.querySelector('.pagination-select').innerHTML = options;

            container.querySelector('.pagination-first').classList.toggle('disabled', this.state.page === 1);
            container.querySelector('.pagination-last').classList.toggle('disabled', this.state.page === this.state.totalPages);
        },

        getState: function() {
            return {
                page: this.state.page,
                pageSize: this.state.pageSize,
                totalPages: this.state.totalPages
            };
        },

        refresh: function() {
            this.load();
        }
    };
</script>
