// product/ozon-profit.js
// 从 product/ozon.js 拆出 — 利润计算模块
//
// 包含：
//   allLogisticsMethods, ozProfitLoadingLogistics, ozProfitCalculationCache
//   getCurrencySymbol / getToken
//   loadOzonShops / loadOzonLogisticsGroups / loadOzonLogisticsMethods
//   processLogisticsMethods / updateAllProfitCells
//   ProfitCalculator / debounce / getWhType / updateProfitCell
//   calculateProfitWithFallback / updateProfitDisplay
//   事件监听：#logistics-group change, #logistics-type change（updateAllProfitCells版）,
//             .cost-input input, .price-input input, #commission-rate input, #packing-fee input
//
// 加载顺序要求（manifest.json content_scripts.js）：
//   ... ozon-export.js → ozon-profit.js → ozon.js
//
// 依赖的全局变量（由 ozon-api.js / ozon-export.js / ozon.js 提供）：
//   whCache, tokenCache, tokenLastUpdated, TOKEN_CACHE_DURATION, CNY2RUB,
//   SKUDATA, SKUDATA_pic, tiddp, config, calcLogisticsFee, initializeDataTable, applyFilters

// 新增：物流分组和利润计算相关代码

// 物流分组相关变量
let allLogisticsMethods = [];
let ozProfitLoadingLogistics = false;
const ozProfitCalculationCache = new Map();

// 获取货币符号
function getCurrencySymbol(currencyCode) {
    const symbols = {
        'CNY': '¥',
        'RUB': '₽',
        'USD': '$',
        'EUR': '€',
        'GBP': '£'
    };
    return symbols[currencyCode] || currencyCode;
}

async function getToken() {
    // 检查缓存是否有效
    const now = Date.now();
    if (tokenCache && (now - tokenLastUpdated) < TOKEN_CACHE_DURATION) {
        console.log('使用缓存的token:', tokenCache);
        console.log('token缓存剩余时间:', Math.round((TOKEN_CACHE_DURATION - (now - tokenLastUpdated)) / 1000), '秒');
        return tokenCache;
    }
    
    return new Promise(function (resolve, reject) {
        chrome.runtime.sendMessage({
            type: "getCookie",
            url: config.url.domainz(),
            name: config.cookieName11
        }, function (token) {
            const currentTime = Date.now();
            if (token && token !== null && token !== undefined && token !== '') {
                // 更新缓存
                tokenCache = token;
                tokenLastUpdated = currentTime;
                console.log('获取到新的token并缓存:', token);
                console.log('token缓存时间:', new Date(tokenLastUpdated).toLocaleString());
                resolve(token);
            } else {
                console.log('未获取到token，返回null');
                resolve(null);
            }
        });
    });
}

