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

// ==================== 商品列表页面函数 ====================

// 删除单个商品
function deleteGoodsItem(id) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', QK_GOODS_CONFIG.urls.deleteGoods + encodeURIComponent(id), true);
    xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
            const responseText = xhr.responseText.trim();
            if (responseText === 'success') {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.deleteSuccess, 'success', 2000);
                }
                if (typeof HeaderPagination !== 'undefined') {
                    HeaderPagination.load();
                } else {
                    window.location.reload();
                }
            } else {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.deleteFail + responseText, 'error');
                }
            }
        } else {
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.networkRequestFail, 'error');
            }
        }
    };
    xhr.onerror = function () {
        if (typeof showToast === 'function') {
            showToast(QK_GOODS_CONFIG.messages.networkConnectError, 'error');
        }
    };
    xhr.send();
}

// 通用AJAX请求函数
function ajaxRequest(url, data, successCallback, errorCallback) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
            try {
                const response = JSON.parse(xhr.responseText);
                successCallback(response);
            } catch (e) {
                errorCallback(QK_GOODS_CONFIG.messages.parseResponseFail);
            }
        } else {
            errorCallback(QK_GOODS_CONFIG.messages.requestFail);
        }
    };
    xhr.onerror = function () {
        errorCallback(QK_GOODS_CONFIG.messages.networkError);
    };
    xhr.send(data);
}

// 编辑商品字段 - 双击进入编辑模式
function editGoodsField(goodsId, field) {
    const cell = document.querySelector(`.goods-${field}-cell[data-goods-id="${goodsId}"]`);
    if (!cell) return;

    const display = cell.querySelector(`.goods-${field}-display`);
    const input = cell.querySelector(`.goods-${field}-input`);

    if (!display || !input) return;

    display.style.display = 'none';
    input.style.display = 'inline-block';
    input.focus();
    input.select();
}

// 保存商品字段
function saveGoodsField(goodsId, field, input) {
    const cell = document.querySelector(`.goods-${field}-cell[data-goods-id="${goodsId}"]`);
    if (!cell) return;

    const display = cell.querySelector(`.goods-${field}-display`);
    let newValue = input.value;
    const oldValue = display.getAttribute(`data-original-${field}`) || '';

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

    // 类型转换和验证
    if (field === 'title') {
        newValue = newValue.trim();
        if (!newValue) {
            input.value = oldValue;
            return;
        }
    } else if (field === 'price') {
        newValue = parseFloat(newValue);
        if (isNaN(newValue) || newValue < 0) {
            input.value = oldValue;
            return;
        }
    } else if (['stock', 'sales'].includes(field)) {
        newValue = parseInt(newValue);
        if (isNaN(newValue) || newValue < 0) {
            input.value = oldValue;
            return;
        }
    }

    // 比较值是否改变（处理数字和字符串类型不一致的问题）
    const oldValueForCompare = field === 'price' ? parseFloat(oldValue) :
        ['stock', 'sales'].includes(field) ? parseInt(oldValue) : oldValue;
    if (newValue === oldValueForCompare) {
        return;
    }

    // 发送AJAX请求
    const action = `update_goods_${field}`;
    const data = `${action}=1&goods_id=${goodsId}&${field}=${field === 'title' ? encodeURIComponent(newValue) : newValue}`;

    ajaxRequest(QK_GOODS_CONFIG.urls.updateGoods, data,
        function (response) {
            if (response.success) {
                // 更新显示
                if (field === 'price') {
                    display.textContent = '¥' + newValue.toFixed(2);
                } else {
                    display.textContent = newValue;
                }
                display.setAttribute(`data-original-${field}`, newValue);
                input.value = newValue;
                if (typeof showToast === 'function') {
                    showToast(response.message, 'success');
                }
            } else {
                input.value = oldValue;
                if (typeof showToast === 'function') {
                    showToast(response.message, 'error');
                }
            }
        },
        function (error) {
            input.value = oldValue;
            if (typeof showToast === 'function') {
                showToast(error + QK_GOODS_CONFIG.messages.tryAgain, 'error');
            }
        }
    );
}

// 取消编辑商品字段
function cancelEditGoodsField(goodsId, field) {
    const cell = document.querySelector(`.goods-${field}-cell[data-goods-id="${goodsId}"]`);
    if (!cell) return;

    const display = cell.querySelector(`.goods-${field}-display`);
    const input = cell.querySelector(`.goods-${field}-input`);
    const oldValue = display.getAttribute(`data-original-${field}`) || '';

    input.value = oldValue;
    input.style.display = 'none';
    display.style.display = 'inline';
}

// 编辑商品标题 - 双击进入编辑模式
function editGoodsTitle(goodsId) {
    editGoodsField(goodsId, 'title');
}

// 保存商品标题
function saveGoodsTitle(goodsId, input) {
    saveGoodsField(goodsId, 'title', input);
}

// 取消编辑商品标题
function cancelEditGoodsTitle(goodsId) {
    cancelEditGoodsField(goodsId, 'title');
}

// 编辑商品价格 - 双击进入编辑模式
function editGoodsPrice(goodsId) {
    editGoodsField(goodsId, 'price');
}

// 保存商品价格
function saveGoodsPrice(goodsId, input) {
    saveGoodsField(goodsId, 'price', input);
}

// 取消编辑商品价格
function cancelEditGoodsPrice(goodsId) {
    cancelEditGoodsField(goodsId, 'price');
}

// 编辑商品库存 - 双击进入编辑模式
function editGoodsStock(goodsId) {
    editGoodsField(goodsId, 'stock');
}

// 保存商品库存
function saveGoodsStock(goodsId, input) {
    saveGoodsField(goodsId, 'stock', input);
}

// 取消编辑商品库存
function cancelEditGoodsStock(goodsId) {
    cancelEditGoodsField(goodsId, 'stock');
}

// 编辑商品销量 - 双击进入编辑模式
function editGoodsSales(goodsId) {
    editGoodsField(goodsId, 'sales');
}

// 保存商品销量
function saveGoodsSales(goodsId, input) {
    saveGoodsField(goodsId, 'sales', input);
}

// 取消编辑商品销量
function cancelEditGoodsSales(goodsId) {
    cancelEditGoodsField(goodsId, 'sales');
}

// 替换商品列表中的缩略图
function replaceListThumbnail(goodsId, 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;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);
        formData.append('action', 'upload_image');
        formData.append('type', 'goods');
        formData.append('image_type', 'thumbnail');

        // 显示上传中状态
        const originalSrc = imgElement.src;
        imgElement.src = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0iIzY2NiIgZD0iTTAgMGgyNHYyNEgweiIvPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik0xMiA2djEyIi8+PHBhdGggZmlsbD0iIzAwNzZiZiIgZD0iTTEyIDhoLTF2M2gxdi0zem0wIDZ2N2gtMXYtN2gzem0tMi0yeiIvPjwvc3ZnPg==';

        // 上传图片
        fetch(QK_GOODS_CONFIG.urls.uploadImage, {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const newImageUrl = data.data.url;

                    // 获取商品当前的图片列表
                    const goodsInfoUrl = '/admin/adgoods.php?action=get_goods_info&id=' + goodsId;
                    console.log('获取商品信息:', goodsInfoUrl);
                    fetch(goodsInfoUrl)
                        .then(response => {
                            console.log('商品信息响应状态:', response.status);
                            return response.json();
                        })
                        .then(goodsData => {
                            console.log('商品信息响应:', goodsData);
                            if (goodsData.success && goodsData.data) {
                                const currentImage = goodsData.data.image || '';
                                let imageArray = [];

                                if (currentImage) {
                                    imageArray = currentImage.split('|');
                                }

                                // 替换第一张缩略图
                                const oldThumbnailUrl = imageArray[0];
                                imageArray[0] = newImageUrl;
                                const newImageString = imageArray.join('|');

                                // 自动删除老的缩略图
                                if (oldThumbnailUrl) {
                                    console.log('删除老的缩略图:', oldThumbnailUrl);
                                    fetch('/admin/adgoods.php', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        },
                                        body: `action=delete_image&image_url=${encodeURIComponent(oldThumbnailUrl)}`
                                    })
                                        .then(response => response.json())
                                        .then(deleteData => {
                                            console.log('删除老缩略图结果:', deleteData);
                                        })
                                        .catch(error => {
                                            console.error('删除老缩略图失败:', error);
                                        });
                                }

                                // 更新商品的image字段
                                const updateUrl = '/admin/adgoods.php';
                                console.log('发送更新请求:', {
                                    url: updateUrl,
                                    body: `update_goods_image=1&goods_id=${goodsId}&image=${encodeURIComponent(newImageString)}`
                                });
                                fetch(updateUrl, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    },
                                    body: `update_goods_image=1&goods_id=${goodsId}&image=${encodeURIComponent(newImageString)}`
                                })
                                    .then(response => {
                                        console.log('响应状态:', response.status);
                                        return response.json();
                                    })
                                    .then(updateData => {
                                        console.log('更新响应:', updateData);
                                        if (updateData.success) {
                                            // 更新图片显示
                                            imgElement.src = newImageUrl;
                                            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');
                            }
                        });
                } 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 updateGoodsSelectField(selectElement, field) {
    if (!selectElement) return;

    const form = selectElement.closest('form');
    if (!form) return;

    const goodsId = form.querySelector('input[name="goods_id"]').value;
    if (!goodsId) return;

    const value = selectElement.value;
    const previousValue = selectElement.getAttribute('data-previous-value');

    selectElement.disabled = true;

    const action = `update_goods_${field}`;
    const fieldName = field === 'category' ? 'category_id' : field;
    const data = `${action}=1&goods_id=${goodsId}&${fieldName}=${value}`;

    ajaxRequest(QK_GOODS_CONFIG.urls.updateGoodsSelect, data,
        function (response) {
            selectElement.disabled = false;
            if (response.success) {
                selectElement.setAttribute('data-previous-value', value);
                if (typeof showToast === 'function') {
                    showToast(response.message, 'success');
                }
            } else {
                selectElement.value = previousValue;
                if (typeof showToast === 'function') {
                    showToast(response.message, 'error');
                }
            }
        },
        function (error) {
            selectElement.disabled = false;
            selectElement.value = previousValue;
            if (typeof showToast === 'function') {
                showToast(error + QK_GOODS_CONFIG.messages.tryAgain, 'error');
            }
        }
    );
}

// 更新商品分类
function updateGoodsCategory(selectElement) {
    updateGoodsSelectField(selectElement, 'category');
}

// 更新商品状态
function updateGoodsStatus(selectElement) {
    updateGoodsSelectField(selectElement, 'status');
}

// 顶部分页专用：渲染商品主列表（供 HeaderPagination 调用）
function renderGoodsMainList(pageData) {
    const goods = pageData.goods || [];
    const categories = pageData.categories || [];
    const tbody = document.querySelector('.admin-table.section-manage tbody');
    if (tbody) {
        tbody.innerHTML = '';
        goods.forEach(good => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td style="width: 40px;">
                        <input type="checkbox" class="item-checkbox" value="${good.id}" style="width: 18px; height: 18px;">
                    </td>
                    <td>${good.id}</td>
                    <td style="display: flex; align-items: center; justify-content: center;">
                        ${good.image && good.image !== 'null' ?
                    `<img src="${escapeHtml(good.image.indexOf('|') > -1 ? good.image.split('|')[0] : good.image)}" alt="${escapeHtml(good.title)}" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(${good.id}, this)">` :
                    `<img src="${QK_GOODS_CONFIG.assets.defaultImage}" alt="默认图片" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(${good.id}, this)">`}
                    </td>
                    <td class="goods-title-cell" data-goods-id="${good.id}">
                        <span class="goods-title-display" ondblclick="editGoodsTitle(${good.id})" data-qk-tip="${escapeHtml(good.title || '')}" data-original-title="${escapeHtml(good.title || '')}">
                            ${escapeHtml(good.title || '')}
                        </span>
                        <input type="text" class="goods-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(good.title || '')}"
                            onblur="saveGoodsTitle(${good.id}, this)"
                            onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsTitle(${good.id});}">
                    </td>
                    <td>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="update_goods_status" value="1">
                            <input type="hidden" name="goods_id" value="${good.id}">
                            <select name="status" data-previous-value="${good.status}" onchange="updateGoodsStatus(this)" class="form-control status-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                <option value="1" ${good.status == 1 ? 'selected' : ''}>上架</option>
                                <option value="0" ${good.status == 0 ? 'selected' : ''}>下架</option>
                            </select>
                        </form>
                    </td>
                    <td class="goods-price-cell" data-goods-id="${good.id}">
                        <span class="goods-price-display" ondblclick="editGoodsPrice(${good.id})" data-original-price="${good.price}" style="color: #f96055; font-weight: 600;">
                            ¥${parseFloat(good.price).toFixed(2)}
                        </span>
                        <input type="number" step="0.01" class="goods-price-input" style="display:none; width: 100px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                            value="${good.price}"
                            onblur="saveGoodsPrice(${good.id}, this)"
                            onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsPrice(${good.id});}">
                    </td>
                    <td class="goods-sales-cell" data-goods-id="${good.id}">
                        <span class="goods-sales-display" ondblclick="editGoodsSales(${good.id})" data-original-sales="${good.sales || 0}" style="color: #f59e0b; font-weight: 600;">
                            ${good.sales || 0}
                        </span>
                        <input type="number" class="goods-sales-input" style="display:none; width: 80px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                            value="${good.sales || 0}"
                            onblur="saveGoodsSales(${good.id}, this)"
                            onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsSales(${good.id});}">
                    </td>
                    <td class="goods-stock-cell" data-goods-id="${good.id}">
                        <span class="goods-stock-display" ondblclick="editGoodsStock(${good.id})" data-original-stock="${good.stock}">
                            ${good.stock}
                        </span>
                        <input type="number" class="goods-stock-input" style="display:none; width: 80px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                            value="${good.stock}"
                            onblur="saveGoodsStock(${good.id}, this)"
                            onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsStock(${good.id});}">
                    </td>
                    <td>
                        <form method="post" class="inline-form category-update-form">
                            <input type="hidden" name="update_goods_category" value="1">
                            <input type="hidden" name="goods_id" value="${good.id}">
                            <select name="category_id" data-previous-value="${good.category_id}" onchange="updateGoodsCategory(this)" class="form-control category-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                <option value="0">未分类</option>
                                ${categories.map(category =>
                        `<option value="${category.id}" ${good.category_id == category.id ? 'selected' : ''}>${escapeHtml(category.name)}</option>`
                    ).join('')}
                            </select>
                        </form>
                    </td>
                    <td>${typeof window.formatDateYMD === 'function' ? window.formatDateYMD(good.create_time) : '-'}</td>
                    <td class="fixed-action-column">
                        <a href="${QK_GOODS_CONFIG.urls.preview}${good.id}.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>
                        <button type="button" class="btn btn-sm btn-primary edit-goods-btn" data-id="${good.id}">编辑</button>
                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteGoodsItem(${good.id})">删除</button>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }
    setTimeout(() => {
        if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
            initCustomScrollbar();
        }
        if (typeof initBatchOperations === 'function') initBatchOperations();
    }, 300);
}

