// product/ozon-export.js
// 从 product/ozon.js 拆出 — 数据导出弹窗模块
//
// 包含：
//   showDataExportModal / initializeDataTable / createDataRow / bindModalEvents
//   applyFilters / clearFilters / selectAllRows / selectNoneRows
//   updateSelectedCount / updateVisibleCount / updateHeaderCheckboxState
//   exportSelectedData / exportAllData / exportDataToExcel / copyDataToClipboard
//   logisticsTiers / exportExcel
//   calcLogisticsFee（供 ozon.js 和 ozon-profit.js 共用的物流费计算）
//
// 加载顺序要求（manifest.json content_scripts.js）：
//   ... ozon-templates.js → ozon-api.js → ozon-export.js → ozon-profit.js → ozon.js
//
// 依赖的全局变量（由 ozon-api.js 或 ozon.js 提供）：
//   whCache, CNY2RUB, SKUDATA, SKUDATA_pic, imagePreviewHtml,
//   buildOzonDataExportModalHtml, rscwevrr, tiddp, getCNY2RUBRate,
//   processMultipleSkus, updateProfitCell, updateVisibleSkus, visibleSkus,
//   loadOzonLogisticsGroups, loadOzonShops, bindSkuImagePreview,
//   applyPriceAdjustment, batchGetWeight, batchFollowSell, priceAdjustCount

// 数据导出弹窗功能
async function showDataExportModal() {
    // 移除已存在的弹窗
    $('#ozon-data-export-modal').remove();
    
    // 新增：汇率展示区域
    let rateHtml = `<div id="cny2rub-rate-info" style="position:absolute;right:60px;top:18px;color:#ffffff;font-size:13px;font-weight:600;z-index:2;">汇率加载中...</div>`;
    
    const modalHtml = buildOzonDataExportModalHtml(rateHtml);
    
    $('body').append(modalHtml);
    
    // 新增：弹窗打开时获取汇率并展示
    getCNY2RUBRate().then(rate => {
        $('#cny2rub-rate-info').text(`当前汇率：1 CNY = ${rate} RUB`);
    });
    
    // 初始化数据
    initializeDataTable();
    
    // 绑定事件
    bindModalEvents();
    
    // 初始化物流分组和物流方式
    // 使用唯一名称的函数，避免与adtnfosku.js冲突
    try {
        // 直接调用函数，因为函数声明会被提升到作用域顶部
        await loadOzonLogisticsGroups();
        // 加载店铺数据
        await loadOzonShops();
    } catch (error) {
        console.error('初始化物流分组和物流方式失败:', error);
    }
}

// 初始化数据表格
function initializeDataTable() {
    const tableBody = $('#data-table-body');
    tableBody.empty();
    
    // 添加图片预览弹窗
    if (!$('#sku-image-modal').length) {
        $('body').append(imagePreviewHtml);
    }
    
    // 获取当前物流方式
    const whTypeStr = '无';
	const logisticsType = $('#logistics-type').val() || 'E邮宝';
	console.log()
    let rowCount = 0;
    $.each(SKUDATA_pic, function (sku, picData) {
        // 确保sku是字符串类型
        const skuStr = String(sku);
        
        // 确保SKUDATA[skuStr]存在
        if (!SKUDATA[skuStr]) {
            SKUDATA[skuStr] = {};
        }
		
        
        const skuData = SKUDATA[skuStr]
        const hasData = skuData && skuData !== 1;
        
        // 添加所有行，即使没有完整数据，也显示基本信息
        const row = createDataRow(skuStr, picData, skuData, hasData, whTypeStr);
        tableBody.append(row);
        rowCount++;
    });
    
    $('#total-count').text(rowCount);
    updateSelectedCount();
    updateHeaderCheckboxState();
    
    // 绑定SKU单元格的鼠标事件
    bindSkuImagePreview();
    
    // 为表格行添加鼠标悬停事件
    $('#data-table-body tr').hover(
        function() {
            $(this).css('background-color', 'rgba(58, 90, 138, 0.1)');
        },
        function() {
            $(this).css('background-color', 'transparent');
        }
    );
    
    updateVisibleSkus();
    $(document).trigger('tableContentChanged');
    
    // 收集所有SKU并发送多个第一个API请求
    const collectedSkus = Object.keys(SKUDATA_pic);
    if (collectedSkus.length > 0) {
        console.log('收集到的SKU数量:', collectedSkus.length);
        console.log('收集到的SKU列表:', collectedSkus);
        // 处理多个SKU的API请求
        processMultipleSkus(collectedSkus);
        
        // 自动计算已有重量的SKU的利润
        setTimeout(async () => {
            console.log('开始自动计算已有重量的SKU的利润');
            let calculatedCount = 0;
            collectedSkus.forEach(async (sku) => {
                const skuData = SKUDATA[sku];
                if (skuData && skuData.zwews && skuData.zwews !== '点击获取' && skuData.zwews !== '无') {
                    await updateProfitCell(sku);
                    calculatedCount++;
                }
            });
            console.log(`自动计算完成，共计算了 ${calculatedCount} 个SKU的利润`);
        }, 1000);
    } else {
        console.log('未收集到SKU数据');
    }
}