// 加载店铺数据 - 使用唯一名称，避免与adtnfosku.js冲突
async function loadOzonShops() {
    const storeSelect = document.getElementById('store');
    if (!storeSelect) {
        console.error("店铺选择器未找到");
        return;
    }

    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading';
    loadingIndicator.style.display = 'inline-block';
    loadingIndicator.style.marginLeft = '10px';
    loadingIndicator.style.color = '#1e88e5';
    loadingIndicator.style.fontSize = '13px';
    storeSelect.parentNode.appendChild(loadingIndicator);

    storeSelect.disabled = true;
    const apiUrl = config.url.selectShop();

    try {
        const token = await getToken();
        console.log('tokenloadOzonShops:', token);

        if (token) {
            // 通过 background 发送请求
            chrome.runtime.sendMessage({
                action: "httpRequest",
                method: "POST",
                url: apiUrl,
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                },
                params: {
                    limit: 10,
                    page: 1
                }
            }, function(response) {
                if (response && !response.error) {
					console.log(response)
                    // const responseData = response.data || response;
                    const responseData = response;
                    console.log('店铺数据loadOzonShops:', responseData);

                    if (responseData && responseData.status === "200") {
                        storeSelect.innerHTML = '<option value="">-- 请选择店铺 --</option>';
                        if (responseData.data && responseData.data.length > 0) {
                            responseData.data.forEach(shop => {
                                const option = document.createElement('option');
                                option.value = shop.appid;
                                option.textContent = shop.tname;
                                storeSelect.appendChild(option);
                            });
                        } else {
                            storeSelect.innerHTML += '<option value="">-- 暂无店铺数据 --</option>';
                        }
                    } else {
                        const msg = responseData?.Message || "店铺数据获取失败";
                        console.error('店铺数据获取失败loadOzonShops:', msg);
                        storeSelect.innerHTML = `<option value="">-- ${msg} --</option>`;
                    }
                } else {
                    console.error("请求失败", response);
                    storeSelect.innerHTML = '<option value="">-- 请求失败 --</option>';
                }
                
                if (loadingIndicator && loadingIndicator.parentNode) {
                    loadingIndicator.parentNode.removeChild(loadingIndicator);
                }
                storeSelect.disabled = false;
            });
        } else {
            console.error("Token获取失败loadOzonShops");
            storeSelect.innerHTML = '<option value="">-- 登录过期 --</option>';
            if (loadingIndicator && loadingIndicator.parentNode) {
                loadingIndicator.parentNode.removeChild(loadingIndicator);
            }
            storeSelect.disabled = false;
        }
    } catch (error) {
        console.error('请求失败loadOzonShops:', error);
        storeSelect.innerHTML = '<option value="">-- 请求异常 --</option>';
        if (loadingIndicator && loadingIndicator.parentNode) {
            loadingIndicator.parentNode.removeChild(loadingIndicator);
        }
        storeSelect.disabled = false;
    }
}
// 确保函数在全局作用域中可用
window.loadOzonShops = loadOzonShops;

// 加载物流分组 - 使用唯一名称，避免与adtnfosku.js冲突
async function loadOzonLogisticsGroups() {
    let groupSelect = null;
    let loadingIndicator = null;
    
    console.log('开始执行loadOzonLogisticsGroups函数');
    
    try {
        // 获取DOM元素（不是jQuery对象）
        groupSelect = document.getElementById('logistics-group');
        
        console.log('获取到的groupSelect:', groupSelect);
        
        // 检查DOM元素是否存在
        if (!groupSelect) {
            console.error("物流分组选择器未找到");
            return;
        }
        
        // 创建并添加loading指示器
        loadingIndicator = document.createElement('div');
        loadingIndicator.className = 'loading';
        loadingIndicator.style.cssText = 'display: inline-block; margin-left: 8px; font-size: 12px; color: #1e88e5;';
        loadingIndicator.textContent = '加载中...';
        groupSelect.parentNode.appendChild(loadingIndicator);
        
        // 禁用选择器
        groupSelect.disabled = true;

        const token = await getToken();

        // 详细日志：完整token信息和缓存情况
        console.log('分组加载时获取到的完整token:', token);
        console.log('分组加载时token缓存状态:', {
            tokenCache: tokenCache,
            tokenLastUpdated: tokenLastUpdated,
            tokenCacheTime: new Date(tokenLastUpdated).toLocaleString(),
            cacheAge: Math.round((Date.now() - tokenLastUpdated) / 1000) + '秒',
            cacheValid: (Date.now() - tokenLastUpdated) < TOKEN_CACHE_DURATION
        });

        if (!token) {
            console.error("用户未登录，无法加载物流分组");
            return;
        }

        console.log('准备发送API请求');
        
        const response = await fetch(config.url.getLogisticsGroups(), {
            method: "POST",
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                limit: 10,
                page: 1
            })
        });

        console.log('API请求完成，响应状态:', response.status);
        
        const res = await response.json();
        
        console.log('API响应数据:', res);
        
        console.log('检查API响应条件:', {
            res: !!res,
            status: res ? res.status : 'undefined',
            statusType: res ? typeof res.status : 'undefined',
            data: res ? !!res.data : 'undefined',
            dataType: res ? typeof res.data : 'undefined',
            dataLength: res && res.data ? res.data.length : 'undefined'
        });
        
        // 检查res.status类型，确保比较正确
        // API返回的状态码是'success'，而不是'200'
        if (res && res.status === "success" && res.data && Array.isArray(res.data)) {
            console.log('开始填充物流分组数据，共', res.data.length, '个分组');
            
            // 使用DOM API清空并填充选择器
            groupSelect.innerHTML = '<option value="">-- 选择分组 --</option>';
            
            let defaultGroupId = null;
            
            console.log('分组数据:', res.data);
            
            res.data.forEach((group, index) => {
                console.log(`处理第${index + 1}个分组:`, group);
                
                const option = document.createElement('option');
                option.value = group.group_id;
                option.textContent = group.group_name;
                
                if (group.is_default === 1) {
                    defaultGroupId = group.group_id;
                    option.selected = true;
                    console.log('设置默认分组:', group.group_name);
                }
                
                groupSelect.appendChild(option);
                console.log('已添加分组到下拉框:', group.group_name);
            });
            console.log('填充完成后，下拉框选项数量:', groupSelect.options.length);
			
            // 如果有默认分组，自动加载其物流方式
            if (defaultGroupId) {
                console.log('自动加载默认分组的物流方式:', defaultGroupId);
                // 直接调用函数
                await loadOzonLogisticsMethods(defaultGroupId);
            }else{
				await loadOzonLogisticsMethods(1);
			}
        } else {
            console.error('API响应不符合预期:', res);
        }
    } catch (error) {
        console.error('加载物流分组失败:', error);
        // 错误情况下清空选择器并显示错误选项
        if (groupSelect) {
            groupSelect.innerHTML = '<option value="">-- 加载失败 --</option>';
        }
    } finally {
        // 移除loading指示器
        if (loadingIndicator && loadingIndicator.parentNode) {
            loadingIndicator.parentNode.removeChild(loadingIndicator);
        }
        // 启用选择器
        if (groupSelect) {
            groupSelect.disabled = false;
        }
    }
}