// 批量操作功能
function initBatchOperations() {
    // 防止重复初始化
    if (window.batchOperationsInitialized) return;
    window.batchOperationsInitialized = true;

    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 batchStatusBtn = document.getElementById('batch-status-btn');
    const batchStatusSelect = document.getElementById('batch-status-select');
    const batchStockBtn = document.getElementById('batch-stock-btn');
    const batchStockInput = document.getElementById('batch-stock-input');
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    const selectAllCheckbox = document.getElementById('select-all-header');

    if (!batchOperationBtn || !batchModal) {
        return;
    }

    // 更新选中数量
    function updateSelectedCount() {
        const selectedCheckboxes = document.querySelectorAll('.item-checkbox:checked');
        if (countNumber) {
            countNumber.textContent = selectedCheckboxes.length;
        }
    }

    // 获取选中的商品ID
    function getSelectedGoodsIds() {
        const selectedCheckboxes = document.querySelectorAll('.item-checkbox:checked');
        return Array.from(selectedCheckboxes).map(checkbox => checkbox.value);
    }

    // 显示模态框
    function showModal() {
        batchModal.style.display = 'flex';
        setTimeout(() => {
            batchModal.classList.add('modal-visible');
        }, 10);
    }

    // 隐藏模态框
    function hideModal(shouldReload = false) {
        batchModal.classList.remove('modal-visible');
        setTimeout(() => {
            batchModal.style.display = 'none';
            if (shouldReload && window.batchOperationSuccess) {
                window.batchOperationSuccess = false;
                window.location.reload();
            }
        }, 300);
    }

    // 批量操作按钮点击
    batchOperationBtn.addEventListener('click', function () {
        const selectedIds = getSelectedGoodsIds();

        if (selectedIds.length === 0) {
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.selectGoodsFirst, 'error');
            } else {
                alert(QK_GOODS_CONFIG.messages.selectGoodsFirst);
            }
            return;
        }
        window.batchOperationSuccess = false;
        updateSelectedCount();
        showModal();
    });

    // 关闭按钮
    closeBatchModal.addEventListener('click', function () {
        hideModal(true);
    });

    // 点击模态框外部关闭
    const modalBackdrop = batchModal.querySelector('.modal-backdrop');
    if (modalBackdrop) {
        modalBackdrop.addEventListener('click', function () {
            hideModal(true);
        });
    }

    // 全选/取消全选
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function () {
            const isChecked = this.checked;
            document.querySelectorAll('.item-checkbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            updateSelectedCount();
        });
    }

    // 单个复选框变化
    document.addEventListener('change', function (event) {
        if (event.target.classList.contains('item-checkbox')) {
            if (selectAllCheckbox) {
                const allCheckboxes = document.querySelectorAll('.item-checkbox');
                selectAllCheckbox.checked = allCheckboxes.length > 0 &&
                    Array.from(allCheckboxes).every(checkbox => checkbox.checked);
            }
            updateSelectedCount();
        }
    });

    // 批量移动
    if (batchMoveBtn) {
        batchMoveBtn.addEventListener('click', function () {
            const selectedIds = getSelectedGoodsIds();
            const categoryId = batchCategorySelect.value;

            if (selectedIds.length === 0) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectGoodsFirst, 'error');
                }
                return;
            }

            if (categoryId === '0') {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectCategory, 'error');
                }
                return;
            }

            batchMoveBtn.disabled = true;
            batchMoveBtn.textContent = QK_GOODS_CONFIG.messages.batchMoving;

            fetch(QK_GOODS_CONFIG.urls.updateGoods, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'batch_move_goods=1&goods_ids=' + selectedIds.join(',') + '&category_id=' + categoryId
            })
                .then(response => response.json())
                .then(data => {
                    batchMoveBtn.disabled = false;
                    batchMoveBtn.textContent = QK_GOODS_CONFIG.messages.batchMoveBtn;

                    if (data.success) {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchMoveSuccess, 'success');
                        }
                        window.batchOperationSuccess = true;
                    } else {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchMoveFail + '：' + data.message, 'error');
                        }
                    }
                })
                .catch(() => {
                    batchMoveBtn.disabled = false;
                    batchMoveBtn.textContent = QK_GOODS_CONFIG.messages.batchMoveBtn;
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.batchMoveFail, 'error');
                    }
                });
        });
    }

    // 批量设置状态
    if (batchStatusBtn) {
        batchStatusBtn.addEventListener('click', function () {
            const selectedIds = getSelectedGoodsIds();
            const status = batchStatusSelect.value;

            if (selectedIds.length === 0) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectGoodsFirst, 'error');
                }
                return;
            }

            if (status === '-1') {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectStatus, 'error');
                }
                return;
            }

            batchStatusBtn.disabled = true;
            batchStatusBtn.textContent = QK_GOODS_CONFIG.messages.batchStatusSetting;

            fetch(QK_GOODS_CONFIG.urls.updateGoods, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'batch_update_goods_status=1&goods_ids=' + selectedIds.join(',') + '&status=' + status
            })
                .then(response => response.json())
                .then(data => {
                    batchStatusBtn.disabled = false;
                    batchStatusBtn.textContent = QK_GOODS_CONFIG.messages.batchStatusBtn;

                    if (data.success) {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchStatusSuccess, 'success');
                        }
                        window.batchOperationSuccess = true;
                    } else {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchStatusFail + '：' + data.message, 'error');
                        }
                    }
                })
                .catch(() => {
                    batchStatusBtn.disabled = false;
                    batchStatusBtn.textContent = QK_GOODS_CONFIG.messages.batchStatusBtn;
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.batchStatusFail, 'error');
                    }
                });
        });
    }

    // 批量修改库存
    if (batchStockBtn && batchStockInput) {
        batchStockBtn.addEventListener('click', function () {
            const selectedIds = getSelectedGoodsIds();
            const stock = batchStockInput.value.trim();

            if (selectedIds.length === 0) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectGoodsFirst, 'error');
                }
                return;
            }

            if (stock === '' || isNaN(stock) || parseInt(stock) < 0) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.invalidStock, 'error');
                }
                return;
            }

            batchStockBtn.disabled = true;
            batchStockBtn.textContent = QK_GOODS_CONFIG.messages.batchStockUpdating;

            fetch(QK_GOODS_CONFIG.urls.updateGoods, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'batch_update_stock=1&goods_ids=' + selectedIds.join(',') + '&stock=' + stock
            })
                .then(response => response.json())
                .then(data => {
                    batchStockBtn.disabled = false;
                    batchStockBtn.textContent = QK_GOODS_CONFIG.messages.batchStockBtn;

                    if (data.success) {
                        if (typeof showToast === 'function') {
                            showToast(data.message, 'success');
                        }
                        window.batchOperationSuccess = true;
                    } else {
                        if (typeof showToast === 'function') {
                            showToast(data.message, 'error');
                        }
                    }
                })
                .catch(() => {
                    batchStockBtn.disabled = false;
                    batchStockBtn.textContent = QK_GOODS_CONFIG.messages.batchStockBtn;
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.batchStockFail, 'error');
                    }
                });
        });
    }

    // 批量删除
    if (batchDeleteBtn) {
        batchDeleteBtn.addEventListener('click', function () {
            const selectedIds = getSelectedGoodsIds();

            if (selectedIds.length === 0) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.selectGoodsFirst, 'error');
                }
                return;
            }

            batchDeleteBtn.disabled = true;
            batchDeleteBtn.textContent = QK_GOODS_CONFIG.messages.batchDeleting;

            fetch(QK_GOODS_CONFIG.urls.updateGoods, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'batch_delete_goods=1&goods_ids=' + selectedIds.join(',')
            })
                .then(response => response.json())
                .then(data => {
                    batchDeleteBtn.disabled = false;
                    batchDeleteBtn.textContent = QK_GOODS_CONFIG.messages.batchDeleteBtn;

                    if (data.success) {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchDeleteSuccess, 'success');
                        }
                        window.batchOperationSuccess = true;
                    } else {
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.batchDeleteFail + '：' + data.message, 'error');
                        }
                    }
                })
                .catch(() => {
                    batchDeleteBtn.disabled = false;
                    batchDeleteBtn.textContent = QK_GOODS_CONFIG.messages.batchDeleteBtn;
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.batchDeleteFail, 'error');
                    }
                });
        });
    }
}

// 自定义滚动条
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) {
        setTimeout(initCustomScrollbar, 500);
        return;
    }
    if (!window.AdminScrollbar || typeof window.AdminScrollbar.initHorizontal !== 'function') return;
    window.AdminScrollbar.initHorizontal({
        scrollContainer: scrollContainer,
        track: scrollbarTrack,
        thumb: scrollbarThumb,
        updateHookName: '_updateScrollbarThumb'
    });
}

// ==================== 商品发布/编辑页面函数 ====================

let specCount = 0;
let modalSpecCount = 0;

// 预览商品
function previewGoods() {
    const goodsIdInput = document.getElementById('goods_id');
    let goodsId = goodsIdInput ? goodsIdInput.value : '';
    if (goodsId && /^\d+$/.test(goodsId)) {
        window.open(QK_GOODS_CONFIG.urls.preview + goodsId + '.html', '_blank');
    } else {
        if (typeof showToast === 'function') {
            showToast(QK_GOODS_CONFIG.messages.previewAfterPublish, 'warning');
        } else {
            alert(QK_GOODS_CONFIG.messages.previewAfterPublish);
        }
    }
}

// 关闭视频插入模态框
function closeVideoInsertModal() {
    const modal = document.getElementById('videoInsertModal');
    if (modal) {
        modal.classList.remove('modal-visible');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
    }
}

// 删除视频
function deleteVideo() {
    closeVideoInsertModal();
}

// 确认插入视频
function confirmVideoInsert() {
    const videoUrl = document.getElementById('video-url').value.trim();
    if (!videoUrl) {
        if (typeof showToast === 'function') {
            showToast(QK_GOODS_CONFIG.messages.enterVideoUrl, 'error');
        } else {
            alert(QK_GOODS_CONFIG.messages.enterVideoUrl);
        }
        return;
    }

    const quill = window.quillInstance;
    if (quill) {
        quill.insertEmbed(quill.getLength(), 'video', videoUrl);
    }

    closeVideoInsertModal();
}

// 关闭规格添加模态弹窗
function closeSpecModal() {
    const specModal = document.getElementById('spec-modal');
    if (specModal) {
        specModal.classList.remove('modal-visible');
        setTimeout(() => {
            specModal.style.display = 'none';
        }, 300);
    }
}