// 创建数据行
function createDataRow(sku, picData, skuData, hasData, whTypeStr) {

    const productName = picData[3] || '无';
    const price = picData[0] || '无';
    const rating = picData[4] || '无';
    const pic = (skuData.photo && typeof skuData.photo === 'string' && skuData.photo.startsWith('http')) ? skuData.photo : '';
    const soldCount = hasData ? (skuData.soldCount || '无') : '无';
    const soldSum = hasData ? (skuData.soldSum ? `${skuData.soldSum} ₽` : '无') : '无';
    const brand = hasData ? (skuData.brand || '无') : '无';
    const shipping = hasData ? (skuData.salesSchema || '无') : '无';
    
    // 获取重量数据
    let weight = '点击获取';
    if (hasData && skuData.zwews) {
        // 检查 skuData.zwews 是否已经包含单位
        const weightStr = String(skuData.zwews);
        if (weightStr.includes('g') || weightStr.includes('kg') || weightStr.includes('гр') || weightStr.includes('кг')) {
            weight = weightStr;
        } else {
            weight = `${weightStr} g`;
        }
    }
    
    // 确保SKUDATA[sku].zwews存在
    if (weight !== '点击获取' && weight !== '无') {
        // 存储原始重量值，不包含单位
        SKUDATA[sku].zwews = skuData.zwews;
    }
    
    const convToCart = hasData ? (skuData.convToCartPdp || '无') : '无';
    // 直接显示取到的跟卖最低价格原始值（纯数字加 ₽ 单位）
    let minSellerPrice = '无';
    if (hasData && skuData.minSellerPrice != null && skuData.minSellerPrice !== '') {
        if (typeof skuData.minSellerPrice === 'object') {
            // 尝试从对象中提取价格（如 price.cardPrice.price）
            const nested = skuData.minSellerPrice.price || skuData.minSellerPrice.value || skuData.minSellerPrice.cardPrice?.price;
            minSellerPrice = nested != null ? String(nested) : '无';
        } else {
            const str = String(skuData.minSellerPrice);
            // 如果已含货币符号直接显示，否则加 ₽
            minSellerPrice = /[¥₽$€]/.test(str) ? str : str + ' ₽';
        }
    }
    const cost = (skuData && typeof skuData.cost !== 'undefined' && skuData.cost !== '') ? parseFloat(skuData.cost) : 0;
    const priceNum = parseFloat(picData[0]) || 0;
    let displayPrice = (picData && picData[0] != null && String(picData[0]).trim() !== '') ? picData[0] : ((skuData && skuData._originPrice) || 0);
    // 确保价格输入框的值是有效数字，避免非数字字符串导致输入框显示为空
    const parsedDisplayPrice = parseFloat(displayPrice);
    displayPrice = (!isNaN(parsedDisplayPrice) && isFinite(parsedDisplayPrice)) ? parsedDisplayPrice : 0;
    // 出售时间（原始日期字符串）
    let sellTime = '无';
    if (hasData && skuData.nullableCreateDate) {
        sellTime = skuData.nullableCreateDate;
    } else if (hasData && skuData.pCreateDate && skuData.pCreateDate !== '未知') {
        sellTime = skuData.pCreateDate;
    }
    // 物流费
    const logisticsInfo = calcLogisticsFee({price: picData[0] || 0, weight: hasData ? (skuData.zwews || '点击获取') : '点击获取', type: whTypeStr});
	const logisticsFee = parseFloat(logisticsInfo.fee) || 0;
    // 佣金 - 使用动态佣金比例
    const commissionRate = parseFloat($('#commission-rate').val()) || 20;
    const commission = priceNum * (commissionRate / 100);
    // 打包费 - 使用动态打包费
    const packingFeeInput = $('#packing-fee').val();
    const packingFee = packingFeeInput !== '' ? parseFloat(packingFeeInput) : 5;
    
    // 利润
    let profit = priceNum - cost - commission - logisticsFee - packingFee;
    let profitRate = priceNum > 0 ? (profit / priceNum) * 100 : 0;
    // 确保利润和利润率不是NaN
    profit = isNaN(profit) ? 0 : profit;
    profitRate = isNaN(profitRate) ? 0 : profitRate;
    // 显示格式
    let profitStr = priceNum > 0 ? `${profit.toFixed(2)} | ${profitRate.toFixed(1)}%` : '0 | 0%';

	const weightCell = weight === '点击获取' ? 
        `<span data-sku="${sku}" class="getacewewce" style="cursor: pointer; color: #1e88e5 !important; font-weight: 600;">点击获取</span>` : 
        weight;
    return `
        <tr data-sku="${sku}" data-has-data="${hasData}" style="
            border-bottom: 1px solid #eaeaea;
            transition: background-color 0.2s;
        ">
            <td style="padding: 6px; text-align: center;">
                <input type="checkbox" class="row-checkbox" style="margin: 0; transform: scale(1.2);">
            </td>
			
            <td class="sku-cell" data-sku="${sku}" style="
                padding: 6px;
                font-family: monospace;
                font-size: 13px;
                font-weight: 600;
                cursor: pointer;
                position: relative;
				display:flex;
				align-items: center;
				justify-content: center;
            ">
			${pic ? `<img src="${pic}" class="sku-thumbnail" data-sku="${sku}" style="width: 32px; height: 32px; object-fit: cover; border-radius: 4px; margin-right: 8px; cursor: pointer; border: 1px solid #eaeaea; flex-shrink:0;" onerror="this.style.display='none'">` : ''}
			<span style="color:#1e88e5; font-weight:600;">${sku}</span>
			<a href="https://www.ozon.ru/product/${sku}" target="_blank" style="color:#1e88e5; text-decoration:none; margin-left:6px; font-size:12px; white-space:nowrap;">查看</a>
			</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">
                <input type="number" class="price-input" data-sku="${sku}" id="price-input-${sku}" value="${displayPrice}" min="0" step="0.01" style="width: 70px; background: #ffffff; border: 1px solid #eaeaea; border-radius: 4px; padding: 2px 4px; font-size: 13px;">
            </td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">
                <span class="seller-count-cell" data-sku="${sku}" style="cursor: pointer; color: #1e88e5; font-weight: 600;">点击获取</span>
            </td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${minSellerPrice}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${weightCell}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 300;" id="fee-cell-${sku}" title="${logisticsInfo.tierName ? logisticsInfo.formulaStr : ''}">${logisticsInfo.fee}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">
                <input type="number" class="cost-input" data-sku="${sku}" id="cost-input-${sku}" value="0" min="0" step="0.01" style="width: 70px; background: #ffffff; border: 1px solid #eaeaea; border-radius: 4px; padding: 2px 4px; font-size: 13px;">
            </td>
            <td style="padding: 6px; color: #1e88e5; font-size: 13px; font-weight: 700;"> <span class="profit-cell" id="profit-cell-${sku}">${profitStr}</span> </td>
            <td style="padding: 6px; font-size: 13px; font-weight: 700;"> <span class="profit-cell" id="whType-cell-${sku}">${whTypeStr}</span> </td>
			<td style="padding: 6px; font-size: 13px; font-weight: 500;">${rating}</td>
			<td style="padding: 6px; font-size: 13px; font-weight: 500;">${soldCount}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${soldSum}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${sellTime}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${brand}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${shipping}</td>
            <td style="padding: 6px; font-size: 13px; font-weight: 500;">${convToCart}</td>
        </tr>
    `;
}