// 将loadOzonLogisticsGroups函数暴露到全局作用域
window.loadOzonLogisticsGroups = loadOzonLogisticsGroups;

// 加载物流方式 - 使用唯一名称，避免与adtnfosku.js冲突
async function loadOzonLogisticsMethods(groupId) {
    if (!groupId || ozProfitLoadingLogistics) return;
    ozProfitLoadingLogistics = true;

    try {
        const token = await getToken();

        if (!token) {
            console.error("用户未登录，无法加载物流方式");
            ozProfitLoadingLogistics = false;
            return;
        }

        // 通过 background 发送请求
        chrome.runtime.sendMessage({
            action: "httpRequest",
            method: "POST",
            url: config.url.getLogisticsMethods(groupId),
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            },
            params: {
                weight: 500,
                price: 100,
                purchase_price: 0,
                currency: 'CNY'
            }
        }, async function(response) {
            if (response && !response.error) {
                const res = response;
                console.log('getLogisticsMethods API响应:', res);
                if (res && res.data && res.data.items) {
                    whCache = res.data.items;
                }
                await updateAllProfitCells();
                console.log(res?.data?.items);
            } else {
                console.error('getLogisticsMethods API失败:', response);
            }
            ozProfitLoadingLogistics = false;
        });

    } catch (error) {
        console.error('加载物流方式失败:', error);
        ozProfitLoadingLogistics = false;
    }
}

// 将loadOzonLogisticsMethods函数暴露到全局作用域
window.loadOzonLogisticsMethods = loadOzonLogisticsMethods;

// 处理物流方式响应
function processLogisticsMethods(profitResponse) {
    window.allLogisticsMethods = profitResponse.all_methods;
    const methodSelect = document.getElementById('logistics-type');
    
    // 检查DOM元素是否存在
    if (!methodSelect) {
        console.error("物流方式选择器未找到");
        return;
    }
    
    methodSelect.innerHTML = '';

    if (!profitResponse.all_methods || profitResponse.all_methods.length === 0) {
        const option = document.createElement('option');
        option.value = '';
        option.textContent = '-- 无可用物流 --';
        methodSelect.appendChild(option);
        return;
    }

    let maxProfit = -Infinity;
    let bestMethodIndex = -1;

    profitResponse.all_methods.forEach((method, index) => {
        const option = document.createElement('option');
        option.value = index;
        option.textContent = `${method.name} (利润: ¥${method.profit.toFixed(2)})`;
        
        // 使用dataset存储额外数据
        option.dataset.profit = method.profit;
        option.dataset.logisticFee = method.logistic_fee;
        option.dataset.profitRate = method.profit_rate;
        option.dataset.commission = method.commission;
        
        methodSelect.appendChild(option);

        if (method.profit > maxProfit) {
            maxProfit = method.profit;
            bestMethodIndex = index;
        }
    });

    // 自动选择最佳方案
    if (bestMethodIndex !== -1) {
        methodSelect.value = bestMethodIndex;
        updateAllProfitCells();
    }
}