// 创建规格项
function createSpecItem(specNumber, specName = '', specPrice = '0', specStock = '99', specImage = '') {
    // 创建规格项HTML
    const specItemHTML = `
            <div class="spec-modal-item" style="display: flex; align-items: center; margin-bottom: 15px;">
                <div style="display: flex; align-items: center; gap: 5px; flex-shrink: 0;">
                    <span style="font-size: 12px; width: 60px; height: 30px; line-height: 30px; text-align: right; padding-right: 5px;">规格${specNumber}：</span>
                    <input type="text" class="form-control spec-name" placeholder="例如：红色" value="${specName}" style="width: 150px; height: 30px; padding: 0 8px; font-size: 12px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                </div>
                <div style="display: flex; align-items: center; gap: 5px; flex-shrink: 0; margin-left: 20px;">
                    <span style="font-size: 12px; min-width: 40px; height: 30px; line-height: 30px;">价格：</span>
                    <input type="number" class="form-control spec-price" placeholder="100" min="0" step="0.01" value="${specPrice}" style="width: 80px; height: 30px; padding: 0 8px; font-size: 12px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                </div>
                <div style="display: flex; align-items: center; gap: 5px; flex-shrink: 0; margin-left: 20px;">
                    <span style="font-size: 12px; min-width: 40px; height: 30px; line-height: 30px;">库存：</span>
                    <input type="number" class="form-control spec-stock" placeholder="50" min="0" value="${specStock}" style="width: 80px; height: 30px; padding: 0 8px; font-size: 12px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                </div>
                <div style="display: flex; align-items: center; gap: 10px; flex-shrink: 0; margin-left: 20px;">
                    <div style="position: relative; width: 30px; height: 30px; cursor: pointer; transition: all 0.2s ease;">
                        <input type="file" accept="image/*" class="spec-image" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; z-index: 1;">
                        <div class="spec-thumbnail" style="width: 30px; height: 30px; border: 1px solid #ddd; border-radius: 4px; overflow: hidden; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; position: relative; z-index: 0; transition: all 0.2s ease;">
                            ${specImage ? `<img src="${specImage}" alt="${specName}" style="width: 100%; height: 100%; object-fit: cover;">` : '<span style="font-size: 16px; color: #999;">+</span>'}
                        </div>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 10px; flex-shrink: 0; margin-left: 20px;">
                    <button type="button" onclick="removeSpecItem(this)" style="width: 42px; height: 30px; padding: 0 8px; font-size: 12px; background-color: #ff4d4f; border: 1px solid #ff4d4f; border-radius: 4px; color: white; cursor: pointer; transition: all 0.2s ease; flex-shrink: 0; box-sizing: border-box;">删除</button>
                </div>
            </div>
        `;

    // 创建DOM元素
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = specItemHTML;
    const specItem = tempDiv.firstElementChild;

    // 为文件输入框添加事件
    const fileInput = specItem.querySelector('.spec-image');
    const thumbnail = specItem.querySelector('.spec-thumbnail');
    const thumbnailContainer = fileInput.parentElement;

    // 为缩略图添加鼠标悬停样式
    thumbnailContainer.addEventListener('mouseenter', function () {
        thumbnail.style.borderColor = '#1890ff';
        thumbnail.style.transform = 'scale(1.05)';
    });
    thumbnailContainer.addEventListener('mouseleave', function () {
        thumbnail.style.borderColor = '#ddd';
        thumbnail.style.transform = 'scale(1)';
    });

    // 为文件输入框添加change事件，显示缩略图
    fileInput.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                thumbnail.innerHTML = `<img src="${e.target.result}" alt="预览图片" style="width: 100%; height: 100%; object-fit: cover;">`;
            };
            reader.readAsDataURL(file);
        }
    });

    // 为删除按钮添加悬停动画
    const deleteButton = specItem.querySelector('button');
    deleteButton.addEventListener('mouseenter', function () {
        this.style.transform = 'translateY(-2px)';
        this.style.boxShadow = '0 2px 4px rgba(255, 77, 79, 0.3)';
    });
    deleteButton.addEventListener('mouseleave', function () {
        this.style.transform = 'translateY(0)';
        this.style.boxShadow = 'none';
    });

    return specItem;
}

// 加载现有规格到模态框
function loadSpecsToModal() {
    // 清空规格项容器
    const specItemsContainer = document.getElementById('spec-items-container');
    if (!specItemsContainer) return;
    specItemsContainer.innerHTML = '';

    // 重置计数器
    modalSpecCount = 0;

    // 从隐藏输入字段读取现有规格
    const specItems = document.querySelectorAll('.spec-item');
    specItems.forEach((item, index) => {
        modalSpecCount++;

        // 读取规格数据
        const specName = item.querySelector('input[name*="name"]').value;
        const specPrice = item.querySelector('input[name*="price"]').value;
        const specStock = item.querySelector('input[name*="stock"]').value;
        const specImage = item.querySelector('input[name*="image"]') ? item.querySelector('input[name*="image"]').value : '';

        // 创建规格项
        const specItem = createSpecItem(modalSpecCount, specName, specPrice, specStock, specImage);

        // 添加到容器
        specItemsContainer.appendChild(specItem);
    });
}

// 添加规格项
function addSpecItem() {
    const currentSpecs = document.querySelectorAll('#spec-items-container .spec-modal-item').length;
    if (currentSpecs >= 6) {
        showToast(QK_GOODS_CONFIG.messages.maxSpecs, 'error');
        return;
    }

    modalSpecCount++;
    const specItemsContainer = document.getElementById('spec-items-container');

    // 创建规格项
    const specItem = createSpecItem(modalSpecCount);

    // 添加到容器
    specItemsContainer.appendChild(specItem);
}

// 移除规格项
function removeSpecItem(button) {
    const specItem = button.closest('.spec-modal-item');
    if (!specItem) return;
    specItem.remove();
    reorderSpecItems();
}

// 重新编号规格项
function reorderSpecItems() {
    const specItems = document.querySelectorAll('#spec-items-container .spec-modal-item');
    specItems.forEach((item, index) => {
        const specNumber = index + 1;
        const specLabel = item.querySelector('span');
        if (specLabel) {
            specLabel.textContent = `规格${specNumber}：`;
        }
    });
    modalSpecCount = specItems.length;
}

// 保存所有规格
function saveAllSpecs() {
    const specItems = document.querySelectorAll('#spec-items-container .spec-modal-item');
    if (specItems.length === 0) {
        showToast(QK_GOODS_CONFIG.messages.addSpecFirst, 'error');
        return;
    }

    // 检查总规格数量
    if (specItems.length > 6) {
        showToast(QK_GOODS_CONFIG.messages.maxSpecs, 'error');
        return;
    }

    // 清空现有的规格标签和隐藏输入字段
    const specsTagsArea = document.getElementById('specs-tags-area');
    const specsContainer = document.getElementById('specs-container');
    if (specsTagsArea) {
        specsTagsArea.innerHTML = '';
    }
    if (specsContainer) {
        specsContainer.innerHTML = '';
    }

    // 验证规格名称
    let hasError = false;
    specItems.forEach((specItem, index) => {
        const specName = specItem.querySelector('.spec-name').value;
        if (!specName) {
            showToast(QK_GOODS_CONFIG.messages.enterSpecName.replace('{num}', index + 1), 'error');
            hasError = true;
            return false; // 终止循环
        }
    });

    if (hasError) {
        return;
    }

    // 处理规格保存
    let processedCount = 0;
    const totalSpecs = specItems.length;

    specItems.forEach((specItem, index) => {
        const currentSpecCount = index + 1;
        const specName = specItem.querySelector('.spec-name').value;
        const specPrice = specItem.querySelector('.spec-price').value;
        const specStock = specItem.querySelector('.spec-stock').value;
        const fileInput = specItem.querySelector('.spec-image');

        // 检查是否有图片文件
        if (fileInput && fileInput.files && fileInput.files.length > 0) {
            const file = fileInput.files[0];
            // 检查文件大小，限制1MB
            const maxFileSize = 1 * 1024 * 1024; // 1MB
            if (file.size > maxFileSize) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.fileTooLarge, 'error');
                } else {
                    alert(QK_GOODS_CONFIG.messages.fileTooLarge);
                }
                processedCount++;
                if (processedCount === totalSpecs) {
                    // 所有规格处理完成
                    closeSpecModal();
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.specUpdateSuccess, 'success');
                    } else {
                        alert(QK_GOODS_CONFIG.messages.specUpdateSuccess);
                    }
                }
                return;
            }
            if (file.type.startsWith('image/')) {
                // 上传图片
                const formData = new FormData();
                formData.append('action', 'upload_image');
                formData.append('file', file);
                formData.append('type', 'goods');
                formData.append('image_type', 'spec');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            let imageUrl = '';
                            if (response.success) {
                                imageUrl = response.data.url;
                            }

                            // 创建输入框内的规格按钮
                            createSpecButton(currentSpecCount, specName, imageUrl);

                            // 创建隐藏的规格输入字段
                            const specsContainer = document.getElementById('specs-container');
                            if (specsContainer) {
                                const hiddenSpecItem = document.createElement('div');
                                hiddenSpecItem.className = 'spec-item';
                                hiddenSpecItem.style.display = 'none';

                                hiddenSpecItem.innerHTML = `
                                    <input type="hidden" name="specs[${currentSpecCount}][name]" value="${specName}">
                                    <input type="hidden" name="specs[${currentSpecCount}][price]" value="${specPrice}">
                                    <input type="hidden" name="specs[${currentSpecCount}][stock]" value="${specStock}">
                                    <input type="hidden" name="specs[${currentSpecCount}][image]" value="${imageUrl}">
                                `;

                                specsContainer.appendChild(hiddenSpecItem);
                            }
                        } catch (e) {
                            console.error(QK_GOODS_CONFIG.messages.uploadSpecImageFail, e);
                            // 创建规格但不包含图片
                            createSpecButton(currentSpecCount, specName, '');


                            const specsContainer = document.getElementById('specs-container');
                            if (specsContainer) {
                                const hiddenSpecItem = document.createElement('div');
                                hiddenSpecItem.className = 'spec-item';
                                hiddenSpecItem.style.display = 'none';

                                hiddenSpecItem.innerHTML = `
                                    <input type="hidden" name="specs[${currentSpecCount}][name]" value="${specName}">
                                    <input type="hidden" name="specs[${currentSpecCount}][price]" value="${specPrice}">
                                    <input type="hidden" name="specs[${currentSpecCount}][stock]" value="${specStock}">
                                `;

                                specsContainer.appendChild(hiddenSpecItem);
                            }
                        } finally {
                            processedCount++;
                            if (processedCount === totalSpecs) {
                                // 所有规格处理完成
                                closeSpecModal();

                                // 清空规格项容器并重置计数器
                                const specItemsContainer = document.getElementById('spec-items-container');
                                if (specItemsContainer) {
                                    specItemsContainer.innerHTML = '';
                                }
                                modalSpecCount = 0;

                                if (typeof showToast === 'function') {
                                    showToast(QK_GOODS_CONFIG.messages.specUpdateSuccess, 'success');
                                } else {
                                    alert(QK_GOODS_CONFIG.messages.specUpdateSuccess);
                                }
                            }
                        }
                    }
                };
                xhr.send(formData);
            } else {
                // 不是图片文件，直接保存
                createSpecButton(currentSpecCount, specName, '');


                const specsContainer = document.getElementById('specs-container');
                if (specsContainer) {
                    const hiddenSpecItem = document.createElement('div');
                    hiddenSpecItem.className = 'spec-item';
                    hiddenSpecItem.style.display = 'none';

                    hiddenSpecItem.innerHTML = `
                        <input type="hidden" name="specs[${currentSpecCount}][name]" value="${specName}">
                        <input type="hidden" name="specs[${currentSpecCount}][price]" value="${specPrice}">
                        <input type="hidden" name="specs[${currentSpecCount}][stock]" value="${specStock}">
                        <input type="hidden" name="specs[${currentSpecCount}][image]" value="">
                    `;

                    specsContainer.appendChild(hiddenSpecItem);
                }
                processedCount++;
                if (processedCount === totalSpecs) {
                    closeSpecModal();

                    // 清空规格项容器并重置计数器
                    const specItemsContainer = document.getElementById('spec-items-container');
                    if (specItemsContainer) {
                        specItemsContainer.innerHTML = '';
                    }
                    modalSpecCount = 0;

                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.specUpdateSuccess, 'success');
                    } else {
                        alert(QK_GOODS_CONFIG.messages.specUpdateSuccess);
                    }
                }
            }
        } else {
            // 没有选择图片，直接保存
            // 检查是否有已有的图片
            let existingImage = '';
            const existingThumbnail = specItem.querySelector('.spec-thumbnail img');
            if (existingThumbnail) {
                existingImage = existingThumbnail.src;
            }

            createSpecButton(currentSpecCount, specName, existingImage);

            const specsContainer = document.getElementById('specs-container');
            if (specsContainer) {
                const hiddenSpecItem = document.createElement('div');
                hiddenSpecItem.className = 'spec-item';
                hiddenSpecItem.style.display = 'none';

                hiddenSpecItem.innerHTML = `
                    <input type="hidden" name="specs[${currentSpecCount}][name]" value="${specName}">
                    <input type="hidden" name="specs[${currentSpecCount}][price]" value="${specPrice}">
                    <input type="hidden" name="specs[${currentSpecCount}][stock]" value="${specStock}">
                    <input type="hidden" name="specs[${currentSpecCount}][image]" value="${existingImage}">
                `;

                specsContainer.appendChild(hiddenSpecItem);
            }
            processedCount++;
            if (processedCount === totalSpecs) {
                closeSpecModal();

                // 清空规格项容器并重置计数器
                const specItemsContainer = document.getElementById('spec-items-container');
                if (specItemsContainer) {
                    specItemsContainer.innerHTML = '';
                }
                modalSpecCount = 0;

                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.specUpdateSuccess, 'success');
                } else {
                    alert(QK_GOODS_CONFIG.messages.specUpdateSuccess);
                }
            }
        }
    });
}