// 绑定弹窗事件
function bindModalEvents() {
    // 关闭弹窗
    $('#close-export-modal').click(() => {
        $('#ozon-data-export-modal').remove();
    });
    
    // 点击背景关闭
    $('#ozon-data-export-modal').click((e) => {
        if (e.target.id === 'ozon-data-export-modal') {
            $('#ozon-data-export-modal').remove();
        }
    });
    
    // 应用过滤
    $('#apply-filters').click(applyFilters);
    
    // 清除过滤
    $('#clear-filters').click(clearFilters);
    
    // 全选/取消全选
    $('#select-all').click(selectAllRows);
    $('#select-none').click(selectNoneRows);
    
    // 表头复选框
    $('#header-checkbox').change(function() {
        const isChecked = $(this).prop('checked');
        $('#data-table-body tr:visible .row-checkbox').prop('checked', isChecked);
        updateSelectedCount();
    });
    
    // 行复选框
    $(document).on('change', '.row-checkbox', function() {
        updateSelectedCount();
        updateHeaderCheckboxState();
    });
    
    // 导出功能
    $('#export-selected-excel').click(() => exportSelectedData('excel'));
    $('#copy-selected').click(() => exportSelectedData('copy'));
    $('#export-all-excel').click(() => exportAllData());
    
    // 价格调整功能
    $('#apply-price-adjust').click(applyPriceAdjustment);
    
    // 批量获取重量功能
    $('#batch-get-weight').click(batchGetWeight);
    
    // 批量获取跟卖数据功能
    $('#batch-get-seller-offers').click(batchGetSellerOffers);
    
    // 一键跟卖功能
    $('#batch-follow-sell').click(batchFollowSell);

    // 保存导出数据
    $('#save-export-data').click(function() {
        try {
            const dataToSave = {
                SKUDATA: SKUDATA,
                SKUDATA_pic: SKUDATA_pic,
                savedAt: new Date().toISOString()
            };
            chrome.storage.local.set({ ozon_export_data: dataToSave }, function() {
                tiddp('数据已保存到本地');
            });
        } catch (e) {
            console.error('保存失败:', e);
            tiddp('保存失败');
        }
    });

    // 删除选中SKU
    $('#delete-selected-skus').click(function() {
        const checkedRows = $('#data-table-body tr:visible .row-checkbox:checked').closest('tr');
        if (checkedRows.length === 0) {
            tiddp('请先勾选要删除的SKU');
            return;
        }
        checkedRows.each(function() {
            const sku = $(this).attr('data-sku');
            $(this).remove();
            if (SKUDATA) delete SKUDATA[sku];
            if (SKUDATA_pic) delete SKUDATA_pic[sku];
        });
        updateSelectedCount();
        updateVisibleCount();
        tiddp('已删除 ' + checkedRows.length + ' 个选中SKU');
    });

    // 在批量调价输入框后面加单位
    $('#price-adjust-type').on('change', function() {
        var type = $(this).val();
        if(type === 'percentage') {
            $('#price-adjust-unit').text('%');
        } else {
            $('#price-adjust-unit').text('元');
        }
    });

    // 恢复原价按钮事件（只针对勾选行）
    $('#restore-origin-price').click(function() {
        $('#data-table-body tr:visible .row-checkbox:checked').closest('tr').each(function() {
            const row = $(this);
            const sku = row.attr('data-sku');
            const picData = SKUDATA_pic[sku];
            const skuData = SKUDATA[sku];
            if (picData && skuData) {
                if (typeof skuData._originPrice !== 'undefined') {
                    picData[0] = skuData._originPrice;
                    skuData.price = skuData._originPrice;
                    row.find('.price-input').val(skuData._originPrice);
                }
                updateProfitCell(sku);
            }
        });
        priceAdjustCount = 0;
        tiddp('已恢复选中商品的原价');
    });
    
    // SKU缩略图悬浮显示大图
    $(document).on('mouseenter', '.sku-thumbnail', function(e) {
        const src = $(this).attr('src');
        let tooltip = $('#sku-image-tooltip');
        if (tooltip.length === 0) {
            tooltip = $('<div id="sku-image-tooltip" style="position: fixed; z-index: 1000000000; background: #fff; border: 1px solid #eaeaea; border-radius: 8px; padding: 4px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: none; pointer-events: none;"><img style="max-width: 300px; max-height: 300px; border-radius: 4px; display: block;"></div>');
            $('body').append(tooltip);
        }
        tooltip.find('img').attr('src', src);
        tooltip.css({left: e.clientX + 15, top: e.clientY + 15}).show();
    }).on('mouseleave', '.sku-thumbnail', function() {
        $('#sku-image-tooltip').hide();
    }).on('mousemove', '.sku-thumbnail', function(e) {
        $('#sku-image-tooltip').css({left: e.clientX + 15, top: e.clientY + 15});
    });
    
    // 查看跟卖记录点击事件
    $(document).on('click', '.seller-count-cell', function() {
        const sku = $(this).attr('data-sku');
        const skuData = SKUDATA[sku];
        if (!skuData) return;
        const productId = skuData.productId || sku;
        showSellerOffersPopup(productId, sku);
    });
    
    // 添加复制按钮的鼠标悬停事件
    $('#copy-selected').hover(
        function() {
            $(this).css({
                'background': 'linear-gradient(90deg, #1a2980 0%, #26d0ce 100%)',
                'color': '#fff',
                'box-shadow': 'none'
            });
        },
        function() {
            $(this).css({
                'background': 'linear-gradient(90deg, #0f2027 0%, #2c5364 100%)',
                'color': '#1e88e5',
                'box-shadow': 'none'
            });
        }
    );
}