// 更新所有利润单元格
async function updateAllProfitCells() {
    // 清空缓存，确保数据是最新的
    ozProfitCalculationCache.clear();
    
    const skuList = Object.keys(SKUDATA_pic);
    for (const sku of skuList) {
		console.log(sku)
        await updateProfitCell(sku);
    }
}

// 新增：物流分组变化监听
$(document).on('change', '#logistics-group', function() {
    const groupId = $(this).val();
    if (groupId) {
        // 使用全局作用域的函数
        window.loadOzonLogisticsMethods(groupId);
    } else {
        // $('#logistics-type').empty().append('<option value="">-- 选择分组 --</option>');
    }
});

// 新增：物流方式变化监听
$(document).on('change', '#logistics-type', async function() {
    await updateAllProfitCells();
});




$(document).on('input', '.cost-input', async function() {
    console.log('检测到成本输入变化');
    
    // 获取SKU，并转换为字符串类型，确保与SKUDATA的键类型一致
    const sku = String($(this).data('sku'));
    const val = $(this).val();
    
    console.log(`SKU: ${sku}, 输入值: ${val}`);
    
    // 确保SKU在SKUDATA中有对应数据
    if (!SKUDATA[sku]) {
        console.log(`SKU ${sku} 在SKUDATA中不存在`);
        // 如果SKU不存在，创建一个空对象
        SKUDATA[sku] = {};
    }
    
    // 更新SKUDATA中的成本值
    SKUDATA[sku].cost = val;
    console.log(`已更新SKUDATA[${sku}].cost = ${val}`);
    
    // 如果弹窗打开且sku一致，则同步弹窗输入框
    if ($('#sku-image-modal').is(':visible')) {
        const modalSku = $('#product-sku').text().replace('SKU: ', '');
        console.log(`模态框打开，当前SKU: ${modalSku}`);
        if (modalSku == sku) {
            $('#cost-input-modal').val(val);
            console.log('已同步模态框成本输入框');
        }
    }
    
    // 清空该SKU相关的缓存，确保获取最新的利润数据
    const picData = SKUDATA_pic[sku];
    if (picData) {
        const priceNum = parseFloat(picData[0]) || 0;
        const weightStr = SKUDATA[sku].zwews || '';
        console.log(`重量字符串: ${weightStr}`);
        
        // 解析重量（支持带单位的重量）
        let weightGrams = 0;
        if (weightStr && weightStr !== '点击获取') {
            let wstr = String(weightStr).toLowerCase();
            if (wstr.includes('kg')) {
                weightGrams = parseFloat(wstr.replace('kg', '')) * 1000;
            } else if (wstr.includes('g')) {
                weightGrams = parseFloat(wstr.replace('g', ''));
            } else if (wstr.includes('гр')) {
                weightGrams = parseFloat(wstr.replace('гр', ''));
            } else if (wstr.includes('кг')) {
                weightGrams = parseFloat(wstr.replace('кг', '')) * 1000;
            } else {
                weightGrams = parseFloat(wstr) || 0;
            }
        }
        
        console.log(`解析后的重量: ${weightGrams}克`);
        
        // 生成缓存键并移除
        const cacheKey = JSON.stringify({
            groupId: $('#logistics-group').val(),
            weight: weightGrams,
            price: priceNum,
            cost: val
        });
        ozProfitCalculationCache.delete(cacheKey);
        console.log(`已删除缓存键: ${cacheKey}`);
    }
    
    // 更新该SKU的利润计算
    console.log('更新利润计算');
    await updateProfitCell(sku);
    console.log('利润计算更新完成');
    
    // 只有当当前SKU是第一个既有重量又有成本的SKU时，才重新加载物流方式
    // 这样可以避免影响其他SKU的物流费计算
    const groupId = $('#logistics-group').val();
    if (groupId) {
        // 检查当前SKU是否既有重量又有成本
        const weightStr = SKUDATA[sku].zwews || '';
        const cost = parseFloat(SKUDATA[sku].cost) || 0;
        
        if (weightStr && weightStr !== '点击获取' && cost > 0) {
            console.log('当前SKU既有重量又有成本，重新加载物流方式');
            // 延迟调用，避免影响当前SKU的利润计算
            // setTimeout(() => {
            //     window.loadOzonLogisticsMethods(groupId);
            // }, 1000);
        }
    }
});
// 监听价格输入变化
$(document).on('input', '.price-input', async function() {
    const sku = $(this).data('sku');
    const newPrice = $(this).val();
    if (SKUDATA_pic && SKUDATA_pic[sku]) {
        SKUDATA_pic[sku][0] = newPrice;
    }
    if (SKUDATA && SKUDATA[sku]) {
        SKUDATA[sku].price = newPrice;
    }
    await updateProfitCell(sku);
});
// 物流费变化时（如有批量获取重量后物流费变化，也应调用updateProfitCell）
// 利润计算核心模块
const ProfitCalculator = {
    // 基础计算逻辑
    calculate: function({ price, cost, weight, whTypeStr, commissionRate, packingFee }) {
        const logisticsInfo = calcLogisticsFee({ price, weight, type: whTypeStr });
        const logisticsFee = parseFloat(logisticsInfo.fee) || 0;
        const commission = price * (commissionRate / 100);
        
        const profit = price - cost - commission - logisticsFee - packingFee;
        const profitRate = price > 0 ? (profit / price) * 100 : 0;
        
        return {
            profit: isNaN(profit) ? 0 : profit,
            profitRate: isNaN(profitRate) ? 0 : profitRate,
            logisticsFee,
            commission,
            logisticsInfo,
			whTypeStr
        };
    },

    // 格式化输出
    formatResult: function(result) {
        return {
            profitStr: `${result.profit.toFixed(2)} | ${result.profitRate.toFixed(1)}%`,
            color: result.profit >= 0 ? '#1e88e5' : '#c82333'
        };
    },

    // 更新UI显示
    updateUI: function(sku, result) {
        const { profitStr, color } = this.formatResult(result);
        // 更新表格行
        const $cell = $(`#profit-cell-${sku}`);
        if ($cell.length) {
            $cell.text(profitStr).parent().css('color', color);
        }
		// 更新表格行
		$(`#fee-cell-${sku}`).text(result.logisticsFee);
		
		
		// 更新弹窗详情
		$(`#whType-cell-${sku}`).html(`
			<div>
			<select style="background: #FFFFFF; border: 1px solid #eeeeee; border-radius: 4px; padding: 6px 8px;  width: 90px; font-size: 13px; font-weight: 500; margin-right: 8px;">
				<option value="">${result.whTypeStr}</option>
			</select>
			</div>
		`);

        // 更新弹窗详情
        if ($('#sku-image-modal').is(':visible')) {
            const currentModalSku = $('#product-sku').text().replace('SKU: ', '');
            if (currentModalSku == sku) {
                $('#profit-info-modal').html(`
                    <div style="color: ${color}">利润：<span style="color: ${color}">${result.profit.toFixed(2)}</span></div>
                    <div style="color: ${color}">利润率：<span style="color: ${color}">${result.profitRate.toFixed(1)}%</span></div>
                `);
				$('#whType-info-modal').html(`
				    <div>物流方式：
					<select style="background: #FFFFFF; border: 1px solid #eeeeee; border-radius: 4px; padding: 6px 8px;  width: 90px; font-size: 13px; font-weight: 500; margin-right: 8px;">
					    <option value="">${result.whTypeStr}</option>
					</select>
					</div>
				`);
				
				
            }
        }
    }
};

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}
// 获取物流方式
async function getWhType(sku) {
    return new Promise(function (resolve, reject) {
		if (!sku.weight||!sku.price || !whCache) return resolve('');
		// 价格先转卢布
		let priceRUB = Number(sku.price) * CNY2RUB;
		// 单位转换
		let weightNum = 0;
		let wstr = String(sku.weight).replace(/\s/g, '').toLowerCase();
		if (wstr.includes('kg')) {
		    weightNum = parseFloat(wstr) * 1000;
		} else if (wstr.includes('g')) {
		    weightNum = parseFloat(wstr);
		} else {
		    weightNum = parseFloat(wstr);
		}
		if (isNaN(weightNum)) return resolve('');
		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) {
				resolve(tier.name);
		    }
		}
		resolve('');
		
    });
}