// 创建规格按钮
function createSpecButton(specNumber, specName, image) {
    const specsTagsArea = document.getElementById('specs-tags-area');
    if (!specsTagsArea) return;

    // 移除空提示和添加按钮
    const emptyTip = specsTagsArea.querySelector('.empty-tip');
    if (emptyTip) emptyTip.remove();
    const addBtn = specsTagsArea.querySelector('.add-item-btn');
    if (addBtn) addBtn.remove();

    const specItem = document.createElement('div');
    specItem.className = 'feature-item';
    specItem.id = `spec-btn-${specNumber}`;
    specItem.dataset.specNumber = specNumber;
    specItem.dataset.specName = specName;
    specItem.dataset.image = image || '';
    specItem.title = specName || '规格' + specNumber;

    // 使用规格图片或默认无缩略图
    const imgUrl = image && image.trim() !== '' ? image : QK_GOODS_CONFIG.assets.defaultImage;

    specItem.innerHTML = `
            <img src="${imgUrl}" alt="${specName || '规格' + specNumber}">
            <span class="delete-btn" onclick="deleteSpecItemNew(${specNumber})">×</span>
        `;

    specsTagsArea.appendChild(specItem);

    // 添加点击事件，用于替换图片
    specItem.addEventListener('click', function (e) {
        if (e.target.classList.contains('delete-btn')) return;
        replaceSpecThumbnail(this);
    });

    // 如果少于6个，添加添加按钮
    const currentSpecs = specsTagsArea.querySelectorAll('.feature-item').length;
    if (currentSpecs < 6) {
        const newAddBtn = document.createElement('button');
        newAddBtn.type = 'button';
        newAddBtn.className = 'add-item-btn';
        newAddBtn.innerHTML = '+';
        newAddBtn.onclick = function () {
            const specModal = document.getElementById('spec-modal');
            if (specModal) {
                // 加载现有规格到模态框
                loadSpecsToModal();

                specModal.style.display = 'flex';
                setTimeout(() => {
                    specModal.classList.add('modal-visible');
                }, 10);
            }
        };
        specsTagsArea.appendChild(newAddBtn);
    }
}

// 替换规格属性缩略图
function replaceSpecThumbnail(specItem) {
    const specNumber = specItem.dataset.specNumber;
    if (!specNumber) return;

    // 创建文件输入框
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.style.display = 'none';
    document.body.appendChild(input);

    // 监听文件选择
    input.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file && file.type.startsWith('image/')) {
            // 显示上传进度
            const specsTagsArea = document.getElementById('specs-tags-area');
            const progressItem = document.createElement('div');
            progressItem.className = 'feature-item upload-progress';
            progressItem.style.pointerEvents = 'none';
            progressItem.innerHTML = `
                    <div class="upload-spinner">
                        <svg class="progress-ring" width="50" height="50">
                            <circle class="progress-ring-circle" cx="25" cy="25" r="20"></circle>
                            <circle class="progress-ring-progress" cx="25" cy="25" r="20" stroke-dasharray="125.6" stroke-dashoffset="125.6"></circle>
                        </svg>
                        <div class="progress-text">上传中</div>
                    </div>
                `;
            specsTagsArea.insertBefore(progressItem, specItem);

            // 上传图片
            const formData = new FormData();
            formData.append('action', 'upload_image');
            formData.append('file', file);
            formData.append('type', 'goods');
            formData.append('image_type', 'spec');

            const xhr = new XMLHttpRequest();
            xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);

            // 监听上传进度
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    const progressCircle = progressItem.querySelector('.progress-ring-progress');
                    if (progressCircle) {
                        const circumference = 2 * Math.PI * 20;
                        const offset = circumference - (percentComplete / 100) * circumference;
                        progressCircle.style.strokeDashoffset = offset;
                    }
                }
            });

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            // 上传成功，替换图片
                            const oldImageUrl = specItem.dataset.image;
                            specItem.dataset.image = response.data.url;
                            const img = specItem.querySelector('img');
                            if (img) {
                                img.src = response.data.url;
                            }

                            // 更新隐藏输入字段
                            const specsContainer = document.getElementById('specs-container');
                            if (specsContainer) {
                                const specItemInput = specsContainer.querySelector(`.spec-item:nth-child(${specNumber}) input[name="specs[${specNumber}][image]"]`);
                                if (specItemInput) {
                                    specItemInput.value = response.data.url;
                                }
                            }

                            // 删除旧图片
                            if (oldImageUrl) {
                                const deleteFormData = new FormData();
                                deleteFormData.append('action', 'delete_image');
                                deleteFormData.append('image_url', oldImageUrl);

                                const deleteXhr = new XMLHttpRequest();
                                deleteXhr.open('POST', QK_GOODS_CONFIG.urls.deleteImage, true);
                                deleteXhr.send(deleteFormData);
                            }

                            // 移除进度框
                            if (progressItem) {
                                progressItem.remove();
                            }

                            if (typeof showToast === 'function') {
                                showToast(QK_GOODS_CONFIG.messages.imageReplaceSuccess, 'success');
                            }
                        } else {
                            // 上传失败
                            if (progressItem) {
                                progressItem.remove();
                            }
                            if (typeof showToast === 'function') {
                                showToast(QK_GOODS_CONFIG.messages.imageUploadFail + response.message, 'error');
                            }
                        }
                    } catch (e) {
                        // 上传失败
                        if (progressItem) {
                            progressItem.remove();
                        }
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.imageUploadRetry, 'error');
                        }
                    } finally {
                        // 移除文件输入框
                        document.body.removeChild(input);
                    }
                }
            };
            xhr.send(formData);
        } else {
            // 不是图片文件
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.selectImageFile, 'error');
            }
            // 移除文件输入框
            document.body.removeChild(input);
        }
    });

    // 触发文件选择
    input.click();
}

// 新布局：删除规格项
function deleteSpecItemNew(specNumber) {
    const specItem = document.getElementById(`spec-btn-${specNumber}`);
    const specsTagsArea = document.getElementById('specs-tags-area');
    if (specItem) {
        specItem.remove();
    }

    // 删除对应的隐藏输入字段
    const specItems = document.querySelectorAll('.spec-item');
    specItems.forEach((item, index) => {
        if (index + 1 === specNumber) {
            item.remove();
        }
    });

    // 显示添加按钮
    const currentSpecs = specsTagsArea.querySelectorAll('.feature-item').length;
    if (currentSpecs < 6) {
        let addBtn = specsTagsArea.querySelector('.add-item-btn');
        if (!addBtn) {
            addBtn = document.createElement('button');
            addBtn.type = 'button';
            addBtn.className = 'add-item-btn';
            addBtn.innerHTML = '+';
            addBtn.onclick = function () {
                const specModal = document.getElementById('spec-modal');
                if (specModal) {
                    // 加载现有规格到模态框
                    loadSpecsToModal();

                    specModal.style.display = 'flex';
                    setTimeout(() => {
                        specModal.classList.add('modal-visible');
                    }, 10);
                }
            };
            specsTagsArea.appendChild(addBtn);
        } else {
            addBtn.style.display = 'flex';
        }
    }

    // 如果没有规格了，显示空提示和添加按钮
    if (currentSpecs === 0) {
        specsTagsArea.innerHTML = '';

        // 添加添加按钮
        const addBtn = document.createElement('button');
        addBtn.type = 'button';
        addBtn.className = 'add-item-btn';
        addBtn.innerHTML = '+';
        addBtn.onclick = function () {
            const specModal = document.getElementById('spec-modal');
            if (specModal) {
                // 加载现有规格到模态框
                loadSpecsToModal();

                specModal.style.display = 'flex';
                setTimeout(() => {
                    specModal.classList.add('modal-visible');
                }, 10);
            }
        };
        specsTagsArea.appendChild(addBtn);

        // 添加空提示
        const emptyTip = document.createElement('span');
        emptyTip.className = 'empty-tip';
        emptyTip.textContent = '无规格属性';
        specsTagsArea.appendChild(emptyTip);
    }

    updateSpecNumbersNew();
}

// 新布局：更新规格编号
function updateSpecNumbersNew() {
    const specItems = document.querySelectorAll('.spec-item');
    const specTags = document.querySelectorAll('#specs-tags-area .feature-item');

    specItems.forEach((item, index) => {
        const specNumber = index + 1;
        const inputs = item.querySelectorAll('input');
        if (inputs[0]) inputs[0].name = `specs[${specNumber}][name]`;
        if (inputs[1]) inputs[1].name = `specs[${specNumber}][price]`;
        if (inputs[2]) inputs[2].name = `specs[${specNumber}][stock]`;
        if (inputs[3]) inputs[3].name = `specs[${specNumber}][image]`;
    });

    specTags.forEach((tag, index) => {
        const specNumber = index + 1;
        tag.id = `spec-btn-${specNumber}`;
        tag.dataset.specNumber = specNumber;
        tag.title = tag.dataset.specName || '规格' + specNumber;
    });
}

// 更新规格项编号
function updateSpecNumbers() {
    const specItems = document.querySelectorAll('.spec-item');
    const specButtons = document.querySelectorAll('#specs-buttons > div');

    specItems.forEach((item, index) => {
        const specNumber = index + 1;
        const inputs = item.querySelectorAll('input');
        if (inputs[0]) inputs[0].name = `specs[${specNumber}][name]`;
        if (inputs[1]) inputs[1].name = `specs[${specNumber}][price]`;
        if (inputs[2]) inputs[2].name = `specs[${specNumber}][stock]`;
        if (inputs[3]) inputs[3].name = `specs[${specNumber}][image]`;
    });

    specButtons.forEach((button, index) => {
        const specNumber = index + 1;
        const specItem = specItems[index];
        if (specItem) {
            const nameInput = specItem.querySelector('input[name^="specs["][name$="][name]"]');
            const specName = nameInput ? nameInput.value : '未命名';
            button.id = `spec-btn-${specNumber}`;
            const span = button.querySelector('span');
            if (span) {
                span.textContent = `规格${specNumber}: ${specName}`;
            }
        }
    });
}

// 关闭商品选择模态框
function closeGoodsSelectModal() {
    // 先处理选择的商品
    confirmGoodsSelection();

    const goodsSelectModal = document.getElementById('goods_select_modal');
    if (goodsSelectModal) {
        goodsSelectModal.classList.remove('modal-visible');
        setTimeout(() => {
            goodsSelectModal.style.display = 'none';
        }, 300);
    }
}

// 加载商品列表
function loadGoodsList(search = '') {
    const goodsList = document.getElementById('goods_list');
    if (!goodsList) return;

    goodsList.innerHTML = `<div style="text-align: center; padding: 20px;">${QK_GOODS_CONFIG.messages.loading}</div>`;

    const xhr = new XMLHttpRequest();
    let url = QK_GOODS_CONFIG.urls.getGoodsList + '&page=1&page_size=100';
    if (search) {
        url += '&search=' + encodeURIComponent(search);
    }
    // 添加当前编辑商品ID，用于排除自身
    const goodsIdInput = document.getElementById('goods_id');
    if (goodsIdInput && goodsIdInput.value) {
        url += '&exclude_id=' + goodsIdInput.value;
    }

    xhr.open('GET', url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            try {
                const data = JSON.parse(xhr.responseText);
                if (data && data.success && data.data && data.data.goods) {
                    renderGoodsList(data.data.goods);
                } else {
                    goodsList.innerHTML = `<div style="text-align: center; padding: 20px;">${QK_GOODS_CONFIG.messages.loadGoodsFail}</div>`;
                }
            } catch (e) {
                goodsList.innerHTML = `<div style="text-align: center; padding: 20px;">${QK_GOODS_CONFIG.messages.loadFail}</div>`;
            }
        }
    };
    xhr.send();
}