// 应用过滤条件
function applyFilters() {
    const minSales = parseInt(String($('#min-sales').val()).replace(/\s/g, '')) || 0;
    const maxSales = parseInt(String($('#max-sales').val()).replace(/\s/g, '')) || Infinity;
    const minPrice = parseFloat(String($('#min-price').val()).replace(/\s/g, '').replace(',', '.')) || 0;
    const maxPrice = parseFloat(String($('#max-price').val()).replace(/\s/g, '').replace(',', '.')) || Infinity;
    const brandFilter = $('#brand-filter').val();
    const shippingFilter = $('#shipping-filter').val();
    const minRating = parseFloat($('#min-rating').val()) || 0;
    const maxRating = parseFloat($('#max-rating').val()) || Infinity;
    const minConvToCart = parseFloat($('#min-conv-to-cart').val()) || 0;
    const maxConvToCart = parseFloat($('#max-conv-to-cart').val()) || Infinity;
	const minConvToProfit = parseFloat($('#min-conv-to-profit').val()) || 0;
	const maxConvToProfit = parseFloat($('#max-conv-to-profit').val()) || Infinity;
    const minWeight = parseFloat($('#min-weight').val()) || 0;
    const maxWeight = parseFloat($('#max-weight').val()) || Infinity;
    const minShelfDate = $('#min-shelf-date').val();
    const maxShelfDate = $('#max-shelf-date').val();
    
    $('#data-table-body tr').each(function() {
        const row = $(this);
        const sku = row.attr('data-sku');
        const hasData = row.attr('data-has-data') === 'true';
        const skuData = SKUDATA[sku];
        const picData = SKUDATA_pic[sku];
        console.log('==123123123=====')
        console.log(skuData)
        console.log('==123123123=====')
        let shouldShow = true;

        // 销量过滤
        if (hasData && skuData.soldCount) {
            const sales = parseInt(String(skuData.soldCount).replace(/\s/g, ''));
            if (sales < minSales || sales > maxSales) {
                shouldShow = false;
            }
        } else if (minSales > 0 || maxSales !== Infinity) {
            shouldShow = false;
        }
        
        // 价格过滤（修复：0价商品不被错误过滤）
        if (shouldShow && picData && typeof picData[0] !== 'undefined' && picData[0] !== '') {
            const price = parseFloat(String(picData[0]).replace(/\s/g, '').replace(',', '.'));
            if (!isNaN(price) && (price < minPrice || price > maxPrice)) {
                shouldShow = false;
            }
        } else if (shouldShow && (minPrice > 0 || maxPrice !== Infinity)) {
            shouldShow = false;
        }
        
        // 品牌过滤
        if (shouldShow && brandFilter && brandFilter !== 'all') {
            if (hasData && skuData.brand) {
                if (skuData.brand !== brandFilter) {
                    shouldShow = false;
                }
            }else {
                shouldShow = false;
            }
        }
        
        // 发货模式过滤
        if (shouldShow && shippingFilter !== 'all') {
            if (hasData && skuData.salesSchema) {
                if (skuData.salesSchema !== shippingFilter) {
                    shouldShow = false;
                }
            } else {
                shouldShow = false;
            }
        }
        
        // 星级过滤（修正：优先用picData[4]，否则用skuData.rating）
        if (shouldShow) {
            let rating = null;
            if (picData && picData[4] && !isNaN(parseFloat(picData[4]))) {
                rating = parseFloat(picData[4]);
            } else if (hasData && skuData.rating && !isNaN(parseFloat(skuData.rating))) {
                rating = parseFloat(skuData.rating);
            }
            if (rating !== null && (rating < minRating || rating > maxRating)) {
                shouldShow = false;
            } else if (rating === null && (minRating > 0 || maxRating !== Infinity)) {
                shouldShow = false;
            }
        }
        
        // 加购率过滤（修正：用skuData.convToCartPdp）
        if (shouldShow) {
            let convToCart = null;
            if (hasData && skuData.convToCartPdp && !isNaN(parseFloat(skuData.convToCartPdp))) {
                convToCart = parseFloat(skuData.convToCartPdp);
            }
            if (convToCart !== null && (convToCart < minConvToCart || convToCart > maxConvToCart)) {
                shouldShow = false;
            } else if (convToCart === null && (minConvToCart > 0 || maxConvToCart !== Infinity)) {
                shouldShow = false;
            }
        }
		
		// 利润率过滤（修正：用skuData.profitRate）
		if (shouldShow) {
		    let profitRate = null;
		    if (hasData && skuData.profitRate && !isNaN(parseFloat(skuData.profitRate))) {
		        profitRate = parseFloat(skuData.profitRate);
		    }
		    if (profitRate !== null && (profitRate < minConvToProfit || profitRate > maxConvToProfit)) {
		        shouldShow = false;
		    } else if (profitRate === null && (minConvToProfit > 0 || maxConvToProfit !== Infinity)) {
		        shouldShow = false;
		    }
		}
        
        // 重量过滤（修复：支持数字和字符串类型的重量）
        if (shouldShow) {
            let weight = null;
            if (hasData && skuData.zwews) {
                let wstr = String(skuData.zwews).replace(/\s/g, '').toLowerCase();
                if (wstr.includes('kg')) {
                    weight = parseFloat(wstr) * 1000;
                } else if (wstr.includes('g')) {
                    weight = parseFloat(wstr);
                } else if (!isNaN(parseFloat(wstr))) {
                    weight = parseFloat(wstr);
                }
            }
            if (weight !== null && (weight < minWeight || weight > maxWeight)) {
                shouldShow = false;
            } else if (weight === null && (minWeight > 0 || maxWeight !== Infinity)) {
                shouldShow = false;
            }
        }
        
        // 出售时间过滤
        if (shouldShow && (minShelfDate || maxShelfDate)) {
            let sellDate = null;
            if (hasData && skuData.nullableCreateDate) {
                sellDate = new Date(skuData.nullableCreateDate);
            } else if (hasData && skuData.pCreateDate && skuData.pCreateDate !== '未知') {
                sellDate = new Date(skuData.pCreateDate);
            }
            if (sellDate && !isNaN(sellDate.getTime())) {
                if (minShelfDate) {
                    const minDate = new Date(minShelfDate);
                    if (sellDate < minDate) shouldShow = false;
                }
                if (maxShelfDate && shouldShow) {
                    const maxDate = new Date(maxShelfDate);
                    maxDate.setHours(23, 59, 59, 999);
                    if (sellDate > maxDate) shouldShow = false;
                }
            } else {
                shouldShow = false;
            }
        }

        row.toggle(shouldShow);
    });
    
    updateVisibleCount();
    updateSelectedCount();
    updateHeaderCheckboxState();
    updateVisibleSkus();
    $(document).trigger('tableContentChanged');
}