// 统一的利润更新函数
async function updateProfitCell(sku) {
    const picData = SKUDATA_pic[sku];
    const skuData = SKUDATA[sku];
	
    if (!picData || !skuData) return;

    $(`#profit-cell-${sku}`).html('<span class="profit-loading"></span>');

    const price = parseFloat(picData[0]) || 0;
    const cost = parseFloat(skuData.cost) || 0;
    const weight = skuData.zwews;

    if (!weight || weight === '无' || weight === '点击获取') {
        $(`#profit-cell-${sku}`).text('无');
        return;
    }
    const logisticsGroupId = $('#logistics-group').val();
    // const logisticsMethodIndex = $('#logistics-type').val();
	let whTypeObject = {
		weight:weight,
		price:price
	}
    const whTypeStr = await getWhType(whTypeObject)
    const commissionRate = parseFloat($('#commission-rate').val()) || 20;
    const packingFee = parseFloat($('#packing-fee').val()) || 5;
	
    // 优先使用接口计算（如果已配置）
    if (logisticsGroupId && whTypeStr && whTypeStr !== '' && cost > 0) {
        try {
            const token = await getToken();
            if (token) {
                const response = await fetch(config.url.calculate(), {
                    method: "POST",
                    headers: { 'Authorization': token, 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        groupid: logisticsGroupId,
                        weight: ProfitCalculator.parseWeight(weight),
                        price: price,
                        purchase_price: cost,
                        currency: 'CNY'
                    })
                });
                const res = await response.json();
                if (res?.status === 'success' && res.all_methods?.[logisticsMethodIndex]) {
                    const method = res.all_methods[logisticsMethodIndex];
                    const result = {
                        profit: method.profit || 0,
                        profitRate: method.profit_rate || 0,
                        logisticsFee: method.logistic_fee || 0,
                        commission: method.commission || 0
                    };
                    ProfitCalculator.updateUI(sku, result);
                    return;
                }
            }
        } catch (e) { console.error('API Profit Calc Error:', e); }
    }

    // 回退到本地计算
    const result = ProfitCalculator.calculate({
        price, cost, weight,
        whTypeStr: whTypeStr || 'E邮宝',
        commissionRate, packingFee
    });
    ProfitCalculator.updateUI(sku, result);
}