// 渲染商品列表
function renderGoodsList(goods) {
    const goodsList = document.getElementById('goods_list');
    if (!goodsList) return;

    if (goods.length === 0) {
        goodsList.innerHTML = `<div style="text-align: center; padding: 20px;">${QK_GOODS_CONFIG.messages.noGoodsFound}</div>`;
        return;
    }

    let html = '<table class="admin-table goods-select-table" style="width: 100%; border-collapse: collapse; table-layout: fixed;">';
    html += '<thead><tr><th>操作</th><th>ID</th><th>缩略图</th><th>商品标题</th><th>价格</th><th>库存</th></tr></thead>';
    html += '<tbody>';
    html += '<style>';
    html += '#goods_list .goods-select-table { table-layout: fixed; width: 100% !important; border-collapse: collapse !important; }';
    html += '#goods_list .goods-select-table th:nth-child(1), #goods_list .goods-select-table td:nth-child(1) { width: 60px !important; min-width: 60px !important; text-align: center !important; }';
    html += '#goods_list .goods-select-table th:nth-child(2), #goods_list .goods-select-table td:nth-child(2) { width: 60px !important; min-width: 60px !important; text-align: center !important; }';
    html += '#goods_list .goods-select-table th:nth-child(3), #goods_list .goods-select-table td:nth-child(3) { width: 80px !important; min-width: 80px !important; text-align: center !important; vertical-align: middle !important; }';
    html += '#goods_list .goods-select-table th:nth-child(4), #goods_list .goods-select-table td:nth-child(4) { width: 300px !important; min-width: 300px !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }';
    html += '#goods_list .goods-select-table th:nth-child(5), #goods_list .goods-select-table td:nth-child(5) { text-align: left !important; }';
    html += '#goods_list .goods-select-table th:nth-child(6), #goods_list .goods-select-table td:nth-child(6) { text-align: left !important; }';
    html += '#goods_list .goods-select-table tbody tr { height: 47px !important; line-height: 47px !important; display: table-row !important; margin: 0 !important; padding: 0 !important; }';
    html += '#goods_list .goods-select-table thead tr { height: 47px !important; line-height: 47px !important; display: table-row !important; margin: 0 !important; padding: 0 !important; }';
    html += '#goods_list .goods-select-table tbody td { vertical-align: middle !important; padding: 6px 12px !important; height: 47px !important; margin: 0 !important; box-sizing: border-box !important; line-height: 47px !important; }';
    html += '#goods_list .goods-select-table thead th { vertical-align: middle !important; padding: 6px 12px !important; text-align: left !important; height: 47px !important; margin: 0 !important; box-sizing: border-box !important; line-height: 47px !important; }';
    html += '#goods_list .goods-select-table * { box-sizing: border-box !important; }';
    html += '#goods_list .goods-thumbnail { width: 32px; height: 32px; object-fit: cover; border-radius: 4px; vertical-align: middle; }';
    html += '</style>';

    const currentParentId = document.getElementById('parent_id')?.value || '';
    const currentParentIds = currentParentId ? currentParentId.split(',') : [];

    goods.forEach(function (good) {
        const isChecked = currentParentIds.includes(good.id.toString());
        // 获取商品缩略图
        let thumbnailHtml = '';
        if (good.image && good.image !== 'null') {
            let firstImage = good.image;
            if (firstImage.indexOf('|') > -1) {
                firstImage = firstImage.split('|')[0];
            }
            thumbnailHtml = '<img src="' + firstImage + '" alt="' + escapeHtml(good.title) + '" class="goods-thumbnail">';
        } else {
            thumbnailHtml = '<img src="' + QK_GOODS_CONFIG.assets.defaultImage + '" alt="默认图片" class="goods-thumbnail">';
        }
        html += '<tr>';
        html += '<td><input type="checkbox" class="goods-checkbox" value="' + good.id + '" data-title="' + escapeHtml(good.title) + '" data-image="' + (good.image || '') + '" ' + (isChecked ? 'checked' : '') + '></td>';
        html += '<td>' + good.id + '</td>';
        html += '<td>' + thumbnailHtml + '</td>';
        html += '<td>' + escapeHtml(good.title) + '</td>';
        html += '<td>¥' + parseFloat(good.price).toFixed(2) + '</td>';
        html += '<td>' + good.stock + '</td>';
        html += '</tr>';
    });

    html += '</tbody></table>';
    goodsList.innerHTML = html;

    // 绑定点击事件
    const rows = document.querySelectorAll('#goods_list tbody tr');
    rows.forEach(function (row) {
        row.addEventListener('click', function (e) {
            if (e.target.type !== 'checkbox') {
                const checkbox = this.querySelector('.goods-checkbox');
                if (checkbox) {
                    checkbox.checked = !checkbox.checked;
                    checkGoodsLimit();
                }
            }
        });
    });

    const checkboxes = document.querySelectorAll('.goods-checkbox');
    checkboxes.forEach(function (checkbox) {
        checkbox.addEventListener('change', function () {
            checkGoodsLimit();
        });
    });

    function checkGoodsLimit() {
        const maxGoods = 6;
        const selectedCheckboxes = document.querySelectorAll('.goods-checkbox:checked');
        if (selectedCheckboxes.length > maxGoods) {
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.maxBoundGoods, 'error');
            } else {
                alert(QK_GOODS_CONFIG.messages.maxBoundGoods);
            }
            selectedCheckboxes[selectedCheckboxes.length - 1].checked = false;
        }
    }
}

// 确认商品选择
function confirmGoodsSelection() {
    const selectedCheckboxes = document.querySelectorAll('.goods-checkbox:checked');
    const parentIdInput = document.getElementById('parent_id');

    if (selectedCheckboxes.length > 0) {
        const goodsIds = [];
        const goodsTitles = [];
        const goodsImages = [];

        const maxGoods = 6;
        if (selectedCheckboxes.length > maxGoods) {
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.maxBoundGoods, 'error');
            }
            return;
        }

        const selectedCount = Math.min(selectedCheckboxes.length, maxGoods);

        for (let i = 0; i < selectedCount; i++) {
            const checkbox = selectedCheckboxes[i];
            goodsIds.push(checkbox.value);
            goodsTitles.push(checkbox.getAttribute('data-title'));
            goodsImages.push(checkbox.getAttribute('data-image') || '');
        }

        parentIdInput.value = goodsIds.join(',');
        renderGoodsButtons(goodsIds, goodsTitles, goodsImages);
    }
}

// 渲染商品按钮
function renderGoodsButtons(goodsIds, goodsTitles, goodsImages) {
    const goodsTagsArea = document.getElementById('goods-tags-area');
    if (!goodsTagsArea) return;

    // 检查是否有数据
    if (!goodsIds || goodsIds.length === 0 || (goodsIds.length === 1 && goodsIds[0] === '')) {
        goodsTagsArea.innerHTML = '';

        // 添加添加按钮
        const addBtn = document.createElement('button');
        addBtn.type = 'button';
        addBtn.className = 'add-item-btn';
        addBtn.innerHTML = '+';
        addBtn.onclick = function () {
            document.getElementById('select_parent_goods').click();
        };
        goodsTagsArea.appendChild(addBtn);

        const emptyTip = document.createElement('span');
        emptyTip.className = 'empty-tip';
        emptyTip.textContent = '无绑定商品';
        goodsTagsArea.appendChild(emptyTip);
        return;
    }

    goodsTagsArea.innerHTML = '';

    goodsIds.forEach(function (id, index) {
        if (!id) return;
        const title = goodsTitles[index];
        let image = goodsImages ? goodsImages[index] : '';

        // 处理多图情况，只取第一张
        if (image && image.indexOf('|') > -1) {
            image = image.split('|')[0];
        }

        const item = document.createElement('div');
        item.className = 'feature-item';
        item.dataset.goodsId = id;
        item.dataset.image = image || '';
        item.title = title;

        // 使用商品图片或默认无缩略图
        const imgUrl = image && image.trim() !== '' && image !== 'null' ? image : QK_GOODS_CONFIG.assets.defaultImage;

        item.innerHTML = `
                <img src="${imgUrl}" alt="${title}">
                <span class="delete-btn" onclick="deleteGoodsItemNew('${id}', event)">×</span>
            `;

        item.addEventListener('click', function (e) {
            if (!e.target.classList.contains('delete-btn')) {
                window.open(QK_GOODS_CONFIG.urls.preview + id + '.html', '_blank');
            }
        });

        goodsTagsArea.appendChild(item);
    });

    // 添加添加按钮（如果少于5个）
    if (goodsIds.length < 6) {
        const addBtn = document.createElement('button');
        addBtn.type = 'button';
        addBtn.className = 'add-item-btn';
        addBtn.innerHTML = '+';
        addBtn.onclick = function () {
            document.getElementById('select_parent_goods').click();
        };
        goodsTagsArea.appendChild(addBtn);
    }
}

// 新布局：删除商品项
function deleteGoodsItemNew(goodsId, event) {
    if (event) {
        event.stopPropagation();
    }

    const currentIds = document.getElementById('parent_id').value.split(',').filter(id => id);
    const goodsTitles = [];
    const goodsImages = [];

    currentIds.forEach(function (id) {
        const item = document.querySelector('#goods-tags-area .feature-item[data-goods-id="' + id + '"]');
        if (item && id !== goodsId) {
            goodsTitles.push(item.title);
            // 从data属性获取图片URL
            goodsImages.push(item.dataset.image || '');
        }
    });

    const newIds = currentIds.filter(id => id !== goodsId);
    document.getElementById('parent_id').value = newIds.join(',');
    renderGoodsButtons(newIds, goodsTitles, goodsImages);
}

// HTML转义
function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

// 初始化功能区悬停大图预览
function initFeatureItemHover() {
    let currentItem = null;

    document.addEventListener('mousemove', function (e) {
        if (currentItem) {
            // 检查currentItem是否仍然存在于DOM中
            if (!document.contains(currentItem)) {
                currentItem = null;
                return;
            }

            const rect = currentItem.getBoundingClientRect();
            const viewportHeight = window.innerHeight;
            const viewportWidth = window.innerWidth;
            const itemCenterY = rect.top + rect.height / 2;
            const isInUpperHalf = itemCenterY < viewportHeight / 2;

            // 计算预览位置
            let previewTop, previewLeft;

            if (isInUpperHalf) {
                // 在页面上半部分，预览显示在下方
                previewTop = rect.bottom + 10;
            } else {
                // 在页面下半部分，预览显示在上方
                previewTop = rect.top - 290;
            }

            // 计算水平位置，确保预览不会超出视口
            const previewWidth = 280;
            const leftPosition = rect.left + rect.width / 2 - previewWidth / 2;

            // 调整水平位置，确保预览在视口内
            previewLeft = Math.max(10, Math.min(leftPosition, viewportWidth - previewWidth - 10));

            // 设置预览位置
            currentItem.style.setProperty('--preview-top', previewTop + 'px');
            currentItem.style.setProperty('--preview-left', previewLeft + 'px');
            currentItem.style.setProperty('--arrow-top', isInUpperHalf ? rect.bottom + 'px' : (rect.top - 10) + 'px');
            currentItem.style.setProperty('--arrow-left', (rect.left + rect.width / 2 - 10) + 'px');
            currentItem.style.setProperty('--arrow-direction', isInUpperHalf ? 'down' : 'up');
        }
    });

    // 为所有feature-item添加鼠标进入事件
    document.addEventListener('mouseenter', function (e) {
        const featureItem = e.target.closest('.feature-item');
        if (featureItem) {
            const img = featureItem.querySelector('img');
            if (img && img.src && !img.src.includes('data:image/svg+xml')) {
                featureItem.style.setProperty('--preview-image', 'url(' + img.src + ')');
                featureItem.classList.add('has-preview');
                currentItem = featureItem;
            }
        }
    }, true);

    document.addEventListener('mouseleave', function (e) {
        const featureItem = e.target.closest('.feature-item');
        if (featureItem) {
            featureItem.classList.remove('has-preview');
            currentItem = null;
        }
    }, true);
}

// 初始化缩略图点击事件
function initThumbnailClickEvents() {
    // 为商品缩略图添加点击事件
    const galleryItems = document.querySelectorAll('#gallery-preview-new .feature-item');
    galleryItems.forEach(function (item) {
        // 启用指针事件
        item.style.pointerEvents = 'auto';
        // 添加点击事件
        item.addEventListener('click', function (e) {
            if (e.target.classList.contains('delete-btn')) return;
            replaceThumbnail(this);
        });
    });

    // 为规格属性缩略图添加点击事件
    const specItems = document.querySelectorAll('#specs-tags-area .feature-item');
    specItems.forEach(function (item) {
        // 启用指针事件
        item.style.pointerEvents = 'auto';
        // 添加点击事件
        item.addEventListener('click', function (e) {
            if (e.target.classList.contains('delete-btn')) return;
            replaceSpecThumbnail(this);
        });
    });
}

// 初始化相册功能
function initGallery() {
    const galleryInput = document.getElementById('gallery');
    const galleryPreviewNew = document.getElementById('gallery-preview-new');

    if (!galleryInput || !galleryPreviewNew) return;

    // 新布局：初始化缩略图上传
    initNewGallery();
}

