/*
// 功能：后台文章管理脚本文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。
*/

// ========== 全局变量定义 ==========
let dropdownCurrentPage = 1;
const dropdownPageSize = 12;
let dropdownArticles = [];
let dropdownFilteredArticles = [];
let dropdownTotalPages = 1;
let isUpdatingVideo = false;
let clickedVideoElement = null;
let selectedImage = null;
let clickedImage = null;
let originalSize = {
    width: 0,
    height: 0
};
const AUTO_CROP_THUMBNAIL_STORAGE_KEY = 'qkcms_article_auto_crop_thumbnail';

// ========== 工具函数 ==========
function showToast(message, type) {
    if (typeof window.showToast === 'function') {
        window.showToast(message, type);
    } else {
        alert(message);
    }
}

// 处理来自子窗口的消息
window.addEventListener('message', function (event) {
    // 验证消息来源
    if (event.origin !== window.location.origin) {
        return;
    }

    // 处理不同类型的消息
    const data = event.data;
    if (data.type === 'toast' && data.func === 'showToast') {
        // 显示提示框
        showToast(data.message, data.options.type || 'info');
    }
    const insertPayload = data && data.payload && data.payload.content ? data.payload : (data && data.data && data.data.content ? data.data : null);
    if (data.type === 'insert_article_content' && insertPayload && insertPayload.content) {
        if (!window.quill) return;
        const html = String(insertPayload.content || '');
        if (!html.trim()) return;
        try {
            window.quill.focus();
            const range = window.quill.getSelection(true);
            const index = range && range.index !== undefined ? range.index : window.quill.getLength();
            window.quill.clipboard.dangerouslyPasteHTML(index, html);
            const ct = document.getElementById('content');
            if (ct) ct.value = window.quill.root.innerHTML;
        } catch (e) { }
    }
});