// 清除过滤条件
function clearFilters() {
    $('#min-sales, #max-sales, #min-price, #max-price, #min-rating, #max-rating, #min-conv-to-cart, #max-conv-to-cart,#min-conv-to-profit, #max-conv-to-profit, #min-weight, #max-weight, #min-shelf-date, #max-shelf-date').val('');
    $('#brand-filter').val('all');
    $('#shipping-filter').val('all');
    $('#price-adjust-value').val('');
    $('#data-table-body tr').show();
    updateVisibleCount();
    updateSelectedCount();
    updateHeaderCheckboxState();
    applyFilters(); //重新应用默认过滤
    updateVisibleSkus();
    $(document).trigger('tableContentChanged');
}

// 全选
function selectAllRows() {
    $('#data-table-body tr:visible .row-checkbox').prop('checked', true);
    updateSelectedCount();
    updateHeaderCheckboxState();
}

// 取消全选
function selectNoneRows() {
    $('.row-checkbox').prop('checked', false);
    updateSelectedCount();
    updateHeaderCheckboxState();
}

// 更新选中数量 - 只统计可见行的选中状态
function updateSelectedCount() {
    const selectedCount = $('#data-table-body tr:visible .row-checkbox:checked').length;
    $('#selected-count').text(selectedCount);
}

// 更新可见数量
function updateVisibleCount() {
    const visibleCount = $('#data-table-body tr:visible').length;
    $('#total-count').text(visibleCount);
}

// 更新表头复选框状态
function updateHeaderCheckboxState() {
    const visibleCheckboxes = $('#data-table-body tr:visible .row-checkbox');
    const checkedVisibleCheckboxes = visibleCheckboxes.filter(':checked');
    
    if (visibleCheckboxes.length === 0) {
        $('#header-checkbox').prop('indeterminate', false).prop('checked', false);
    } else if (checkedVisibleCheckboxes.length === 0) {
        $('#header-checkbox').prop('indeterminate', false).prop('checked', false);
    } else if (checkedVisibleCheckboxes.length === visibleCheckboxes.length) {
        $('#header-checkbox').prop('indeterminate', false).prop('checked', true);
    } else {
        $('#header-checkbox').prop('indeterminate', true).prop('checked', false);
    }
}

// 导出选中数据 - 只导出可见行的选中数据
function exportSelectedData(type) {
    console.log('exportSelectedData被调用，类型:', type);
    
    const selectedSkus = [];
    $('#data-table-body tr:visible .row-checkbox:checked').each(function() {
        const sku = $(this).closest('tr').attr('data-sku');
        selectedSkus.push(sku);
    });
    
    console.log('选中的SKU（仅可见行）:', selectedSkus);
    
    if (selectedSkus.length === 0) {
        tiddp('请先选择要导出的数据');
        return;
    }
    
    if (type === 'excel') {
        console.log('开始导出选中数据到Excel');
        exportDataToExcel(selectedSkus, '选中数据');
    } else if (type === 'copy') {
        console.log('开始复制选中数据');
        copyDataToClipboard(selectedSkus);
    }
}

// 导出全部数据
function exportAllData() {
    console.log('exportAllData被调用');
    
    // 只获取有数据的SKU
    const validSkus = [];
    $.each(SKUDATA_pic, function (sku, picData) {
        const skuData = SKUDATA[sku];
        const hasData = skuData && skuData !== 1;
        
        if (hasData) {
            validSkus.push(sku);
        }
    });
    
    console.log('有效SKU数量:', validSkus.length);
    
    if (validSkus.length === 0) {
        tiddp('没有有效数据可导出');
        return;
    }
    
    exportDataToExcel(validSkus, '全部数据');
}

// 导出数据到Excel
function exportDataToExcel(skus, filename) {
    console.log('开始导出数据，SKU数量:', skus.length);
    
    const headers = ["sku","商家id","30天销量","30天销售额","价格","划线价","促销比例","sku,卖价","产品名称","星级","品牌","一级类目","三级类目","30天销售变化","平均售价","最低售价","加购率","浏览量","体积/公斤","发货模式","重量","配送天数","库存","出售时间"];
    
    console.log('导出列名:', headers);
    
    const data = skus.map(sku => {
        const picData = SKUDATA_pic[sku];
        const skuData = SKUDATA[sku];
        
        console.log(`\n=== 处理SKU ${sku} ===`);
        console.log(`picData数组:`, picData);
        console.log(`skuData对象:`, skuData);
        
        // 确保picData存在且有足够的元素
        if (!picData || !Array.isArray(picData)) {
            console.warn(`SKU ${sku} 的picData无效:`, picData);
            return [sku, ...Array(headers.length - 1).fill('无')];
        }
        
        // 打印关键数据映射
        console.log(`数据映射 - SKU ${sku}:`);
        console.log(`  价格: picData[0] =`, picData[0]);
        console.log(`  划线价: picData[1] =`, picData[1]);
        console.log(`  促销比例: picData[2] =`, picData[2]);
        console.log(`  产品名称: picData[3] =`, picData[3]);
        console.log(`  星级: picData[4] =`, picData[4]);
        console.log(`  评论数: picData[5] =`, picData[5]);
        console.log(`  商家ID: picData[6] =`, picData[6]);
        
        const row = [
            sku,
            picData[6] ? picData[6].split('&')[0] : '无',
            rscwevrr(skuData.soldCount),
            rscwevrr(skuData.soldSum),
            picData[0] || '无',
            picData[1] || '无',
            picData[2] || '无',
            sku + ',' + (picData[0] || '无'),
            picData[3] || '无',
            picData[4] || '无',
            rscwevrr(skuData.brand),
            rscwevrr(skuData.category1),
            rscwevrr(skuData.category3),
            rscwevrr(skuData.salesDynamics),
            rscwevrr(skuData.avgPrice),
            rscwevrr(skuData.minSellerPrice),
            rscwevrr(skuData.convToCartPdp),
            rscwevrr(skuData.views),
            rscwevrr(skuData.volume),
            rscwevrr(skuData.salesSchema),
            rscwevrr(skuData.zwews),
            rscwevrr(skuData.avgDeliveryDays),
            rscwevrr(skuData.stock),
            rscwevrr(skuData.nullableCreateDate)
        ];
        
        console.log(`生成的行数据:`, row);
        
        return row;
    });
    
    console.log('\n=== 导出数据汇总 ===');
    console.log('总数据行数:', data.length);
    console.log('列名:', headers);
    console.log('前5行数据样本:', data.slice(0, 5));
    console.log('准备导出的数据结构:', { headers, dataLength: data.length });
    
    try {
        exportExcel(`${filename}_${new Date().toISOString().slice(0, 10)}.xlsx`, [headers, ...data]);
        tiddp('导出成功');
    } catch (error) {
        console.error('导出失败:', error);
        tiddp('导出失败: ' + error.message);
    }
}