// 新布局：删除缩略图
function deleteThumbnailNew(element) {
    const thumbnailItem = element.closest('.feature-item');
    if (!thumbnailItem) return;

    const imageUrl = thumbnailItem.dataset.imageUrl;
    const galleryPreview = document.getElementById('gallery-preview-new');

    if (imageUrl) {
        const formData = new FormData();
        formData.append('action', 'delete_image');
        formData.append('image_url', imageUrl);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', QK_GOODS_CONFIG.urls.deleteImage, true);
        xhr.send(formData);
    }

    thumbnailItem.remove();

    // 显示添加按钮
    const addBtn = galleryPreview.querySelector('.add-item-btn');
    if (addBtn) addBtn.style.display = 'flex';

    // 如果没有图片了，显示空提示
    const currentImages = galleryPreview.querySelectorAll('.feature-item').length;
    if (currentImages === 0) {
        const emptyTip = galleryPreview.querySelector('.empty-tip');
        if (!emptyTip) {
            galleryPreview.innerHTML = '<span class="empty-tip">无缩略图</span>';
        } else {
            emptyTip.style.display = 'flex';
        }
    }
}

// 新布局：初始化缩略图功能
function initNewGallery() {
    const galleryInput = document.getElementById('gallery');
    const galleryPreview = document.getElementById('gallery-preview-new');

    if (!galleryInput || !galleryPreview) return;

    galleryInput.addEventListener('change', function (e) {
        const files = e.target.files;
        if (files.length > 0) {
            const currentImages = galleryPreview.querySelectorAll('.feature-item').length;

            if (currentImages >= 6) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.maxUploadImages, 'error');
                }
                return;
            }

            const remainingSlots = 6 - currentImages;
            for (let i = 0; i < Math.min(files.length, remainingSlots); i++) {
                const file = files[i];
                if (file.type.startsWith('image/')) {
                    uploadGalleryImageNew(file);
                }
            }
        }
    });
}

// 创建上传进度框
function createUploadProgressItem() {
    const galleryPreview = document.getElementById('gallery-preview-new');
    if (!galleryPreview) return null;

    // 隐藏空提示
    const emptyTip = galleryPreview.querySelector('.empty-tip');
    if (emptyTip) {
        emptyTip.style.display = 'none';
    }

    const progressItem = document.createElement('div');
    progressItem.className = 'feature-item upload-progress';
    progressItem.style.pointerEvents = 'none';

    progressItem.innerHTML = `
            <div class="upload-spinner">
                <svg class="progress-ring" width="50" height="50">
                    <circle class="progress-ring-circle" cx="25" cy="25" r="20"></circle>
                    <circle class="progress-ring-progress" cx="25" cy="25" r="20" stroke-dasharray="125.6" stroke-dashoffset="125.6"></circle>
                </svg>
                <div class="progress-text">上传中</div>
            </div>
        `;

    // 在添加按钮之前插入
    const addBtn = galleryPreview.querySelector('.add-item-btn');
    if (addBtn) {
        galleryPreview.insertBefore(progressItem, addBtn);
    } else {
        galleryPreview.appendChild(progressItem);
    }

    return progressItem;
}

// 新布局：上传缩略图
function uploadGalleryImageNew(file) {
    // 创建上传进度框
    const progressItem = createUploadProgressItem();
    if (!progressItem) return;

    // 获取进度环元素
    const progressCircle = progressItem.querySelector('.progress-ring-progress');
    const circumference = 2 * Math.PI * 20; // 2πr，r=20

    const formData = new FormData();
    formData.append('action', 'upload_image');
    formData.append('file', file);
    formData.append('type', 'goods');
    formData.append('image_type', 'thumbnail');

    const xhr = new XMLHttpRequest();
    xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);

    // 监听上传进度
    xhr.upload.addEventListener('progress', function (e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            // 更新进度环
            if (progressCircle) {
                const offset = circumference - (percentComplete / 100) * circumference;
                progressCircle.style.strokeDashoffset = offset;
            }
        }
    });

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    // 上传成功，替换为实际图片
                    const galleryPreview = document.getElementById('gallery-preview-new');
                    if (galleryPreview && progressItem) {
                        // 移除进度框
                        progressItem.remove();
                        // 添加实际图片
                        addGalleryItemNew(response.data.url, file.name);
                    }
                } else {
                    // 上传失败，移除进度框并显示错误
                    if (progressItem) {
                        progressItem.remove();
                    }
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.imageUploadFail + response.message, 'error');
                    }
                }
            } catch (e) {
                // 上传失败，移除进度框并显示错误
                if (progressItem) {
                    progressItem.remove();
                }
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.imageUploadRetry, 'error');
                }
            }
        }
    };
    xhr.send(formData);
}

// 新布局：添加缩略图项
function addGalleryItemNew(imageUrl, fileName) {
    const galleryPreview = document.getElementById('gallery-preview-new');
    if (!galleryPreview) return;

    // 隐藏空提示
    const emptyTip = galleryPreview.querySelector('.empty-tip');
    if (emptyTip) {
        emptyTip.style.display = 'none';
    }

    const thumbnailItem = document.createElement('div');
    thumbnailItem.className = 'feature-item';
    thumbnailItem.dataset.imageUrl = imageUrl;

    // 初始状态禁用悬停预览
    thumbnailItem.style.pointerEvents = 'none';

    thumbnailItem.innerHTML = `
            <img src="${imageUrl}" alt="商品缩略图">
            <span class="delete-btn" onclick="deleteThumbnailNew(this)">×</span>
            <input type="hidden" name="gallery[]" value="${imageUrl}">
        `;

    // 在添加按钮之前插入
    const addBtn = galleryPreview.querySelector('.add-item-btn');
    if (addBtn) {
        galleryPreview.insertBefore(thumbnailItem, addBtn);
    } else {
        galleryPreview.appendChild(thumbnailItem);
    }

    // 图片加载完成后启用悬停预览和点击事件
    const img = thumbnailItem.querySelector('img');
    if (img) {
        img.onload = function () {
            thumbnailItem.style.pointerEvents = 'auto';
            // 添加点击事件，用于替换图片
            thumbnailItem.addEventListener('click', function (e) {
                if (e.target.classList.contains('delete-btn')) return;
                replaceThumbnail(this);
            });
        };
        // 图片加载失败也启用悬停预览和点击事件（使用默认图片）
        img.onerror = function () {
            thumbnailItem.style.pointerEvents = 'auto';
            // 添加点击事件，用于替换图片
            thumbnailItem.addEventListener('click', function (e) {
                if (e.target.classList.contains('delete-btn')) return;
                replaceThumbnail(this);
            });
        };
        // 对于已缓存的图片，onload可能不会触发，直接启用
        if (img.complete) {
            thumbnailItem.style.pointerEvents = 'auto';
            // 添加点击事件，用于替换图片
            thumbnailItem.addEventListener('click', function (e) {
                if (e.target.classList.contains('delete-btn')) return;
                replaceThumbnail(this);
            });
        }
    }
}

// 替换商品缩略图
function replaceThumbnail(thumbnailItem) {
    // 创建文件输入框
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.style.display = 'none';
    document.body.appendChild(input);

    // 监听文件选择
    input.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file && file.type.startsWith('image/')) {
            // 显示上传进度
            const galleryPreview = document.getElementById('gallery-preview-new');
            const progressItem = document.createElement('div');
            progressItem.className = 'feature-item upload-progress';
            progressItem.style.pointerEvents = 'none';
            progressItem.innerHTML = `
                    <div class="upload-spinner">
                        <svg class="progress-ring" width="50" height="50">
                            <circle class="progress-ring-circle" cx="25" cy="25" r="20"></circle>
                            <circle class="progress-ring-progress" cx="25" cy="25" r="20" stroke-dasharray="125.6" stroke-dashoffset="125.6"></circle>
                        </svg>
                        <div class="progress-text">上传中</div>
                    </div>
                `;
            galleryPreview.insertBefore(progressItem, thumbnailItem);

            // 上传图片
            const formData = new FormData();
            formData.append('action', 'upload_image');
            formData.append('file', file);
            formData.append('type', 'goods');
            formData.append('image_type', 'thumbnail');

            const xhr = new XMLHttpRequest();
            xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);

            // 监听上传进度
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    const progressCircle = progressItem.querySelector('.progress-ring-progress');
                    if (progressCircle) {
                        const circumference = 2 * Math.PI * 20;
                        const offset = circumference - (percentComplete / 100) * circumference;
                        progressCircle.style.strokeDashoffset = offset;
                    }
                }
            });

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            // 上传成功，替换图片
                            const oldImageUrl = thumbnailItem.dataset.imageUrl;
                            thumbnailItem.dataset.imageUrl = response.data.url;
                            const img = thumbnailItem.querySelector('img');
                            if (img) {
                                img.src = response.data.url;
                            }
                            // 查找现有的输入字段，可能是gallery[]或existing_images[]
                            let inputField = thumbnailItem.querySelector('input[name="gallery[]"]');
                            if (!inputField) {
                                inputField = thumbnailItem.querySelector('input[name="existing_images[]"]');
                            }
                            if (inputField) {
                                inputField.value = response.data.url;
                            } else {
                                // 如果没有输入字段，创建一个新的existing_images[]字段，保持顺序
                                const newInput = document.createElement('input');
                                newInput.type = 'hidden';
                                newInput.name = 'existing_images[]';
                                newInput.value = response.data.url;
                                thumbnailItem.appendChild(newInput);
                            }

                            // 删除旧图片
                            if (oldImageUrl) {
                                const deleteFormData = new FormData();
                                deleteFormData.append('action', 'delete_image');
                                deleteFormData.append('image_url', oldImageUrl);

                                const deleteXhr = new XMLHttpRequest();
                                deleteXhr.open('POST', QK_GOODS_CONFIG.urls.deleteImage, true);
                                deleteXhr.send(deleteFormData);
                            }

                            // 移除进度框
                            if (progressItem) {
                                progressItem.remove();
                            }

                            if (typeof showToast === 'function') {
                                showToast(QK_GOODS_CONFIG.messages.imageReplaceSuccess, 'success');
                            }
                        } else {
                            // 上传失败
                            if (progressItem) {
                                progressItem.remove();
                            }
                            if (typeof showToast === 'function') {
                                showToast(QK_GOODS_CONFIG.messages.imageUploadFail + response.message, 'error');
                            }
                        }
                    } catch (e) {
                        // 上传失败
                        if (progressItem) {
                            progressItem.remove();
                        }
                        if (typeof showToast === 'function') {
                            showToast(QK_GOODS_CONFIG.messages.imageUploadRetry, 'error');
                        }
                    } finally {
                        // 移除文件输入框
                        document.body.removeChild(input);
                    }
                }
            };
            xhr.send(formData);
        } else {
            // 不是图片文件
            if (typeof showToast === 'function') {
                showToast(QK_GOODS_CONFIG.messages.selectImageFile, 'error');
            }
            // 移除文件输入框
            document.body.removeChild(input);
        }
    });

    // 触发文件选择
    input.click();
}

// 上传相册图片
function uploadGalleryImage(file) {
    const formData = new FormData();
    formData.append('action', 'upload_image');
    formData.append('file', file);
    formData.append('type', 'goods');
    formData.append('image_type', 'thumbnail');

    const xhr = new XMLHttpRequest();
    xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    addGalleryItem(response.data.url, file.name);
                } else {
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.imageUploadFail + response.message, 'error');
                    }
                }
            } catch (e) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.imageUploadRetry, 'error');
                }
            }
        }
    };
    xhr.send(formData);
}

// 添加相册项
function addGalleryItem(imageUrl, fileName) {
    const galleryPreview = document.getElementById('gallery-preview');
    const galleryInputField = document.getElementById('gallery-input');

    const previewId = 'preview-' + Date.now() + Math.random().toString(36).substr(2, 9);

    const galleryItem = document.createElement('div');
    galleryItem.className = 'input-button';
    galleryItem.dataset.previewId = previewId;
    galleryItem.dataset.originalName = fileName;

    if (galleryInputField) {
        const inputWidth = galleryInputField.offsetWidth;
        const buttonWidth = (inputWidth - 100) / 5;
        galleryItem.style.width = buttonWidth + 'px';
        galleryItem.style.minWidth = buttonWidth + 'px';
    }

    galleryItem.innerHTML = `
        <img src="${imageUrl}" alt="商品缩略图" style="width: 20px; height: 20px; object-fit: cover; margin-right: 4px; border-radius: 2px;">
        <span>${fileName}</span>
        <span class="delete-btn">×</span>
        <input type="hidden" name="gallery[]" value="${imageUrl}">
    `;

    galleryPreview.appendChild(galleryItem);

    // 创建预览元素
    const previewElement = document.createElement('div');
    previewElement.className = 'image-preview';
    previewElement.id = previewId;
    previewElement.style.display = 'none';
    previewElement.style.position = 'fixed';
    previewElement.style.zIndex = '999999';
    previewElement.style.border = '1px solid #ddd';
    previewElement.style.borderRadius = '4px';
    previewElement.style.overflow = 'hidden';
    previewElement.style.backgroundColor = 'white';
    previewElement.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
    previewElement.style.pointerEvents = 'none';
    previewElement.innerHTML = `<img src="${imageUrl}" alt="商品图片" style="max-width: 400px; max-height: 400px; object-fit: contain;">`;
    document.body.appendChild(previewElement);

    // 绑定鼠标悬停事件
    galleryItem.addEventListener('mouseenter', function () {
        const preview = document.getElementById(this.dataset.previewId);
        if (preview) {
            const rect = this.getBoundingClientRect();
            preview.style.top = (rect.bottom + 5) + 'px';
            preview.style.left = rect.left + 'px';
            preview.style.display = 'block';
        }
    });

    galleryItem.addEventListener('mouseleave', function () {
        const preview = document.getElementById(this.dataset.previewId);
        if (preview) {
            preview.style.display = 'none';
        }
    });

    // 绑定删除按钮
    const deleteBtn = galleryItem.querySelector('.delete-btn');
    deleteBtn.addEventListener('click', function (e) {
        e.stopPropagation();
        const imageInput = galleryItem.querySelector('input[name="gallery[]"]');
        const imageUrl = imageInput ? imageInput.value : '';

        if (imageUrl) {
            const formData = new FormData();
            formData.append('action', 'delete_image');
            formData.append('image_url', imageUrl);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', QK_GOODS_CONFIG.urls.deleteImage, true);
            xhr.send(formData);
        }

        const preview = document.getElementById(galleryItem.dataset.previewId);
        if (preview) {
            preview.remove();
        }
        galleryItem.remove();
    });
}