// 解析重量字符串为数字（克）
ProfitCalculator.parseWeight = function(weight) {
    let wstr = String(weight).replace(/\s/g, '').toLowerCase();
    if (wstr.includes('kg')) return parseFloat(wstr) * 1000;
    return parseFloat(wstr) || 0;
};

// 使用原有计算公式作为回退
function calculateProfitWithFallback(sku, priceNum, cost, weight, whTypeStr) {
    const logisticsType = whTypeStr || 'E邮宝';
    const logisticsInfo = calcLogisticsFee({price: priceNum, weight: weight, type: logisticsType});
    const logisticsFee = parseFloat(logisticsInfo.fee) || 0;
    
    // 获取动态佣金比例，默认为20%
    const commissionRate = parseFloat($('#commission-rate').val()) || 20;
    const commission = priceNum * (commissionRate / 100);
    
    let profit, profitRate;
    
    // 当成本为0或未填写时，使用简化公式：利润 = 价格 - 物流费 - 佣金
    if (cost === 0 || !cost) {
        console.log(`成本为0或未填写，使用简化公式计算利润: 价格(${priceNum}) - 物流费(${logisticsFee}) - 佣金(${commission})`);
        profit = priceNum - logisticsFee - commission;
        profitRate = priceNum > 0 ? (profit / priceNum) * 100 : 0;
    } else {
        // 获取动态打包费，默认为5元
        const packingFeeInput = $('#packing-fee').val();
        const packingFee = packingFeeInput !== '' ? parseFloat(packingFeeInput) : 5;
        
        profit = priceNum - cost - commission - logisticsFee - packingFee;
        profitRate = priceNum > 0 ? (profit / priceNum) * 100 : 0;
    }
    
    updateProfitDisplay(sku, profit, profitRate, logisticsFee, commission, logisticsInfo);
}