// 复制数据到剪贴板
function copyDataToClipboard(skus) {
    const data = skus.map(sku => {
        const picData = SKUDATA_pic[sku];
        const price = picData && picData[0] ? picData[0] : '无';
        
        return `${sku},${price}`;
    });
    
    const csvContent = data.join('\n');
    
    console.log('复制内容:', csvContent);
    
    navigator.clipboard.writeText(csvContent).then(() => {
        tiddp('SKU和价格已复制到剪贴板');
    }).catch(() => {
        tiddp('复制失败，请手动复制');
    });
}

// 物流档位和公式定义
const logisticsTiers = {
    'E邮宝': [
        {
            name: '哈萨克斯坦（超级轻小件）',
            weightMin: 0,
            weightMax: 500,
            priceMin: 0,
            priceMax: 1500,
            formula: (w) => (1.7 + 0.034 * w).toFixed(2),
            formulaStr: '1.7 + 0.034 × 克值'
        },
        {
            name: '白俄罗斯（轻小件）',
            weightMin: 1,
            weightMax: 2000,
            priceMin: 1500,
            priceMax: 7000,
            priceInclusive: 'exclusive',
            formula: (w) => (14.4 + 0.0315 * w).toFixed(2),
            formulaStr: '14.4 + 0.0315 × 克值'
        }
    ],
    'UNI': [
        {
            name: 'UNI Standard Extra Small（超级轻小件）',
            weightMin: 0,
            weightMax: 500,
            priceMin: 0,
            priceMax: 1500,
            formula: (w) => (3 + 0.035 * w).toFixed(2),
            formulaStr: '3 + 0.035 × 克值'
        },
        {
            name: 'UNI Economy Budget（低客单标准件）',
            weightMin: 501,
            weightMax: 25000,
            priceMin: 0,
            priceMax: 1500,
            formula: (w) => (23 + 0.017 * w).toFixed(2),
            formulaStr: '23 + 0.017 × 克值'
        },
        {
            name: 'UNI Standard Small（轻小件）',
            weightMin: 1,
            weightMax: 2000,
            priceMin: 1500,
            priceMax: 7000,
            priceInclusive: 'exclusive',
            formula: (w) => (16 + 0.025 * w).toFixed(2),
            formulaStr: '16 + 0.025 × 克值'
        },
        {
            name: 'UNI Standard Big（大件）',
            weightMin: 2100,
            weightMax: 25000,
            priceMin: 1501,
            priceMax: 7000,
            formula: (w) => (w * 0.017 + 36).toFixed(2),
            formulaStr: '克值 × 0.017 + 36'
        },
        {
            name: 'UNI Standard Premium Small（高客单轻小件）',
            weightMin: 1,
            weightMax: 5000,
            priceMin: 7000,
            priceMax: Infinity,
            formula: (w) => (22 + 0.035 * w).toFixed(2),
            formulaStr: '22 + 0.035 × 克值'
        },
        {
            name: 'UNI Standard Premium Big（高客单大件）',
            weightMin: 5001,
            weightMax: 25000,
            priceMin: 7000,
            priceMax: Infinity,
            formula: (w) => (62 + 0.028 * w).toFixed(2),
            formulaStr: '62 + 0.028 × 克值'
        }
    ]
};