// 初始化编辑器
function initEditor() {
    if (typeof Quill === 'undefined' || !document.getElementById('quill-editor')) {
        return;
    }

    // 注册视频 blot
    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') {
                if (value) {
                    this.domNode.setAttribute('autoplay', '');
                } else {
                    this.domNode.removeAttribute('autoplay');
                }
            } else {
                super.format(name, value);
            }
        }
    }
    VideoBlot.blotName = 'video';
    VideoBlot.tagName = 'video';
    Quill.register(VideoBlot);

    const quill = new Quill('#quill-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{
                    'header': 1
                }, {
                    'header': 2
                }],
                [{
                    'list': 'ordered'
                }, {
                    'list': 'bullet'
                }],
                [{
                    'indent': '-1'
                }, {
                    'indent': '+1'
                }],
                [{
                    'align': []
                }],
                ['link', 'image', 'video'],
                ['clean']
            ]
        },
        placeholder: '请输入商品详情...'
    });

    window.quillInstance = quill;

    // 从textarea加载内容
    const content = document.getElementById('content');
    if (content && content.value) {
        quill.root.innerHTML = content.value;
    }

    // 编辑器内容变化时更新textarea
    quill.on('text-change', function () {
        if (content) {
            content.value = quill.root.innerHTML;
        }
    });

    // 处理图片上传
    const toolbar = quill.getModule('toolbar');
    toolbar.addHandler('image', function () {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.setAttribute('multiple', 'multiple');
        input.onchange = function () {
            const files = this.files;
            if (files && files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    uploadEditorImage(files[i], quill);
                }
            }
        };
        input.click();
    });

    // 视频插入
    toolbar.addHandler('video', function () {
        const modal = document.getElementById('videoInsertModal');
        if (modal) {
            modal.style.display = 'flex';
            setTimeout(() => {
                modal.classList.add('modal-visible');
            }, 10);
        }
    });

    // 图片和视频点击事件
    setupMediaClickListeners(quill);

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

    // 视频属性设置
    setupVideoProperties(quill);
}

// 图片属性相关变量
let selectedImage = null;

// 打开图片属性模态框
function openImagePropertiesModal(parent, img) {
    selectedImage = parent;
    const modal = document.getElementById('imagePropertiesModal');
    if (!modal) return;

    // 填充表单数据
    document.getElementById('imageUrl').value = img.src;
    document.getElementById('imageWidth').value = img.width || '';
    document.getElementById('imageHeight').value = img.height || '';
    document.getElementById('imageAlt').value = img.alt || '';

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

// 关闭图片属性模态框
function closeModalFunc() {
    const modal = document.getElementById('imagePropertiesModal');
    if (modal) {
        modal.classList.remove('modal-visible');
        setTimeout(() => {
            modal.style.display = 'none';
            selectedImage = null;
        }, 300);
    }
}

// 应用图片属性更改
function applyChangesFunc() {
    if (!selectedImage) return;

    const img = selectedImage.querySelector('img');
    if (!img) return;

    // 应用更改
    img.src = document.getElementById('imageUrl').value;
    img.width = document.getElementById('imageWidth').value;
    img.height = document.getElementById('imageHeight').value;
    img.alt = document.getElementById('imageAlt').value;

    closeModalFunc();
}

// 设置媒体点击监听器
function setupMediaClickListeners(quill) {
    document.addEventListener('click', function (event) {
        if (event.target.closest('.ql-custom')) return;

        if (!quill || !quill.root) return;

        const img = event.target.closest('img');
        if (img && quill.root.contains(img)) {
            event.preventDefault();
            const parent = img.parentElement;
            openImagePropertiesModal(parent, img);
        }

        const video = event.target.closest('video');
        if (video && quill.root.contains(video)) {
            event.preventDefault();
            openVideoInsertModal(video);
        }
    });
}

// 设置图片属性
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');

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

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        const modal = document.getElementById('imagePropertiesModal');
        if (modal && (event.target === modal || event.target.classList.contains('modal-backdrop'))) {
            closeModalFunc();
        }
    });

    // 按ESC键关闭
    document.addEventListener('keydown', function (event) {
        const modal = document.getElementById('imagePropertiesModal');
        if (event.key === 'Escape' && modal && modal.classList.contains('modal-visible')) {
            closeModalFunc();
        }
    });

    // 保持宽高比
    if (widthInput && heightInput) {
        widthInput.addEventListener('input', function () {
            if (document.getElementById('preserveAspectRatio') && document.getElementById('preserveAspectRatio').checked && selectedImage) {
                const img = selectedImage.querySelector('img');
                if (img) {
                    const aspectRatio = img.height / img.width;
                    heightInput.value = Math.round(widthInput.value * aspectRatio);
                }
            }
        });

        heightInput.addEventListener('input', function () {
            if (document.getElementById('preserveAspectRatio') && document.getElementById('preserveAspectRatio').checked && selectedImage) {
                const img = selectedImage.querySelector('img');
                if (img) {
                    const aspectRatio = img.width / img.height;
                    widthInput.value = Math.round(heightInput.value * aspectRatio);
                }
            }
        });
    }
}

// 设置视频属性
function setupVideoProperties(quill) {
    let selectedVideo = null;

    window.openVideoInsertModal = function (video) {
        selectedVideo = video;
        const modal = document.getElementById('videoInsertModal');
        if (!modal) return;

        // 填充表单数据
        document.getElementById('video-url').value = video.src || '';
        document.getElementById('video-width').value = video.width || '790';
        document.getElementById('video-height').value = video.height || '550';
        document.getElementById('autoplay').checked = video.hasAttribute('autoplay');

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

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

    window.confirmVideoInsert = function () {
        if (!selectedVideo) {
            // 新插入视频
            const videoUrl = document.getElementById('video-url').value;
            if (!videoUrl) return;

            const quill = window.quillInstance;
            if (quill) {
                let range = quill.getSelection();
                // 如果没有选区，将光标设置到末尾
                if (!range) {
                    range = {
                        index: quill.getLength(),
                        length: 0
                    };
                    quill.setSelection(range.index, range.length);
                }
                quill.insertEmbed(range.index, 'video', {
                    src: videoUrl,
                    width: document.getElementById('video-width').value,
                    height: document.getElementById('video-height').value,
                    autoplay: document.getElementById('autoplay').checked
                });
            }
        } else {
            // 更新现有视频
            selectedVideo.src = document.getElementById('video-url').value;
            selectedVideo.width = document.getElementById('video-width').value;
            selectedVideo.height = document.getElementById('video-height').value;
            if (document.getElementById('autoplay').checked) {
                selectedVideo.setAttribute('autoplay', '');
            } else {
                selectedVideo.removeAttribute('autoplay');
            }
        }
        closeVideoInsertModal();
    };

    window.deleteVideo = function () {
        if (selectedVideo) {
            const quill = window.quillInstance;
            if (quill) {
                let index = 0;
                while (index < quill.getLength()) {
                    const [block] = quill.getLeaf(index);
                    if (block && block.domNode === selectedVideo) {
                        quill.deleteText(index, 1);
                        break;
                    }
                    index++;
                }
            }
            closeVideoInsertModal();
        }
    };
}

// 上传编辑器图片
function uploadEditorImage(file, quill) {
    const formData = new FormData();
    formData.append('action', 'upload_image');
    formData.append('file', file);
    formData.append('type', 'goods');
    formData.append('image_type', 'detail');

    const xhr = new XMLHttpRequest();
    xhr.open('POST', QK_GOODS_CONFIG.urls.uploadImage, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    const range = quill.getSelection();
                    quill.insertEmbed(range.index, 'image', response.data.url);
                } else {
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.imageUploadFail + response.message, 'error');
                    }
                }
            } catch (e) {
                if (typeof showToast === 'function') {
                    showToast(QK_GOODS_CONFIG.messages.imageUploadRetry, 'error');
                }
            }
        }
    };
    xhr.send(formData);
}

// 初始化分类本地存储
function initCategoryStorage() {
    const categorySelect = document.getElementById('category_id');
    if (!categorySelect) return;

    // 只在发布模式下使用本地存储
    if (window.location.href.includes('&add')) {
        const CATEGORY_KEY = 'goods_category_id';

        // 从本地存储读取并设置值
        const savedCategory = localStorage.getItem(CATEGORY_KEY);
        if (savedCategory !== null) {
            categorySelect.value = savedCategory;
        }

        // 添加change事件监听器
        categorySelect.addEventListener('change', function () {
            localStorage.setItem(CATEGORY_KEY, this.value);
        });
    }
}

// 加载编辑模式下的规格数据
function loadEditSpecs() {
    if (QK_GOODS_CONFIG.isEditMode && QK_GOODS_CONFIG.savedSpecs && Object.keys(QK_GOODS_CONFIG.savedSpecs).length > 0) {
        try {
            const savedSpecs = QK_GOODS_CONFIG.savedSpecs;
            const specKeys = Object.keys(savedSpecs);
            if (specKeys.length > 0) {
                const specsInput = document.getElementById('specs-input');
                if (specsInput) {
                    specsInput.placeholder = '';
                }

                // 清空并重新创建隐藏的规格输入字段（PHP已经渲染了可见的按钮）
                const specsContainer = document.getElementById('specs-container');
                if (specsContainer) {
                    specsContainer.innerHTML = '';

                    specKeys.forEach(function (key, index) {
                        const specCount = index + 1;
                        const spec = savedSpecs[key];

                        const hiddenSpecItem = document.createElement('div');
                        hiddenSpecItem.className = 'spec-item';
                        hiddenSpecItem.style.display = 'none';

                        hiddenSpecItem.innerHTML = `
                        <input type="hidden" name="specs[${specCount}][name]" value="${spec.name || ''}">
                        <input type="hidden" name="specs[${specCount}][price]" value="${spec.price || ''}">
                        <input type="hidden" name="specs[${specCount}][stock]" value="${spec.stock || ''}">
                        <input type="hidden" name="specs[${specCount}][image]" value="${spec.image || ''}">
                    `;
                        specsContainer.appendChild(hiddenSpecItem);
                    });
                }
            }
        } catch (e) {
            console.error('加载规格数据失败', e);
        }
    }
}