// 更新利润显示
function updateProfitDisplay(sku, profit, profitRate, logisticsFee, commission, logisticsInfo) {
    const picData = SKUDATA_pic[sku];
    if (!picData) return;
    
    const priceNum = parseFloat(picData[0]) || 0;
    
    // 处理 NaN 和 Infinity
    if (isNaN(profit) || !isFinite(profit)) {
        profit = 0;
    }
    if (isNaN(profitRate) || !isFinite(profitRate)) {
        profitRate = 0;
    }
    
    let profitStr = priceNum > 0 ? `${profit.toFixed(2)} | ${profitRate.toFixed(1)}%` : '无';
    
    // 更新利润单元格
    $(`#profit-cell-${sku}`).text(profitStr);
    $(`#whType-cell-${sku}`).text(whTypeStr);
    $(`#fee-cell-${sku}`).text(logisticsFee);
    
    // 更新物流费单元格
    const row = $(`#data-table-body tr[data-sku="${sku}"]`);
    if (row.length > 0) {
        let logisticsTooltip = '';
        
        // 简化物流费显示，不再使用复杂的区间计算
        logisticsTooltip = `物流费: ¥${logisticsFee.toFixed(2)}\n佣金: ¥${commission.toFixed(2)}`;
        
        // 更新物流费单元格内容和title
        const logisticsCell = row.find('td').eq(4);
        logisticsCell.text(logisticsFee.toFixed(2)).attr('title', logisticsTooltip);
    }
    
    // 同步弹窗中的利润显示和物流费
    if ($('#sku-image-modal').is(':visible')) {
        const modalSku = $('#product-sku').text().replace('SKU: ', '');
        if (modalSku == sku) {
            // 更新弹窗中的利润显示，使用与计算时相同的颜色逻辑
            const profitColor = profit >= 0 ? '#1e88e5' : '#c82333';
            $('#profit-info-modal').html(`
                <div style="color: ${profitColor}">利润：<span style="color: ${profitColor}">${profit.toFixed(2)}</span></div>
                <div style="color: ${profitColor}">利润率：<span style="color: ${profitColor}">${profitRate.toFixed(1)}%</span></div>
            `);
			$('#whType-info-modal').html(`
			    <div>物流方式：
				<select style="background: #FFFFFF; border: 1px solid #eeeeee; border-radius: 4px; padding: 6px 8px;  width: 90px; font-size: 13px; font-weight: 500; margin-right: 8px;">
				    <option value="">${whTypeStr}</option>
				</select>
				</div>
			`);
            
            // 更新弹窗中的物流费显示
            const logisticsFeeValue = parseFloat(logisticsFee) || 0;
            const formattedLogisticsFee = logisticsFeeValue > 0 ? `¥${logisticsFeeValue.toFixed(2)}` : '无';
            $('#product-details').find('div:contains(物流费)').next('div').text(formattedLogisticsFee);
        }
    }
}

// 监听佣金比例变化，重新计算所有商品的利润
$(document).on('input', '#commission-rate', async function() {
    // 清空缓存，确保数据是最新的
    ozProfitCalculationCache.clear();
    
    // 重新计算所有可见商品的利润
    const visibleRows = $('#data-table-body tr:visible');
    for (let i = 0; i < visibleRows.length; i++) {
        const row = $(visibleRows[i]);
        const sku = row.attr('data-sku');
        if (sku) {
            await updateProfitCell(sku);
        }
    }
});

// 监听打包费变化，重新计算所有商品的利润
$(document).on('input', '#packing-fee', async function() {
    // 清空缓存，确保数据是最新的
    ozProfitCalculationCache.clear();
    
    // 重新计算所有可见商品的利润
    const visibleRows = $('#data-table-body tr:visible');
    for (let i = 0; i < visibleRows.length; i++) {
        const row = $(visibleRows[i]);
        const sku = row.attr('data-sku');
        if (sku) {
            await updateProfitCell(sku);
        }
    }
});