// 添加缺失的exportExcel函数
function exportExcel(filename, data) {
    // 创建工作簿和工作表
    var wb = XLSX.utils.book_new(); // 工作簿，即一个Excel文件
    var ws = XLSX.utils.aoa_to_sheet(data); // 工作表，即Excel内部的工作表
    
    // 设置列宽
    ws['!cols'] = [
        {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, 
        {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, 
        {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, 
        {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, 
        {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}, {wpx: 100}
    ];

    // "SheetJS" 为工作表名称，即Excel文件中工作表
    XLSX.utils.book_append_sheet(wb, ws, "SheetJS");

    // 写出Excel工作簿
    XLSX.writeFile(wb, filename);
}

// 物流费计算函数
function calcLogisticsFee({price, weight, type}) {
	
    const defaultResult = { fee: 0, tierName: '', formulaStr: '' };
    if (!weight || !type ||!whCache) return defaultResult;
    // 价格先转卢布
    let priceRUB = Number(price) * CNY2RUB;
	console.log(priceRUB)
    // 单位转换
    let weightNum = 0;
    let wstr = String(weight).replace(/\s/g, '').toLowerCase();
	console.log(wstr)
    if (wstr.includes('kg')) {
        weightNum = parseFloat(wstr) * 1000;
    } else if (wstr.includes('g')) {
        weightNum = parseFloat(wstr);
    } else {
        weightNum = parseFloat(wstr);
    }
	console.log(weightNum)
    if (isNaN(weightNum)) return defaultResult;
    for (const tier of whCache) {
        const weightMatch = weightNum >= tier.weight.min && weightNum <= tier.weight.max;

        let priceMatch = false;
        if (tier.priceInclusive === 'exclusive') {
            priceMatch = priceRUB > tier.price.min && priceRUB <= tier.price.max;
        } else if (tier.price.max === Infinity) {
            priceMatch = priceRUB >= tier.price.min;
        } else {
            priceMatch = priceRUB >= tier.price.min && priceRUB <= tier.price.max;
        }

        if (priceMatch && weightMatch) {
			let base = tier.logistic_fee.base *1
			let growth = tier.logistic_fee.growth *1
            return {
                fee: (base + growth * weightNum).toFixed(2),
                tierName: `${type}`,
                formulaStr: tier.formulaStr,
                weightMin: tier.weight.min,
                weightMax: tier.weight.max,
                priceMin: tier.price.min,
                priceMax: tier.price.max,
                priceInclusive: tier.priceInclusive
            };
        }
    }
    return defaultResult;
}

// 从offer对象中提取价格原始字符串和数字值
function extractOfferPrice(offer) {
    if (!offer) return { raw: null, num: 0 };
    // 新数据结构：price.cardPrice.price
    if (offer.price && offer.price.cardPrice && offer.price.cardPrice.price) {
        const raw = String(offer.price.cardPrice.price);
        const numStr = raw.replace(/[¥₽\s]/g, '').replace(',', '.');
        const num = parseFloat(numStr);
        return { raw: raw, num: (!isNaN(num) && num > 0) ? num : 0 };
    }
    // 兼容旧数据结构
    const priceFields = ['price', 'finalPrice', 'salePrice', 'originalPrice', 'currentPrice'];
    for (const field of priceFields) {
        const val = offer[field];
        if (val == null) continue;
        if (typeof val === 'object') {
            const nested = val.price || val.value || val.amount || val.current || val.original;
            if (nested != null) {
                const raw = String(nested);
                const numStr = raw.replace(/[¥₽\s]/g, '').replace(',', '.');
                const num = parseFloat(numStr);
                if (!isNaN(num) && num > 0) return { raw: raw, num: num };
            }
        } else {
            const raw = String(val);
            const numStr = raw.replace(/[¥₽\s]/g, '').replace(',', '.');
            const num = parseFloat(numStr);
            if (!isNaN(num) && num > 0) return { raw: raw, num: num };
        }
    }
    return { raw: null, num: 0 };
}

// 获取跟卖数据
async function fetchSellerOffers(productId) {
    try {
        const url = `https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fmodal%2FotherOffersFromSellers%3Fproduct_id%3D${productId}%26page_changed%3Dtrue`;
        const response = await fetch(url, {
            credentials: 'include',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        if (!response.ok) {
            throw new Error('请求失败: ' + response.status);
        }
        const data = await response.json();
        
        // 解析widgetStates中的跟卖数据
        let offers = [];
        let sellerCount = 0;
        let minPriceRaw = null;
        
        if (data.widgetStates) {
            for (const key in data.widgetStates) {
                // 优先匹配 webSellerList 格式的key
                if (!key.startsWith('webSellerList')) continue;
                try {
                    const widget = JSON.parse(data.widgetStates[key]);
                    // 尝试多种可能的结构
                    if (widget.offers && Array.isArray(widget.offers)) {
                        offers = widget.offers;
                    } else if (widget.items && Array.isArray(widget.items)) {
                        offers = widget.items;
                    } else if (widget.sellers && Array.isArray(widget.sellers)) {
                        offers = widget.sellers;
                    } else if (Array.isArray(widget)) {
                        offers = widget;
                    }
                    
                    if (offers.length > 0) {
                        sellerCount = offers.length;
                        // 取第一条记录的价格作为最低价格
                        const firstResult = extractOfferPrice(offers[0]);
                        minPriceRaw = firstResult.raw;
                        break;
                    }
                } catch (e) {
                    // 继续尝试下一个widget
                }
            }
        }
        
        // 也尝试直接从catalog或其他顶级字段获取
        if (offers.length === 0 && data.catalog && data.catalog.offers) {
            offers = data.catalog.offers;
            sellerCount = offers.length;
            // 取第一条记录的价格
            const firstResult = extractOfferPrice(offers[0]);
            minPriceRaw = firstResult.raw;
        }
        
        return {
            success: true,
            offers: offers,
            sellerCount: sellerCount,
            minPrice: minPriceRaw !== null ? minPriceRaw : '无'
        };
    } catch (error) {
        console.error('获取跟卖数据失败:', error);
        return { success: false, error: error.message, offers: [], sellerCount: 0, minPrice: '无' };
    }
}

// 安全格式化价格，防止对象显示为[object Object]
function formatPriceValue(price) {
    if (price == null || price === '无') return null;
    if (typeof price === 'object') {
        const nested = price.price || price.value || price.amount || price.current;
        if (nested != null) {
            const parsed = parseFloat(nested);
            if (!isNaN(parsed) && parsed > 0) return parsed;
        }
        return null;
    }
    const parsed = parseFloat(price);
    if (!isNaN(parsed) && parsed > 0) return parsed;
    return null;
}

// 更新跟卖数量单元格
function updateSellerCountCell(sku, count, minPrice) {
    const cell = $(`.seller-count-cell[data-sku="${sku}"]`);
    if (cell.length) {
        cell.text(count > 0 ? count : '无');
        cell.css('color', count > 0 ? '#1e88e5' : '#999');
    }
    // 同时更新最低跟卖价
    const row = cell.closest('tr');
    const minPriceCell = row.find('td').eq(4); // 跟卖最低价列索引
    if (minPriceCell.length) {
        if (count > 0 && minPrice && minPrice !== '无') {
            minPriceCell.text(minPrice);
            if (SKUDATA[sku]) {
                SKUDATA[sku].sellerCount = count;
                SKUDATA[sku].minFollowSellPrice = minPrice;
            }
        } else {
            minPriceCell.text('无');
            if (SKUDATA[sku]) {
                SKUDATA[sku].sellerCount = count;
                SKUDATA[sku].minFollowSellPrice = '无';
            }
        }
    }
}

// 批量获取跟卖数据
async function batchGetSellerOffers() {
    // 获取选中的SKU，如果没有选中则获取所有可见SKU
    const selectedSkus = [];
    const checkedRows = $('#data-table-body tr:visible .row-checkbox:checked');
    if (checkedRows.length > 0) {
        checkedRows.each(function() {
            selectedSkus.push($(this).closest('tr').attr('data-sku'));
        });
    } else {
        $('#data-table-body tr:visible').each(function() {
            selectedSkus.push($(this).attr('data-sku'));
        });
    }
    
    if (selectedSkus.length === 0) {
        tiddp('没有可获取跟卖数据的产品');
        return;
    }
    
    // 过滤出需要获取跟卖数据的SKU（跳过已有数据的）
    const skusToProcess = [];
    selectedSkus.forEach(sku => {
        const cell = $(`.seller-count-cell[data-sku="${sku}"]`);
        if (cell.length && cell.text() === '点击获取') {
            skusToProcess.push(sku);
        }
    });
    
    if (skusToProcess.length === 0) {
        tiddp('选中的产品都已具有跟卖数据，无需重复获取');
        return;
    }
    
    const button = $('#batch-get-seller-offers');
    const originalText = button.text();
    button.text('获取中...').prop('disabled', true);
    
    let successCount = 0;
    let failCount = 0;
    
    try {
        for (let i = 0; i < skusToProcess.length; i++) {
            const sku = skusToProcess[i];
            button.text(`获取中... (${i + 1}/${skusToProcess.length})`);
            
            try {
                const skuData = SKUDATA[sku];
                const productId = skuData && skuData.productId ? skuData.productId : sku;
                
                const result = await fetchSellerOffers(productId);
                if (result.success) {
                    updateSellerCountCell(sku, result.sellerCount, result.minPrice);
                    successCount++;
                } else {
                    failCount++;
                    const cell = $(`.seller-count-cell[data-sku="${sku}"]`);
                    if (cell.length) {
                        cell.text('获取失败').css('color', '#c82333');
                    }
                }
            } catch (error) {
                console.error(`获取SKU ${sku} 跟卖数据失败:`, error);
                failCount++;
                const cell = $(`.seller-count-cell[data-sku="${sku}"]`);
                if (cell.length) {
                    cell.text('获取失败').css('color', '#c82333');
                }
            }
            
            // 延迟，避免请求过于频繁
            if (i < skusToProcess.length - 1) {
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        }
    } finally {
        button.text(originalText).prop('disabled', false);
        tiddp(`跟卖数据获取完成：成功 ${successCount} 个，失败 ${failCount} 个`);
    }
}

// 显示跟卖记录弹窗
async function showSellerOffersPopup(productId, sku) {
    // 先移除已存在的弹窗，避免重复创建导致事件绑定混乱
    $('#seller-offers-modal').remove();
    // 显示加载中
    const loadingId = 'seller-offers-loading-' + Date.now();
    $('body').append(`<div id="${loadingId}" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.7);color:#fff;padding:12px 24px;border-radius:8px;z-index:1000000000;font-size:14px;">加载中...</div>`);
    
    const result = await fetchSellerOffers(productId);
    $(`#${loadingId}`).remove();
    
    if (!result.success) {
        tiddp('获取跟卖数据失败: ' + result.error);
        return;
    }
    
    // 更新单元格数据
    updateSellerCountCell(sku, result.sellerCount, result.minPrice);
    
    // 构建弹窗内容
    let offersHtml = '';
    if (result.offers.length === 0) {
        offersHtml = '<tr><td colspan="6" style="padding:20px;text-align:center;color:#999;">暂无跟卖数据</td></tr>';
    } else {
        result.offers.forEach((offer, index) => {
            const sellerName = offer.name || offer.sellerName || offer.seller || '未知卖家';
            const priceResult = extractOfferPrice(offer);
            const priceDisplay = priceResult.raw || '无';
            const delivery = offer.advantages?.[0]?.contentRs?.headRs?.[0]?.content || offer.deliveryText || offer.delivery || '无';
            const ratingRaw = offer.rating?.totalScore;
            const rating = ratingRaw != null ? parseFloat(ratingRaw).toFixed(2) : (offer.sellerRating || '无');
            const reviewsCount = offer.rating?.reviewsCount != null ? offer.rating.reviewsCount : '无';
            offersHtml += `
                <tr style="border-bottom:1px solid #eaeaea;">
                    <td style="padding:10px;font-size:13px;">${index + 1}</td>
                    <td style="padding:10px;font-size:13px;font-weight:600;">${sellerName}</td>
                    <td style="padding:10px;font-size:13px;color:#c82333;font-weight:600;">${priceDisplay}</td>
                    <td style="padding:10px;font-size:13px;">${delivery}</td>
                    <td style="padding:10px;font-size:13px;">${rating}</td>
                    <td style="padding:10px;font-size:13px;">${reviewsCount}</td>
                </tr>
            `;
        });
    }
    
    const modalHtml = `
        <div id="seller-offers-modal" style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000000000;
            display: flex;
            align-items: center;
            justify-content: center;
        ">
            <div style="
                background: #ffffff;
                border-radius: 12px;
                width: 800px;
                max-width: 90vw;
                max-height: 80vh;
                display: flex;
                flex-direction: column;
                box-shadow: 0 10px 40px rgba(0,0,0,0.2);
                overflow: hidden;
            ">
                <div style="
                    padding: 16px 24px;
                    border-bottom: 1px solid #eeeeee;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    background: linear-gradient(135deg, #1e88e5 0%, #1565c0 100%);
                    color: #ffffff;
                ">
                    <h3 style="margin:0;font-size:16px;font-weight:700;">SKU: ${sku} 的跟卖记录</h3>
                    <span style="font-size:13px;">共 ${result.sellerCount} 个卖家</span>
                    <button id="close-seller-offers-modal" style="
                        background: transparent;
                        border: none;
                        color: #ffffff;
                        font-size: 20px;
                        cursor: pointer;
                        padding: 0;
                        width: 32px;
                        height: 32px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 4px;
                        transition: background 0.2s;
                    ">×</button>
                </div>
                <div style="flex:1;overflow:auto;padding:0;">
                    <table style="width:100%;border-collapse:collapse;">
                        <thead style="position:sticky;top:0;background:#f8f9fa;z-index:10;">
                            <tr style="border-bottom:2px solid #eaeaea;">
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">序号</th>
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">卖家名称</th>
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">价格</th>
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">配送</th>
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">评分</th>
                                <th style="padding:10px;text-align:left;font-size:13px;font-weight:700;color:#555;">评价数量</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${offersHtml}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    $('body').append(modalHtml);
    
    // 绑定关闭事件（使用事件委托+命名空间，确保可靠触发）
    $(document).off('click.sellerOffersClose').on('click.sellerOffersClose', '#close-seller-offers-modal', function(e) {
        e.stopPropagation();
        $('#seller-offers-modal').remove();
    });
    $(document).off('click.sellerOffersBackdrop').on('click.sellerOffersBackdrop', '#seller-offers-modal', function(e) {
        if (e.target.id === 'seller-offers-modal') {
            $('#seller-offers-modal').remove();
        }
    });
    // ESC键关闭
    $(document).off('keydown.sellerOffersEsc').on('keydown.sellerOffersEsc', function(e) {
        if (e.key === 'Escape') {
            $('#seller-offers-modal').remove();
        }
    });
}

// 物流方式切换时刷新表格
$(document).on('change', '#logistics-type', function() {
    initializeDataTable();
    applyFilters(); // 新增：切换物流方式后自动应用当前过滤条件
});