// 加载编辑模式下的绑定商品数据
function loadBoundGoods() {
    const parentIdInput = document.getElementById('parent_id');
    if (!parentIdInput) return;

    const currentParentId = parentIdInput.value;
    if (currentParentId && currentParentId !== '0' && currentParentId !== '') {
        const parentIds = currentParentId.split(',').filter(id => id.trim() !== '');
        if (parentIds.length > 0) {
            // 批量获取商品信息，只发送一次请求
            const xhr = new XMLHttpRequest();
            xhr.open('GET', QK_GOODS_CONFIG.urls.getGoodsInfo + '&ids=' + parentIds.join(','), true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        if (data && data.success && data.data) {
                            const goodsData = {};
                            data.data.forEach(function (good) {
                                goodsData[good.id] = {
                                    title: good.title,
                                    image: good.image || ''
                                };
                            });
                            const goodsTitles = parentIds.map(id => goodsData[id]?.title || '未知商品');
                            const goodsImages = parentIds.map(id => goodsData[id]?.image || '');
                            renderGoodsButtons(parentIds, goodsTitles, goodsImages);
                        }
                    } catch (e) {
                        console.error('加载绑定商品数据失败', e);
                    }
                }
            };
            xhr.send();
        }
    }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function () {
    // 判断当前页面类型
    const isListPage = document.getElementById('batch-operation-btn') !== null;
    const isFormPage = document.getElementById('goods-form') !== null;

    if (isListPage) {
        // 初始化 HeaderPagination
        if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.state.page = QK_GOODS_CONFIG.pagination.currentPage;
            HeaderPagination.state.pageSize = QK_GOODS_CONFIG.pagination.pageSize;
            HeaderPagination.state.total = QK_GOODS_CONFIG.pagination.totalGoods;
            HeaderPagination.state.totalPages = QK_GOODS_CONFIG.pagination.totalPages;

            HeaderPagination.cache.page = QK_GOODS_CONFIG.pagination.currentPage;
            HeaderPagination.cache.pageSize = QK_GOODS_CONFIG.pagination.pageSize;
            HeaderPagination.cache.totalPages = QK_GOODS_CONFIG.pagination.totalPages;

            HeaderPagination.init();
            HeaderPagination.updateUI();
        }

        initBatchOperations();
        setTimeout(function () {
            if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && typeof initCustomScrollbar === 'function') {
                initCustomScrollbar();
            }
        }, 500);
    } else if (isFormPage) {
        // 商品发布/编辑页面
        initEditor();
        initGallery();
        initCategoryStorage();
        initFeatureItemHover();
        initThumbnailClickEvents();

        // 加载编辑模式下的数据
        loadEditSpecs();
        loadBoundGoods();

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

        // 绑定商品选择
        const selectParentGoodsBtn = document.getElementById('select_parent_goods');
        const goodsSelectModal = document.getElementById('goods_select_modal');
        if (selectParentGoodsBtn && goodsSelectModal) {
            selectParentGoodsBtn.addEventListener('click', function () {
                const currentGoods = document.getElementById('goods-tags-area').querySelectorAll('.feature-item').length;
                if (currentGoods >= 6) {
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.maxBoundGoods, 'error');
                    }
                    return;
                }
                goodsSelectModal.style.display = 'flex';
                setTimeout(() => {
                    goodsSelectModal.classList.add('modal-visible');
                }, 10);
                loadGoodsList(''); // 自动加载商品列表
            });
        }

        // 绑定商品弹窗关闭
        const goodsModalClose = document.querySelector('#goods_select_modal .modal-close');
        if (goodsModalClose) {
            goodsModalClose.addEventListener('click', closeGoodsSelectModal);
        }

        // 绑定搜索按钮
        const goodsSearchBtn = document.querySelector('#goods_select_modal .btn-primary');
        const goodsSearchInput = document.getElementById('goods_search');
        if (goodsSearchBtn) {
            goodsSearchBtn.addEventListener('click', function () {
                if (goodsSearchInput) {
                    loadGoodsList(goodsSearchInput.value);
                }
            });
        }

        // 绑定搜索框回车事件
        if (goodsSearchInput) {
            goodsSearchInput.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    loadGoodsList(this.value);
                }
            });
        }
    }
});

// 绑定事件监听器
function bindEventListeners() {
    function getGoodsAddUrl() {
        return '?tab=adgoods&add';
    }

    function extractGoodsIdFromResponse(data) {
        if (!data) return '';
        if (data.goods_id !== undefined && data.goods_id !== null) return String(data.goods_id);
        if (data.data && data.data.goods_id !== undefined && data.data.goods_id !== null) return String(data.data.goods_id);
        return '';
    }

    // 商品缩略图区域
    const galleryAddBtn = document.getElementById('gallery-add-btn');
    if (galleryAddBtn) {
        galleryAddBtn.addEventListener('click', function () {
            if (document.querySelectorAll('#gallery-preview-new .feature-item').length >= 6) {
                showToast(QK_GOODS_CONFIG.messages.maxUploadImages, 'error');
            } else {
                const galleryInput = document.getElementById('gallery');
                if (galleryInput) {
                    galleryInput.click();
                }
            }
        });
    }

    // 绑定其他商品区域
    const goodsAddBtn = document.querySelector('#goods-tags-area .add-item-btn');
    if (goodsAddBtn) {
        goodsAddBtn.addEventListener('click', function () {
            if (document.querySelectorAll('#goods-tags-area .feature-item').length >= 6) {
                showToast(QK_GOODS_CONFIG.messages.maxBoundGoods, 'error');
            } else {
                const selectParentGoods = document.getElementById('select_parent_goods');
                if (selectParentGoods) {
                    selectParentGoods.click();
                }
            }
        });
    }

    // 规格属性区域
    const specAddBtn = document.querySelector('#specs-tags-area .add-item-btn');
    if (specAddBtn) {
        specAddBtn.addEventListener('click', function () {
            if (document.querySelectorAll('#specs-tags-area .feature-item').length >= 6) {
                showToast(QK_GOODS_CONFIG.messages.maxSpecs, 'error');
            } else {
                const specModal = document.getElementById('spec-modal');
                if (specModal) {
                    // 加载现有规格到模态框
                    loadSpecsToModal();

                    specModal.style.display = 'flex';
                    setTimeout(() => {
                        specModal.classList.add('modal-visible');
                    }, 10);
                }
            }
        });
    }

    // 绑定商品弹窗
    const goodsModalClose = document.querySelector('#goods_select_modal .modal-close');
    const goodsSearchInputModal = document.getElementById('goods_search');
    if (goodsModalClose) {
        goodsModalClose.addEventListener('click', closeGoodsSelectModal);
    }
    const goodsSearchBtn = document.querySelector('#goods_select_modal .btn-primary');
    if (goodsSearchBtn) {
        goodsSearchBtn.addEventListener('click', function () {
            if (goodsSearchInputModal) {
                loadGoodsList(goodsSearchInputModal.value);
            }
        });
    }
    if (goodsSearchInputModal) {
        goodsSearchInputModal.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                loadGoodsList(this.value);
            }
        });
    }

    // 规格弹窗
    const specModalClose = document.querySelector('#spec-modal .modal-close');
    if (specModalClose) {
        specModalClose.addEventListener('click', closeSpecModal);
    }
    const specAddItemBtn = document.querySelector('#spec-modal .btn-primary:nth-child(1)');
    if (specAddItemBtn) {
        specAddItemBtn.addEventListener('click', addSpecItem);
    }
    const specSaveBtn = document.querySelector('#spec-modal .btn-primary:nth-child(2)');
    if (specSaveBtn) {
        specSaveBtn.addEventListener('click', saveAllSpecs);
    }

    // 视频弹窗
    const videoModalClose = document.querySelector('#videoInsertModal .modal-close');
    if (videoModalClose) {
        videoModalClose.addEventListener('click', closeVideoInsertModal);
    }
    const videoCancelBtn = document.querySelector('#videoInsertModal .btn-secondary');
    if (videoCancelBtn) {
        videoCancelBtn.addEventListener('click', closeVideoInsertModal);
    }
    const videoDeleteBtn = document.querySelector('#videoInsertModal .btn-danger');
    if (videoDeleteBtn) {
        videoDeleteBtn.addEventListener('click', deleteVideo);
    }
    const videoConfirmBtn = document.querySelector('#videoInsertModal .btn-primary');
    if (videoConfirmBtn) {
        videoConfirmBtn.addEventListener('click', confirmVideoInsert);
    }

    // 预览和取消按钮
    const previewBtn = document.getElementById('preview-button');
    if (previewBtn) {
        previewBtn.addEventListener('click', previewGoods);
    }
    const cancelBtn = document.getElementById('cancel-button');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', function () {
            window.location.href = QK_GOODS_CONFIG.urls.list;
        });
    }
    const continuePublishBtn = document.getElementById('continue-publish-button');
    if (continuePublishBtn) {
        continuePublishBtn.addEventListener('click', function () {
            window.location.href = getGoodsAddUrl();
        });
    }

    // 商品表单提交处理
    const goodsForm = document.getElementById('goods-form');
    if (goodsForm) {
        goodsForm.addEventListener('submit', function (e) {
            e.preventDefault();

            // 更新富文本内容到隐藏文本域
            if (window.quillInstance) {
                document.getElementById('content').value = window.quillInstance.root.innerHTML;
            }

            const formData = new FormData(this);
            const submitBtn = document.getElementById('submit-button');
            const originalBtnText = submitBtn.textContent;

            // 禁用提交按钮，防止重复提交
            submitBtn.disabled = true;
            submitBtn.textContent = QK_GOODS_CONFIG.messages.submitInProgress;

            // 获取提交的action按钮名称
            const action = submitBtn.name;
            formData.append(action, '1');

            fetch(QK_GOODS_CONFIG.urls.updateGoods, {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (typeof showToast === 'function') {
                            showToast(data.message || QK_GOODS_CONFIG.messages.operationSuccess, 'success');
                        }
                        submitBtn.disabled = false;
                        if (action === 'publish_goods') {
                            const newGoodsId = extractGoodsIdFromResponse(data);
                            if (newGoodsId && /^\d+$/.test(newGoodsId)) {
                                let goodsIdInput = document.getElementById('goods_id');
                                if (!goodsIdInput) {
                                    goodsIdInput = document.createElement('input');
                                    goodsIdInput.type = 'hidden';
                                    goodsIdInput.id = 'goods_id';
                                    goodsIdInput.name = 'goods_id';
                                    goodsForm.appendChild(goodsIdInput);
                                }
                                goodsIdInput.value = newGoodsId;

                                const formModeInput = document.getElementById('form_mode');
                                if (formModeInput) {
                                    formModeInput.value = 'edit';
                                }

                                submitBtn.textContent = '更新商品';
                                submitBtn.name = 'update_goods';
                                window.isEditMode = true;

                                const newUrl = QK_GOODS_CONFIG.urls.edit + newGoodsId;
                                if (window.history && typeof window.history.replaceState === 'function') {
                                    window.history.replaceState({ goodsId: newGoodsId, mode: 'edit', publishedJustNow: true }, '', newUrl);
                                }

                                if (continuePublishBtn) {
                                    continuePublishBtn.style.display = '';
                                }
                            } else {
                                submitBtn.textContent = originalBtnText;
                            }
                        } else {
                            submitBtn.textContent = originalBtnText;
                        }
                    } else {
                        if (typeof showToast === 'function') {
                            showToast(data.message || QK_GOODS_CONFIG.messages.operationFail, 'error');
                        }
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalBtnText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    if (typeof showToast === 'function') {
                        showToast(QK_GOODS_CONFIG.messages.submitFailRetry, 'error');
                    }
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalBtnText;
                });
        });
    }

    // 动态添加的删除按钮
    document.addEventListener('click', function (e) {
        // 缩略图删除
        if (e.target.closest('.feature-item[data-image-url] .delete-btn')) {
            const deleteBtn = e.target.closest('.delete-btn');
            deleteThumbnailNew(deleteBtn);
        }

        // 绑定商品删除
        if (e.target.closest('#goods-tags-area .feature-item .delete-btn')) {
            const deleteBtn = e.target.closest('.delete-btn');
            const goodsId = deleteBtn.closest('.feature-item').dataset.goodsId;
            deleteGoodsItemNew(goodsId, e);
        }

        // 规格删除
        if (e.target.closest('#specs-tags-area .feature-item .delete-btn')) {
            const deleteBtn = e.target.closest('.delete-btn');
            const specNumber = deleteBtn.closest('.feature-item').dataset.specNumber;
            deleteSpecItemNew(specNumber);
        }

        // 规格项删除
        if (e.target.closest('button') && e.target.closest('button').textContent.trim() === '删除') {
            const button = e.target.closest('button');
            const specItem = button.closest('.spec-modal-item');
            if (specItem && specItem.closest('#spec-items-container')) {
                removeSpecItem(button);
            }
        }

        // 编辑按钮点击
        if (e.target.closest('.edit-goods-btn')) {
            const btn = e.target.closest('.edit-goods-btn');
            const goodsId = btn.getAttribute('data-id');
            if (goodsId) {
                window.location.href = QK_GOODS_CONFIG.urls.edit + goodsId;
            }
        }
    });
}

// 在DOM加载完成后绑定事件监听器
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bindEventListeners);
} else {
    bindEventListeners();
}

// 暴露全局函数
window.deleteGoodsItem = deleteGoodsItem;
window.editGoodsTitle = editGoodsTitle;
window.saveGoodsTitle = saveGoodsTitle;
window.cancelEditGoodsTitle = cancelEditGoodsTitle;
window.editGoodsPrice = editGoodsPrice;
window.saveGoodsPrice = saveGoodsPrice;
window.cancelEditGoodsPrice = cancelEditGoodsPrice;
window.editGoodsStock = editGoodsStock;
window.saveGoodsStock = saveGoodsStock;
window.cancelEditGoodsStock = cancelEditGoodsStock;
window.editGoodsSales = editGoodsSales;
window.saveGoodsSales = saveGoodsSales;
window.cancelEditGoodsSales = cancelEditGoodsSales;
window.updateGoodsCategory = updateGoodsCategory;
window.updateGoodsStatus = updateGoodsStatus;
window.replaceListThumbnail = replaceListThumbnail;