function escapeHtml(text) {
    if (text === null || text === undefined) return '';
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function updateDimensions(sourceInput, targetInput, ratio) {
    const sourceValue = parseInt(sourceInput.value);
    if (!isNaN(sourceValue)) targetInput.value = Math.round(sourceValue * ratio);
}

function getAutoCropThumbnailCheckbox() {
    return document.getElementById('auto_crop_thumbnail');
}

function getAutoCropThumbnailEnabled() {
    const checkbox = getAutoCropThumbnailCheckbox();
    return !!(checkbox && checkbox.checked);
}

function getStoredAutoCropThumbnailPreference() {
    let checked = true;
    try {
        const savedValue = window.localStorage.getItem(AUTO_CROP_THUMBNAIL_STORAGE_KEY);
        if (savedValue !== null) checked = savedValue === '1';
    } catch (e) { }
    return checked;
}

function persistAutoCropThumbnailPreference(checked) {
    try {
        window.localStorage.setItem(AUTO_CROP_THUMBNAIL_STORAGE_KEY, checked ? '1' : '0');
    } catch (e) { }
}

function initAutoCropThumbnailPreference() {
    const checkbox = getAutoCropThumbnailCheckbox();
    if (!checkbox || checkbox.dataset.bound === '1') return;
    checkbox.dataset.bound = '1';

    checkbox.checked = getStoredAutoCropThumbnailPreference();
    checkbox.addEventListener('change', function () {
        persistAutoCropThumbnailPreference(checkbox.checked);
    });
}

function bindSafeBackdropClose(modal, onClose) {
    if (!modal || typeof onClose !== 'function') return;
    if (modal.__safeBackdropCloseBound) return;
    modal.__safeBackdropCloseBound = true;
    modal.__backdropMouseDown = false;

    modal.addEventListener('mousedown', function (e) {
        modal.__backdropMouseDown = (e.target === modal || e.target.classList.contains('modal-backdrop'));
    });

    modal.addEventListener('mouseup', function (e) {
        const isBackdrop = (e.target === modal || e.target.classList.contains('modal-backdrop'));
        if (modal.__backdropMouseDown && isBackdrop) {
            onClose();
        }
        modal.__backdropMouseDown = false;
    });

    modal.addEventListener('mouseleave', function () {
        modal.__backdropMouseDown = false;
    });
}

// ========== 模态框样式添加 ==========
window.addModalStyles = function () {
    if (!document.getElementById('modal-styles')) {
        const style = document.createElement('style');
        style.id = 'modal-styles';
        style.textContent = `.modal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.5);opacity:0;transition:opacity 0.3s ease;z-index:9998}.modal{position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:none;align-items:center;justify-content:center;opacity:0;transition:opacity 0.3s ease}.modal-visible{display:flex!important;opacity:1}.modal-visible .modal-backdrop{opacity:1}.modal-content{background-color:white;border-radius:8px;box-shadow:0 4px 20px rgba(0,0,0,0.15);width:90%;max-width:550px;max-height:90vh;overflow-y:auto;position:relative;z-index:9999;transform:scale(0.95);transition:transform 0.3s ease}.modal-visible .modal-content{transform:scale(1)}.modal-header{padding:16px 20px;border-bottom:1px solid #e0e0e0;display:flex;justify-content:space-between;align-items:center}.modal-title{margin:0;font-size:18px;font-weight:600;color:#333}.modal-close{background:none;border:none;font-size:24px;cursor:pointer;color:#666;padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s}.modal-close:hover{background-color:#f5f5f5;color:#333}.modal-body{padding:20px}.modal-actions{padding:16px 20px;border-top:1px solid #e0e0e0;display:flex;justify-content:flex-end;gap:10px;background:#f9f9f9;border-radius:0 0 8px 8px}.form-group{margin-bottom:16px}.form-group label{display:block;margin-bottom:6px;font-weight:500;color:#333}.form-control{width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:4px;font-size:14px;transition:border-color 0.2s;box-sizing:border-box}.form-control:focus{outline:none;border-color:#17a2b8;box-shadow:0 0 0 2px rgba(23,162,184,0.2)}.submit-button{padding:8px 16px;border:none;border-radius:4px;color:white;font-size:14px;cursor:pointer;transition:background-color 0.2s}.submit-button:hover{opacity:0.9}textarea{resize:vertical;min-height:80px}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.btn{padding:8px 16px;border:none;border-radius:4px;font-size:14px;font-weight:500;cursor:pointer;transition:all 0.2s}.btn:disabled{opacity:0.6;cursor:not-allowed}.btn-secondary{background-color:#6c757d;color:white}.btn-secondary:hover{background-color:#5a6268}.btn-success{background-color:#28a745;color:white}.btn-success:hover{background-color:#218838}.btn-primary{background-color:#007bff;color:white}.btn-primary:hover{background-color:#0069d9}`;
        document.head.appendChild(style);
        if (!document.getElementById('modal-override-styles')) {
            const override = document.createElement('style');
            override.id = 'modal-override-styles';
            override.textContent = `.modal-close{width:28px;height:28px;border:none;background:#dbdbdb;border-radius:50%;cursor:pointer;position:relative;transition:all .3s ease;color:transparent;font-size:0;padding:0;display:inline-flex;align-items:center;justify-content:center}.modal-close::before,.modal-close::after{content:'';position:absolute;top:50%;left:50%;width:12px;height:2px;background:#fff;transform:translate(-50%,-50%) rotate(45deg);transition:all .3s ease}.modal-close::after{transform:translate(-50%,-50%) rotate(-45deg)}.modal-close:hover{background:#ff5252;transform:rotate(90deg)}.modal-close:hover::before,.modal-close:hover::after{width:14px}`;
            document.head.appendChild(override);
        }
    }
};

// ========== 文章列表渲染函数（供公用分页组件使用） ==========
function renderArticlesList(data) {
    const tbody = document.querySelector('.admin-table.section-manage tbody');
    if (!tbody || !data.articles) return;

    tbody.innerHTML = '';
    data.articles.forEach(article => {
        const templates = window.articleTemplates || {};
        const currentTemplate = article.template ? String(article.template) : 'post.php';
        const templateOptions = Object.keys(templates).length > 0
            ? Object.entries(templates).map(([templatePath, templateName]) =>
                `<option value="${escapeHtml(templatePath)}" ${currentTemplate === templatePath ? 'selected' : ''}>${escapeHtml(templateName)}</option>`
            ).join('')
            : `<option value="post.php" ${currentTemplate === 'post.php' ? 'selected' : ''}>post.php（默认）</option>`;

        const row = document.createElement('tr');
        row.innerHTML = `
                    <td style="width: 40px;"><input type="checkbox" class="article-checkbox" value="${article.id}"></td>
                    <td>${article.id}</td>
                    <td>${article.thumbnail ?
                `<img src="${escapeHtml(article.thumbnail)}" alt="${escapeHtml(article.title)}" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(${article.id}, this)">` :
                `<img src="/assets/images/moren.jpg" alt="默认图片" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(${article.id}, this)">`}
                    </td>
                    <td class="article-title-cell" data-article-id="${article.id}">
                        <span class="article-title-display" ondblclick="editArticleTitle(${article.id})" data-qk-tip="${escapeHtml(article.title || '')}" data-original-title="${escapeHtml(article.title || '')}">
                            ${escapeHtml(article.title || '')}
                        </span>
                        <input type="text" class="article-title-input" style="display:none; width: 100%; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                            value="${escapeHtml(article.title || '')}"
                            onblur="saveArticleTitle(${article.id}, this)"
                            onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditArticleTitle(${article.id});}">
                    </td>
                    <td>
                        <form method="post" class="inline-form category-update-form">
                            <input type="hidden" name="update_category" value="1">
                            <input type="hidden" name="article_id" value="${article.id}">
                            <select name="category_id" onchange="updateCategory(this)" class="form-control category-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                ${data.categories ? data.categories.map(category =>
                    `<option value="${category.id}" ${article.category_id == category.id ? 'selected' : ''}>${escapeHtml(category.name)}</option>`
                ).join('') : `<option value="${article.category_id}">${escapeHtml(article.category_name || '未知分类')}</option>`}
                            </select>
                        </form>
                    </td>
                    <td>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="update_property" value="1">
                            <input type="hidden" name="article_id" value="${article.id}">
                            <select name="property" onchange="updateProperty(this)" class="form-control status-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                ${data.properties ? data.properties.map(prop =>
                    `<option value="${prop.id}" ${article.property == prop.id ? 'selected' : ''}>${escapeHtml(prop.name)}</option>`
                ).join('') : ''}
                            </select>
                        </form>
                    </td>
                    <td>${article.comment_count || 0}</td>
                    <td>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="update_template" value="1">
                            <input type="hidden" name="article_id" value="${article.id}">
                            <select name="template" onchange="updateTemplate(this)" class="form-control template-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                ${templateOptions}
                            </select>
                        </form>
                    </td>
                    <td>${typeof window.formatDateYMD === 'function' ? window.formatDateYMD(article.created_at) : '-'}</td>
                    <td>${typeof window.formatDateYMD === 'function' ? window.formatDateYMD(article.updated_at) : '-'}</td>
                    <td class="fixed-action-column">
                        ${(() => {
                            let preview_url = '/post_id' + article.id + '.php';
                            if (article.custom_url && String(article.custom_url).trim() !== '') {
                                let custom_url = String(article.custom_url).trim();
                                if (custom_url.indexOf('/') !== 0) {
                                    custom_url = '/' + custom_url;
                                }
                                preview_url = custom_url;
                            }
                            return `<a href="${escapeHtml(preview_url)}" target="_blank" class="btn btn-sm btn-secondary">预览</a>`;
                        })()}
                        <button type="button" class="btn btn-sm btn-primary edit-article-btn" data-id="${article.id}" data-title="${escapeHtml(article.title || '')}" data-category="${article.category_id || ''}" data-keywords="${escapeHtml(article.keywords || '')}" data-property="${article.property || 0}" data-thumbnail="${escapeHtml(article.thumbnail || '')}" data-description="${escapeHtml(article.description || '')}" data-points="${article.points || 0}" data-mp4url="${escapeHtml(article.mp4url || '')}" data-custom-url="${escapeHtml(article.custom_url || '')}">编辑</button>
                        <button type="button" onclick="deleteArticleConfirm(${article.id})" class="btn btn-sm btn-danger">删除</button>
                    </td>
                `;
        tbody.appendChild(row);
    });

    // 初始化滚动条和批量操作
    if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
        initCustomScrollbar();
    }
    if (typeof initBatchOperations === 'function') initBatchOperations();
}



// ========== 文章操作函数 ==========
function editArticleTitle(articleId) {
    const cell = document.querySelector('.article-title-cell[data-article-id="' + articleId + '"]');
    if (!cell) return;
    const display = cell.querySelector('.article-title-display');
    const input = cell.querySelector('.article-title-input');
    if (!display || !input) return;
    display.style.display = 'none';
    input.style.display = 'inline-block';
    input.focus();
    input.select();
}

function saveArticleTitle(articleId, input) {
    // 检查是否有阻止blur事件的标志
    if (window.preventTitleBlur) {
        return;
    }

    const cell = document.querySelector('.article-title-cell[data-article-id="' + articleId + '"]');
    if (!cell) return;
    const display = cell.querySelector('.article-title-display');
    const newTitle = input.value.trim();
    const oldTitle = display.getAttribute('data-original-title') || '';

    input.style.display = 'none';
    display.style.display = 'inline-block';

    if (!newTitle || newTitle === oldTitle) {
        input.value = oldTitle;
        return;
    }

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/article.php?action=update_article_title', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        showToast('文章标题更新成功', 'info');
                        display.textContent = newTitle;
                        display.setAttribute('data-qk-tip', newTitle);
                        display.setAttribute('data-original-title', newTitle);
                    } else {
                        input.value = oldTitle;
                        showToast(response.message || '保存失败', 'error');
                    }
                } catch (e) {
                    input.value = oldTitle;
                    showToast('保存失败，请重试', 'error');
                }
            } else {
                input.value = oldTitle;
                showToast('网络请求失败', 'error');
            }
        }
    };
    xhr.onerror = function () {
        input.value = oldTitle;
        showToast('网络错误，请重试', 'error');
    };
    xhr.send('article_id=' + encodeURIComponent(articleId) + '&title=' + encodeURIComponent(newTitle));
}

function cancelEditArticleTitle(articleId) {
    const cell = document.querySelector('.article-title-cell[data-article-id="' + articleId + '"]');
    if (!cell) return;
    const display = cell.querySelector('.article-title-display');
    const input = cell.querySelector('.article-title-input');
    input.value = display.getAttribute('data-original-title') || '';
    input.style.display = 'none';
    display.style.display = 'inline-block';
}

function replaceListThumbnail(articleId, imgElement) {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/png,image/jpeg,image/gif';
    fileInput.style.display = 'none';
    document.body.appendChild(fileInput);

    fileInput.click();

    fileInput.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (!file) {
            document.body.removeChild(fileInput);
            return;
        }

        // 验证文件类型
        const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
        const allowedExtensions = ['.png', '.jpg', '.jpeg', '.gif'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();

        if (!allowedTypes.includes(file.type) || !allowedExtensions.includes(fileExtension)) {
            showToast('只能上传 PNG、JPG、GIF 格式的图片文件！', 'error');
            document.body.removeChild(fileInput);
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('action', 'upload_image');
        formData.append('type', 'article');
        formData.append('image_type', 'thumbnail');
        formData.append('auto_crop_thumbnail', getStoredAutoCropThumbnailPreference() ? '1' : '0');

        const originalSrc = imgElement.src;
        imgElement.src = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0iIzY2NiIgZD0iTTAgMGgyNHYyNEgweiIvPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik0xMiA2djEyIi8+PHBhdGggZmlsbD0iIzAwNzZiZiIgZD0iTTEyIDhoLTF2M2gxdi0zem0wIDZ2N2gtMXYtN2gzem0tMi0yeiIvPjwvc3ZnPg==';

        fetch('/admin/article.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const newImageUrl = data.data.url;

                    // 尝试获取文章信息，删除老缩略图
                    const articleInfoUrl = '/admin/article.php?action=get_article_info&id=' + articleId;
                    fetch(articleInfoUrl)
                        .then(response => response.json())
                        .then(articleData => {
                            if (articleData.success && articleData.data) {
                                const currentThumbnail = articleData.data.thumbnail || '';

                                if (currentThumbnail) {
                                    fetch('/admin/article.php', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        },
                                        body: `action=delete_image&image_url=${encodeURIComponent(currentThumbnail)}`
                                    })
                                        .then(response => response.json())
                                        .then(deleteData => {
                                            console.log('删除老缩略图结果:', deleteData);
                                        })
                                        .catch(error => {
                                            console.error('删除老缩略图失败:', error);
                                        });
                                }
                            } else {
                            }
                        })
                        .catch(error => {
                            console.error('获取文章信息失败:', error);
                        })
                        .finally(() => {
                            // 无论获取文章信息是否成功，都更新缩略图
                            const updateUrl = '/admin/article.php';
                            fetch(updateUrl, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: `update_thumbnail=1&article_id=${articleId}&thumbnail=${encodeURIComponent(newImageUrl)}`
                            })
                                .then(response => response.json())
                                .then(updateData => {
                                    if (updateData.success && updateData.data && updateData.data.url) {
                                        // 使用服务器返回的最终URL
                                        imgElement.src = updateData.data.url;
                                        if (typeof showToast === 'function') {
                                            showToast('缩略图替换成功', 'success');
                                        }
                                    } else {
                                        imgElement.src = originalSrc;
                                        if (typeof showToast === 'function') {
                                            showToast('更新缩略图失败: ' + (updateData.message || '未知错误'), 'error');
                                        }
                                    }
                                })
                                .catch(error => {
                                    console.error('更新失败:', error);
                                    imgElement.src = originalSrc;
                                    if (typeof showToast === 'function') {
                                        showToast('更新缩略图失败: ' + error.message, 'error');
                                    }
                                });
                        });
                } else {
                    imgElement.src = originalSrc;
                    if (typeof showToast === 'function') {
                        showToast('上传图片失败', 'error');
                    }
                }
            })
            .catch(error => {
                imgElement.src = originalSrc;
                if (typeof showToast === 'function') {
                    showToast('上传图片失败', 'error');
                }
            })
            .finally(() => {
                document.body.removeChild(fileInput);
            });
    });
}

function updateArticleField(selectElement, fieldName, successMessage) {
    const form = selectElement.closest('form');
    const articleId = form.querySelector('input[name="article_id"]').value;
    const fieldValue = selectElement.value;
    const formData = new FormData();
    formData.append('update_' + fieldName, '1');
    formData.append('article_id', articleId);
    formData.append(fieldName, fieldValue);
    selectElement.disabled = true;

    const xhr = new XMLHttpRequest();
    xhr.open('POST', window.location.href, true);
    xhr.onload = function () {
        selectElement.disabled = false;
        if (xhr.status >= 200 && xhr.status < 300) {
            showToast(successMessage, 'success');
        }
    };
    xhr.onerror = function () {
        selectElement.disabled = false;
    };
    xhr.send(formData);
}

function updateCategory(selectElement) {
    updateArticleField(selectElement, 'category_id', '分类更新成功');
}

function updateProperty(selectElement) {
    updateArticleField(selectElement, 'property', '属性更新成功');
}

function updateTemplate(selectElement) {
    updateArticleField(selectElement, 'template', '模板绑定成功');
}

function deleteArticleConfirm(articleId) {
    const xhr = new XMLHttpRequest();
    const url = '?tab=articles&delete_article=' + encodeURIComponent(articleId) + '&ajax=1';
    xhr.open('GET', url, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    showToast(response.message, response.success ? 'success' : 'error');
                    if (response.success && typeof HeaderPagination !== 'undefined' && typeof HeaderPagination.load === 'function') {
                        HeaderPagination.load();
                    }
                } catch (e) {
                    showToast('删除失败，请重试', 'error');
                }
            } else {
                showToast('网络请求失败', 'error');
            }
        }
    };
    xhr.onerror = function () {
        showToast('网络错误，请检查连接', 'error');
    };
    xhr.send();
}

// ========== 批量操作函数 ==========
function initBatchOperations() {
    const batchOperationBtn = document.getElementById('batch-operation-btn');
    const batchModal = document.getElementById('batch-operation-modal');
    const closeBatchModal = document.getElementById('close-batch-modal');
    const countNumber = document.getElementById('count-number');
    const batchMoveBtn = document.getElementById('batch-move-btn');
    const batchCategorySelect = document.getElementById('batch-category-select');
    const batchPropertyBtn = document.getElementById('batch-property-btn');
    const batchPropertySelect = document.getElementById('batch-property-select');
    const batchTemplateSelect = document.getElementById('batch-template-select');
    const batchTemplateBtn = document.getElementById('batch-template-btn');
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    const selectAllCheckbox = document.getElementById('select-all-articles');
    const articleCheckboxes = document.querySelectorAll('.article-checkbox');

    if (typeof window.addModalStyles === 'function') window.addModalStyles();

    function updateSelectedCount() {
        countNumber.textContent = document.querySelectorAll('.article-checkbox:checked').length;
    }

    function getSelectedArticleIds() {
        return Array.from(document.querySelectorAll('.article-checkbox:checked')).map(cb => cb.value);
    }

    const staticBound = batchModal && batchModal.dataset.batchOpsBound === '1';
    if (!staticBound && batchModal) batchModal.dataset.batchOpsBound = '1';

    if (!staticBound && batchOperationBtn) {
        batchOperationBtn.onclick = function () {
            const selectedIds = getSelectedArticleIds();
            if (selectedIds.length === 0) {
                showToast('请先选择文章', 'error');
                return;
            }
            window.batchOperationSuccess = false;
            updateSelectedCount();
            batchModal.style.display = 'flex';
            setTimeout(() => batchModal.classList.add('modal-visible'), 10);

            window.closeOnEscape = function (e) {
                if (e.key === 'Escape' && batchModal.classList.contains('modal-visible')) {
                    closeBatchOperationModal();
                    document.removeEventListener('keydown', window.closeOnEscape);
                }
            };
            document.addEventListener('keydown', window.closeOnEscape);
        };
    }

    window.isConfirmDialogOpen = false;
    window.batchOperationSuccess = false;

    function closeBatchOperationModal() {
        if (window.isConfirmDialogOpen) return;
        batchModal.classList.remove('modal-visible');
        setTimeout(() => {
            batchModal.style.display = 'none';
            if (window.batchOperationSuccess) {
                window.batchOperationSuccess = false;
                window.location.reload();
            }
        }, 300);
    }

    if (!staticBound && closeBatchModal) {
        closeBatchModal.onclick = closeBatchOperationModal;
    }

    if (selectAllCheckbox) {
        selectAllCheckbox.onchange = function () {
            articleCheckboxes.forEach(checkbox => checkbox.checked = this.checked);
            updateSelectedCount();
        };
    }

    articleCheckboxes.forEach(checkbox => {
        checkbox.onchange = updateSelectedCount;
    });

    function batchOperation(action, selectedIds, params, button, loadingText, successText) {
        if (selectedIds.length === 0) {
            showToast('请先选择文章', 'error');
            return;
        }

        button.disabled = true;
        button.textContent = loadingText;

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/admin/ajaxx.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                button.disabled = false;
                button.textContent = successText;
                if (xhr.status === 200) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        showToast(data.message || successText, data.success ? 'info' : 'error', 1500);
                        window.batchOperationSuccess = data.success;
                    } catch (error) {
                        showToast('操作失败，请重试', 'info', 1500);
                    }
                } else {
                    showToast(successText + '失败，请重试！', 'info', 1500);
                }
            }
        };
        xhr.onerror = function () {
            button.disabled = false;
            button.textContent = successText;
            showToast('网络错误，请检查连接后重试！', 'info', 1500);
        };

        let data = 'action=' + action + '&article_ids=' + selectedIds.join(',');
        for (const [key, value] of Object.entries(params)) {
            data += '&' + key + '=' + encodeURIComponent(value);
        }
        xhr.send(data);
    }

    if (!staticBound && batchMoveBtn) {
        batchMoveBtn.onclick = function () {
            const selectedIds = getSelectedArticleIds();
            const categoryId = batchCategorySelect.value;

            if (categoryId === '0') {
                showToast('请选择分类', 'error');
                return;
            }

            batchOperation('batch_update_category', selectedIds, {
                category_id: categoryId
            }, batchMoveBtn, '移动中...', '批量移动文章');
        };
    }

    if (!staticBound && batchPropertyBtn) {
        batchPropertyBtn.onclick = function () {
            const selectedIds = getSelectedArticleIds();
            const propertyId = batchPropertySelect.value;

            if (propertyId === '0') {
                showToast('请选择属性', 'error');
                return;
            }

            batchOperation('batch_update_property', selectedIds, {
                property_id: propertyId
            }, batchPropertyBtn, '修改中...', '批量修改属性');
        };
    }

    if (!staticBound && batchTemplateBtn) {
        batchTemplateBtn.onclick = function () {
            const selectedIds = getSelectedArticleIds();
            const template = batchTemplateSelect.value;

            if (template === '0') {
                showToast('请选择模板', 'error');
                return;
            }

            batchOperation('batch_update_template', selectedIds, {
                template: template
            }, batchTemplateBtn, '绑定中...', '批量绑定模板');
        };
    }

    if (!staticBound && batchDeleteBtn) {
        batchDeleteBtn.onclick = function (e) {
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }

            const selectedIds = getSelectedArticleIds();
            if (selectedIds.length === 0) {
                showToast('请先选择文章', 'error');
                return false;
            }

            batchDeleteBtn.disabled = true;
            batchDeleteBtn.textContent = '删除中...';

            const xhr = new XMLHttpRequest();
            const url = '?tab=articles&batch_delete=1&ajax=1&article_ids=' + encodeURIComponent(selectedIds.join(','));
            xhr.open('GET', url, true);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    batchDeleteBtn.disabled = false;
                    batchDeleteBtn.textContent = '批量删除';
                    if (xhr.status === 200) {
                        try {
                            const data = JSON.parse(xhr.responseText);
                            showToast(data.message || '删除成功', data.success ? 'info' : 'error', 1500);
                            window.batchOperationSuccess = data.success;
                        } catch (error) {
                            showToast('删除失败，请重试', 'info', 1500);
                        }
                    } else {
                        showToast('删除文章失败，请重试！', 'info', 1500);
                    }
                }
            };
            xhr.onerror = function () {
                batchDeleteBtn.disabled = false;
                batchDeleteBtn.textContent = '批量删除';
                showToast('网络错误，请检查连接后重试！', 'info', 1500);
            };
            xhr.send();
            return false;
        };
    }
}

// ========== 自定义滚动条函数 ==========
function initCustomScrollbar() {
    const scrollContainer = document.querySelector('.admin-table-scroll');
    const scrollbarTrack = document.querySelector('.counter-custom-scrollbar-track');
    const scrollbarThumb = document.querySelector('.counter-custom-scrollbar-thumb');

    if (!scrollContainer || !scrollbarTrack || !scrollbarThumb) return;
    if (!window.AdminScrollbar || typeof window.AdminScrollbar.initHorizontal !== 'function') return;
    window.AdminScrollbar.initHorizontal({
        scrollContainer: scrollContainer,
        track: scrollbarTrack,
        thumb: scrollbarThumb,
        updateHookName: '_updateScrollbarThumb'
    });
}



// ========== 视频操作函数 ==========
window.openVideoInsertModal = function (videoElement, clickedVideo) {
    const modal = document.getElementById('videoInsertModal');
    if (!modal) return;

    if (typeof window.addModalStyles === 'function') window.addModalStyles();

    const videoUrlInput = document.getElementById('video-url');
    const autoplayCheckbox = document.getElementById('autoplay');
    const preserveAspectRatioCheckbox = document.getElementById('videoPreserveAspectRatio');
    const videoWidthInput = document.getElementById('video-width');
    const videoHeightInput = document.getElementById('video-height');
    const videoBuyContentCheckbox = document.getElementById('video-buy-content');
    const videoBuyPointsInput = document.getElementById('video-buy-points');
    const buyContentSection = document.querySelector('.buy-content-section');

    clickedVideoElement = clickedVideo;

    let hasExistingBuyTag = false;
    if (clickedVideo) {
        const currentHtml = quill.root.innerHTML;
        const buyTagRegex = /\[qkcms:buy——(\d+)个积分\]/g;
        const matches = currentHtml.match(buyTagRegex);
        hasExistingBuyTag = matches && matches.length > 0;
    }

    if (videoElement) {
        const video = clickedVideo || videoElement.querySelector('video');
        if (video) {
            if (videoUrlInput) videoUrlInput.value = video.getAttribute('src') || '';
            if (autoplayCheckbox) autoplayCheckbox.checked = video.hasAttribute('autoplay');
            if (videoWidthInput) videoWidthInput.value = video.getAttribute('width') || '790';
            if (videoHeightInput) videoHeightInput.value = video.getAttribute('height') || '550';
        }
    } else {
        if (videoUrlInput) videoUrlInput.value = '';
        if (autoplayCheckbox) autoplayCheckbox.checked = false;
        if (videoWidthInput) videoWidthInput.value = '790';
        if (videoHeightInput) videoHeightInput.value = '550';
        if (preserveAspectRatioCheckbox) preserveAspectRatioCheckbox.checked = true;
    }

    isUpdatingVideo = !!videoElement;

    if (hasExistingBuyTag) {
        if (buyContentSection) buyContentSection.style.display = 'none';
        modal.querySelector('.modal-content').style.height = '430px';
        modal.querySelector('.modal-content').style.maxHeight = '430px';
    } else {
        if (buyContentSection) buyContentSection.style.display = 'block';
        modal.querySelector('.modal-content').style.height = '510px';
        modal.querySelector('.modal-content').style.maxHeight = '510px';
    }

    if (videoWidthInput) {
        videoWidthInput.addEventListener('input', function () {
            if (preserveAspectRatioCheckbox.checked) {
                updateDimensions(videoWidthInput, videoHeightInput, 550 / 790);
            }
        });
    }
    if (videoHeightInput) {
        videoHeightInput.addEventListener('input', function () {
            if (preserveAspectRatioCheckbox.checked) {
                updateDimensions(videoHeightInput, videoWidthInput, 790 / 550);
            }
        });
    }

    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('modal-visible'), 10);
    bindSafeBackdropClose(modal, window.closeVideoInsertModal);

    const closeOnEsc = function (e) {
        if (e.key === 'Escape' && modal.classList.contains('modal-visible')) {
            window.closeVideoInsertModal();
            document.removeEventListener('keydown', closeOnEsc);
        }
    };
    document.addEventListener('keydown', closeOnEsc);
};

window.closeVideoInsertModal = function () {
    const modal = document.getElementById('videoInsertModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('modal-visible');
    }
    clickedVideoElement = null;
};

window.closeAiPluginModal = function () {
    const modal = document.getElementById('aiPluginModal');
    if (modal) {
        modal.classList.remove('modal-visible');
        setTimeout(() => {
            modal.style.display = 'none';
            document.getElementById('ai-plugin-content').innerHTML = '';
        }, 300);
    }
};

window.deleteVideo = function () {
    if (!clickedVideoElement) {
        showToast('未选择要删除的视频', 'warning');
        return;
    }

    let videoDeleted = false;

    try {
        let parent = clickedVideoElement.parentElement;
        while (parent && parent !== quill.root) {
            if (parent.classList.contains('ql-blank') || parent.classList.contains('ql-block') || parent.tagName === 'P' || parent.tagName === 'DIV') break;
            parent = parent.parentElement;
        }
        if (parent && parent !== quill.root) {
            parent.remove();
            videoDeleted = true;
        } else {
            clickedVideoElement.remove();
            videoDeleted = true;
        }
    } catch (error) { }

    if (!videoDeleted) {
        try {
            const videoIndex = quill.getIndex(clickedVideoElement);
            if (videoIndex !== null && videoIndex !== undefined && videoIndex !== -1) {
                quill.deleteText(videoIndex, 1);
                videoDeleted = true;
            } else {
                const currentHtml = quill.root.innerHTML;
                const newHtml = currentHtml.replace(clickedVideoElement.outerHTML, '');
                if (newHtml !== currentHtml) {
                    quill.root.innerHTML = newHtml;
                    videoDeleted = true;
                }
            }
        } catch (error) { }
    }

    const mp4urlInput = document.getElementById('mp4url');
    if (mp4urlInput) mp4urlInput.value = '';

    quill.updateContents({});
    quill.focus();

    const contentTextarea = document.getElementById('content');
    if (contentTextarea) contentTextarea.value = quill.root.innerHTML;

    showToast(videoDeleted ? '视频已删除' : '删除视频失败', videoDeleted ? 'success' : 'error');
    clickedVideoElement = null;
    isUpdatingVideo = false;
    window.closeVideoInsertModal();
};

window.confirmVideoInsert = function () {
    const videoUrl = document.getElementById('video-url').value.trim();
    if (!videoUrl) {
        showToast('请输入视频URL', 'warning');
        return;
    }

    const autoplay = document.getElementById('autoplay').checked;
    let width = document.getElementById('video-width').value;
    let height = document.getElementById('video-height').value;
    const buyContent = document.getElementById('video-buy-content').checked;
    const buyPoints = document.getElementById('video-buy-points').value;

    let updated = false;

    if (isUpdatingVideo) {
        if (clickedVideoElement) {
            clickedVideoElement.setAttribute('src', videoUrl);
            clickedVideoElement.setAttribute('width', width);
            clickedVideoElement.setAttribute('height', height);
            if (autoplay) {
                clickedVideoElement.setAttribute('autoplay', '');
            } else {
                clickedVideoElement.removeAttribute('autoplay');
            }

            if (buyContent) {
                const currentHtml = quill.root.innerHTML;
                const videoHtml = clickedVideoElement.outerHTML;
                const buyTagRegex = /\[qkcms:buy——(\d+)个积分\]([\s\S]*?)\[\/qkcms:buy\]/g;
                let match, foundBuyTag = false,
                    oldBuyTag = null;

                while ((match = buyTagRegex.exec(currentHtml)) !== null) {
                    if (match[2].includes(videoHtml)) {
                        foundBuyTag = true;
                        oldBuyTag = match[0];
                        break;
                    }
                }

                if (foundBuyTag && oldBuyTag) {
                    const newBuyTag = `[qkcms:buy——${buyPoints}个积分]${match[2]}[/qkcms:buy]`;
                    const newHtml = currentHtml.replace(oldBuyTag, newBuyTag);
                    if (newHtml !== currentHtml) {
                        quill.root.innerHTML = newHtml;
                        showToast('已更新付费积分', 'info');
                    } else {
                        showToast('更新积分失败', 'error');
                    }
                } else {
                    const buyContentHtml = `[qkcms:buy——${buyPoints}个积分]${videoHtml}[/qkcms:buy]`;
                    try {
                        const oldHtml = quill.root.innerHTML;
                        const newHtml = oldHtml.replace(videoHtml, buyContentHtml);
                        if (newHtml !== oldHtml) {
                            quill.root.innerHTML = newHtml;
                        } else {
                            const tempContainer = document.createElement('div');
                            tempContainer.innerHTML = buyContentHtml;
                            const buyElement = tempContainer.firstChild;
                            if (buyElement && clickedVideoElement.parentNode) {
                                clickedVideoElement.parentNode.replaceChild(buyElement, clickedVideoElement);
                            } else {
                                throw new Error('无法替换视频元素');
                            }
                        }
                    } catch (error) {
                        showToast('添加付费标识失败', 'error');
                    }
                }
            } else {
                showToast('视频属性已更新', 'info');
            }
            updated = true;
        }
    }

    if (!updated) {
        if (isUpdatingVideo) {
            showToast('更新视频失败：未找到视频元素', 'error');
        } else {
            const isCodeMode = window.isCodeModeGlobal || false;

            if (isCodeMode) {
                let videoCode = `[video src="${videoUrl}" width="${width}" height="${height}"]`;
                if (buyContent) videoCode = `[qkcms:buy——${buyPoints}个积分]${videoCode}[/qkcms:buy]`;

                const contentTextarea = document.getElementById('content');
                if (contentTextarea) {
                    const currentContent = contentTextarea.value;
                    const selection = quill.getSelection();
                    const range = selection ? selection.index : currentContent.length;
                    const newContent = currentContent.substring(0, range) + videoCode + currentContent.substring(range);
                    contentTextarea.value = newContent;
                    quill.setText('');
                    quill.setText(newContent);
                } else {
                    const currentContent = quill.getText();
                    const selection = quill.getSelection();
                    const range = selection ? selection.index : quill.getLength();
                    const newContent = currentContent.substring(0, range) + videoCode + currentContent.substring(range);
                    quill.setText('');
                    quill.setText(newContent);
                }
            } else {
                const selection = quill.getSelection();
                const index = selection ? selection.index : quill.getLength();

                if (buyContent) {
                    const videoHtml = `[qkcms:buy——${buyPoints}个积分]<video src="${videoUrl}" width="${width}" height="${height}" ${autoplay ? 'autoplay' : ''} controls></video>[/qkcms:buy]`;
                    try {
                        quill.clipboard.dangerouslyPasteHTML(index, videoHtml);
                    } catch (error) {
                        quill.root.innerHTML += videoHtml;
                    }
                } else {
                    try {
                        quill.insertEmbed(index, 'video', {
                            src: videoUrl,
                            width: width,
                            height: height,
                            autoplay: autoplay
                        });
                    } catch (error) {
                        const videoHtml = `<video src="${videoUrl}" width="${width}" height="${height}" ${autoplay ? 'autoplay' : ''} controls></video>`;
                        try {
                            quill.clipboard.dangerouslyPasteHTML(index, videoHtml);
                        } catch (e) {
                            quill.root.innerHTML += videoHtml;
                        }
                    }
                }
            }
        }
    }

    setTimeout(() => {
        const contentTextarea = document.getElementById('content');
        contentTextarea.value = window.isCodeModeGlobal ? quill.getText() : quill.root.innerHTML;
    }, 100);

    if (!updated) {
        showToast(buyContent ? '视频已插入，已添加付费标识' : '视频已插入', 'success');
    }
    window.closeVideoInsertModal();
};

function addVideoClickListeners() {
    const videos = quill.root.querySelectorAll('video, .video-container');
    videos.forEach(video => {
        video.addEventListener('click', function (e) {
            clickedVideoElement = video;
            const selection = quill.getSelection();
            clickedVideoElementIndex = selection ? selection.index : findElementIndex(video);
            e.preventDefault();
            e.stopPropagation();

            if (typeof window.openVideoInsertModal === 'function') {
                window.openVideoInsertModal(video, video);
            }
        });
    });
}

function findElementIndex(element) {
    try {
        const length = quill.getLength();
        for (let i = 0; i < length; i++) {
            const [leaf] = quill.getLeaf(i);
            if (leaf && leaf.domNode) {
                if (leaf.domNode === element || leaf.domNode.contains(element)) {
                    return i;
                }
            }
        }
        return null;
    } catch (error) {
        return null;
    }
}

// ========== 缩略图操作函数 ==========
function getThumbnailElements() {
    return {
        articleForm: document.getElementById('article-form'),
        thumbnailInput: document.getElementById('thumbnail'),
        thumbnailUploadBtn: document.getElementById('thumbnail-upload-btn'),
        thumbnailUrlInput: document.getElementById('thumbnail-url-input'),
        thumbnailDeleteBtn: document.getElementById('thumbnail-delete-btn'),
        thumbnailPreviewBoxWrap: document.getElementById('thumbnail-preview-box-wrap')
    };
}

function removeClearThumbnailInput() {
    const clearThumbnailInput = document.querySelector('input[name="clear_thumbnail"]');
    if (clearThumbnailInput) clearThumbnailInput.remove();
}

function ensureClearThumbnailInput() {
    const { articleForm } = getThumbnailElements();
    if (!articleForm) return null;
    let clearThumbnailInput = articleForm.querySelector('input[name="clear_thumbnail"]');
    if (!clearThumbnailInput) {
        clearThumbnailInput = document.createElement('input');
        clearThumbnailInput.type = 'hidden';
        clearThumbnailInput.name = 'clear_thumbnail';
        articleForm.appendChild(clearThumbnailInput);
    }
    clearThumbnailInput.value = '1';
    return clearThumbnailInput;
}

function setThumbnailHiddenValue(name, value) {
    const { articleForm } = getThumbnailElements();
    if (!articleForm) return null;
    let input = articleForm.querySelector('input[name="' + name + '"]');
    if (!input) {
        input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        articleForm.appendChild(input);
    }
    input.value = value;
    return input;
}

function removeThumbnailHiddenValue(name) {
    const { articleForm } = getThumbnailElements();
    if (!articleForm) return;
    const input = articleForm.querySelector('input[name="' + name + '"]');
    if (input) input.remove();
}

function escapeAttribute(value) {
    return escapeHtml(value).replace(/"/g, '&quot;');
}

function getThumbnailDisplayText(url, sourceType) {
    if (sourceType === 'url') return url;
    const normalized = String(url || '').replace(/\\/g, '/');
    const parts = normalized.split('/');
    return parts[parts.length - 1] || normalized;
}

function inferThumbnailSourceType(url) {
    const value = String(url || '').trim();
    if (!value) return 'upload';
    try {
        const parsed = new URL(value, window.location.origin);
        if (parsed.origin !== window.location.origin) return 'url';
        return parsed.pathname.indexOf('/uploads/') === 0 ? 'upload' : 'url';
    } catch (e) {
        return value.indexOf('/uploads/') === 0 ? 'upload' : 'url';
    }
}

function shouldDeleteUploadedThumbnail(url, sourceType) {
    if (sourceType !== 'upload') return false;
    try {
        const parsed = new URL(url, window.location.origin);
        return parsed.origin === window.location.origin && parsed.pathname.indexOf('/uploads/') === 0;
    } catch (e) {
        return false;
    }
}

function renderThumbnailEmptyState() {
    const { thumbnailPreviewBoxWrap, thumbnailUrlInput, thumbnailInput, thumbnailDeleteBtn } = getThumbnailElements();
    if (!thumbnailPreviewBoxWrap) return;
    thumbnailPreviewBoxWrap.innerHTML = '';
    if (thumbnailUrlInput) thumbnailUrlInput.value = '';
    if (thumbnailInput) thumbnailInput.value = '';
    if (thumbnailDeleteBtn) thumbnailDeleteBtn.classList.remove('has-value');
    removeThumbnailHiddenValue('existing_thumbnail');
    removeThumbnailHiddenValue('thumbnail_source_type');
    bindDeleteThumbnailEvents();
}

function renderThumbnailExistingState(url, sourceType) {
    const { thumbnailPreviewBoxWrap, thumbnailUrlInput, thumbnailDeleteBtn } = getThumbnailElements();
    if (!thumbnailPreviewBoxWrap) return;
    thumbnailPreviewBoxWrap.innerHTML = '<div class="thumbnail-preview-box" data-thumbnail="' + escapeAttribute(url) + '" style="width:80px;height:40px;display:flex;align-items:center;justify-content:center;overflow:hidden;"><img src="' + escapeAttribute(url) + '" alt="缩略图预览" style="max-width:100%;max-height:100%;object-fit:cover;"></div>';
    if (thumbnailUrlInput) thumbnailUrlInput.value = getThumbnailDisplayText(url, sourceType);
    if (thumbnailDeleteBtn) thumbnailDeleteBtn.classList.add('has-value');
    setThumbnailHiddenValue('existing_thumbnail', url);
    setThumbnailHiddenValue('thumbnail_source_type', sourceType);
    removeClearThumbnailInput();
    bindDeleteThumbnailEvents();
}

function renderThumbnailFileState(fileName, previewSrc) {
    const { thumbnailPreviewBoxWrap, thumbnailUrlInput, thumbnailDeleteBtn } = getThumbnailElements();
    if (!thumbnailPreviewBoxWrap) return;
    thumbnailPreviewBoxWrap.innerHTML = '<div class="thumbnail-preview-box" style="width:80px;height:40px;display:flex;align-items:center;justify-content:center;overflow:hidden;"><img src="' + escapeAttribute(previewSrc) + '" alt="缩略图预览" style="max-width:100%;max-height:100%;object-fit:cover;"></div>';
    if (thumbnailUrlInput) thumbnailUrlInput.value = fileName;
    if (thumbnailDeleteBtn) thumbnailDeleteBtn.classList.add('has-value');
    removeThumbnailHiddenValue('existing_thumbnail');
    setThumbnailHiddenValue('thumbnail_source_type', 'upload');
    removeClearThumbnailInput();
    bindDeleteThumbnailEvents();
}

function applyThumbnailUrlValue(rawUrl, silent) {
    const { thumbnailInput } = getThumbnailElements();
    const thumbnailUrl = String(rawUrl || '').trim();
    if (!thumbnailUrl) return false;
    if (!/^https?:\/\/.+/i.test(thumbnailUrl) && thumbnailUrl.charAt(0) !== '/') {
        if (!silent) showToast('请输入完整图片URL，或以 / 开头的站内路径', 'error');
        return false;
    }
    if (thumbnailInput) thumbnailInput.value = '';
    renderThumbnailExistingState(thumbnailUrl, 'url');
    if (!silent) showToast('已使用URL缩略图', 'success');
    return true;
}

function bindDeleteThumbnailEvents() {
    document.querySelectorAll('.delete-thumbnail').forEach(button => {
        const newButton = button.cloneNode(true);
        if (button.parentNode) button.parentNode.replaceChild(newButton, button);

        newButton.addEventListener('click', function () {
            const { articleForm } = getThumbnailElements();
            if (!articleForm) return;
            const existingThumbnailInput = articleForm.querySelector('input[name="existing_thumbnail"]');
            const sourceTypeInput = articleForm.querySelector('input[name="thumbnail_source_type"]');

            try {
                if (existingThumbnailInput) {
                    const thumbnailUrl = existingThumbnailInput.value;
                    const sourceType = sourceTypeInput ? String(sourceTypeInput.value || 'upload') : inferThumbnailSourceType(thumbnailUrl);
                    if (thumbnailUrl && shouldDeleteUploadedThumbnail(thumbnailUrl, sourceType)) {
                        const formData = new FormData();
                        formData.append('action', 'delete_thumbnail');
                        formData.append('thumbnail_url', thumbnailUrl);
                        fetch('ajaxx.php', {
                            method: 'POST',
                            body: formData
                        });
                    }
                }
                ensureClearThumbnailInput();
                renderThumbnailEmptyState();
                showToast('缩略图已删除', 'success');
            } catch (error) {
                showToast('删除缩略图失败，请重试', 'error');
            }
        });
    });
}

function bindThumbnailUploadBtn() {
    const { thumbnailUploadBtn, thumbnailInput } = getThumbnailElements();
    if (thumbnailUploadBtn && thumbnailInput) {
        if (thumbnailUploadBtn.dataset.bound === '1' && thumbnailInput.dataset.bound === '1') return;
        thumbnailUploadBtn.dataset.bound = '1';
        thumbnailInput.dataset.bound = '1';
        thumbnailUploadBtn.addEventListener('click', function () {
            thumbnailInput.click();
        });

        thumbnailInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (file) {
                if (!file.type.startsWith('image/')) {
                    showToast('请选择图片文件', 'error');
                    return;
                }

                const reader = new FileReader();
                reader.onload = function (e) {
                    renderThumbnailFileState(file.name, e.target.result);
                    showToast('缩略图已选择', 'success');
                };

                reader.onerror = function () {
                    showToast('读取图片失败，请重试', 'error');
                };

                reader.readAsDataURL(file);
            }
        });
    }
}

function bindThumbnailUrlInput() {
    const { thumbnailUrlInput } = getThumbnailElements();
    if (!thumbnailUrlInput) return;
    if (thumbnailUrlInput.dataset.bound === '1') return;
    thumbnailUrlInput.dataset.bound = '1';
    thumbnailUrlInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            applyThumbnailUrlValue(this.value, false);
        }
    });
    thumbnailUrlInput.addEventListener('blur', function () {
        const currentValue = String(this.value || '').trim();
        if (!currentValue) return;
        if (!/^https?:\/\/.+/i.test(currentValue) && currentValue.charAt(0) !== '/') return;
        const existingThumbnailInput = document.querySelector('input[name="existing_thumbnail"]');
        const currentExisting = existingThumbnailInput ? String(existingThumbnailInput.value || '').trim() : '';
        if (currentValue === currentExisting) return;
        applyThumbnailUrlValue(currentValue, false);
    });
}

// ========== 图片操作函数 ==========
function openModal(image, clickedImg) {
    // 设置标志，防止触发文章标题输入框的blur事件
    window.preventTitleBlur = true;

    selectedImage = image;
    clickedImage = clickedImg;
    const img = clickedImg || image.querySelector('img');
    originalSize.width = img.clientWidth;
    originalSize.height = img.clientHeight;
    document.getElementById('imageWidth').value = originalSize.width;
    document.getElementById('imageHeight').value = originalSize.height;
    document.getElementById('imageAlt').value = img.alt || '';
    document.getElementById('imageUrl').value = img.src || '';

    const modal = document.getElementById('imagePropertiesModal');
    modal.style.display = 'flex';
    requestAnimationFrame(() => modal.classList.add('modal-visible'));

    // 延迟清除标志，确保blur事件已经处理完毕
    setTimeout(() => {
        window.preventTitleBlur = false;
    }, 100);
}

function closeModalFunc() {
    // 设置标志，防止触发文章标题输入框的blur事件
    window.preventTitleBlur = true;

    const modal = document.getElementById('imagePropertiesModal');
    if (!modal) return;
    modal.classList.remove('modal-visible');
    setTimeout(() => {
        modal.style.display = 'none';
        document.getElementById('imageWidth').value = '';
        document.getElementById('imageHeight').value = '';
        document.getElementById('imageAlt').value = '';
        document.getElementById('imageUrl').value = '';
        document.getElementById('preserveAspectRatio').checked = true;
        selectedImage = null;
        clickedImage = null;

        // 延迟清除标志，确保blur事件已经处理完毕
        setTimeout(() => {
            window.preventTitleBlur = false;
        }, 100);
    }, 300);
}

function applyChangesFunc() {
    try {
        if (!selectedImage || !clickedImage) return;
        const img = clickedImage;
        const width = parseInt(document.getElementById('imageWidth').value);
        const height = parseInt(document.getElementById('imageHeight').value);
        const validWidth = Math.max(50, isNaN(width) ? originalSize.width : width);
        const validHeight = Math.max(50, isNaN(height) ? originalSize.height : height);

        if (document.getElementById('preserveAspectRatio').checked) {
            const aspectRatio = originalSize.width / originalSize.height;
            const finalWidth = validWidth;
            const finalHeight = Math.round(validWidth / aspectRatio);
            img.style.width = finalWidth + 'px';
            img.style.height = finalHeight + 'px';
            img.setAttribute('width', String(finalWidth));
            img.setAttribute('height', String(finalHeight));
        } else {
            img.style.width = validWidth + 'px';
            img.style.height = validHeight + 'px';
            img.setAttribute('width', String(validWidth));
            img.setAttribute('height', String(validHeight));
        }
        img.alt = document.getElementById('imageAlt').value.trim();
        img.src = document.getElementById('imageUrl').value.trim();

        const contentTextarea = document.getElementById('content');
        if (contentTextarea) {
            contentTextarea.value = quill.root.innerHTML;
            contentTextarea.dataset.skipAutoSave = 'true';
        }
        const range = quill.getSelection();
        if (range) quill.setSelection(range.index, range.length);
        window.preventArticleSuccessToast = true;
        showToast('图片属性已更新', 'info');
        closeModalFunc();
        setTimeout(() => {
            window.preventArticleSuccessToast = false;
            if (contentTextarea) delete contentTextarea.dataset.skipAutoSave;
        }, 500);
    } catch (error) {
        showToast('更新图片属性失败，请重试', 'error');
    }
}

// ========== 预览函数 ==========
function previewArticle() {
    const articleIdInput = document.getElementById('article_id');
    let articleId = articleIdInput ? articleIdInput.value : '';
    if (articleId && /^\d+$/.test(articleId)) {
        window.open('../post_id' + articleId + '.html', '_blank');
    } else {
        showToast('先发布文章再预览', 'warning');
    }
}

// ========== DOMContentLoaded 主初始化函数 ==========
document.addEventListener('DOMContentLoaded', function () {
    // HeaderPagination的初始化已移至admin.php
    // 这里不需要再调用init()和load()

    // 存储分类数据供JavaScript使用
    const categoriesData = window.categoriesData || [];

    const downloadRemoteCheckbox = document.getElementById('download_remote_images');
    if (downloadRemoteCheckbox) {
        const storageKey = 'qk_download_remote_images';
        try {
            const saved = localStorage.getItem(storageKey);
            if (saved !== null) {
                downloadRemoteCheckbox.checked = saved === '1';
            }
        } catch (e) { }
        downloadRemoteCheckbox.addEventListener('change', function () {
            try {
                localStorage.setItem(storageKey, downloadRemoteCheckbox.checked ? '1' : '0');
            } catch (e) { }
        });
    }



    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    const tbody = document.querySelector('.admin-table.section-manage tbody');


    // 初始化批量操作
    initBatchOperations();

    // 初始化自定义滚动条（仅在电脑端）
    if (!isMobile && typeof initCustomScrollbar === 'function') {
        initCustomScrollbar();
    }

    function getArticleCategoryIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        let categoryId = urlParams.get('category_id');

        if (!categoryId) {
            for (const key of urlParams.keys()) {
                const match = key.match(/^cid(\d+)$/);
                if (match) {
                    categoryId = match[1];
                    break;
                }
            }
        }

        return categoryId;
    }

    function getArticleReturnUrl() {
        const categorySelect = document.getElementById('category_id');
        let categoryId = categorySelect ? String(categorySelect.value || '').trim() : '';

        if (!/^\d+$/.test(categoryId) || categoryId === '0') {
            categoryId = getArticleCategoryIdFromUrl();
        }

        if (/^\d+$/.test(categoryId) && categoryId !== '0') {
            return `${window.location.origin}/admin/?tab=articles&category_id=${categoryId}`;
        }

        return `${window.location.origin}/admin/?tab=articles`;
    }

    function getArticleAddUrl(categoryId) {
        let addUrl = `${window.location.origin}/admin/?tab=articles&add`;
        if (/^\d+$/.test(String(categoryId || '')) && String(categoryId) !== '0') {
            addUrl += `&category_id=${String(categoryId)}`;
        }
        return addUrl;
    }

    function getSelectedCategoryInfo() {
        const categorySelect = document.getElementById('category_id');
        const categoryId = categorySelect ? String(categorySelect.value || '').trim() : '';
        let categoryName = '';
        if (categorySelect) {
            const opt = categorySelect.options && categorySelect.selectedIndex >= 0 ? categorySelect.options[categorySelect.selectedIndex] : null;
            categoryName = opt ? String(opt.text || '').trim() : '';
        }
        return { categoryId, categoryName };
    }

    function updateCancelButtonLabel() {
        const cancelButton = document.getElementById('cancel-button');
        if (!cancelButton) return;
        const info = getSelectedCategoryInfo();
        if (/^\d+$/.test(info.categoryId) && info.categoryId !== '0' && info.categoryName) {
            cancelButton.textContent = '返回' + info.categoryName;
        } else {
            cancelButton.textContent = '返回';
        }
    }

    // 处理添加文章按钮
    const showAddFormBtn = document.getElementById('show-add-form-btn');
    if (showAddFormBtn) {
        showAddFormBtn.addEventListener('click', function (e) {
            e.preventDefault();
            const categoryId = getArticleCategoryIdFromUrl();

            window.location.href = getArticleAddUrl(categoryId);
        });
    }

    // 处理编辑文章按钮
    document.addEventListener('click', function (e) {
        if (e.target.classList.contains('edit-article-btn')) {
            e.preventDefault();
            const articleId = e.target.getAttribute('data-id');
            window.location.href = `${window.location.origin}/admin/?tab=articles&edit_id${articleId}`;
        }

        if (e.target.classList.contains('delete-article-btn')) {
            const articleId = e.target.dataset.id;
            const xhr = new XMLHttpRequest();
            const url = '?tab=articles&delete_article=' + encodeURIComponent(articleId) + '&ajax=1';
            xhr.open('GET', url, true);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            showToast(response.message, response.success ? 'success' : 'error');
                            if (response.success) setTimeout(() => window.location.reload(), 1500);
                        } catch (e) {
                            showToast('删除失败，请重试', 'error');
                        }
                    } else {
                        showToast('删除文章失败，请重试！', 'error');
                    }
                }
            };
            xhr.onerror = function () {
                showToast('网络错误，请检查连接后重试！', 'error');
            };
            xhr.send();
        }
    });

    // 处理全选复选框
    document.addEventListener('change', function (event) {
        if (event.target.id === 'select-all-articles') {
            const isChecked = event.target.checked;
            document.querySelectorAll('.article-checkbox').forEach(checkbox => checkbox.checked = isChecked);
        } else if (event.target.classList.contains('article-checkbox')) {
            const selectAllCheckbox = document.getElementById('select-all-articles');
            if (selectAllCheckbox) {
                const allCheckboxes = document.querySelectorAll('.article-checkbox');
                selectAllCheckbox.checked = Array.from(allCheckboxes).every(checkbox => checkbox.checked);
            }
        }
    });

    function initArticleHeaderMenuScrollbar(menuId) {
        const menu = document.getElementById(menuId);
        if (!menu) return;
        if (!window.AdminScrollbar || typeof window.AdminScrollbar.initVerticalMenu !== 'function') return;
        window.AdminScrollbar.initVerticalMenu({
            menu: menu,
            contentSelector: '.counter-column-menu-content',
            trackSelector: '.counter-column-menu-vscroll',
            thumbSelector: '.counter-column-menu-vthumb',
            thumbHeight: 80,
            updateHookName: '_articleMenuScrollbarUpdate'
        });
    }

    function initArticleHeaderMenuScrollbars() {
        initArticleHeaderMenuScrollbar('category-dropdown-menu');
        initArticleHeaderMenuScrollbar('property-dropdown-menu');
        initArticleHeaderMenuScrollbar('template-dropdown-menu');
    }

    initArticleHeaderMenuScrollbars();

    function closeAllArticleMenus() {
        const menus = ['category-dropdown-menu', 'property-dropdown-menu', 'template-dropdown-menu'];
        menus.forEach(menuId => {
            const menu = document.getElementById(menuId);
            if (menu) {
                menu.style.display = 'none';
            }
        });
    }

    window.addEventListener('scroll', function() {
        closeAllArticleMenus();
    }, { passive: true });

    window.toggleCategoryMenu = function () {
        const categoryHeader = document.getElementById('category-header');
        const categoryDropdownMenu = document.getElementById('category-dropdown-menu');
        if (!categoryHeader || !categoryDropdownMenu) return;

        closeAllArticleMenus();

        const isOpen = categoryDropdownMenu.style.display === 'block';
        if (isOpen) {
            categoryDropdownMenu.style.display = 'none';
            return;
        }

        if (categoryDropdownMenu.parentElement !== document.body) {
            document.body.appendChild(categoryDropdownMenu);
        }

        const rect = categoryHeader.getBoundingClientRect();
        categoryDropdownMenu.style.position = 'fixed';
        categoryDropdownMenu.style.top = (rect.bottom - 23) + 'px';
        categoryDropdownMenu.style.left = rect.left + 'px';
        categoryDropdownMenu.style.zIndex = '2147483647';
        categoryDropdownMenu.style.display = 'block';
        if (typeof categoryDropdownMenu._articleMenuScrollbarUpdate === 'function') {
            window.requestAnimationFrame(categoryDropdownMenu._articleMenuScrollbarUpdate);
        }
    };

    window.togglePropertyMenu = function () {
        const propertyHeader = document.getElementById('property-header');
        const propertyDropdownMenu = document.getElementById('property-dropdown-menu');
        if (!propertyHeader || !propertyDropdownMenu) return;

        closeAllArticleMenus();

        const isOpen = propertyDropdownMenu.style.display === 'block';
        if (isOpen) {
            propertyDropdownMenu.style.display = 'none';
            return;
        }

        if (propertyDropdownMenu.parentElement !== document.body) {
            document.body.appendChild(propertyDropdownMenu);
        }

        const rect = propertyHeader.getBoundingClientRect();
        propertyDropdownMenu.style.position = 'fixed';
        propertyDropdownMenu.style.top = (rect.bottom - 23) + 'px';
        propertyDropdownMenu.style.left = rect.left + 'px';
        propertyDropdownMenu.style.zIndex = '2147483647';
        propertyDropdownMenu.style.display = 'block';
        if (typeof propertyDropdownMenu._articleMenuScrollbarUpdate === 'function') {
            window.requestAnimationFrame(propertyDropdownMenu._articleMenuScrollbarUpdate);
        }
    };

    // 当前筛选状态
    let currentFilter = {
        category_id: 0,
        property_id: 0,
        template: ''
    };

    window.filterCategory = function (categoryId) {
        const categoryDropdownMenu = document.getElementById('category-dropdown-menu');
        if (categoryDropdownMenu) categoryDropdownMenu.style.display = 'none';

        currentFilter.category_id = categoryId;

        let categoryName = '所有分类';
        if (categoryId > 0) {
            const categoryItem = document.querySelector(`[data-category-id="${categoryId}"]`);
            if (categoryItem) categoryName = categoryItem.textContent;
        }

        let url = `/admin/ajaxx.php?action=get_articles&page=1&page_size=15&category_id=${categoryId}`;
        if (currentFilter.property_id > 0) {
            url += `&property_id=${currentFilter.property_id}`;
        }
        if (currentFilter.template) {
            url += `&template=${encodeURIComponent(currentFilter.template)}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderArticlesList(data.data);
                    showToast(`已筛选 ${categoryName} 分类的文章`, 'info', 2000);
                } else {
                    showToast('获取文章列表失败: ' + (data.message || '未知错误'), 'error');
                }
            })
            .catch(() => {
                showToast('网络错误，请检查连接后重试！', 'error');
            });
    };

    window.filterProperty = function (propertyId) {
        const propertyDropdownMenu = document.getElementById('property-dropdown-menu');
        if (propertyDropdownMenu) propertyDropdownMenu.style.display = 'none';

        currentFilter.property_id = propertyId;

        let propertyName = '所有属性';
        if (propertyId > 0) {
            const propertyItem = document.querySelector(`[data-property-id="${propertyId}"]`);
            if (propertyItem) propertyName = propertyItem.textContent;
        }

        let url = `/admin/ajaxx.php?action=get_articles&page=1&page_size=15&property_id=${propertyId}`;
        if (currentFilter.category_id > 0) {
            url += `&category_id=${currentFilter.category_id}`;
        }
        if (currentFilter.template) {
            url += `&template=${encodeURIComponent(currentFilter.template)}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderArticlesList(data.data);
                    showToast(`已筛选 ${propertyName} 属性的文章`, 'info', 2000);
                } else {
                    showToast('获取文章列表失败: ' + (data.message || '未知错误'), 'error');
                }
            })
            .catch(() => {
                showToast('网络错误，请检查连接后重试！', 'error');
            });
    };

    window.toggleTemplateMenu = function () {
        const templateHeader = document.getElementById('template-header');
        const templateDropdownMenu = document.getElementById('template-dropdown-menu');
        if (!templateHeader || !templateDropdownMenu) return;

        closeAllArticleMenus();

        const isOpen = templateDropdownMenu.style.display === 'block';
        if (isOpen) {
            templateDropdownMenu.style.display = 'none';
            return;
        }

        if (templateDropdownMenu.parentElement !== document.body) {
            document.body.appendChild(templateDropdownMenu);
        }

        const rect = templateHeader.getBoundingClientRect();
        templateDropdownMenu.style.position = 'fixed';
        templateDropdownMenu.style.top = (rect.bottom - 23) + 'px';
        templateDropdownMenu.style.left = rect.left + 'px';
        templateDropdownMenu.style.zIndex = '2147483647';
        templateDropdownMenu.style.display = 'block';
        if (typeof templateDropdownMenu._articleMenuScrollbarUpdate === 'function') {
            window.requestAnimationFrame(templateDropdownMenu._articleMenuScrollbarUpdate);
        }
    };

    window.filterTemplate = function (templatePath) {
        const templateDropdownMenu = document.getElementById('template-dropdown-menu');
        if (templateDropdownMenu) templateDropdownMenu.style.display = 'none';

        currentFilter.template = templatePath ? String(templatePath) : '';

        let templateName = '所有模板';
        if (currentFilter.template) {
            const templateItem = Array.from(document.querySelectorAll('[data-template]')).find(el => el.dataset.template === currentFilter.template);
            if (templateItem) templateName = templateItem.textContent;
        }

        let url = `/admin/ajaxx.php?action=get_articles&page=1&page_size=15`;
        if (currentFilter.category_id > 0) url += `&category_id=${currentFilter.category_id}`;
        if (currentFilter.property_id > 0) url += `&property_id=${currentFilter.property_id}`;
        if (currentFilter.template) url += `&template=${encodeURIComponent(currentFilter.template)}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderArticlesList(data.data);
                    showToast(`已筛选 ${templateName} 的文章`, 'info', 2000);
                } else {
                    showToast('获取文章列表失败: ' + (data.message || '未知错误'), 'error');
                }
            })
            .catch(() => {
                showToast('网络错误，请检查连接后重试！', 'error');
            });
    };

    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', function (e) {
        const categoryHeader = document.getElementById('category-header');
        const categoryDropdownMenu = document.getElementById('category-dropdown-menu');
        if (categoryHeader && categoryDropdownMenu) {
            if (!categoryHeader.contains(e.target) && !categoryDropdownMenu.contains(e.target)) {
                categoryDropdownMenu.style.display = 'none';
            }
        }

        const propertyHeader = document.getElementById('property-header');
        const propertyDropdownMenu = document.getElementById('property-dropdown-menu');
        if (propertyHeader && propertyDropdownMenu) {
            if (!propertyHeader.contains(e.target) && !propertyDropdownMenu.contains(e.target)) {
                propertyDropdownMenu.style.display = 'none';
            }
        }

        const templateHeader = document.getElementById('template-header');
        const templateDropdownMenu = document.getElementById('template-dropdown-menu');
        if (templateHeader && templateDropdownMenu) {
            if (!templateHeader.contains(e.target) && !templateDropdownMenu.contains(e.target)) {
                templateDropdownMenu.style.display = 'none';
            }
        }
    });



    // 功能类型选择处理
    const functionTypeSelect = document.getElementById('function_type');
    const toolUrlContainer = document.getElementById('tool-url-container');
    const redirectUrlContainer = document.getElementById('redirect-url-container');
    const statusSwitchContainer = document.getElementById('status-switch-container');
    const priceContainer = document.getElementById('price-container');
    const customField1Container = document.getElementById('custom-field-1-container');
    const customField2Container = document.getElementById('custom-field-2-container');
    const customField3Container = document.getElementById('custom-field-3-container');
    const customField1Label = customField1Container ? customField1Container.querySelector('label') : null;
    const customField2Label = customField2Container ? customField2Container.querySelector('label') : null;
    const customField3Label = customField3Container ? customField3Container.querySelector('label') : null;
    const customField1Input = document.getElementById('custom_field_1');
    const customField2Input = document.getElementById('custom_field_2');
    const customField3Input = document.getElementById('custom_field_3');
    const toolUrlInput = document.getElementById('tool_url');
    const templateSelect = document.getElementById('template');
    const templateCustomFieldMetaMap = window.templateCustomFieldMetaMap || {};
    const isEditMode = window.isEditMode || false;
    let functionTypeTouched = false;

    if (!isEditMode) {
        const savedType = localStorage.getItem('function_type') || 'tool';
        if (functionTypeSelect) functionTypeSelect.value = savedType;
    }

    function trySetTemplateToToolResource() {
        if (!templateSelect) return;

        const candidates = ['skin/post5.php', 'post5.php'];
        let target = '';
        for (let i = 0; i < candidates.length; i++) {
            const v = candidates[i];
            const exists = Array.from(templateSelect.options || []).some(opt => String(opt.value) === v);
            if (exists) {
                target = v;
                break;
            }
        }
        if (!target) return;

        const cur = String(templateSelect.value || '');
        if (cur === target) return;

        templateSelect.value = target;
        try {
            templateSelect.dispatchEvent(new Event('change', { bubbles: true }));
        } catch (e) { }
    }

    function resetCustomFieldMeta() {
        const fields = [
            { label: customField1Label, input: customField1Input, index: 1 },
            { label: customField2Label, input: customField2Input, index: 2 },
            { label: customField3Label, input: customField3Input, index: 3 }
        ];
        fields.forEach(function (field) {
            const defaultLabel = field.label ? (field.label.getAttribute('data-default-label') || ('自定义字段' + field.index)) : ('自定义字段' + field.index);
            if (field.label) field.label.textContent = defaultLabel;
            if (field.input) field.input.placeholder = field.input.getAttribute('data-default-placeholder') || defaultLabel;
        });
    }

    function applyCustomFieldMeta() {
        resetCustomFieldMeta();
        if (!templateSelect) return;
        const currentTemplate = String(templateSelect.value || '').replace(/\\/g, '/');
        const templateBaseName = currentTemplate ? currentTemplate.split('/').pop() : '';
        const lookupKeys = [currentTemplate];
        if (templateBaseName) {
            lookupKeys.push(templateBaseName);
            lookupKeys.push('skin/' + templateBaseName);
        }
        const meta = lookupKeys.reduce(function (found, key) {
            if (found || !key) return found;
            return templateCustomFieldMetaMap[key] || null;
        }, null);
        if (!meta) return;
        const fields = [
            { key: 'custom_field_1', label: customField1Label, input: customField1Input },
            { key: 'custom_field_2', label: customField2Label, input: customField2Input },
            { key: 'custom_field_3', label: customField3Label, input: customField3Input }
        ];
        fields.forEach(function (field) {
            const text = typeof meta[field.key] === 'string' ? meta[field.key].trim() : '';
            if (!text) return;
            if (field.label) field.label.textContent = text;
        });
    }

    function updateFields(allowAutoTemplate) {
        if (!functionTypeSelect) return;
        const selectedType = functionTypeSelect.value;

        if (selectedType === 'tool') {
            resetCustomFieldMeta();
            toolUrlContainer.style.display = 'block';
            toolUrlContainer.querySelector('label').textContent = '操作区工具文件URL';
            toolUrlInput.placeholder = '';
            redirectUrlContainer.style.display = 'none';
            statusSwitchContainer.style.display = 'block';
            priceContainer.style.display = 'block';
            customField1Container.style.display = 'none';
            customField2Container.style.display = 'none';
            customField3Container.style.display = 'none';
            if (allowAutoTemplate === true) trySetTemplateToToolResource();
        } else if (selectedType === 'resource') {
            resetCustomFieldMeta();
            toolUrlContainer.style.display = 'block';
            toolUrlContainer.querySelector('label').textContent = '操作区资源文件URL';
            toolUrlInput.placeholder = '';
            redirectUrlContainer.style.display = 'block';
            statusSwitchContainer.style.display = 'none';
            priceContainer.style.display = 'block';
            customField1Container.style.display = 'none';
            customField2Container.style.display = 'none';
            customField3Container.style.display = 'none';
            document.getElementById('status_switch').value = '1';
            if (allowAutoTemplate === true) trySetTemplateToToolResource();
        } else if (selectedType === 'custom') {
            toolUrlContainer.style.display = 'none';
            redirectUrlContainer.style.display = 'none';
            statusSwitchContainer.style.display = 'none';
            priceContainer.style.display = 'none';
            customField1Container.style.display = 'block';
            customField2Container.style.display = 'block';
            customField3Container.style.display = 'block';
            applyCustomFieldMeta();
        }

        if (!isEditMode) localStorage.setItem('function_type', selectedType);
    }

    updateFields(false);
    if (functionTypeSelect) {
        functionTypeSelect.addEventListener('change', function () {
            functionTypeTouched = true;
            updateFields(true);
        });
        functionTypeSelect.addEventListener('mousedown', function () {
            functionTypeTouched = true;
        });
        functionTypeSelect.addEventListener('touchstart', function () {
            functionTypeTouched = true;
        }, { passive: true });
    }
    if (templateSelect) {
        templateSelect.addEventListener('change', function () {
            if (functionTypeSelect && functionTypeSelect.value === 'custom') {
                applyCustomFieldMeta();
            }
        });
    }

    // 表单提交验证
    const articleForm = document.querySelector('form[name="article-form"]');
    if (articleForm) {
        articleForm.addEventListener('submit', function (e) {
            const submitBtn = document.getElementById('submit-button');
            if (submitBtn) {
                submitBtn.dataset.originalText = submitBtn.textContent;
            }

            if (window.isCodeModeGlobal) {
                const codeButton = document.querySelector('.ql-code-button');
                if (codeButton) codeButton.click();
            }
            window.isCodeModeGlobal = false;

            const descriptionTextarea = document.getElementById('description');
            const contentTextarea = document.getElementById('content');

            if (window.quill) {
                let content = window.quill.root.innerHTML;
                content = content.replace(/<div[^>]*class=["'].*ql-code-block-container.*["'][^>]*>([\s\S]*?)<\/div>/gi, function (match, code) {
                    const tempContainer = document.createElement('div');
                    tempContainer.innerHTML = match;
                    let codeContent = tempContainer.textContent.trim();
                    return '[qkcms:code]\n' + codeContent + '\n[/qkcms:code]';
                });
                content = content.replace(/<pre[^>]*class=["'].*ql-code-block.*["'][^>]*>([\s\S]*?)<\/pre>/gi, function (match, code) {
                    let cleanCode = code.replace(/<[^>]+>/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&').trim();
                    return '[qkcms:code]\n' + cleanCode + '\n[/qkcms:code]';
                });
                content = content.replace(/<div[^>]*class=["'].*ql-code-block.*["'][^>]*>([\s\S]*?)<\/div>/gi, function (match, code) {
                    let cleanCode = code.replace(/<[^>]+>/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&').trim();
                    return '[qkcms:code]\n' + cleanCode + '\n[/qkcms:code]';
                });
                content = content.replace(/\/uploads\/Temp\//g, '/uploads/');
                contentTextarea.value = content;
            }

            if (descriptionTextarea && descriptionTextarea.value.trim() === '' && contentTextarea && contentTextarea.value.trim() !== '') {
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = contentTextarea.value;
                let plainText = tempDiv.textContent || tempDiv.innerText || '';
                plainText = plainText.replace(/\[qkcms:buy——\d+个积分\]/g, '').replace(/\[\/qkcms:buy\]/g, '');
                const autoDescription = plainText.trim().substring(0, 100);
                descriptionTextarea.value = autoDescription + (plainText.length > 100 ? '...' : '');
            }

            const titleInput = document.querySelector('input[name="title"]');
            if (titleInput && !titleInput.value.trim()) {
                e.preventDefault();
                showToast('请输入文章标题', 'error');
                titleInput.focus();
                return;
            }
            if (contentTextarea && !contentTextarea.value.trim()) {
                e.preventDefault();
                showToast('请输入文章内容', 'error');
                return;
            }
            if (titleInput && titleInput.value.length > 200) {
                e.preventDefault();
                showToast('文章标题不能超过200个字符', 'error');
                titleInput.focus();
                return;
            }
        });
    }

    // 预览按钮
    const previewButton = document.getElementById('preview-button');
    if (previewButton) previewButton.addEventListener('click', previewArticle);

    const cancelButton = document.getElementById('cancel-button');
    if (cancelButton) {
        updateCancelButtonLabel();
        const categorySelect = document.getElementById('category_id');
        if (categorySelect) {
            categorySelect.addEventListener('change', updateCancelButtonLabel);
        }
        cancelButton.addEventListener('click', function () {
            window.location.href = getArticleReturnUrl();
        });
    }

    const continuePublishButton = document.getElementById('continue-publish-button');
    if (continuePublishButton) {
        continuePublishButton.addEventListener('click', function () {
            let categoryId = '';
            const info = getSelectedCategoryInfo();
            categoryId = info.categoryId;

            if (!/^\d+$/.test(categoryId) || categoryId === '0') {
                categoryId = getArticleCategoryIdFromUrl();
            }

            window.location.href = getArticleAddUrl(categoryId);
        });
    }

    // 初始化随机浏览量
    const formModeInput = document.getElementById('form_mode');
    const articleIdInput = document.getElementById('article_id');
    const viewCountInput = document.getElementById('views');
    let articleId = articleIdInput ? articleIdInput.value : '';
    if (articleId && !/^\d+$/.test(articleId)) articleId = '';
    if (formModeInput && formModeInput.value === 'add' && !articleId && viewCountInput && viewCountInput.value.trim() === '') {
        viewCountInput.value = Math.floor(Math.random() * 1501) + 500;
    }

    // 绑定缩略图相关事件
    bindDeleteThumbnailEvents();
    bindThumbnailUploadBtn();
    bindThumbnailUrlInput();
    initAutoCropThumbnailPreference();

    // 初始化Quill编辑器
    if (typeof Quill !== 'undefined' && Quill.imports) {
        const Block = Quill.import('blots/block');
        class VideoBlot extends Block {
            static create(value) {
                const node = super.create();
                node.setAttribute('controls', '');
                if (typeof value === 'object' && value !== null) {
                    node.setAttribute('width', value.width || '790');
                    node.setAttribute('height', value.height || '550');
                    if (value.autoplay) node.setAttribute('autoplay', '');
                    const src = typeof value.src === 'string' ? value.src : String(value.src);
                    if (src && src !== 'true' && src !== 'false' && src !== 'null') node.setAttribute('src', src);
                } else if (typeof value === 'string') {
                    node.setAttribute('width', '790');
                    node.setAttribute('height', '550');
                    node.setAttribute('src', value);
                }
                return node;
            }
            static value(node) {
                return {
                    src: node.getAttribute('src'),
                    width: node.getAttribute('width'),
                    height: node.getAttribute('height'),
                    autoplay: node.hasAttribute('autoplay')
                };
            }
            format(name, value) {
                if (name === 'src' && value) this.domNode.setAttribute('src', value);
                else if (name === 'width' && value) this.domNode.setAttribute('width', value);
                else if (name === 'height' && value) this.domNode.setAttribute('height', value);
                else if (name === 'autoplay') value ? this.domNode.setAttribute('autoplay', '') : this.domNode.removeAttribute('autoplay');
                else super.format(name, value);
            }
        }
        VideoBlot.blotName = 'video';
        VideoBlot.tagName = 'video';
        Quill.register(VideoBlot);

        // 添加自定义CSS来增大代码块图标大小和调整间距
        const style = document.createElement('style');
        style.textContent = `
                    .ql-toolbar .ql-code-block {
                        font-size: 18px;
                        width: 40px;
                        height: 40px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin: 0 2px;
                    }
                    .ql-toolbar .ql-code-block::before {
                        font-size: 20px;
                    }
                `;
        document.head.appendChild(style);

        // 创建Quill编辑器
        const quill = new Quill('#quill-editor', {
            theme: 'snow',
            placeholder: '请输入文章内容...',
            modules: {
                toolbar: [
                    [{
                        'header': [1, 2, 3, 4, 5, 6, false]
                    }],
                    [{
                        'font': []
                    }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{
                        'color': []
                    }, {
                        'background': []
                    }],
                    [{
                        'align': []
                    }],
                    [{
                        'list': 'ordered'
                    }, {
                        'list': 'bullet'
                    }],
                    ['blockquote'],
                    ['code-block'],
                    ['link', 'image', 'video'],
                    ['clean'],
                    [{
                        'custom': 'buy'
                    }, {
                        'custom': 'code'
                    }, {
                        'custom': 'ai'
                    }]
                ]
            }
        });

        window.quill = quill;
        const contentTextarea = document.getElementById('content');
        if (contentTextarea.value) quill.root.innerHTML = contentTextarea.value;

        // 跟踪用户点击的图片或视频
        let clickedElement = null;
        let clickedElementIndex = null;

        quill.root.addEventListener('click', function (e) {
            const target = e.target;
            if (target.tagName === 'IMG') {
                clickedElement = target;
                const selection = quill.getSelection();
                clickedElementIndex = selection ? selection.index : findElementIndex(target);
            } else if (target.tagName === 'VIDEO' || (target.classList && target.classList.contains('video-container'))) {
                clickedElement = target;
                const selection = quill.getSelection();
                clickedElementIndex = selection ? selection.index : findElementIndex(target);
                e.preventDefault();
            } else {
                clickedElement = null;
                clickedElementIndex = null;
            }
        });

        // 图片上传处理器
        const toolbar = quill.getModule('toolbar');
        if (toolbar && toolbar.addHandler) {
            let imgMenu = null;
            let imgMenuStyleInjected = false;
            function injectImgMenuStyle() {
                if (imgMenuStyleInjected) return;
                imgMenuStyleInjected = true;
                const st = document.createElement('style');
                st.textContent = `.qk-imgmenu{position:fixed;z-index:10050;min-width:200px;background:#fff;border:1px solid #e5e7eb;box-shadow:0 8px 20px rgba(0,0,0,.08);border-radius:8px;overflow:hidden}.qk-imgmenu .item{display:flex;align-items:center;gap:10px;padding:10px 12px;cursor:pointer;font-size:14px;color:#111827}.qk-imgmenu .item:hover{background:#f3f4f6}.qk-imgmenu .sep{height:1px;background:#f0f0f0;margin:4px 0}`;
                document.head.appendChild(st);
            }
            function closeImgMenu() {
                if (imgMenu) imgMenu.remove();
                imgMenu = null;
                document.removeEventListener('mousedown', outsideHandler, true);
                window.removeEventListener('resize', closeImgMenu, true);
                window.removeEventListener('scroll', closeImgMenu, true);
            }
            function outsideHandler(e){ if (!imgMenu || e.target.closest('.qk-imgmenu')) return; closeImgMenu(); }
            function handleLocalUpload() {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                input.multiple = true;
                input.click();
                input.onchange = function () {
                    const files = input.files;
                    if (!files || files.length === 0) return;
                    function uploadOne(file) {
                        const formData = new FormData();
                        formData.append('file', file);
                        formData.append('action', 'upload_image');
                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', 'ajaxx.php', true);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                try {
                                    const res = JSON.parse(xhr.responseText);
                                    if (res.success && res.data && res.data.url) {
                                        const url = res.data.url;
                                        setTimeout(() => {
                                            quill.focus();
                                            const range = quill.getSelection(true);
                                            const isCodeMode = window.isCodeModeGlobal || false;
                                            if (isCodeMode) {
                                                const imgHtml = `<img src="${url}" alt="图片">`;
                                                const currentContent = quill.getText();
                                                const pos = range && range.index !== undefined ? range.index : currentContent.length;
                                                const newContent = currentContent.slice(0, pos) + imgHtml + currentContent.slice(pos);
                                                quill.setText('');
                                                quill.setText(newContent);
                                                const ct = document.getElementById('content');
                                                if (ct) ct.value = newContent;
                                            } else if (range && range.index !== undefined) {
                                                try { quill.insertEmbed(range.index, 'image', url); }
                                                catch { quill.clipboard.dangerouslyPasteHTML(range.index, `<img src="${url}" alt="图片">`); }
                                            } else {
                                                quill.root.innerHTML = `<img src="${url}" alt="图片">` + quill.root.innerHTML;
                                            }
                                            showToast('图片上传成功', 'success');
                                        }, 50);
                                    } else showToast(res.message || '图片上传失败', 'error');
                                } catch { showToast('图片上传失败', 'error'); }
                            }
                        };
                        xhr.onerror = function () { showToast('网络错误，请重试', 'error'); };
                        xhr.send(formData);
                    }
                    for (let i = 0; i < files.length; i++) uploadOne(files[i]);
                };
            }
            window.closeImageUrlInsertModal = function () {
                const modal = document.getElementById('imageUrlInsertModal');
                if (!modal) return;
                if (modal._closeOnBackdropMouseDown) {
                    modal.removeEventListener('mousedown', modal._closeOnBackdropMouseDown);
                    modal._closeOnBackdropMouseDown = null;
                }
                if (modal._closeOnBackdropMouseUp) {
                    modal.removeEventListener('mouseup', modal._closeOnBackdropMouseUp);
                    modal._closeOnBackdropMouseUp = null;
                }
                modal._backdropPressStarted = false;
                modal.classList.remove('modal-visible');
                setTimeout(()=>{ modal.style.display='none'; },200);
            };
            function insertImageUrl(url) {
                const imgHtml = `<img src="${url}" alt="图片">`;
                quill.focus();
                const range = quill.getSelection(true);
                const isCodeMode = window.isCodeModeGlobal || false;
                if (isCodeMode) {
                    const currentContent = quill.getText();
                    const pos = range && range.index !== undefined ? range.index : currentContent.length;
                    const newContent = currentContent.slice(0, pos) + imgHtml + currentContent.slice(pos);
                    quill.setText('');
                    quill.setText(newContent);
                    const ct = document.getElementById('content');
                    if (ct) ct.value = newContent;
                    return;
                }
                if (range && range.index !== undefined) {
                    try { quill.insertEmbed(range.index, 'image', url); }
                    catch { quill.clipboard.dangerouslyPasteHTML(range.index, imgHtml); }
                } else {
                    quill.root.innerHTML = imgHtml + quill.root.innerHTML;
                }
            }
            function openImageUrlModal() {
                const modal = document.getElementById('imageUrlInsertModal');
                const input = document.getElementById('cloudImageUrlInput');
                const cancelBtn = document.getElementById('cloudImageUrlCancelBtn');
                const confirmBtn = document.getElementById('cloudImageUrlConfirmBtn');
                if (!modal || !input || !cancelBtn || !confirmBtn) {
                    const url = prompt('请输入图片URL', '');
                    if (url) insertImageUrl(url);
                    return;
                }
                if (typeof window.addModalStyles === 'function') window.addModalStyles();
                input.value = '';
                modal.style.display = 'flex';
                setTimeout(()=>modal.classList.add('modal-visible'),10);
                setTimeout(()=>input.focus(),50);
                modal._backdropPressStarted = false;
                if (modal._closeOnBackdropMouseDown) modal.removeEventListener('mousedown', modal._closeOnBackdropMouseDown);
                if (modal._closeOnBackdropMouseUp) modal.removeEventListener('mouseup', modal._closeOnBackdropMouseUp);
                modal._closeOnBackdropMouseDown = function (e) {
                    modal._backdropPressStarted = (e.target === modal || e.target.classList.contains('modal-backdrop'));
                };
                modal._closeOnBackdropMouseUp = function (e) {
                    const isBackdrop = (e.target === modal || e.target.classList.contains('modal-backdrop'));
                    if (modal._backdropPressStarted && isBackdrop) {
                        window.closeImageUrlInsertModal();
                    }
                    modal._backdropPressStarted = false;
                };
                modal.addEventListener('mousedown', modal._closeOnBackdropMouseDown);
                modal.addEventListener('mouseup', modal._closeOnBackdropMouseUp);
                cancelBtn.onclick = ()=> window.closeImageUrlInsertModal();
                confirmBtn.onclick = ()=> { const u = input.value.trim(); if (!u) { showToast('请输入图片URL','warning'); input.focus(); return; } window.closeImageUrlInsertModal(); insertImageUrl(u); };
                input.onkeydown = (e)=>{ if (e.key === 'Enter') { e.preventDefault(); confirmBtn.click(); } };
            }
            function openAiImage() {
                if (typeof window.qkOpenCommonToolPlugin === 'function') {
                    window.qkOpenCommonToolPlugin('46_aiimage', 'AI生图', '工具');
                    return;
                }
                const modal = document.getElementById('aiPluginModal');
                const contentContainer = document.getElementById('ai-plugin-content');
                if (!modal || !contentContainer) return;
                if (typeof window.addModalStyles === 'function') window.addModalStyles();
                const titleEl = modal.querySelector('.modal-title');
                if (titleEl) titleEl.textContent = 'AI生图';
                contentContainer.innerHTML = '<div style="text-align:center;padding:50px 0"><div style="display:inline-block;width:40px;height:40px;border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;animation:spin 1s linear infinite"></div><p style="margin-top:20px;color:#666">加载中...</p><style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style></div>';
                modal.style.display = 'flex';
                setTimeout(()=>modal.classList.add('modal-visible'),10);
                fetch('/admin/Plugin.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=load_plugin_by_id&plugin_id=46'
                }).then(r=>r.json()).then(data=>{
                    if (data && data.success) {
                        contentContainer.innerHTML = data.html;
                        contentContainer.querySelectorAll('script').forEach(script=>{
                            const ns = document.createElement('script');
                            ns.textContent = script.textContent;
                            document.head.appendChild(ns);
                            script.remove();
                        });
                        if (typeof window.onload === 'function') window.onload();
                    } else contentContainer.innerHTML = '<div style="color:red;text-align:center;padding:20px">加载失败</div>';
                }).catch(()=>{ contentContainer.innerHTML = '<div style="color:red;text-align:center;padding:20px">网络错误</div>'; });
            }
            function openImageMenu() {
                injectImgMenuStyle();
                closeImgMenu();
                imgMenu = document.createElement('div');
                imgMenu.className = 'qk-imgmenu';
                imgMenu.innerHTML = `
                    <div class="item" data-act="local">上传本地图片</div>
                    <div class="item" data-act="url">URL云端图片</div>
                    ${window.aiImagePluginExists ? '<div class="sep"></div><div class="item" data-act="ai">AI生图功能</div>' : ''}
                `;
                document.body.appendChild(imgMenu);
                const btn = document.querySelector('.ql-toolbar button.ql-image');
                const r = btn ? btn.getBoundingClientRect() : {left:20, bottom:80};
                const mr = imgMenu.getBoundingClientRect();
                const top = Math.min(r.bottom + 6, window.innerHeight - mr.height - 8);
                const left = Math.min(r.left, window.innerWidth - mr.width - 8);
                imgMenu.style.top = top + 'px';
                imgMenu.style.left = left + 'px';
                imgMenu.addEventListener('click', function (e) {
                    const item = e.target.closest('.item');
                    if (!item) return;
                    const act = item.getAttribute('data-act');
                    closeImgMenu();
                    if (act === 'local') handleLocalUpload();
                    else if (act === 'url') openImageUrlModal();
                    else if (act === 'ai') openAiImage();
                });
                setTimeout(()=>document.addEventListener('mousedown', outsideHandler, true),0);
                window.addEventListener('resize', closeImgMenu, true);
                window.addEventListener('scroll', closeImgMenu, true);
            }
            toolbar.addHandler('image', function () {
                openImageMenu();
            });

            // 视频按钮处理器 - 调用视频属性模态弹窗
            toolbar.addHandler('video', function () {
                // 调用现有的视频插入模态弹窗函数
                window.openVideoInsertModal(null, null);
            });

            // 代码块按钮处理器 - 插入自定义代码块标记
            toolbar.addHandler('code-block', function () {
                const selection = quill.getSelection();
                const index = selection ? selection.index : 0;
                const codeBlockStart = '[qkcms:code]';
                const codeBlockEnd = '[/qkcms:code]';
                quill.insertText(index, codeBlockStart);
                quill.insertText(index + codeBlockStart.length, '\n// 在此输入代码\n');
                quill.insertText(index + codeBlockStart.length + '\n// 在此输入代码\n'.length, codeBlockEnd);
                quill.setSelection(index + codeBlockStart.length + 1, 0);
                document.getElementById('content').value = quill.root.innerHTML;
                showToast('已插入代码块标记', 'success');
            });
        }

        // 自定义按钮处理
        const customButtons = document.querySelectorAll('.ql-custom');
        let savedSelection = null;

        if (customButtons.length > 0) {
            const buyButton = customButtons[0];
            buyButton.title = '付费';
            buyButton.style.display = 'inline-block';
            buyButton.style.verticalAlign = 'middle';
            buyButton.style.position = 'relative';
            buyButton.style.pointerEvents = 'auto';
            buyButton.style.cursor = 'pointer';

            const clickContainer = document.createElement('span');
            clickContainer.style.pointerEvents = 'auto';
            clickContainer.style.display = 'inline-block';
            clickContainer.style.cursor = 'pointer';
            clickContainer.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:18px; height:18px; margin-right:4px; vertical-align:middle;"><path d="M7 18C7 19.1 7.9 20 9 20C10.1 20 11 19.1 11 18C11 16.9 10.1 16 9 16C7.9 16 7 16.9 7 18ZM1 2V4H3L6.6 11.59L5.24 14.04C5.09 14.32 5 14.65 5 15A2 2 0 0 0 7 17H19V15H7.42A0.25 0.25 0 0 1 7.25 14.75C7.25 14.7 7.26 14.66 7.27 14.63L8.1 13H15.55C16.3 13 16.96 12.58 17.3 11.97L20.88 5.5C20.95 5.34 21 5.17 21 5A1 1 0 0 0 20 4H5.21L4.27 2H1ZM15 18C15 19.1 15.9 20 17 20C18.1 20 19 19.1 19 18C19 16.9 18.1 16 17 16C15.9 16 15 16.9 15 18Z" fill="#4B5563"/></svg> 付费';
            buyButton.innerHTML = '';
            buyButton.appendChild(clickContainer);

            const handleBuyButtonClick = function (e) {
                e.preventDefault();
                e.stopPropagation();
                savedSelection = quill.getSelection();

                if (clickedElement) {
                    const points = prompt('请输入此付费内容的积分：', '10');
                    if (points !== null) {
                        const videoContent = clickedElement.outerHTML;
                        const buyContent = `[qkcms:buy——${points}个积分]${videoContent}[/qkcms:buy]`;
                        const oldHtml = clickedElement.outerHTML;
                        const newHtml = quill.root.innerHTML.replace(oldHtml, buyContent);
                        quill.root.innerHTML = newHtml;
                        clickedElement = null;
                        clickedElementIndex = null;
                        setTimeout(() => {
                            const contentTextarea = document.getElementById('content');
                            if (contentTextarea) contentTextarea.value = quill.root.innerHTML;
                        }, 100);
                        showToast('已为视频添加付费标识', 'success');
                    }
                } else {
                    if (savedSelection) quill.setSelection(savedSelection.index, savedSelection.length);
                    const selection = quill.getSelection();
                    let wrapped = false;
                    const contentHtml = quill.root.innerHTML;
                    const hasBuyTag = contentHtml.includes('[qkcms:buy') && contentHtml.includes('[/qkcms:buy]');
                    if (hasBuyTag) {
                        showToast('一个文章只能插入一个付费标识', 'warning');
                        return;
                    }

                    if (selection && selection.length > 0) {
                        try {
                            const delta = quill.getContents(selection.index, selection.length);
                            const tempQuill = new Quill(document.createElement('div'));
                            tempQuill.setContents(delta);
                            const selectedHtml = tempQuill.root.innerHTML;
                            const points = prompt('请输入此付费内容的积分：', '10');
                            if (points !== null) {
                                const buyContent = `[qkcms:buy——${points}个积分]${selectedHtml}[/qkcms:buy]`;
                                quill.deleteText(selection.index, selection.length);
                                quill.clipboard.dangerouslyPasteHTML(selection.index, buyContent);
                                wrapped = true;
                            }
                        } catch (error) {
                            showToast('包装文本失败，请重试', 'error');
                        }
                    } else if (selection) {
                        let targetElement = clickedElement;
                        let content = '';
                        let elementIndex = clickedElementIndex !== null ? clickedElementIndex : selection.index;

                        if (!targetElement) {
                            const [block] = quill.getLeaf(selection.index);
                            if (block && block.domNode) {
                                if (block.domNode.tagName === 'IMG' || block.domNode.tagName === 'VIDEO' || (block.domNode.classList && block.domNode.classList.contains('video-container'))) {
                                    targetElement = block.domNode;
                                    content = targetElement.outerHTML;
                                } else {
                                    const img = block.domNode.querySelector('img');
                                    const video = block.domNode.querySelector('video');
                                    const videoContainer = block.domNode.querySelector('.video-container');
                                    if (img) {
                                        targetElement = img;
                                        content = img.outerHTML;
                                    } else if (video) {
                                        targetElement = video;
                                        content = video.outerHTML;
                                    } else if (videoContainer) {
                                        targetElement = videoContainer;
                                        content = videoContainer.outerHTML;
                                    }
                                }
                            }
                        } else {
                            content = targetElement.outerHTML;
                        }

                        if (targetElement && content) {
                            const points = prompt('请输入此付费内容的积分：', '10');
                            if (points !== null) {
                                const buyContent = `[qkcms:buy——${points}个积分]${content}[/qkcms:buy]`;
                                try {
                                    quill.deleteText(elementIndex, 1);
                                    quill.clipboard.dangerouslyPasteHTML(elementIndex, buyContent);
                                    wrapped = true;
                                    clickedElement = null;
                                    clickedElementIndex = null;
                                } catch (error) {
                                    try {
                                        const oldHtml = targetElement.outerHTML;
                                        const newHtml = quill.root.innerHTML.replace(oldHtml, buyContent);
                                        quill.root.innerHTML = newHtml;
                                        wrapped = true;
                                        clickedElement = null;
                                        clickedElementIndex = null;
                                    } catch (e2) {
                                        showToast('包装内容失败，请重试', 'error');
                                    }
                                }
                            }
                        }
                    }

                    if (!wrapped) {
                        const videos = quill.root.querySelectorAll('video, .video-container');
                        if (videos.length > 0) {
                            const videoElement = videos[0];
                            const videoContent = videoElement.outerHTML;
                            const points = prompt('请输入此付费内容的积分：', '10');
                            if (points !== null) {
                                const buyContent = `[qkcms:buy——${points}个积分]${videoContent}[/qkcms:buy]`;
                                try {
                                    const tempDiv = document.createElement('div');
                                    tempDiv.innerHTML = buyContent;
                                    const buyElement = tempDiv.firstChild;
                                    videoElement.parentNode.replaceChild(buyElement, videoElement);
                                    wrapped = true;
                                } catch (error) {
                                    showToast('包装视频失败，请重试', 'error');
                                }
                            }
                        }
                    }

                    if (wrapped) {
                        setTimeout(() => {
                            const contentTextarea = document.getElementById('content');
                            if (contentTextarea) contentTextarea.value = quill.root.innerHTML;
                        }, 100);
                        showToast('已为选中内容添加付费标识', 'success');
                    } else {
                        showToast('请先选中要隐藏的内容（文本、图片或视频）', 'warning');
                    }
                }
            };

            buyButton.addEventListener('click', handleBuyButtonClick);
            clickContainer.addEventListener('click', handleBuyButtonClick);
        }





        if (customButtons.length > 1) {
            const codeButton = customButtons[1];
            codeButton.title = '切换源代码/HTML';
            codeButton.className = 'ql-code-button';
            codeButton.style.display = 'inline-block';
            codeButton.style.verticalAlign = 'middle';
            codeButton.style.pointerEvents = 'auto';
            codeButton.style.cursor = 'pointer';
            codeButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="21 53 470 438" style="margin-right:4px; vertical-align:middle;"><path d="M405 53L299 160L299 395L405 299ZM21 160L21 473Q21 477 24.50 480Q28 483 32 483Q34 483 35 482.50Q36 482 37 482Q59 472 87 465.50Q115 459 139 459Q170 459 201.50 466Q233 473 256 491L256 160Q233 142 201.50 135Q170 128 139 128Q107 128 76 135Q45 142 21 160ZM491 471L491 448L491 160Q481 153 470.50 148Q460 143 448 139L448 427Q430 421 411.50 418.50Q393 416 373 416Q355 416 333.50 420Q312 424 291 431.50Q270 439 256 448L256 491Q270 482 291 474.50Q312 467 333.50 463Q355 459 373 459Q400 459 426 464Q452 469 475 481Q477 482 480 482Q484 482 487.50 478.50Q491 475 491 471Z" fill="#4B5563"/></svg> 富文本';

            let isCodeMode = false;
            codeButton.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();

                if (isCodeMode) {
                    let htmlContent = contentTextarea.value;
                    if (htmlContent && htmlContent.trim() !== '') {
                        try {
                            const tempDiv = document.createElement('div');
                            tempDiv.innerHTML = htmlContent;
                            const imgs = tempDiv.querySelectorAll('img');
                            imgs.forEach(img => {
                                const sw = img.style && img.style.width ? parseInt(img.style.width, 10) : 0;
                                const sh = img.style && img.style.height ? parseInt(img.style.height, 10) : 0;
                                if (sw && !img.getAttribute('width')) img.setAttribute('width', String(sw));
                                if (sh && !img.getAttribute('height')) img.setAttribute('height', String(sh));
                            });
                            htmlContent = tempDiv.innerHTML;
                        } catch (e) { }
                        htmlContent = htmlContent.replace(/src="\s*`([^`]+)`\s*"/g, 'src="$1"');
                        quill.setText('');
                        quill.clipboard.dangerouslyPasteHTML(0, htmlContent);
                        quill.updateContents({});
                        setTimeout(() => {
                            try {
                                const imgs = quill.root.querySelectorAll('img');
                                imgs.forEach(img => {
                                    const w = img.getAttribute('width');
                                    const h = img.getAttribute('height');
                                    if (w) img.style.width = parseInt(w, 10) + 'px';
                                    if (h) img.style.height = parseInt(h, 10) + 'px';
                                });
                            } catch (e) { }
                            const videos = quill.root.querySelectorAll('video');
                            const tempDiv = document.createElement('div');
                            tempDiv.innerHTML = htmlContent;
                            const originalVideos = tempDiv.querySelectorAll('video');
                            videos.forEach((video, index) => {
                                if (originalVideos[index]) {
                                    const originalVideo = originalVideos[index];
                                    const attributes = originalVideo.attributes;
                                    for (let i = 0; i < attributes.length; i++) {
                                        const attr = attributes[i];
                                        video.setAttribute(attr.name, attr.value);
                                    }
                                }
                            });
                            contentTextarea.value = quill.root.innerHTML;
                        }, 100);
                    }
                    codeButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="21 53 470 438" style="margin-right:4px; vertical-align:middle;"><path d="M405 53L299 160L299 395L405 299ZM21 160L21 473Q21 477 24.50 480Q28 483 32 483Q34 483 35 482.50Q36 482 37 482Q59 472 87 465.50Q115 459 139 459Q170 459 201.50 466Q233 473 256 491L256 160Q233 142 201.50 135Q170 128 139 128Q107 128 76 135Q45 142 21 160ZM491 471L491 448L491 160Q481 153 470.50 148Q460 143 448 139L448 427Q430 421 411.50 418.50Q393 416 373 416Q355 416 333.50 420Q312 424 291 431.50Q270 439 256 448L256 491Q270 482 291 474.50Q312 467 333.50 463Q355 459 373 459Q400 459 426 464Q452 469 475 481Q477 482 480 482Q484 482 487.50 478.50Q491 475 491 471Z" fill="#4B5563"/></svg> 富文本';
                    showToast('已切换到富文本模式', 'success');
                } else {
                    let htmlContent = quill.root.innerHTML;
                    contentTextarea.value = htmlContent;
                    quill.setText('');
                    if (htmlContent.trim() !== '') quill.setText(htmlContent);
                    codeButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="21 53 470 438" style="margin-right:4px; vertical-align:middle;"><path d="M405 53L299 160L299 395L405 299ZM21 160L21 473Q21 477 24.50 480Q28 483 32 483Q34 483 35 482.50Q36 482 37 482Q59 472 87 465.50Q115 459 139 459Q170 459 201.50 466Q233 473 256 491L256 160Q233 142 201.50 135Q170 128 139 128Q107 128 76 135Q45 142 21 160ZM491 471L491 448L491 160Q481 153 470.50 148Q460 143 448 139L448 427Q430 421 411.50 418.50Q393 416 373 416Q355 416 333.50 420Q312 424 291 431.50Q270 439 256 448L256 491Q270 482 291 474.50Q312 467 333.50 463Q355 459 373 459Q400 459 426 464Q452 469 475 481Q477 482 480 482Q484 482 487.50 478.50Q491 475 491 471Z" fill="#4B5563"/></svg> 源代码';
                    showToast('已切换到代码模式', 'success');
                }
                isCodeMode = !isCodeMode;
                window.isCodeModeGlobal = isCodeMode;
            });
        }

        if (window.deepseekPluginSwitch) {
            if (customButtons.length > 2) {
                const aiButton = customButtons[2];
                aiButton.title = '智能';
                aiButton.style.display = 'inline-block';
                aiButton.style.verticalAlign = 'middle';
                aiButton.style.pointerEvents = 'auto';
                aiButton.style.cursor = 'pointer';
                aiButton.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:18px; height:18px; margin-right:4px; vertical-align:middle;"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" fill="#4B5563"/></svg> AI生文';
                aiButton.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    // 打开模态弹窗
                    const modal = document.getElementById('aiPluginModal');
                    const contentContainer = document.getElementById('ai-plugin-content');

                    if (modal && contentContainer) {
                        // 添加模态弹窗样式
                        if (typeof window.addModalStyles === 'function') {
                            window.addModalStyles();
                        }

                        // 显示加载中状态
                        contentContainer.innerHTML = '<div style="text-align:center;padding:50px 0"><div style="display:inline-block;width:40px;height:40px;border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;animation:spin 1s linear infinite"></div><p style="margin-top:20px;color:#666">加载中...</p><style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style></div>';

                        // 显示模态弹窗
                        modal.style.display = 'flex';
                        setTimeout(() => modal.classList.add('modal-visible'), 10);

                        // 加载插件
                        fetch('/admin/Plugin.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            body: 'action=load_plugin_by_id&plugin_id=22'
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    contentContainer.innerHTML = data.html;

                                    // 执行插件脚本
                                    contentContainer.querySelectorAll('script').forEach(script => {
                                        const newScript = document.createElement('script');
                                        newScript.textContent = script.textContent;
                                        document.head.appendChild(newScript);
                                        script.remove();
                                    });

                                    // 覆盖插件的插入内容函数
                                    window.articleGenerator.insertContent = function (articleData) {
                                        if (!articleData) {
                                            showToast('请先生成文章', 'warning');
                                            return;
                                        }

                                        const title = articleData.title;
                                        const keywords = articleData.keywords || '';
                                        const content = articleData.content;

                                        // 生成描述（从内容中提取前100个字符）
                                        const tempDiv = document.createElement('div');
                                        tempDiv.innerHTML = content;
                                        let plainText = tempDiv.textContent || tempDiv.innerText || '';
                                        plainText = plainText.replace(/\[qkcms:buy——\d+个积分\]/g, '').replace(/\[\/qkcms:buy\]/g, '');
                                        const description = plainText.trim().substring(0, 100) + (plainText.length > 100 ? '...' : '');

                                        // 向文章表单插入内容
                                        document.getElementById('title').value = title;
                                        document.getElementById('keywords').value = keywords;
                                        document.getElementById('description').value = description;

                                        if (window.quill) {
                                            window.quill.root.innerHTML = content;
                                            document.getElementById('content').value = content;
                                        }

                                        showToast('内容已插入到文章', 'success');

                                        // 关闭模态弹窗
                                        window.closeAiPluginModal();
                                    };

                                    // 触发插件的onload
                                    if (typeof window.onload === 'function') {
                                        window.onload();
                                    }
                                } else {
                                    contentContainer.innerHTML = '<div style="color:red;text-align:center;padding:20px">加载失败: ' + (data.message || '未知错误') + '</div>';
                                }
                            })
                            .catch(error => {
                                contentContainer.innerHTML = '<div style="color:red;text-align:center;padding:20px">网络错误，请重试</div>';
                            });

                        bindSafeBackdropClose(modal, window.closeAiPluginModal);

                        // 按ESC键关闭
                        const closeOnEscape = function (e) {
                            if (e.key === 'Escape' && modal.classList.contains('modal-visible')) {
                                window.closeAiPluginModal();
                                document.removeEventListener('keydown', closeOnEscape);
                            }
                        };
                        document.addEventListener('keydown', closeOnEscape);
                    }
                });
            }
        }

        // 文本变化事件
        quill.on('text-change', function (delta, oldDelta, source) {
            const isCodeMode = window.isCodeModeGlobal || false;
            if (source === 'user') {
                contentTextarea.value = isCodeMode ? quill.getText() : quill.root.innerHTML;
            }
        });

        // 自动设置缩略图相关函数
        function extractFirstImageFileName() {
            try {
                const content = quill.root.innerHTML;
                if (!content) return null;
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = content;
                const images = tempDiv.querySelectorAll('img');
                if (images.length === 0) return null;
                for (let i = 0; i < images.length; i++) {
                    const img = images[i];
                    const src = img.getAttribute('src');
                    if (!src || src.startsWith('data:image/')) continue;
                    return src.split('/').pop().split('?')[0];
                }
                return null;
            } catch (error) {
                return null;
            }
        }

        function checkAndAutoSetThumbnail() {
            return false;
        }

        function debounce(func, wait) {
            let timeout = null;
            return function (...args) {
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        }

        const debouncedCheckThumbnail = debounce(checkAndAutoSetThumbnail, 2000);
        quill.on('text-change', function (delta, oldDelta, source) {
            if (source !== 'user') return;
            const insertedImages = delta.ops.filter(op => op.insert && op.insert.image);
            if (insertedImages.length > 0) debouncedCheckThumbnail();
            else {
                setTimeout(() => {
                    if (quill.root.innerHTML.includes('<img ') && !document.querySelector('input[name="existing_thumbnail"]').value.trim()) {
                        debouncedCheckThumbnail();
                    }
                }, 1000);
            }
        });

        quill.root.addEventListener('load', function (e) {
            if (e.target.tagName === 'IMG') {
                setTimeout(() => {
                    if (!document.querySelector('input[name="existing_thumbnail"]').value.trim()) {
                        checkAndAutoSetThumbnail();
                    }
                }, 500);
            }
        }, true);

        function checkThumbnailWithTimeout() {
            let checkCount = 0;
            const maxChecks = 5;
            const checkInterval = setInterval(() => {
                checkCount++;
                if (checkAndAutoSetThumbnail() || checkCount >= maxChecks) clearInterval(checkInterval);
            }, 3000);
        }
        setTimeout(() => {
            if (!checkAndAutoSetThumbnail()) checkThumbnailWithTimeout();
        }, 2000);

        // 图片属性设置
        setupImageProperties(quill);

        function setupImageProperties(quill) {
            const closeModal = document.getElementById('closeModal');
            const cancelChanges = document.getElementById('cancelChanges');
            const applyChanges = document.getElementById('applyChanges');
            const widthInput = document.getElementById('imageWidth');
            const heightInput = document.getElementById('imageHeight');
            const modal = document.getElementById('imagePropertiesModal');

            closeModal.addEventListener('click', closeModalFunc);
            cancelChanges.addEventListener('click', closeModalFunc);
            applyChanges.addEventListener('click', applyChangesFunc);
            bindSafeBackdropClose(modal, closeModalFunc);

            document.addEventListener('keydown', function (event) {
                if (event.key === 'Escape' && modal.classList.contains('modal-visible')) closeModalFunc();
            });

            document.addEventListener('click', function (event) {
                if (event.target.closest('.ql-custom') || event.target.closest('#buy-menu')) return;

                const img = event.target.closest('img');
                if (img && quill.root.contains(img)) {
                    if (event.ctrlKey) {
                        event.preventDefault();
                        let index = 0;
                        while (index < quill.getLength()) {
                            const [block] = quill.getLeaf(index);
                            if (block && block.domNode === img.parentElement) {
                                quill.setSelection(index, 1);
                                break;
                            }
                            index++;
                        }
                    } else {
                        event.preventDefault();
                        const parent = img.parentElement;
                        openModal(parent, img);
                    }
                }

                const video = event.target.closest('video');
                if (video && quill.root.contains(video)) {
                    if (event.ctrlKey) {
                        event.preventDefault();
                        let videoContainer = video.parentElement;
                        while (videoContainer && !videoContainer.classList.contains('video-container') && !videoContainer.classList.contains('ql-editor')) {
                            videoContainer = videoContainer.parentElement;
                        }
                        let index = 0;
                        while (index < quill.getLength()) {
                            const [block] = quill.getLeaf(index);
                            if (block && block.domNode && (block.domNode === videoContainer || block.domNode.contains(videoContainer))) {
                                quill.setSelection(index, 1);
                                break;
                            }
                            index++;
                        }
                    } else {
                        event.preventDefault();
                        let videoContainer = video.parentElement;
                        while (videoContainer && !videoContainer.classList.contains('video-container') && !videoContainer.classList.contains('ql-editor')) {
                            videoContainer = videoContainer.parentElement;
                        }
                        window.openVideoInsertModal(videoContainer, video);
                    }
                }
            });

            widthInput.addEventListener('input', function () {
                if (document.getElementById('preserveAspectRatio').checked && selectedImage) {
                    const img = selectedImage.querySelector('img');
                    const aspectRatio = img.clientHeight / img.clientWidth;
                    updateDimensions(widthInput, document.getElementById('imageHeight'), aspectRatio);
                }
            });
            heightInput.addEventListener('input', function () {
                if (document.getElementById('preserveAspectRatio').checked && selectedImage) {
                    const img = selectedImage.querySelector('img');
                    const aspectRatio = img.clientWidth / img.clientHeight;
                    updateDimensions(heightInput, document.getElementById('imageWidth'), aspectRatio);
                }
            });
        }

        // 添加视频点击监听器
        addVideoClickListeners();
        quill.on('text-change', () => setTimeout(addVideoClickListeners, 100));
    }

    // 自定义下拉框初始化（仅在编辑模式下）
    const formModeElement = document.getElementById('form_mode');
    const formMode = formModeElement ? formModeElement.value : '';

    if (formMode === 'edit') {
        const dropdownBtn = document.getElementById('article-select-btn');
        const dropdownOptions = document.getElementById('article-dropdown-options');
        const dropdownSearch = document.getElementById('article-dropdown-search');
        const nativeSelect = document.getElementById('article-dropdown');
        const pageInput = document.getElementById('page-input');

        function initArticleSelectMenuScrollbar() {
            if (!dropdownOptions) return;
            if (!window.AdminScrollbar || typeof window.AdminScrollbar.initVerticalMenu !== 'function') return;
            window.AdminScrollbar.initVerticalMenu({
                menu: dropdownOptions,
                contentSelector: '#article-options-list',
                trackSelector: '.counter-column-menu-vscroll',
                thumbSelector: '.counter-column-menu-vthumb',
                thumbHeight: 80,
                updateHookName: '_articleSelectMenuScrollbarUpdate'
            });
        }

        function updateArticleSelectMenuScrollbar() {
            if (!dropdownOptions) return;
            if (typeof dropdownOptions._articleSelectMenuScrollbarUpdate === 'function') {
                window.requestAnimationFrame(dropdownOptions._articleSelectMenuScrollbarUpdate);
            }
        }

        initArticleSelectMenuScrollbar();

        function renderOptions() {
            const optionsList = document.getElementById('article-options-list');
            const nativeSelect = document.getElementById('article-dropdown');
            const dropdownPageInfo = document.getElementById('article-dropdown-page-info');

            dropdownPageInfo.textContent = `第${dropdownCurrentPage}页`;
            pageInput.value = dropdownCurrentPage;

            optionsList.innerHTML = '';
            nativeSelect.innerHTML = '';

            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '选择文章';
            nativeSelect.appendChild(defaultOption);

            const fragment = document.createDocumentFragment();

            dropdownFilteredArticles.forEach(article => {
                const customOption = document.createElement('div');
                customOption.className = 'article-dropdown-option';
                customOption.textContent = article.title;
                customOption.dataset.value = article.id;
                fragment.appendChild(customOption);

                const nativeOption = document.createElement('option');
                nativeOption.value = article.id;
                nativeOption.textContent = article.title;
                nativeSelect.appendChild(nativeOption);
            });

            optionsList.appendChild(fragment);
            updateArticleSelectMenuScrollbar();
        }

        document.getElementById('article-options-list').addEventListener('click', function (e) {
            const option = e.target.closest('.article-dropdown-option');
            if (option) {
                dropdownBtn.textContent = option.textContent;
                nativeSelect.value = option.dataset.value;
                dropdownOptions.style.display = 'none';

                const articleId = option.dataset.value;
                fetch('/admin/ajaxx.php?action=get_article&id=' + articleId, {
                    timeout: 10000
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const article = data.data;
                            let articleIdInput = document.querySelector('input[name="article_id"]');
                            if (!articleIdInput) {
                                articleIdInput = document.createElement('input');
                                articleIdInput.type = 'hidden';
                                articleIdInput.name = 'article_id';
                                document.getElementById('article-form').appendChild(articleIdInput);
                            }
                            articleIdInput.value = article.id;
                            document.getElementById('article_id').value = article.id;

                            document.getElementById('title').value = article.title || '';
                            document.getElementById('description').value = article.description || '';
                            document.getElementById('keywords').value = article.keywords || '';
                            document.getElementById('views').value = article.views || 0;
                            document.getElementById('article_points').value = article.points || 0;

                            const contentTextarea = document.getElementById('content');
                            contentTextarea.value = article.content || '';
                            window.quill && (window.quill.root.innerHTML = article.content || '');

                            if (article.type) {
                                const typeRadio = document.querySelector('input[name="type"][value="' + article.type + '"]');
                                typeRadio && (typeRadio.checked = true);
                            }

                            document.getElementById('article_property') && article.property && (document.getElementById('article_property').value = article.property);
                            document.getElementById('category_id') && article.category_id && (document.getElementById('category_id').value = article.category_id);

                            if (article.thumbnail) {
                                renderThumbnailExistingState(article.thumbnail, inferThumbnailSourceType(article.thumbnail));
                            } else {
                                renderThumbnailEmptyState();
                            }
                            bindThumbnailUploadBtn();
                            bindThumbnailUrlInput();
                        } else {
                            showToast('获取文章详情失败: ' + data.message, 'error');
                        }
                    })
                    .catch(error => showToast('获取文章详情出错: ' + error.message, 'error'));
            }
        });

        const searchBtn = document.getElementById('article-search-btn');

        function performArticleDropdownSearch() {
            const searchTerm = dropdownSearch.value.trim();
            const url = `/admin/ajaxx.php?action=get_articles&page=1&page_size=${dropdownPageSize}&search=${encodeURIComponent(searchTerm)}`;
            fetch(url, {
                timeout: 10000
            })
                .then(response => {
                    if (!response.ok) throw new Error('HTTP error! status: ' + response.status);
                    return response.json();
                })
                .then(data => {
                    let fetchedArticles = [];
                    if (data && data.success) {
                        if (data.data?.articles?.length) fetchedArticles = data.data.articles;
                        else if (Array.isArray(data)) fetchedArticles = data;
                    }
                    dropdownArticles = fetchedArticles;
                    dropdownFilteredArticles = [...dropdownArticles];
                    dropdownCurrentPage = 1;
                    dropdownTotalPages = fetchedArticles.length < dropdownPageSize ? 1 : Math.ceil(fetchedArticles.length / dropdownPageSize);
                    pageInput.value = dropdownCurrentPage;
                    document.getElementById('article-dropdown-page-info').textContent = `第${dropdownCurrentPage}页`;
                    renderOptions();
                    setTimeout(() => {
                        if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
                            initCustomScrollbar();
                        }
                        if (typeof initBatchOperations === 'function') initBatchOperations();
                    }, 500);
                })
                .catch(error => { });
        }

        searchBtn.addEventListener('click', performArticleDropdownSearch);
        dropdownSearch.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') performArticleDropdownSearch();
        });

        pageInput.addEventListener('change', function () {
            let page = parseInt(this.value);
            if (isNaN(page) || page < 1) {
                page = 1;
                this.value = page;
                showToast('已经是第一页了！', 'info');
            } else if (page > dropdownTotalPages) {
                page = dropdownTotalPages;
                this.value = page;
                showToast('已经是最后一页了！', 'info');
            }
            loadArticlesForSearch(page);
        });

        pageInput.addEventListener('input', function () {
            let inputPage = parseInt(this.value);
            if (isNaN(inputPage) || inputPage < 1) inputPage = 1;
            else if (inputPage > dropdownTotalPages) inputPage = dropdownTotalPages;
            if (inputPage !== dropdownCurrentPage) loadArticlesForSearch(inputPage);
        });

        dropdownBtn.addEventListener('click', function () {
            dropdownOptions.style.display = dropdownOptions.style.display === 'block' ? 'none' : 'block';
            if (dropdownOptions.style.display === 'block') {
                dropdownSearch.focus();
                updateArticleSelectMenuScrollbar();
            }
        });

        document.addEventListener('click', function (event) {
            if (!event.target.closest('.article-custom-dropdown')) dropdownOptions.style.display = 'none';
        });

        function loadArticlesForSearch(page = 1) {
            const url = `/admin/ajaxx.php?action=get_articles&page=${page}&page_size=${dropdownPageSize}`;
            fetch(url, {
                timeout: 10000
            })
                .then(response => {
                    if (!response.ok) throw new Error('HTTP error! status: ' + response.status);
                    return response.json();
                })
                .then(data => {
                    let fetchedArticles = [];
                    if (data) {
                        if (data.data?.articles?.length) fetchedArticles = data.data.articles;
                        else if (Array.isArray(data)) fetchedArticles = data;
                    }
                    if (!fetchedArticles.length) return;

                    dropdownArticles = fetchedArticles;
                    dropdownFilteredArticles = [...dropdownArticles];
                    dropdownCurrentPage = page;
                    dropdownTotalPages = fetchedArticles.length < dropdownPageSize ? page : page + 1;
                    dropdownTotalPages = Math.max(dropdownTotalPages, 1);

                    document.getElementById('article-dropdown-page-info').textContent = `第${dropdownCurrentPage}页`;
                    pageInput.value = dropdownCurrentPage;
                    renderOptions();

                    setTimeout(() => {
                        if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
                            initCustomScrollbar();
                        }
                        if (typeof initBatchOperations === 'function') initBatchOperations();
                    }, 500);
                })
                .catch(error => { });
        }

        loadArticlesForSearch();
    }
});

window.addEventListener('popstate', function () {
    if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
        initCustomScrollbar();
    }
});
