// 获取物流缓存
let whCacheDetail = null;
let CNY2RUBDetail = 10.93; // 默认1，实际用接口值覆盖
// DOM元素
let storeSelect, salePriceHYInput,packageWeightHYInput,salePriceHYText,packageWeightHYText,productNameInput, salePriceInput, packageWeightInput, purchasePriceInput;
let logisticsCostElement, estimatedProfitElement, profitMarginElement, resetBtn, submitBtn,distributingGoodsCloseBtn;
let logisticsGroupSelect, logisticsMethodSelect, logisticsDetailsContainer;
let goodsDataStore, sku, userid;
let skuTypeSingle, skuTypeMultiple, sourceUrlsContainer, addUrlBtn;
let multipleSkus = []; // 存储多个SKU的数组
let productInfo;
let currency_code, currency;
let pendingGoodsWeight = null;
let pendingGoodsSku = null;
let commission;
let prices = []; // 存储价格数组
// 存储API响应数据
let singleSkuAnalysisResponse = null; // 单个SKU分析响应
let multipleSkuSearchResponses = {}; // 多个SKU搜索响应，键为SKU值
let singleSKUstrong =null
let multipleSKUstrong =null
// 新增函数：加载物流分组
async function loadLogisticsGroups() {
    try {
        const loadingIndicator = document.createElement('div');
        loadingIndicator.className = 'loading';
        logisticsGroupSelect.parentNode.appendChild(loadingIndicator);

        logisticsGroupSelect.disabled = true;

        // 获取用户token
        const cookie = await new Promise(resolve => {
            config.getCookie({
                "url": config.url.domainz(),
                "name": config.cookieName11
            }, resolve);
        });
        console.log('cookieloadLogisticsGroups:', cookie);

        if (!cookie || !cookie.value) {
            throw new Error("用户未登录");
        }

        // 添加token变量定义
        const token = cookie.value;
        console.log('tokenloadLogisticsGroups:', token);

        // 调用API获取分组数据 - 修改传参方式
        const response = await request(config.url.getLogisticsGroups(), {
            method: "POST",
            responseType: "json",
            body: {
                // 可以根据API需求添加其他参数，如分页等
                // limit: 10,
                // page: 1
            },
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            }
        });
        console.log('获取物流分组响应loadLogisticsGroups:', response);

        if (response) {
            logisticsGroupSelect.innerHTML = '<option value="">-- 请选择物流分组 --</option>';
			// 添加默认分组标识变量
            let defaultGroupId = null;
            response.data.forEach(group => {
                const option = document.createElement('option');
                option.value = group.group_id;
                option.textContent = group.group_name;
                // 检查是否为默认分组
                if (group.is_default === 1) {
                    option.selected = true;
                    defaultGroupId = group.group_id;
                }
                logisticsGroupSelect.appendChild(option);
            });
            // 如果找到默认分组，加载对应的物流方式
            if (defaultGroupId) {
				console.log(defaultGroupId)
                logisticsGroupSelect.value = defaultGroupId;
                logisticsMethodSelect.disabled = false;
                logisticsMethodSelect.innerHTML = '<option value="">-- 加载中... --</option>';
                await loadLogisticsMethods(defaultGroupId);
            }else{
				await loadLogisticsMethods(1);
			}
			
        } else {
            throw new Error(response?.Message || "分组数据获取失败");
        }
    } catch (error) {
        console.error('tokenloadLogisticsGroups:', token);
        console.error('加载分组失败loadLogisticsGroups:', error);
        logisticsGroupSelect.innerHTML = '<option value="">-- 加载失败 --</option>';
    } finally {
        const loading = logisticsGroupSelect.parentNode.querySelector('.loading');
        if (loading) loading.remove();
        logisticsGroupSelect.disabled = false;
    }
}

// 新增函数：加载物流方式
// 添加请求锁标志
let isLoadingLogisticsMethods = false;
// 在全局添加缓存对象
const calculationCache = new Map();

// 新增处理函数
function processLogisticsMethods(profitResponse) {
	console.log(profitResponse)
    window.allLogisticsMethods = profitResponse.all_methods;

    // 清空并填充物流方式下拉菜单
    logisticsMethodSelect.innerHTML = '<option value="">-- 请选择物流方式 --</option>';

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

    // 处理所有物流方式
    profitResponse.all_methods.forEach((method, index) => {
        const option = document.createElement('option');
        option.value = index;
        option.textContent = `${method.name} (利润: ${getCurrencySymbol(currency)}${method.profit.toFixed(2)})`;

        // 存储额外数据
        option.dataset.profit = method.profit;
        option.dataset.logisticFee = method.logistic_fee;
        option.dataset.profitRate = method.profit_rate;
        option.dataset.commission = method.commission;

        logisticsMethodSelect.appendChild(option);

        // 跟踪最佳方法
        if (method.profit > maxProfit) {
            maxProfit = method.profit;
            bestMethodIndex = index;
        }
    });

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

async function loadLogisticsMethods(groupId) {
    if (!groupId || isLoadingLogisticsMethods) return;
    isLoadingLogisticsMethods = true;

    try {
        // 获取用户token
        const cookie = await new Promise(resolve => {
            config.getCookie({ "url": config.url.domainz(), "name": config.cookieName11 }, resolve);
        });
        if (!cookie?.value) throw new Error("用户未登录");
        const token = cookie.value;

        // 获取物流方式
        const response = await request(config.url.getLogisticsMethods(groupId), {
            method: "POST",
            responseType: "json",
            body: { weight: 500, price: 100, purchase_price: 0, currency: 'CNY' },
            headers: { 'Authorization': token, 'Content-Type': 'application/json' }
        });

        console.log('获取物流方式响应:', response);

        // if (response?.data?.items?.length > 0) {
			whCacheDetail = response.data.items
			console.log(whCacheDetail)
			setSkuData()
        // }
    } catch (error) {
        console.error('加载物流方式失败:', error);
    } finally {
        isLoadingLogisticsMethods = false;
    }
}


// 计算利润
function updateProfitDisplay() {
    const selectedOption = logisticsMethodSelect.options[logisticsMethodSelect.selectedIndex];
    if (!selectedOption || selectedOption.value === "") return;

    // 直接从option的dataset获取数据
    const profit = parseFloat(selectedOption.dataset.profit);
    const logisticFee = parseFloat(selectedOption.dataset.logisticFee);
    const profitRate = parseFloat(selectedOption.dataset.profitRate);

    // 获取当前货币符号
    const currencySymbol = getCurrencySymbol(currency_code);

    // 更新UI显示
    logisticsCostElement.textContent = `${currencySymbol}${logisticFee.toFixed(2)}`;
    estimatedProfitElement.textContent = `${currencySymbol}${profit.toFixed(2)}`;
    profitMarginElement.textContent = `${profitRate.toFixed(2)}%`;

    commission = parseFloat(selectedOption.dataset.commission);
    console.log('当前佣金:', commission);

    // 设置颜色
    estimatedProfitElement.className = profit >= 0
        ? 'profit-value positive' : 'profit-value negative';
    profitMarginElement.className = profitRate >= 0
        ? 'profit-value positive' : 'profit-value negative';
}

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

// 新增函数：获取单个SKU的完整分析数据（包含两个API请求）
async function getCompleteSkuAnalysis(skuValue, headers) {
    try {
        // 1. 发送单个SKU分析请求
        const analyticsResponse = await new Promise((resolve) => {
            const params = {
                url: productPageUrl || window.location.href
            };
            httpPostoz('https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3', params, resolve);
        });
        
if(!analyticsResponse || !analyticsResponse.items || analyticsResponse.items.length==0){
            var emptyResp = analyticsResponse || {};
            OzAnalytics.shapeEmptyAnalytics(emptyResp, sku);
            console.log(emptyResp);
            return callback(emptyResp);
        }
        const searchData = await getProductDetailnew(headers, analyticsResponse.items[0].variantId);
        
        
        
        // 3. 合并两个响应数据
        const mergedData = {
            items: [],
            totals: '1',
            updateDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
            benchmark: {
                gmvSum: analyticsResponse?.benchmark?.gmvSum || 0,
                salesDynamics: analyticsResponse?.benchmark?.salesDynamics || 0,
                soldCount: analyticsResponse?.benchmark?.soldCount || 0,
                avgGmv: analyticsResponse?.benchmark?.avgGmv || 0,
                sumMissedGmv: analyticsResponse?.benchmark?.sumMissedGmv || 0
            },
            productDetail: {
                variant_id: skuValue,
                name: searchData?.name || productNameInput.value,
                description: searchData?.description || '',
                categories: searchData?.categories || [],
                images: searchData?.images || [],
                specifications: searchData?.specifications || {}
            }
        };
        
        return mergedData;
    } catch (error) {
        console.error('获取SKU完整分析数据失败:', error);
        // 返回默认数据结构
        return {
            items: [],
            totals: '1',
            updateDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
            benchmark: {
                gmvSum: 0,
                salesDynamics: 0,
                soldCount: 0,
                avgGmv: 0,
                sumMissedGmv: 0
            },
            productDetail: {
                variant_id: skuValue,
                name: productNameInput.value,
                description: '',
                categories: [],
                images: []
            }
        };
    }
}
async function getProductDetailnew(headers, sku) {
    if (!sku) {
        console.log('SKU为空，跳过商品详情搜索');
        return null;
    }

    try {
        let pourl = 'https://seller.ozon.ru/api/site/seller-prototype/create-bundle-by-variant-id';
        let paa = JSON.stringify({"company_id":""+headers['x-o3-company-id']+"","variant_id":""+sku+"","source":"SOURCE_UI_COPY_MERGED"});
        console.log('搜索商品详情，SKU:', sku);

        const response = await fetch(pourl, {
            method: "POST",
            headers: headers,
            body: paa,
        });

        if (!response.ok) {
            //console.error('商品详情请求失败:', response.status, response.statusText);
            return null;
        }

        const data = await response.json();
        console.log(data.item);

        if (data.item) {
            const firstItem = data.item;
            //console.log('找到商品详情:', firstItem);
			const specs = getProductSpecifications(firstItem);
			        //console.log('提取到的规格信息:', specs);
			        
			        // 如果需要，可以将规格信息添加到商品对象中
			        firstItem.specifications = specs;
            return firstItem;
        } else {
            console.log('未找到相关商品1');
            return null;
        }
    } catch (error) {
        console.error('获取商品详情失败:', error);
        return null;
    }
}
// 重置表单
function resetForm() {
    storeSelect.value = '';
    productNameInput.value = '';
    //salePriceInput.value = '';
    packageWeightInput.value = '';
    purchasePriceInput.value = '';
    logisticsGroupSelect.value = '';
    logisticsMethodSelect.value = '';
}

function submitFormMessage(text){
	const message = text
	showCustomConfirm({
	    message,
	    onConfirm: async () => {}
	})
}

// 自定义确认弹窗
function showCustomConfirm(options) {
    // 移除已存在的确认弹窗
    const existingModal = document.getElementById('custom-confirm-modal');
    if (existingModal) {
        existingModal.remove();
    }

    const { message, onConfirm, type = 'default' } = options;

    let icon, color, title, confirmButtonColor, confirmButtonTextColor;

    switch (type) {
        case 'danger':
            title = '确认降价';
            color = '#ffffff';
            confirmButtonColor = '#c82333';
            confirmButtonTextColor = '#FFFFFF';
            icon = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 16V8" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M8 12L12 16L16 12" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
            break;
        case 'success':
            title = '确认涨价';
            color = '#ffffff';
            confirmButtonColor = '#1e88e5';
            confirmButtonTextColor = '#FFFFFF';
            icon = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 8V16" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 12L12 8L8 12" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
            break;
        default:
            title = '操作确认';
            color = '#ffffff';
            confirmButtonColor = '#1e88e5';
            confirmButtonTextColor = '#FFFFFF';
            icon = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 16V12" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 8H12.01" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
    }

    const modalHtml = `
        <div id="custom-confirm-modal" style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #ffffff;
            overflow:hidden;
            backdrop-filter: blur(5px);
            z-index: 1000000000;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            opacity: 0;
            transition: opacity 0.2s ease;
        ">
            <div style="
                background: #ffffff;
                border: 1px solid #eeeeee;
                border-radius: 12px;
                width: 480px;
                display: flex;
                flex-direction: column;
                color: #151515;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
                transform: scale(0.95);
                transition: transform 0.2s ease;
                overflow:hidden;
            ">
                <!-- Header -->
                <div style="
                    padding: 16px 24px;
                    border-bottom: 1px solid #eeeeee;
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    background:linear-gradient(135deg, #1e88e5, #0d47a1);
                ">
                    ${icon}
                    <h3 style="margin: 0; color: ${color}; font-size: 18px; font-weight: 600;">${title}</h3>
                </div>
                
                <!-- Message -->
                <div style="
                    padding: 24px;
                    font-size: 15px;
                    line-height: 1.6;
                    white-space: pre-wrap;
                    color: #151515;
                ">
                    ${message}
                </div>
                
                <!-- Footer/Actions -->
                <div style="
                    padding: 16px 24px;
                    border-top: 1px solid #eeeeee;
                    display: flex;
                    justify-content: flex-end;
                    gap: 12px;
                    background: #eeeeee;
                ">
                    <button id="confirm-cancel" style="
                        background: #FFFFFF;
                        border: 1px solid #eeeeee;
                        border-radius: 6px;
                        padding: 10px 20px;
                        font-size: 14px;
                        font-weight: 600;
                        cursor: pointer;
                        transition: all 0.2s;
                    ">取消</button>
                    <button id="confirm-ok" style="
                        background: ${confirmButtonColor};
                        color: ${confirmButtonTextColor};
                        border: none;
                        border-radius: 6px;
                        padding: 10px 20px;
                        font-size: 14px;
                        font-weight: 700;
                        cursor: pointer;
                        transition: all 0.2s;
                    ">确定</button>
                </div>
            </div>
        </div>
    `;

    // 使用原生DOM方法添加到body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    const modal = document.getElementById('custom-confirm-modal');
    const modalContent = modal.querySelector('div');
    
    // Trigger animations
    setTimeout(() => {
        modal.style.opacity = '1';
        modalContent.style.transform = 'scale(1)';
    }, 10);

    const closeModal = () => {
        modal.style.opacity = '0';
        modalContent.style.transform = 'scale(0.95)';
        setTimeout(() => {
            modal.remove();
        }, 200);
    };

    // 绑定确定按钮事件
    const confirmOk = document.getElementById('confirm-ok');
    confirmOk.addEventListener('click', () => {
        closeModal();
        if (onConfirm && typeof onConfirm === 'function') {
            onConfirm();
        }
    });

    // 绑定取消按钮事件
    const confirmCancel = document.getElementById('confirm-cancel');
    confirmCancel.addEventListener('click', closeModal);
    
    // 绑定背景点击事件
    modal.addEventListener('click', (e) => {
        if (e.target.id === 'custom-confirm-modal') {
            closeModal();
        }
    });
}

// 提交表单
// 在submitForm函数中实现铺货逻辑
async function submitForm() {

    if (!storeSelect.value) {
        submitFormMessage('请选择店铺');
        return;
    }

    // if (!productNameInput.value) {
    //     submitFormMessage('请输入产品名称');
    //     return;
    // }
    // if (!hasValidUrl) {
    //     submitFormMessage('请至少输入一个有效的货源URL');
    //     return;
    // }

//     if (!purchasePriceInput.value) {
//     alert('请输入进货价格');
//     return;
// }

//     if (!salePriceInput.value) {
//         alert('请输入销售价格');
//         return;
//     }

    // if (!packageWeightInput.value) {
    //     alert('请输入包裹重量');
    //     return;
    // }
	
	const selectedCheckboxes = document.querySelectorAll('.sku-checkbox:checked');
	const selectedSkus = Array.from(selectedCheckboxes).map(cb => cb.dataset.sku);
	
	if (selectedSkus.length === 0) {
	    submitFormMessage('请至少选择一个SKU');
	    return;
	}
    // if (multipleSkus.length === 0) {
    //     submitFormMessage('请至少选择一个SKU');
    //     return;
    // }
	let multipleSelectedSkus =[]
	for (let i = multipleSkus.length - 1; i >= 0; i--) {
		const sku = multipleSkus[i].sku;
		if (selectedSkus.some(selectedSku => 
			sku === selectedSku || 
			(typeof sku === 'string' && sku.includes(selectedSku))
		)) {
			multipleSelectedSkus.push(multipleSkus[i]);
		}
	}
	 

    // 检查是否有至少一个有效的URL
    const urlInputs = document.querySelectorAll('.sourceUrlInput');
    let hasValidUrl = false;
    for (let i = 0; i < urlInputs.length; i++) {
        if (urlInputs[i].value.trim()) {
            hasValidUrl = true;
            break;
        }
    }

    

    // 获取当前页面URL作为sourcing_uri
    const sourcing_uri = productPageUrl;
    const cookie = await new Promise(resolve => {
        config.getCookie({ "url": config.url.domainz(), "name": config.cookieName11 }, resolve);
    });
    const token = cookie.value;

    // 获取物流费用（转换为数值）
    const logisticsCostText = logisticsCostElement.textContent;
    const logistic_cost = parseFloat(logisticsCostText.replace(/[^\d.]/g, ''));

    // 获取预估利润（转换为数值）
    const profitText = estimatedProfitElement.textContent;
    const profit = parseFloat(profitText.replace(/[^\d.]/g, ''));

    // 获取利润率（转换为数值）
    const profitRateText = profitMarginElement.textContent;
    const profit_rate = parseFloat(profitRateText.replace(/[^\d.%]/g, ''));

    
    // 转换 SKU 格式
    const transformedSkus = multipleSelectedSkus.flatMap(item => {
        // 确保 sku 是数组格式
        const skus = Array.isArray(item.sku) ? item.sku : [item.sku];

        return skus.flatMap(sku => {
            // 处理嵌套数组的情况
            if (Array.isArray(sku)) {
                return sku.map(s => ({
                    sku: s,
                    price: item.price
                }));
            }
            return {
                sku: sku,
                price: item.price
            };
        });
    });

    

    // 收集所有URL
    const sourceUrls = [];
    document.querySelectorAll('.sourceUrlInput').forEach(input => {
        const url = input.value.trim();
        if (url) {
            sourceUrls.push(url);
        }
    });

    // 构建skulist字符串（格式：sku1,price1;sku2,price2）
    const skulist = transformedSkus.map(item => `${item.sku},${item.price}`).join(';');

    // 准备铺货数据
    const formData = {
        userid: userid,
        sku: sku[0], // 使用主SKU
        weight: parseFloat(packageWeightHYText), 
        price: parseFloat(salePriceHYText),
        logistic_cost: logistic_cost,
        id: storeSelect.value,
        appid: storeSelect.value,
        profit: profit,
        profit_rate: profit_rate,
        purchase_price: parseFloat(purchasePriceInput.value) || 0,
        commission: commission,
        product_name: productNameInput.value,
        sourcing_uri: sourcing_uri,
        source_urls: JSON.stringify(sourceUrls), // 将URL数组转换为JSON字符串
        skulist: skulist,           // 新格式
        urls: sourceUrls.join(','), // 用逗号分隔
        flowOrCopy: document.getElementById('flow-or-copy').value,        // 固定值
        noBrand: document.getElementById('flow-or-brand').value,            // 固定值
        jobtype: 2,                 // 固定值
        currency_code: currency,
    };

    console.log('formData:', formData);

    //移除原有的sku字段
    delete formData.sku;

    try {
        // 显示提交中状态
        submitBtn.disabled = true;
        submitBtn.textContent = '提交中...';

        // 构建skulists数组，存储sku的完整信息
        const skulists = [];
        
        // 根据SKU类型构建不同的skulists数据
        if (skuTypeSingle && skuTypeSingle.checked) {
            // 单个SKU模式
            let singleSkuData;
            // 检查是否有存储的响应数据
            if (singleSkuAnalysisResponse) {
                // 使用存储的响应数据
                singleSkuData = singleSkuAnalysisResponse;
            } else {
                // 构建一个默认的数据结构
                singleSkuData = {
                    items: [],
                    totals: '1',
                    updateDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
                    benchmark: {
                        gmvSum: 0,
                        salesDynamics: 0,
                        soldCount: 0,
                        avgGmv: 0,
                        sumMissedGmv: 0
                    },
                    productDetail: {
                        variant_id: sku[0],
                        name: productNameInput.value,
                        description: '',
                        categories: [],
                        images: []
                    }
                };
            }
            skulists.push(singleSkuData);
        } else if (skuTypeMultiple && skuTypeMultiple.checked) {
			
			// 多个SKU模式
			// 构建多个SKU的完整信息
			for (const item of multipleSelectedSkus) {
				const skuValue = Array.isArray(item.sku) ? item.sku[0] : item.sku;
				let multiSkuData;
				// 检查是否有存储的响应数据
				if (multipleSkuSearchResponses[skuValue]) {
					// 使用存储的响应数据
					multiSkuData = multipleSkuSearchResponses[skuValue];
				} else {
					// 构建一个默认的数据结构，优先使用单个SKU分析的响应数据
					if (singleSkuAnalysisResponse && singleSkuAnalysisResponse.productDetail) {
						// 使用单个SKU分析的响应数据作为基础
						multiSkuData = {
							variant_id: skuValue,
							name: productNameInput.value,
							description: singleSkuAnalysisResponse.productDetail.description || '',
							categories: singleSkuAnalysisResponse.productDetail.categories || [],
							images: singleSkuAnalysisResponse.productDetail.images || []
						};
					} else {
						// 完全默认的数据结构
						multiSkuData = {
							variant_id: skuValue,
							name: productNameInput.value,
							description: '多SKU产品',
							categories: [],
							images: []
						};
					}
				}
				skulists.push(multiSkuData);
			}
		}
        console.log('skulists:', skulists);

        // 先发送请求到config.url.skusList()
        
        const skusListResponse = await request(config.url.skusList(), {
            method: "POST",
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(skulists)
        });

       

        // 然后发送请求到config.url.pushItem()，使用formData作为请求体
        const response = await request(config.url.pushItem(), {
            method: "POST",
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        console.log('responseSubmitForm:', response);
        // const result = await response.json();
        if (response && response.status == 'success') {
            
            // 清理表单
            resetForm();

            // 清理利润计算
            logisticsCostElement.textContent = '¥0.00';
            estimatedProfitElement.textContent = '¥0.00';
            profitMarginElement.textContent = '0.00%';

            // 清理SKU设置
            multipleSkus = [];
			multipleSelectedSkus= []
			if (skuTypeSingle) skuTypeSingle.checked = true;
            updateSkuListDisplay();

            // 清理货源URL
            sourceUrlsContainer.innerHTML = '';
            addNewUrlInput(); // 添加一个空URL输入框
            
            // 关闭弹窗
            submitFormMessage('铺货成功！产品已添加到您的店铺');
            setInterval(function(){
                window.parent.postMessage({ type: 'CLOSE_IFRAME' }, '*');
		    },2000);

            
            
        } else {
            throw new Error(response.msg || "铺货失败");
        }
    } catch (error) {
        console.error('铺货请求失败:', error);
        submitFormMessage('铺货失败');
        return;
    } finally {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '一键铺货';
    }
}

function getToken() {
    return document.cookie.match('(^|;) ?' + config.cookieName11 + '=([^;]*)(;|$)')?.[2];
}

// 初始化SKU处理逻辑
function initSkuHandling() {
    if (!skuTypeSingle || !skuTypeMultiple) return;
    // 默认选中单个SKU时，添加当前SKU到multipleSkus数组
    if (skuTypeSingle.checked) {
        // 清空现有数组
        multipleSkus = [];
        // 添加当前SKU
        if (sku) {
            if (Array.isArray(sku)) {
                // 当sku是数组时，为每个SKU创建单独的对象
                sku.forEach((skuCode, index) => {
                    // 使用解析到的价格（如果存在），否则使用当前价格
                    const price = prices && prices[index] ? prices[index] : parseFloat(salePriceInput.value) || 0;
                    multipleSkus.push({ sku: skuCode, price: price });
                });
            } else {
                // 当sku不是数组时，直接添加
                multipleSkus.push({ sku: sku, price: parseFloat(salePriceInput.value) || 0 });
            }
        }
    }

    // 添加销售价格变化时，只更新第一个SKU的价格（主SKU）
    salePriceInput.addEventListener('input', function () {
        const newPrice = parseFloat(this.value) || 0;
        // 只更新第一个SKU的价格（主SKU）
        if (multipleSkus.length > 0) {
            multipleSkus[0].price = newPrice;
        }
    });
}


async function httpPost(url, params = {}, callback = () => {}) {
    getCookies().then(({token}) => {
        // 使用 Chrome runtime API 发送跨域请求
        chrome.runtime.sendMessage({
            action: "httpRequest",
            method: "POST",
            url: url,
            params: params,
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            }
        }, callback);
    })
}
async function getWeightskuinfo(iteminfo) {
    // const cookie = await new Promise(resolve => {
    //     chrome.cookies.get({ "url": config.url.domainz(), "name": config.cookieName11 }, resolve);
    // });
    // const token = cookie.value;
    const cookie = await getCookies();
    console.log('cookie:', cookie);
    const token = cookie.token;
    const pendingGoodsWeight = sessionStorage.getItem('pendingGoodsWeight');
    const pendingGoodsSku = sessionStorage.getItem('pendingGoodsSku');
    const request = {
        "url": config.url.weightskuinfo(),
        "params": {
            "weight": pendingGoodsWeight,
            "sku": pendingGoodsSku,
            "iteminfo": iteminfo,
        }
    }
    httpPost(request["url"], request["params"], (res) => {
        console.log('weightskuResponse:', res);
                    //  sendResponse(res)
                 });
    // const weightskuResponse = await request(config.url.weightskuinfo(), {
    //             method: "POST",
    //             responseType: "json",
    //             body: {
    //                 weight: pendingGoodsWeight,
    //                 sku: sessionStorage.getItem('pendingGoodsSku'),
    //             },
    //             headers: { 'Authorization': token, 'Content-Type': 'application/json' }
    //         });
}
// 新增：手动获取重量的函数
async function handleGetWeight(pendingGoodsWeight) {
    // 显示加载状态
    const getWeightBtn = document.getElementById('getWeightBtn');
    const originalText = getWeightBtn.innerHTML;
    getWeightBtn.innerHTML = '<i>⏳</i> 获取中...';
    getWeightBtn.disabled = true;
    
    try {
        // 1. 尝试从sessionStorage获取已有的重量数据pendingGoodsWeight
        const storedWeight = sessionStorage.getItem('pendingGoodsWeight');
        const storedSku = sessionStorage.getItem('pendingGoodsSku');
        
        console.log('从sessionStorage获取到重量数据:', storedWeight);
        packageWeightInput.value = pendingGoodsWeight;
        // if (storedWeight && storedSku) {
        //     console.log('从sessionStorage获取到重量数据:', storedWeight);
        //     packageWeightInput.value = pendingGoodsWeight;
        //     pendingGoodsWeight = storedWeight;
        //     pendingGoodsSku = storedSku;
            
        //     // 触发利润计算
        //     if (logisticsGroupSelect.value) {
        //         handleInputChange();
        //     }
        //     return;
        // }
        // 2. 如果没有缓存的重量数据，则重新获取
        //console.log('没有缓存的重量数据，尝试重新获取...');
        
        
        
        // 3. 如果所有尝试都失败，提示用户
        //alert('获取重量失败，请手动输入包裹重量');
    } catch (error) {
        console.error('获取重量时发生错误:', error);
        alert('获取重量时发生错误，请手动输入包裹重量');
    } finally {
        // 恢复按钮状态
        getWeightBtn.innerHTML = originalText;
        getWeightBtn.disabled = false;
    }
}
// 在文件顶部的全局变量区域添加
let isFormInitialized = false;
// 初始化表单
async function initForm() {
    if (isFormInitialized) {
        console.log('表单已经初始化，跳过重复初始化');
        return;
    }
    isFormInitialized = true;
    const storedWeight = sessionStorage.getItem('pendingGoodsWeight');
    if (storedWeight) {
        const parsedWeight = parseFloat(storedWeight);
        if (!isNaN(parsedWeight)) {
            pendingGoodsWeight = parsedWeight;
        }
    }
    // 自动设置包裹重量输入框的值
    if (pendingGoodsWeight && packageWeightInput) {
        packageWeightInput.value = pendingGoodsWeight;
        console.log('已自动设置包裹重量:', pendingGoodsWeight, 'g');
    }
    packageWeightInput = document.getElementById('packageWeight');
    // 初始化获取重量按钮
    const getWeightBtn = document.getElementById('getWeightBtn');
    console.log('pendingGoodsWeight66666:', pendingGoodsWeight);
    if (pendingGoodsWeight) {
        getWeightBtn.addEventListener('click', () => handleGetWeight(pendingGoodsWeight));
    }
    
    // if (getWeightBtn && pendingGoodsWeight) {
    //     console.log('添加点击事件监听器');
    //     getWeightBtn.addEventListener('click', () => handleGetWeight(pendingGoodsWeight));
    // }
    console.log('pendingGoodsWeight1:', pendingGoodsWeight);
    //packageWeightInput.value = pendingGoodsWeight;
  
	console.log('pendingGoodsWeight2:', pendingGoodsWeight);
    let itemInfo = productInfo;
    // 设置货币符号
    const currencySymbol = getCurrencySymbol(currency);
    // document.getElementById('purchasePriceSymbol').textContent = currencySymbol;
    // document.getElementById('salePriceSymbol').textContent = currencySymbol;
    //document.getElementById('logisticsCostSymbol').textContent = currencySymbol; // 物流费用固定显示人民币符号
    // 获取DOM元素
    storeSelect = document.getElementById('store');
    productNameInput = document.getElementById('productName');
    salePriceInput = document.getElementById('salePrice');
	
	salePriceHYInput = document.getElementById('salePriceHY');
	packageWeightHYInput = document.getElementById('packageWeightHY');
	salePriceHYInput.addEventListener('input', function () {
	    salePriceHYText = parseFloat(this.value) || 0;
	});
	packageWeightHYInput.addEventListener('input', function () {
	    packageWeightHYText = parseFloat(this.value) || 0;
	});
    
    purchasePriceInput = document.getElementById('purchasePrice');
    logisticsCostElement = document.getElementById('logisticsCost');
    estimatedProfitElement = document.getElementById('estimatedProfit');
    profitMarginElement = document.getElementById('profitMargin');
    // resetBtn = document.getElementById('resetBtn');
    submitBtn = document.getElementById('submitBtn');
	//关闭按钮 start
	distributingGoodsCloseBtn = document.getElementById('distributing-goods-close-btn');
	console.log(distributingGoodsCloseBtn)
	if (distributingGoodsCloseBtn) {
		// 移除可能存在的旧监听器
		distributingGoodsCloseBtn.replaceWith(distributingGoodsCloseBtn.cloneNode(true));
		const newCloseBtn = document.getElementById('distributing-goods-close-btn');
		
		newCloseBtn.addEventListener('click', function() {
			console.log('关闭按钮被点击');
			// 向父页面发送关闭消息
			window.parent.postMessage({
				type: 'CLOSE_IFRAME',
				source: 'distributing-goods-iframe',
				timestamp: Date.now()
			}, '*'); 
			
			console.log('已发送关闭消息');
		});
		
		console.log('关闭按钮事件绑定成功');
	} else {
		console.error('未找到关闭按钮元素');
	}
	//关闭按钮 end
	
    // 获取货源URL相关元素
    sourceUrlsContainer = document.getElementById('sourceUrlsContainer');
    addUrlBtn = document.getElementById('addUrlBtn');

    // 添加URL按钮点击事件
    addUrlBtn.addEventListener('click', addNewUrlInput);

    loadShops();

    // 获取新增的DOM元素
    logisticsGroupSelect = document.getElementById('logisticsGroup');
    logisticsMethodSelect = document.getElementById('logisticsMethod');
    // 确认选择器是否与HTML中的元素匹配
    logisticsDetailsContainer = document.querySelector('.logistics-method-details');

    await new Promise(resolve => setTimeout(resolve, 100));

    // 加载物流分组（不再需要等待店铺选择）
    await loadLogisticsGroups();
    storeSelect.addEventListener('change', function () {
        // 当店铺被选择时可以重新加载物流分组（可选）
        // loadLogisticsGroups();
    });

    // 填充表单
    productNameInput.value = "";
    //salePriceInput.value = "";
    purchasePriceInput.value = "";
    // console.log('pendingGoodsWeight:',window.pendingGoodsWeight)
    // if(window.pendingGoodsWeight){
    //     packageWeightInput.value = window.pendingGoodsWeight;
    // }
    
    
    
    console.log('initForm-itemInfo:', itemInfo);
    salePriceInput.value = itemInfo[0].Price;
    // 初始计算利润
    if (logisticsGroupSelect.value && logisticsMethodSelect.value ) {
        updateProfitDisplay();
    }
	
    salePriceInput.addEventListener('input', handleInputChange);
    packageWeightInput.addEventListener('input', handleInputChange);
    // purchasePriceInput.addEventListener('input', handleInputChange);
    purchasePriceInput.addEventListener('input', function() {
		// 当进货价格变化且有效时立即触发计算
		if (this.value > 0 && logisticsGroupSelect.value) {
			handleInputChange();
		}
	});
    // 确保物流方式默认状态
    logisticsMethodSelect.innerHTML = '<option value="">-- 请先选择分组 --</option>';
    logisticsMethodSelect.disabled = true;

    // 添加分组变化监听
    logisticsGroupSelect.addEventListener('change', function () {
		let groupId = this.value;
		loadLogisticsMethods(groupId)
        // logisticsMethodSelect.disabled = !this.value;
    });
	
    // 添加销售价格变化时更新SKU价格
    // salePriceInput.addEventListener('input', function() {
    //     const newPrice = parseFloat(this.value) || 0;
    //     // 更新所有SKU的价格
    //     multipleSkus.forEach(item => {
    //         item.price = newPrice;
    //     });
    // });
    // 物流方式下拉菜单change事件
    logisticsMethodSelect.addEventListener('change', function () {
        updateProfitDisplay(); // 使用已有的函数更新利润显示
        //showLogisticsDetails(); // 刷新物流详情
    });
    // resetBtn.addEventListener('click', resetForm);
    submitBtn.addEventListener('click', submitForm);
    // 通知父页面iframe已准备好
    window.parent.postMessage({ type: 'IFRAME_READY' }, '*');
	
	document.addEventListener('click', function(e) {
	    const target = e.target.closest('.sku-list-table-cell-weight');
	    if (!target) return;
	    let self = target;
		if (self.dataset.weight !='点击获取') return;
	    self.textContent = '↻ 查询中...';
	    
	    setTimeout(async () => {
	        let suk = self.dataset.sku;
	        const weightValue = ((await getWaith(suk)) || '无')
	            .replace('гр', 'g')
	            .replace('кг', 'kg');
	        self.textContent = weightValue;
			self.style.cssText = '';          // 删除所有内联样式
			multipleSkus.forEach((skuItem, index) => {
				if (skuItem.sku === suk) {
					multipleSkus[index].weight = weightValue
				}
			});
			if(multipleSkus.length>1){
				multipleSKUstrong = multipleSkus
			}else{
				singleSKUstrong = multipleSkus
			}
			setSkuListData();
	    }, 0);
	});
	
    // 初始化SKU列表显示
    updateSkuListDisplay();

}
function setSkuData(){
	// 获取SKU类型选择器元素
	skuTypeSingle = document.querySelector('input[name="skuType"][value="single"]');
	skuTypeMultiple = document.querySelector('input[name="skuType"][value="multiple"]');
	
	// 添加SKU类型选择器事件监听
	if (skuTypeSingle && skuTypeMultiple) {
	    // 初始化处理
	    initSkuHandling();
	    // 添加单选按钮切换事件
	    skuTypeSingle.addEventListener('change', function () {
	        if (this.checked) {
	            // 选择单个SKU时，重置multipleSkus数组并只添加当前SKU
	            multipleSkus = [];
				let skuListContainer = document.getElementById('skuListContainer');
				
				skuListContainer.innerHTML = `
				    <div class="sku-list-empty">
				        <p>SKU信息加载中...</p>
				    </div>
				`;
				
	            if (sku) {
	                multipleSkus.push({ sku: sku[0], price: parseFloat(salePriceInput.value) || 0 });
	            }
				console.log('切换到单个SKU模式，当前SKU:', multipleSkus);
	            updateSkuListDisplay();
	        
	            // 发送第一个API请求（单SKU分析）
	            if (sku && sku[0]) {
					if(singleSKUstrong){
						multipleSkus = singleSKUstrong.slice(0, 1);
						setSkuListData();
						return
					}
	                console.log('发送单个SKU分析请求，SKU:', sku[0]);
	                // 获取Ozon卖家平台的cookie
	                getCookiesoz().then(({token, sc_company_id}) => {
	                    if (token && sc_company_id) {
	                        const headers = {
	                            "Accept": 'application/json, text/plain, */*',
	                            "Accept-Encoding": 'gzip, deflate, br, zstd',
	                            "Accept-Language": 'zh-Hans',
	                            "Content-Type": 'application/json',
	                            "Origin": 'https://seller.ozon.ru',
	                            "Sec-Ch-Ua": 'Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
	                            "Sec-Ch-Ua-Mobile": '?1',
	                            "Sec-Ch-Ua-Platform": '"Android"',
	                            "Sec-Fetch-Dest": 'empty',
	                            "Sec-Fetch-Mode": 'cors',
	                            "Sec-Fetch-Site": 'same-origin',
	                            "x-o3-company-id": sc_company_id,
	                            "x-o3-language": 'zh-Hans',
	                            "User-Agent": 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36'
	                        };
	                        // 使用新函数获取完整分析数据
	                        getCompleteSkuAnalysis(sku[0], headers).then(response => {
	                            console.log('单个SKU分析请求响应:', response);
	                            // 存储响应数据
								const weight = response.productDetail.specifications.weight;
								
	                            // 提取重量并设置到包裹重量输入框
	                            if (response.productDetail && response.productDetail.specifications && response.productDetail.specifications.weight) {
	                                const weight = response.productDetail.specifications.weight;
	                                if (weight) {
										packageWeightHYInput.value = weight ||0
	                                    multipleSkus[0].weight = weight ||0
	                                    console.log('已从商品数据设置包裹重量:', weight, 'g');
	                                }
	                            }
								console.log('更新后的 multipleSkus:', multipleSkus);
								singleSKUstrong = multipleSkus
								setSkuListData();
	                        });
	                    } else {
	                        console.error('获取Ozon卖家平台cookie失败，无法发送SKU分析请求');
	                    }
	                });
	            }
	        }
	    });
		
		// 初始化时，如果默认选中单个SKU，自动触发API请求
		if (skuTypeSingle.checked && sku && sku[0]) {
			console.log('初始化时默认选中单个SKU，自动发送分析请求，SKU:', sku[0]);
			multipleSkus = multipleSkus.slice(0, 1);
			// 获取Ozon卖家平台的cookie
			getCookiesoz().then(({token, sc_company_id}) => {
				if (token && sc_company_id) {
					const headers = {
						"Accept": 'application/json, text/plain, */*',
						"Accept-Encoding": 'gzip, deflate, br, zstd',
						"Accept-Language": 'zh-Hans',
						"Content-Type": 'application/json',
						"Origin": 'https://seller.ozon.ru',
						"Sec-Ch-Ua": 'Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
						"Sec-Ch-Ua-Mobile": '?1',
						"Sec-Ch-Ua-Platform": '"Android"',
						"Sec-Fetch-Dest": 'empty',
						"Sec-Fetch-Mode": 'cors',
						"Sec-Fetch-Site": 'same-origin',
						"x-o3-company-id": sc_company_id,
						"x-o3-language": 'zh-Hans',
						"User-Agent": 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36'
					};
					// 使用新函数获取完整分析数据
					getCompleteSkuAnalysis(sku[0], headers).then(response => {
						console.log('单个SKU分析请求响应:', response);
						// 提取重量并设置到包裹重量输入框（接口 403/空数据时 productDetail 不存在，跳过即可）
						if (response && response.productDetail && response.productDetail.specifications && response.productDetail.specifications.weight) {
							const weight = response.productDetail.specifications.weight;
							if (weight) {
								multipleSkus[0].weight = weight ||0
								packageWeightHYInput.value = weight ||0
								console.log('已从商品数据设置包裹重量:', weight, 'g');
							}
						}
						console.log('更新后的 multipleSkus:', multipleSkus);
						singleSKUstrong = multipleSkus
						setSkuListData();
					});
				} else {
					console.error('获取Ozon卖家平台cookie失败，无法发送SKU分析请求');
				}
			});
		}
	    
	
	    skuTypeMultiple.addEventListener('change', function () {
	        if (this.checked) {
				let skuListContainer = document.getElementById('skuListContainer');
				multipleSkus =[]
				skuListContainer.innerHTML = `
				    <div class="sku-list-empty">
				        <p>SKU信息加载中...</p>
				    </div>
				`;
				
				// 选择多个SKU时，如果数组为空，添加当前SKU作为默认
				if (multipleSkus.length === 0 && sku) {
					for (let i = 0; i < sku.length; i++) {
						multipleSkus.push({ sku: sku[i], price: parseFloat(salePriceInput.value) || 0 ,weight:'',fee:0,whType:'',cost:0,profit:'0|0%'});
					}
					updateSkuListDisplay();
				} else {
					updateSkuListDisplay();
				}
				if(multipleSKUstrong){
					multipleSkus = multipleSKUstrong
					setSkuListData();
					return
				}
				try {
					// 使用 await 确保请求完成
					const response = request(
						`https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fmodal%2FotherOffersFromSellers%3Fproduct_id%3D${sku[0]}%26page_changed%3Dtrue`,
						{
							method: "POST",
							responseType: "json",
						}
					).then(response => {
						console.log('API完整响应:', response);
						if (response && response.widgetStates) {
							const widgetStates = response.widgetStates;
							console.log('提取的 widgetStates:', widgetStates);
					
							// 用于存储所有提取的SKU
							const sellerSkus = new Set();
					
							// 遍历 widgetStates 对象的所有键
							for (const key in widgetStates) {
								// 检查键是否以 'webSellerList' 开头
								if (key.startsWith('webSellerList')) {
									try {
										// 解析值为对象
										const sellerData = JSON.parse(widgetStates[key]);
										console.log(`解析 ${key} 得到的数据:`, sellerData);
					
										// 提取卖家列表中的SKU
										extractSkusFromSellerData(sellerData, sellerSkus);
									} catch (parseError) {
										console.error(`解析 ${key} 的值失败:`, parseError);
									}
								}
							}
					
							console.log('提取到的卖家SKU:', Array.from(sellerSkus));
							//console.log('提取到的multipleSkus222222：', multipleSkus);
							// 添加到 multipleSkus
							sellerSkus.forEach(skuValue => {
								if (!multipleSkus.some(item => item.sku === skuValue)) {
									// 尝试获取每个SKU的价格，这里需要根据实际情况修改
									// 暂时使用不同的价格作为示例
									let skuPrice = parseFloat(salePriceInput.value) || 0;
									// 为了演示不同的价格，我们可以根据SKU的最后几位数字生成不同的价格
									if (skuValue && skuValue.length > 4) {
										const priceSuffix = parseInt(skuValue.slice(-4));
										skuPrice = (skuPrice * (1 + priceSuffix / 10000)).toFixed(2);
									}
									multipleSkus.push({
										sku: skuValue,
										price: skuPrice
									});
								}
							});
					
							console.log('更新后的 multipleSkus:', multipleSkus);
							multipleSKUstrong = multipleSkus
							updateSkuListDisplay();
							
							// 发送第二个API请求（多SKU搜索）
							if (multipleSkus.length > 0) {
								console.log('发送多个SKU搜索请求，SKU列表:', multipleSkus.map(item => item.sku));
								// 构建请求参数
								const params = {
									url: productPageUrl || window.location.href
								};
								// 先获取Ozon卖家平台的cookie，然后发送第二个API请求
								getCookiesoz().then(({token, sc_company_id}) => {
									if (token && sc_company_id) {
										let headers = {
											"Accept": 'application/json, text/plain, */*',
											"Accept-Encoding": 'gzip, deflate, br, zstd',
											"Accept-Language": 'zh-Hans',
											"Content-Type": 'application/json',
											"Origin": 'https://seller.ozon.ru',
											"Sec-Ch-Ua": 'Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
											"Sec-Ch-Ua-Mobile": '?1',
											"Sec-Ch-Ua-Platform": '"Android"',
											"Sec-Fetch-Dest": 'empty',
											"Sec-Fetch-Mode": 'cors',
											"Sec-Fetch-Site": 'same-origin',
											"x-o3-company-id": sc_company_id,
											"x-o3-language": 'zh-Hans',
											"User-Agent": 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36'
										};
										// 遍历所有SKU，一一调用获取完整分析数据的函数
										multipleSkus.forEach((skuItem, index) => {
											// 延迟发送请求，避免请求过于频繁
											setTimeout(async () => {
												let sku = skuItem.sku;
												// 如果SKU是数组，遍历数组中的每个SKU
												if (Array.isArray(sku)) {
													sku.forEach((singleSku, subIndex) => {
														setTimeout(async () => {
															console.log('发送SKU完整分析请求，SKU:', singleSku);
															// 使用新函数获取完整分析数据
															getCompleteSkuAnalysis(singleSku, headers).then(async => {
																console.log('SKU', singleSku, '完整分析响应:', completeData);
																// 存储响应数据
																multipleSkuSearchResponses[singleSku] = completeData;
																let weight = completeData.productDetail.specifications.weight;
																if (weight) {
																	multipleSkus.forEach((skuItem, index) => {
																		if (skuItem.sku === singleSku) {
																			multipleSkus[index].weight = weight ||0
																			
																		}
																	});
																	
																}
																// 对于第一个SKU，提取重量并设置到包裹重量输入框
																// if (index === 0 && subIndex === 0) {
																	
																// 	// if (completeData.productDetail && completeData.productDetail.specifications && completeData.productDetail.specifications.weight) {
																		
																// 	// }
																// 	console.log('index:',index);
																// 	console.log('subindex:',subIndex);
																// 	console.log('completeData:',completeData);
																// 	const weight = completeData.productDetail.specifications.weight;
																// 	if (weight && packageWeightInput) {
																// 		packageWeightInput.value = weight;
																// 		console.log('已从第一个SKU数据设置包裹重量:', weight, 'g');
																		
																// 		// 触发利润计算
																// 		if (logisticsGroupSelect.value) {
																// 			handleInputChange();
																// 		}
																// 	}
																// }
															});
														}, subIndex * 500);
													});
													setSkuListData();
												} else {
													console.log('发送SKU完整分析请求，SKU:', sku);
													// 使用新函数获取完整分析数据
													getCompleteSkuAnalysis(sku, headers).then(completeData => {
														console.log('SKU', sku, '完整分析响应:', completeData);
														// 存储响应数据
														multipleSkuSearchResponses[sku] = completeData;
														
														let weight = completeData.productDetail.specifications.weight;
														if (weight) {
															multipleSkus.forEach((skuItem, index) => {
																if (skuItem.sku === sku) {
																	multipleSkus[index].weight = weight ||0
																}
															});
														}
														setSkuListData()
														
														// 对于第一个SKU，提取重量并设置到包裹重量输入框
														// if (index === 0) {
														// 	if (completeData.productDetail && completeData.productDetail.specifications && completeData.productDetail.specifications.weight) {
														// 		const weight = completeData.productDetail.specifications.weight;
														// 		if (weight && packageWeightInput) {
														// 			packageWeightInput.value = weight;
														// 			console.log('已从第一个SKU数据设置包裹重量:', weight, 'g');
																	
														// 			// 触发利润计算
														// 			if (logisticsGroupSelect.value) {
														// 				handleInputChange();
														// 			}
														// 		}
														// 	}
														// }
													});
												}
											}, index * 500);
										});
										multipleSKUstrong = multipleSkus
									} else {
										console.error('获取Ozon卖家平台cookie失败，无法发送多SKU搜索请求');
									}
								});
							}
						}
					});
	
	
	
				} catch (error) {
					console.error('API请求失败:', error);
				}
				console.log('切换到多个SKU模式，当前SKU列表:', multipleSkus);
	        }
	    });
	}
}
async function setSkuListData(){

	if(whCacheDetail){
		for(var i in multipleSkus){
			if(multipleSkus[i].weight){
				let whType= await getWhType(multipleSkus[i])
				multipleSkus[i].whType =whType
				let price =multipleSkus[i].price
				let cost =multipleSkus[i].cost||0
				let weight =multipleSkus[i].weight
				let result = profitCalculate(
					price, cost, weight,
				    whType,
				    20, 5
				);
				
				multipleSkus[i].profit = result.profit.toFixed(2)+'|'+result.profitRate.toFixed(1)+'%'
				multipleSkus[i].fee = result.logisticsInfo.fee || 0
				
			}
			
		}
		updateSkuListDisplay();
	}
	
}
// 获取物流方式
async function getWhType(sku) {
    return new Promise(function (resolve, reject) {
		if (!sku.weight||!sku.price || !whCacheDetail) return resolve('');
		// 价格先转卢布
		let priceRUB = Number(sku.price) * CNY2RUBDetail;
		// 单位转换
		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 whCacheDetail) {
		    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('');
		
    });
}
function profitCalculate(price, cost, weight, whType, commissionRate, packingFee) {
	const logisticsInfo = calcLogisticsFee({ price, weight, type: whType });
	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,
		whType
	};
}
// 物流费计算函数
function calcLogisticsFee({price, weight, type}) {
	
    const defaultResult = { fee: 0, tierName: '', formulaStr: '' };
    if (!weight || !type ||!whCacheDetail) return defaultResult;
    // 价格先转卢布
    let priceRUB = Number(price) * CNY2RUBDetail;
	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 whCacheDetail) {
        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;
}
// 全局变量：当前页码和每页显示数量
let currentPage = 1;
const itemsPerPage = 10;
// 利润率过滤阈值（低于该值的行会被隐藏）。null 表示不过滤。
let profitMarginFilter = null;

// 从 "10.50|40.00%" 这类 profit 字段里提取利润率数值；拿不到返回 null。
function extractProfitMarginPct(profit) {
    if (profit == null) return null;
    const s = String(profit);
    const m = s.match(/(-?\d+(?:\.\d+)?)\s*%/);
    if (m) return parseFloat(m[1]);
    const parts = s.split('|');
    if (parts.length >= 2) {
        const n = parseFloat(parts[1]);
        if (!isNaN(n)) return n;
    }
    return null;
}

// 更新SKU列表显示
function updateSkuListDisplay() {
    let skuListContainer = document.getElementById('skuListContainer');
    if (!skuListContainer) return;
	
	// 检查是否为多个SKU模式
	const skuTypeMultiple = document.querySelector('input[name="skuType"][value="multiple"]');
	const isMultipleSkuMode = skuTypeMultiple && skuTypeMultiple.checked;
	
    // 只有多个SKU模式且有SKU时才显示SKU列表
    // if (!isMultipleSkuMode || multipleSkus.length === 0) {
       
    //    skuListContainer.innerHTML = `
    //        <div class="sku-list-empty">
    //            <p>SKU信息加载中...</p>
    //        </div>
    //    `;
    // } else {
        // 处理SKU数据，确保每个SKU都是单独的对象
        let processedSkus = [];
        //console.log('multipleSkus111:',multipleSkus)
		
        multipleSkus.forEach(item => {
            if (typeof item.sku === 'string') {
                // 增强SKU分割逻辑，处理各种分隔符
                let skus = [];
                if (item.sku.includes(',')) {
                    // 逗号分隔
                    skus = item.sku.split(',').map(s => s.trim());
                } else if (item.sku.includes(' ')) {
                    // 空格分隔
                    skus = item.sku.split(' ').map(s => s.trim()).filter(s => s);
                } else if (item.sku.includes('.')) {
                    // 点分隔
                    skus = item.sku.split('.').map(s => s.trim()).filter(s => s);
                } else if (item.sku.includes('-')) {
                    // 连字符分隔
                    skus = item.sku.split('-').map(s => s.trim()).filter(s => s);
                } else {
                    // 单个SKU
                    skus = [item.sku];
                }
                
                // 过滤掉空字符串
                skus = skus.filter(sku => sku && sku.length > 0);
                
                // 添加每个SKU
                skus.forEach(sku => {
                    processedSkus.push({ sku: sku, price: item.price,weight: item.weight||'点击获取',fee:item.fee||0,cost: item.cost||0,whType: item.whType||'E邮宝',profit: item.profit||'0|0%',image: item.image||'' });
                });
            } else if (Array.isArray(item.sku)) {
                // 如果SKU是数组，遍历添加每个SKU
                item.sku.forEach(sku => {
                    processedSkus.push({ sku: sku, price: item.price,weight: item.weight||'点击获取',fee:item.fee||0,cost: item.cost||0,whType: item.whType||'E邮宝',profit: item.profit||'0|0%',image: item.image||'' });
                });
            } else {
                // 否则直接添加
                processedSkus.push(item);
            }
        });

        // 控制台输出所有SKU数据
        console.log('处理后的SKU列表:', processedSkus);

        // 计算总页数
        const totalPages = Math.ceil(processedSkus.length / itemsPerPage);
        // 确保当前页码在有效范围内
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }

        // 计算当前页显示的数据范围
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageSkus = processedSkus.slice(startIndex, endIndex);
		
        skuListContainer.innerHTML = `
            <div class="sku-list-header-actions">
                <button type="button" id="delete-selected-skus" class="delete-selected-btn">删除选中</button>
				<div style="display:flex;align-items:center">
					<div class="url-input-group" style="margin-right:20px;">
						批量调价：
						<select id="price-adjust-type" style="
						    background: #FFFFFF;
						    border: 1px solid #eeeeee;
						    border-radius: 4px;
						    padding: 6px 8px;
						    width: 70px;
						    font-size: 13px;
						    font-weight: 500;
						">
						    <option value="percentage">比例</option>
						    <option value="fixed">固定</option>
						</select>
						<input type="number" min="0" step="0" id="sku-price-input" style="width: 50px; padding: 4px; border: 1px solid #ddd; border-radius: 3px;" placeholder="">
						<span id="price-adjust-unit" style="color:#151515;font-size:13px;font-weight:600;margin-left:4px;">%</span>
						<select id="price-adjust-direction" style="
						    background: #FFFFFF;
						    border: 1px solid #eeeeee;
						    border-radius: 4px;
						    padding: 6px 8px;
						    
						    width: 80px;
						    font-size: 13px;
						    font-weight: 500;
						">
						    <option value="up">上涨</option>
						    <option value="down">下降</option>
						</select>
						<button type="button" id="price-set" class="setPriceBtn">设置</button>
						
					</div>
					<div class="url-input-group">
						批量成本：
						<input type="text" id="sku-cost-input" style="width: 50px; padding: 4px; border: 1px solid #ddd; border-radius: 3px;" placeholder="">
						<button type="button" id="cost-set" class="setCostBtn">设置</button>
					</div>
					<div class="url-input-group" style="margin-left:20px;">
						利润率≥
						<input type="number" id="profit-margin-filter" value="${profitMarginFilter == null ? '' : profitMarginFilter}" placeholder="例如 40" style="width: 60px; padding: 4px; border: 1px solid #ddd; border-radius: 3px;">
						<span style="color:#151515;font-size:13px;font-weight:600;margin-left:4px;">%</span>
						<button type="button" id="profit-filter-apply" class="setPriceBtn">过滤</button>
						<button type="button" id="profit-filter-clear" class="setPriceBtn" style="background:#999;">清除</button>
					</div>

				</div>
                <div class="sku-list-pagination-info">
                    共 ${processedSkus.length} 个SKU，每页显示 ${itemsPerPage} 个，共 ${totalPages} 页
                </div>
            </div>
			
            <div class="sku-list-table">
                <div class="sku-list-table-header">
                    <div class="sku-list-table-header-checkbox">
                        <input type="checkbox" id="select-all-skus">
                    </div>
                    <div class="sku-list-table-header-image">图片</div>
                    <div class="sku-list-table-header-sku">SKU</div>
                    <div class="sku-list-table-header-weight">重量</div>
                    <div class="sku-list-table-header-fee">物流费</div>
                    <div class="sku-list-table-header-price">价格</div>
					<div class="sku-list-table-header-whType">物流方式</div>
                    <div class="sku-list-table-header-cost">成本</div>
                    <div class="sku-list-table-header-profit">利润|利润率</div>
                    <div class="sku-list-table-header-action">操作</div>
                </div>
                ${currentPageSkus.map((item, index) => `
                    <div class="sku-list-table-row" data-profit-margin="${extractProfitMarginPct(item.profit) ?? ''}">
                        <div class="sku-list-table-cell-checkbox">
                            <input type="checkbox" class="sku-checkbox" data-sku="${item.sku}">
                        </div>
                        <div class="sku-list-table-cell-image">
                            ${item.image
                                ? `<img src="${item.image}" alt="sku" loading="lazy">`
                                : `<span class="sku-img-placeholder">—</span>`}
                        </div>
                        <div class="sku-list-table-cell-sku">${item.sku}</div>
                        <div data-sku="${item.sku}" data-weight="${item.weight}" class="sku-list-table-cell-weight" style="${item.weight =='点击获取' ||item.weight== '↻ 查询中...'?'color: #1e88e5 !important; font-weight: 600;':''}">${item.weight}</div>
                        <div class="sku-list-table-cell-fee">${item.fee}</div>
                        <div class="sku-list-table-cell-price">
                            <input type="number" class="sku-price-input" data-sku="${item.sku}" value="${parseFloat(item.price).toFixed(2)}" min="0" step="0.01" style="width: 80px; padding: 4px; border: 1px solid #ddd; border-radius: 3px;">
                        </div>
						<div class="sku-list-table-cell-whType">${item.whType}</div>
						<div class="sku-list-table-cell-cost">
						    <input type="number" class="sku-cost-input" data-sku="${item.sku}" value="${parseFloat(item.cost).toFixed(2)}" min="0" step="0" style="width: 80px; padding: 4px; border: 1px solid #ddd; border-radius: 3px;">
						</div>
						<div class="sku-list-table-cell-profit">${item.profit}</div>
                        <div class="sku-list-table-cell-action">
                            <button type="button" class="deleteSkuBtn" data-sku="${item.sku}">删除</button>
                        </div>
                    </div>
                `).join('')}
            </div>
            <div class="sku-list-pagination">
                <button type="button" id="prev-page" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>
                <span class="current-page">第 ${currentPage} / ${totalPages} 页</span>
                <button type="button" id="next-page" ${currentPage === totalPages ? 'disabled' : ''}>下一页</button>
            </div>
            <style>
                .sku-list-header-actions {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 10px;
                }
                .delete-selected-btn {
                    background: #dc3545;
                    color: white;
                    border: none;
                    border-radius: 3px;
                    padding: 6px 12px;
                    cursor: pointer;
                    font-size: 14px;
                }
                .delete-selected-btn:hover {
                    background: #c82333;
                }
                .sku-list-pagination-info {
                    font-size: 14px;
                    color: #666;
                }
                .sku-list-table {
                    width: 100%;
                    border-collapse: collapse;
                    background: #f8f9fa;
                    border-radius: 4px;
                    overflow: hidden;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    margin-bottom: 10px;
                }
                .sku-list-table-header {
                    display: flex;
                    background: #343a40;
                    color: white;
                    font-weight: bold;
                }
                .sku-list-table-header-checkbox,
                .sku-list-table-header-image,
                .sku-list-table-header-sku,
				.sku-list-table-header-weight,
				.sku-list-table-header-fee,
				.sku-list-table-header-price,
				.sku-list-table-header-whType,
				.sku-list-table-header-cost,
				.sku-list-table-header-profit,
                .sku-list-table-header-action {
                    padding: 12px;
                    text-align: left;
                }
                .sku-list-table-header-checkbox {
                    width: 40px;
                }
                .sku-list-table-header-image {
                    width: 64px;
                }
                .sku-list-table-header-sku {
                    flex: 2;
                }
				.sku-list-table-header-weight {
				    flex: 1;
				}
				.sku-list-table-header-fee {
				    flex: 1;
				}
                .sku-list-table-header-price {
                    flex: 1;
                }
				.sku-list-table-header-whType {
				    flex: 2;
				}
				.sku-list-table-header-cost {
				    flex: 1;
				}
				.sku-list-table-header-profit {
				    flex: 2;
				}
                .sku-list-table-header-action {
                    width: 80px;
                }
                .sku-list-table-row {
                    display: flex;
                    border-bottom: 1px solid #dee2e6;
                }
                .sku-list-table-row:hover {
                    background: #e9ecef;
                }
                .sku-list-table-cell-checkbox,
                .sku-list-table-cell-image,
                .sku-list-table-cell-sku,
                .sku-list-table-cell-weight,
                .sku-list-table-cell-fee,
                .sku-list-table-cell-price,
				.sku-list-table-cell-whType,
                .sku-list-table-cell-cost,
                .sku-list-table-cell-profit,
                .sku-list-table-cell-action {
                    padding: 10px 12px;
                }
                .sku-list-table-cell-checkbox {
                    width: 40px;
                }
                .sku-list-table-cell-image {
                    width: 64px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .sku-list-table-cell-image img {
                    width: 44px;
                    height: 44px;
                    object-fit: cover;
                    border-radius: 4px;
                    border: 1px solid #e9ecef;
                    background: #fff;
                }
                .sku-img-placeholder {
                    color: #adb5bd;
                    font-size: 12px;
                }
                .sku-list-table-row.hidden-by-filter {
                    display: none !important;
                }
                .sku-list-table-cell-sku {
                    flex: 2;
                    word-break: break-all;
                }
				.sku-list-table-cell-weight {
				    flex: 1;
				    word-break: break-all;
					cursor: pointer;
				}
				.sku-list-table-cell-fee {
				    flex: 1;
				    word-break: break-all;
				}
                .sku-list-table-cell-price {
                    flex: 1;
                }
				.sku-list-table-cell-whType {
				    flex: 2;
				    word-break: break-all;
				}
				.sku-list-table-cell-cost {
				    flex: 1;
				}
				.sku-list-table-cell-profit {
				    flex: 2;
				    word-break: break-all;
				}
                .sku-list-table-cell-action {
                    width: 80px;
                }
                .deleteSkuBtn {
                    background: #dc3545;
                    color: white;
                    border: none;
                    border-radius: 3px;
                    padding: 4px 8px;
                    cursor: pointer;
                    font-size: 12px;
                }
                .deleteSkuBtn:hover {
                    background: #c82333;
                }
				.setPriceBtn {
				    background: linear-gradient(135deg, #1e88e5, #1565c0);
				    color: white;
				    border: none;
				    border-radius: 3px;
				    padding: 4px 8px;
				    cursor: pointer;
				    font-size: 12px;
				}
				.setPriceBtn:hover {
				    background: linear-gradient(135deg, #1e88e5, #1565c0);
				}
				.setCostBtn {
				    background: linear-gradient(135deg, #1e88e5, #1565c0);
				    color: white;
				    border: none;
				    border-radius: 3px;
				    padding: 4px 8px;
				    cursor: pointer;
				    font-size: 12px;
				}
				.setCostBtn:hover {
				    background: linear-gradient(135deg, #1e88e5, #1565c0);
				}
                .sku-checkbox {
                    transform: scale(1.2);
                }
                .sku-list-pagination {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    gap: 10px;
                    margin-top: 10px;
                }
                .sku-list-pagination button {
                    background: #6c757d;
                    color: white;
                    border: none;
                    border-radius: 3px;
                    padding: 6px 12px;
                    cursor: pointer;
                    font-size: 14px;
                }
                .sku-list-pagination button:hover:not(:disabled) {
                    background: #5a6268;
                }
                .sku-list-pagination button:disabled {
                    background: #adb5bd;
                    cursor: not-allowed;
                }
                .current-page {
                    font-size: 14px;
                    color: #666;
                }
            </style>
        `;

	
		hideLoading()
	
        // 添加删除按钮事件
        document.querySelectorAll('.deleteSkuBtn').forEach(btn => {
            btn.addEventListener('click', function() {
                const skuToDelete = this.dataset.sku;
                if (skuToDelete) {
                    // 找到原始multipleSkus中对应的SKU并删除
                    for (let i = multipleSkus.length - 1; i >= 0; i--) {
                        if (multipleSkus[i].sku === skuToDelete || 
                            (typeof multipleSkus[i].sku === 'string' && multipleSkus[i].sku.includes(skuToDelete))) {
                            multipleSkus.splice(i, 1);
                            break;
                        }
                    }
                    // 重置页码到第一页
                    currentPage = 1;
                    updateSkuListDisplay();
                }
            });
        });
		
		

        // 添加删除选中按钮事件
        const deleteSelectedBtn = document.getElementById('delete-selected-skus');
        if (deleteSelectedBtn) {
            deleteSelectedBtn.addEventListener('click', function() {
                const selectedCheckboxes = document.querySelectorAll('.sku-checkbox:checked');
                const selectedSkus = Array.from(selectedCheckboxes).map(cb => cb.dataset.sku);
                
                if (selectedSkus.length === 0) {
                    alert('请先选择要删除的SKU');
                    return;
                }
                
               for (let i = multipleSkus.length - 1; i >= 0; i--) {
                        const sku = multipleSkus[i].sku;
                        if (selectedSkus.some(selectedSku => 
                            sku === selectedSku || 
                            (typeof sku === 'string' && sku.includes(selectedSku))
                        )) {
                            multipleSkus.splice(i, 1);
                        }
                    }
                    // 重置页码到第一页
                    currentPage = 1;
                    updateSkuListDisplay();
            });
        }
		
		//添加批量设置价格
		
		const priceSet = document.getElementById('price-set');
		if (priceSet) {
		    priceSet.addEventListener('click', function() {
				const priceNew = document.getElementById('sku-price-input');
				const adjustDirection = document.getElementById('price-adjust-direction').value;
				const adjustType = document.getElementById('price-adjust-type').value;
				const type = adjustDirection === 'up' ? 'success' : 'danger';
				// let priceNews = priceNew.value/100
		        // if (confirm(`是否确定批量${adjustDirection === 'up' ? '上涨' : '下降'}价格？`)) {
		            // 删除选中的SKU
		            for (let i = multipleSkus.length - 1; i >= 0; i--) {
						if (adjustType === 'percentage') {
						    // 比例调整
						    if (adjustDirection === 'up') {
						        multipleSkus[i].price = multipleSkus[i].price * (1 + priceNew.value / 100);
						    } else {
						        multipleSkus[i].price = multipleSkus[i].price * (1 - priceNew.value / 100);
						    }
						} else {
						    // 固定价格调整
						    if (adjustDirection === 'up') {
						        multipleSkus[i].price = (multipleSkus[i].price*1) + (priceNew.value*1);
						    } else {
						        multipleSkus[i].price = (multipleSkus[i].price*1) - (priceNew.value*1)
						    }
						}
						
		            }
		            // 重置页码到第一页
		            currentPage = 1;
		            setSkuListData();
		        // }
		    });
		}
		
		// 添加全选按钮事件
		const priceAdjustType = document.getElementById('price-adjust-type');
		const priceAdjustUnit = document.getElementById('price-adjust-unit');
		if (priceAdjustType) {
		    priceAdjustType.addEventListener('change', function() {
		        if(this.value === 'percentage') {
		            priceAdjustUnit.textContent ='%';
		        } else {
		            priceAdjustUnit.textContent='元';
		        }
		    });
		}
		
		
		const costSet = document.getElementById('cost-set');
		if (costSet) {
		    costSet.addEventListener('click', function() {
				const costNew = document.getElementById('sku-cost-input');
		        // if (confirm(`是否确定批量设置成本？`)) {
		            // 删除选中的SKU
		            for (let i = multipleSkus.length - 1; i >= 0; i--) {
		                multipleSkus[i].cost = costNew.value
		            }
		            // 重置页码到第一页
		            currentPage = 1;
		            setSkuListData();
		        // }
		    });
		}

		// 利润率过滤
		const profitFilterApply = document.getElementById('profit-filter-apply');
		const profitFilterClear = document.getElementById('profit-filter-clear');
		const profitFilterInput = document.getElementById('profit-margin-filter');
		function applyProfitMarginFilter() {
			document.querySelectorAll('.sku-list-table-row').forEach(row => {
				if (profitMarginFilter == null) {
					row.classList.remove('hidden-by-filter');
					return;
				}
				const raw = row.getAttribute('data-profit-margin');
				const val = raw === '' ? null : parseFloat(raw);
				if (val == null || isNaN(val) || val < profitMarginFilter) {
					row.classList.add('hidden-by-filter');
				} else {
					row.classList.remove('hidden-by-filter');
				}
			});
		}
		if (profitFilterApply) {
			profitFilterApply.addEventListener('click', function() {
				const v = parseFloat(profitFilterInput.value);
				profitMarginFilter = isNaN(v) ? null : v;
				applyProfitMarginFilter();
			});
		}
		if (profitFilterClear) {
			profitFilterClear.addEventListener('click', function() {
				profitMarginFilter = null;
				if (profitFilterInput) profitFilterInput.value = '';
				applyProfitMarginFilter();
			});
		}
		// 表格重绘后如果之前设置了过滤阈值，自动重新应用一次
		if (profitMarginFilter != null) applyProfitMarginFilter();
	
		
		
		
        // 添加全选按钮事件
        const selectAllBtn = document.getElementById('select-all-skus');
        if (selectAllBtn) {
            selectAllBtn.addEventListener('change', function() {
                const checked = this.checked;
                document.querySelectorAll('.sku-checkbox').forEach(checkbox => {
                    checkbox.checked = checked;
                });
            });
        }

        // 添加单个复选框事件
        document.querySelectorAll('.sku-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = Array.from(document.querySelectorAll('.sku-checkbox')).every(cb => cb.checked);
                const selectAllBtn = document.getElementById('select-all-skus');
                if (selectAllBtn) {
                    selectAllBtn.checked = allChecked;
                }
            });
        });

        // 添加分页按钮事件
        const prevPageBtn = document.getElementById('prev-page');
        const nextPageBtn = document.getElementById('next-page');
        
        if (prevPageBtn) {
            prevPageBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    updateSkuListDisplay();
                }
            });
        }
        
        if (nextPageBtn) {
            nextPageBtn.addEventListener('click', function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    updateSkuListDisplay();
                }
            });
        }

        // 为价格输入框添加事件监听器
        document.querySelectorAll('.sku-price-input').forEach(input => {
            input.addEventListener('input', function() {
                const sku = this.getAttribute('data-sku');
                const newPrice = parseFloat(this.value) || 0;
                
                // 更新 multipleSkus 数组中对应 SKU 的价格
				for(var i in multipleSkus){
					 if (multipleSkus[i].sku === sku) {
						 multipleSkus[i].price = newPrice
					 }
				}
                console.log(`已更新SKU ${sku} 的价格为 ${newPrice}`);
            });
            input.addEventListener('blur', function() {
                setSkuListData();
            });
        });
		
		// 为成本输入框添加事件监听器
		document.querySelectorAll('.sku-cost-input').forEach(input => {
		    input.addEventListener('input', function() {
		        const sku = this.getAttribute('data-sku');
		        const newCost = parseFloat(this.value) || 0;
		        
		        // 更新 multipleSkus 数组中对应 SKU 的成本
		        for(var i in multipleSkus){
		        	 if (multipleSkus[i].sku === sku) {
		        		 multipleSkus[i].cost = newCost
		        	 }
		        }
		        console.log(`已更新SKU ${sku} 的成本为 ${newCost}`);
		    });
		    input.addEventListener('blur', function() {
		        setSkuListData();
		    });
		});
    // }
}

async function getWaith(sku) {
	console.log(sku)
    const cartItemIds = [];
    
    try {
        // Step 1: Get current cart items
        const summaryResponse = await fetch('https://www.ozon.ru/api/composer-api.bx/_action/summary', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const summaryData = await summaryResponse.json();
        
        // Collect item IDs
        summaryData.forEach(item => {
            cartItemIds.push(item.id);
        });

        // Step 2: Clear cart
        if (cartItemIds.length > 0) {
            const clearCartParams = {
                items: cartItemIds
            };
            const str = JSON.stringify(clearCartParams);
            const clearCartData = {
                name: "deleteItems",
                params: str
            };

            await fetch('https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fcart%3Fpage_changed%3Dtrue', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(clearCartData)
            });
        }

        // Step 3: Add new item to cart
        const addToCartData = [{
            id: Number(sku),
            quantity: 1
        }];

        await fetch('https://www.ozon.ru/api/composer-api.bx/_action/v2/addToCart', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(addToCartData)
        });

        const addResponselast = await fetch('https://www.ozon.ru/cart?tab=0', {
            method: 'GET'
        });
        const htmlText = await addResponselast.text();
        
        const match = htmlText.match(/"info":"[^•]+•\s*([^"]+)/);
        const weight = match ? match[1].trim() : null;
     
        return weight;

    } catch (error) {
        console.error('Operation failed:', error);
        return '无 ';
    }
}
function extractSkusFromSellerData(sellerData, skuSet) {
    if (!sellerData) return;

    // 尝试多种可能的路径来查找卖家列表
    const sellers =
        sellerData.sellers || // 直接包含 sellers 数组
        sellerData.data?.sellers || // 包含在 data 对象中的 sellers
        sellerData.content?.sellers; // 包含在 content 对象中的 sellers

    if (Array.isArray(sellers)) {
        sellers.forEach(seller => {
            if (seller.sku) {
                skuSet.add(seller.sku);
            }
        });
    }
}
async function getFxoutValue1() {
    try {

        return await new Promise((resolve) => {
            chrome.runtime.sendMessage({
                action: "getCookie",
                url: config.url.domainz(),
                name: "fxout"
            }, (response) => resolve(response || 0));
        });
    } catch (error) {
        console.error("获取cookie出错:", error);
        return 0;
    }
}

// 新增函数：防抖函数
function debounce(func, delay = 500) {
    let timeoutId;
    return function (...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
}

// 修改handleInputChange为防抖版本
const handleInputChange = debounce(function () {
    const weight = parseFloat(packageWeightInput.value) || 0;
    const price = parseFloat(salePriceInput.value) || 0;
    const purchasePrice = parseFloat(purchasePriceInput.value) || 0;
    const groupId = logisticsGroupSelect.value;

    // 检查分组是否已选择（分组是先决条件）
    if (!groupId) {
        return;
    }

    // 检查产品信息是否填写完整
    const productInfoComplete = weight > 0 && 
                               price > 0 && 
                               purchasePrice > 0;
    if (purchasePrice > 0 && weight > 0) {
    // 清除旧缓存（关键）
    calculationCache.clear();
    
    // 显示计算中状态
    logisticsCostElement.innerHTML = `<span class="calculating">计算中...</span>`;
    estimatedProfitElement.innerHTML = `<span class="calculating">计算中...</span>`;
    profitMarginElement.innerHTML = `<span class="calculating">计算中...</span>`;
    
    // 主动触发物流加载
    // loadLogisticsMethods(groupId);
  }
    // 产品信息完整且物流分组已选择时加载物流方式
    if (productInfoComplete) {
        // 添加计算中的视觉反馈
        logisticsCostElement.innerHTML = `<span class="calculating">计算中...</span><div class="profit-loading"></div>`;
        estimatedProfitElement.innerHTML = `<span class="calculating">计算中...</span>`;
        profitMarginElement.innerHTML = `<span class="calculating">计算中...</span>`;

        // loadLogisticsMethods(groupId);
    }

    // 当有有效输入时验证物流方式并计算利润
    if (purchasePrice>0 && weight > 0 && price > 0 && logisticsMethodSelect.value) {
        validateLogisticsMethods(purchasePrice,weight , price); // 重量转换为克
        updateProfitDisplay(); // 确保调用利润计算
    }
});

// 新增：验证物流方法是否有效
function validateLogisticsMethods(purchasePrice,weightGrams, salePrice) {
    let hasValidMethod = false;

    // 遍历所有物流方式选项
    for (let i = 0; i < logisticsMethodSelect.options.length; i++) {
        const option = logisticsMethodSelect.options[i];
        if (!option.value) continue; // 跳过提示选项

        const minWeight = parseFloat(option.dataset.minWeight);
        const maxWeight = parseFloat(option.dataset.maxWeight);
        const minPrice = parseFloat(option.dataset.minPrice);
        const maxPrice = parseFloat(option.dataset.maxPrice);
        const minPurchasePrice = parseFloat(option.dataset.minPurchasePrice);
        const maxPurchasePrice = parseFloat(option.dataset.maxPurchasePrice);

        // 检查是否在有效范围内
        const isValid = weightGrams >= minWeight &&
            weightGrams <= maxWeight &&
            salePrice >= minPrice &&
            salePrice <= maxPrice &&
            purchasePrice >= minPurchasePrice &&
            purchasePrice <= maxPurchasePrice;

        // 更新选项状态
        option.disabled = !isValid;
        option.hidden = !isValid;

        if (isValid) hasValidMethod = true;
    }

    // 如果没有有效物流方式，重置选择
    if (!hasValidMethod && logisticsMethodSelect.value) {
        logisticsMethodSelect.value = "";
    }
}
// 新增函数：显示物流方式详情
function showLogisticsDetails() {
    // 首先检查容器元素是否存在
    if (!logisticsDetailsContainer) return;

    const selectedOption = logisticsMethodSelect.options[logisticsMethodSelect.selectedIndex];
    if (!selectedOption || selectedOption.value === "") {
        logisticsDetailsContainer.classList.remove('active');
        return;
    }

    const detailsHTML = `
        <div class="method-item">
            <span>基础费用:</span>
            <span>¥${parseFloat(selectedOption.dataset.base).toFixed(2)}</span>
        </div>
        <div class="method-item">
            <span>续重单价:</span>
            <span>¥${parseFloat(selectedOption.dataset.growth).toFixed(4)}/克</span>
        </div>
        <div class="method-item">
            <span>重量范围:</span>
            <span>${selectedOption.dataset.minWeight}g - ${selectedOption.dataset.maxWeight}g</span>
        </div>
        <div class="method-item">
            <span>价格范围:</span>
            <span>¥${selectedOption.dataset.minPrice} - ¥${selectedOption.dataset.maxPrice}</span>
        </div>
    `;

    logisticsDetailsContainer.innerHTML = detailsHTML;
    logisticsDetailsContainer.classList.add('active');
}

// 新增函数：加载店铺数据
function loadShops() {
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading';
    loadingIndicator.style.display = 'inline-block';
    loadingIndicator.style.marginLeft = '10px';
    storeSelect.parentNode.appendChild(loadingIndicator);

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

    // 从cookies获取token
    config.getCookie({
        "url": config.url.domainz(),
        "name": config.cookieName11
    }, function (cookie) {
        console.log('cookieloadShops:', cookie);

        let token = '';
        if (cookie && cookie.value) {
            token = cookie.value;
            console.log('tokenloadShops:', token);

            // 发送带token的请求
            request(apiUrl, {
                method: "POST",
                responseType: "json",
                body: {
                    limit: 10,
                    page: 1
                },
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                console.log('店铺数据loadShops:', res);
                if (res && res.status === "200") {
                    console.log('店铺数据loadShops:', res);
                    // 清空现有选项
                    storeSelect.innerHTML = '<option value="">-- 请选择店铺 --</option>';

                    // 填充店铺数据
                    if (res.data && res.data.length > 0) {
                        res.data.forEach(shop => {
                            const option = document.createElement('option');
                            option.value = shop.appid; // 使用id作为值
                            option.textContent = shop.tname; // 使用tname作为显示文本
                            storeSelect.appendChild(option);
                        });
                    } else {
                        storeSelect.innerHTML += '<option value="">-- 暂无店铺数据 --</option>';
                    }
                } else {
                    const msg = res?.Message || "店铺数据获取失败";
                    console.error('店铺数据获取失败loadShops:', msg);
                    storeSelect.innerHTML = `<option value="">-- ${msg} --</option>`;
                }
            }).catch(error => {
                console.error('tokenloadShops:', token);
                console.error('请求失败loadShops:', error);
                storeSelect.innerHTML = '<option value="">-- 请求异常 --</option>';
            }).finally(() => {
                storeSelect.parentNode.removeChild(loadingIndicator);
                storeSelect.disabled = false;
            });
        } else {
            // Token获取失败处理
            console.error("Token获取失败loadShops");
            storeSelect.innerHTML = '<option value="">-- 登录过期 --</option>';
            storeSelect.parentNode.removeChild(loadingIndicator);
            storeSelect.disabled = false;
        }
    });
}

// 新增：初始化数据存储对象
window.goodsDataStore = {};

// 新增：当商品数据更新时处理的函数
// 新增：全局变量，用于存储待处理的商品数据
let pendingGoodsData = null;
let weightDataApplied = false;


// 存储商品页URL
let productPageUrl = '';


window.addEventListener('message', async (event) => {
    // 检查event.data是否存在
    if (!event.data || typeof event.data !== 'object') {
        return;
    }
    
    if (event.data.type === 'SET_PRODUCT_URL') {
        productPageUrl = event.data.url;
        console.log('Received product page URL:', productPageUrl);
        console.log('window.goodsPWeight:', window.goodsPWeight);
        // 先获取商品信息
        await getProductInfo(productPageUrl);
    }
    // 新增：处理产品重量数据
    // else if (event.data.type === 'PRODUCT_WEIGHT_DATA') {
    //     const weightGrams = event.data.weightGrams;
    //     console.log('接收到产品重量数据(g):', weightGrams);
    //     window.goodsPWeight = weightGrams;


    // }
});
//发送消息到backgroundscript
function sendMessageToBackgroudScript(type, params, callback) {
    // 处理3个参数的情况：type, params, callback
    if (arguments.length === 3) {
        chrome.runtime.sendMessage({ type, params }, function (response) {
            if (callback) callback(response);
        });
    } 
    // 处理2个参数的情况：message, callback
    else {
        chrome.runtime.sendMessage(type, function (response) {
            if (params) params(response);
        });
    }
}


async function getProductInfo(url) {
    return new Promise((resolve) => {
        sendMessageToBackgroudScript({
            "Type": "CollectionGoodsku",
            "IsVerifyDuplicate": true,
            "link": url
        }, function (response) {
            console.log('getProductInfo 收到响应');
            resolve();
        });
    });
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.type === "PRODUCT_DATA_RESPONSE") {
        // 处理接收到的商品数据
		// 新增：弹窗打开时获取汇率并展示
		getCNY2RUBRate();
        handleProductDataResponse(request.data);
        initForm();
    }
});
chrome.runtime.onMessage.addListener(function (message) {
    if (message.type === 'FORWARDED_WEIGHT_DATA') {
        console.log('-------------------------------');
        console.log('message:', message);
        pendingGoodsWeight = message.data.weightGrams;
        pendingGoodsSku = message.data.sku;
        iteminfo = message.data.iteminfo;
        console.log('message.data:', message.data);
        console.log('pendingGoodsSku:', pendingGoodsSku);
        console.log('pendingGoodsWeight:', pendingGoodsWeight);
        sessionStorage.setItem('pendingGoodsWeight', pendingGoodsWeight);
        sessionStorage.setItem('pendingGoodsSku', pendingGoodsSku);
        getWeightskuinfo(iteminfo);
    }
});

function handleProductDataResponse(response) {
    console.log('从productacquisition.js接收到的商品数据:', response);
   
    // 确保response.Skus存在
    if (!response || !response.Skus) {
        console.error('接收到的商品数据不包含Skus字段');
        return;
    }

    // 从response.Skus中提取SKU信息
    productInfo = response.Skus;
    let skuArray = [];
    prices = []; // 清空全局价格数组
    currency_code = productInfo[0].Currency;
    currency = currency_code;
    //console.log('productInfo[0].SkuCode:', productInfo[0].SkuCode);
    // 提取SKU代码和价格
    if (Array.isArray(productInfo) && productInfo[0].SkuCode != null && productInfo[0].SkuCode != undefined) {
        productInfo.forEach(item => {
            if (item.SkuCode) {
                skuArray.push(item.SkuCode);
                // 存储价格（如果有）
                if (item.Price) prices.push(item.Price);
            }
        });
    } else if (productInfo && response.Url) {
        const parts = response.Url.split('/');
        console.log('parts:', parts);
        if (parts.length >= 3) {
            const segment = parts[2];
            const lastHyphenIndex = segment.lastIndexOf('-');
            if (lastHyphenIndex !== -1) {
                const skuCode = segment.substring(lastHyphenIndex + 1);
                if (/^\d+$/.test(skuCode)) {
                    skuArray.push(skuCode);
                    if (productInfo[0].Price) prices.push(productInfo[0].Price);
                }
            }
        }
    }
    sku = skuArray;

    console.log('提取到的SKU数组:', skuArray);
    console.log('提取到的价格数组:', prices);

    // 清空现有的multipleSkus数组
    multipleSkus = [];

    // 将提取的SKU添加到multipleSkus数组中
    const currentPrice = parseFloat(salePriceInput?.value) || 0;
	console.log(skuArray)
    skuArray.forEach((skuCode, index) => {
        // 使用解析到的价格（如果存在），否则使用当前价格
        const price = prices[index] || currentPrice;

        if (skuCode && !multipleSkus.some(item => item.sku === skuCode)) {
            multipleSkus.push({
                sku: skuCode,
                price: price
            });
        }
    });

    console.log('更新后的multipleSkus数组:', multipleSkus);
    // updateSkuListDisplay();
}

function getCookies() {
    let resPromise = new Promise(function (resolve, reject) {
        chrome.runtime.sendMessage({
            type: "getCookie",
            url: "https://sczfai.com",
            name: 'token'
        }, function (token) {
            if (token && token !== null && token !== undefined && token !== '') {
                resolve({ token })
            } else {
                resolve("")
            }
        });
    });
    return resPromise
}

// 从background.js迁移的函数 - 获取Ozon卖家平台的cookie
async function getCookiesoz() {
    let resPromise = new Promise(async function (resolve, reject) {
        config.getCookie({"url": "https://seller.ozon.ru", "name": 'sc_company_id'}, function (cookie) {
            if (cookie && cookie.value) {
                let token = cookie.value;
                let sc_company_id = cookie.value;
                resolve({token, sc_company_id})
            } else {
                resolve({token: "", sc_company_id: ""})
            }
        })
    });
    return resPromise
}

// ggetSkuFromurl 由 common/js/ozon-analytics.js 提供（已挂到全局）

// 5.19 新增：按 SKU 反查商品基础信息（用于上报 SpiderOzon 的 serrchdata 字段）
async function getProductDetaisearch(headers, sku) {
    if (!sku) return null;
    try {
        const body = OzAnalytics.buildSearchRequestBody(headers['x-o3-company-id'], sku);
        const resp = await fetch(OzAnalytics.SEARCH_URL, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(body),
        });
        if (!resp.ok) return null;
        return await resp.json();
    } catch (e) {
        console.error('搜索商品图片信息失败:', e);
        return null;
    }
}

// 5.19 新增：上报到自家服务器 /SpiderOzon/adtoAll（转发给 bg 落地，统一 SERVER_HOST）
function sendToSpiderOzon(dataObj, sku) {
    try {
        chrome.runtime.sendMessage({ action: "spiderPost", dataObj: dataObj, sku: sku }, () => {});
    } catch (e) {
        console.error('sendToSpiderOzon 转发失败:', e);
    }
}

// 发送 Ozon 卖家 API 请求（单 SKU 分析）。请求体/headers/响应整形均走共享模块。
async function httpPostoz(url, params = {}, callback = () => {}) {
    try {
        const {token, sc_company_id} = await getCookiesoz();
        const headers = OzAnalytics.buildHeaders(sc_company_id, true);
        const sku = OzAnalytics.ggetSkuFromurl(params.url);
        const requestBody = OzAnalytics.buildRequestBody(sku);
        const pourl = OzAnalytics.ANALYTICS_URL;

        const firstResponse = await fetch(pourl, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(requestBody),
        });
        if (!firstResponse.ok) {
            throw new Error(`第一个请求失败: ${firstResponse.status} ${firstResponse.statusText}`);
        }
        const firstData = await firstResponse.json();

        if (!firstData.items || firstData.items.length === 0) {
            sendToSpiderOzon({ seller_analytics: firstData, serrchdata: null, prinfo: null }, sku);
            return callback(OzAnalytics.shapeEmptyAnalytics(firstData, sku));
        }

        let productsearch = null;
        let productDetail = null;
        try { productsearch = await getProductDetaisearch(headers, sku); } catch (e) { console.log('getProductDetaisearch 失败:', e); }
        try { productDetail = await getProductDetailnew(headers, firstData.items[0].variantId); } catch (e) { console.log('getProductDetailnew 失败:', e); }

        sendToSpiderOzon({ seller_analytics: firstData, serrchdata: productsearch, prinfo: productDetail }, sku);

        if (productDetail) {
            callback(OzAnalytics.shapeMergedWithDetail(firstData, productDetail));
        } else {
            callback(OzAnalytics.shapeFallbackWithoutDetail(firstData));
        }
    } catch (error) {
        console.error('httpPostoz请求失败:', error);
        callback({ error: true, message: error.message, stack: error.stack });
    }
}

// 从background.js迁移的函数 - 获取商品详情（多SKU搜索）
async function getProductDetail(headers, sku) {
    if (!sku) {
        console.log('SKU为空，跳过商品详情搜索');
        return null;
    }

    try {
        let pourl = 'https://seller.ozon.ru/api/v1/search-variant-model';
        let paa = JSON.stringify({name: sku, limit: "10"});

        console.log('搜索商品详情，SKU:', sku);

        const response = await fetch(pourl, {
            method: "POST",
            headers: headers,
            body: paa,
        });

        if (!response.ok) {
            //console.error('商品详情请求失败:', response.status, response.statusText);
            return null;
        }

        const data = await response.json();
        //console.log('商品搜索API返回数据');

        if (data.items && Array.isArray(data.items) && data.items.length > 0) {
            const firstItem = data.items[0];
            //console.log('找到商品详情:', firstItem);
		const specs = getProductSpecifications(firstItem);
		        //console.log('提取到的规格信息:', specs);
		        
		        // 如果需要，可以将规格信息添加到商品对象中
		        firstItem.specifications = specs;
            return firstItem;
        } else {
            console.log('未找到相关商品');
            return null;
        }
    } catch (error) {
        console.error('获取商品详情失败:', error);
        return null;
    }
}

/**
 * 从商品属性中提取尺寸和重量信息
 * @param {Object} productItem - 商品数据对象
 * @returns {Object} 包含尺寸和重量信息的对象
 */
/**
 * 从商品属性中提取尺寸和重量信息
 * @param {Object} productItem - 商品数据对象
 * @returns {Object} 包含尺寸和重量信息的对象
 */
function extractProductDimensions(productItem) {
    const result = {
        weight: productItem.weight,    // 重量
        length: productItem.depth,    // 长度
        width: productItem.width,     // 宽度
        height: productItem.height,     // 高度
        unit: 'g/mm',    // 默认单位（重量是克，尺寸是厘米）
        success: false
    };

    try {
        if (!productItem || !productItem.attributes || !Array.isArray(productItem.attributes)) {
            console.error('商品数据格式不正确');
            return result;
        }

        // 遍历 attributes 数组
        productItem.attributes.forEach(attr => {
            const key = attr.key;
            const value = attr.value;

            switch (key) {
                case '4497': // 重量
                    if (value && value.trim() !== '') {
                        result.weight = parseInt(value, 10);
                        console.log('找到重量:', result.weight, 'g');
                    }
                    break;
                    
                case '9454': // 长度
                    if (value && value.trim() !== '') {
                        result.length = parseInt(value, 10);
                        console.log('找到长度:', result.length, 'mm');
                    }
                    break;
                    
                case '9455': // 宽度
                    if (value && value.trim() !== '') {
                        result.width = parseInt(value, 10);
                        console.log('找到宽度:', result.width, 'mm');
                    }
                    break;
                    
                case '9456': // 高度
                    if (value && value.trim() !== '') {
                        result.height = parseInt(value, 10);
                        console.log('找到高度:', result.height, 'mm');
                    }
                    break;
            }
        });

        // 检查是否成功提取到数据
        result.success = !!(result.weight || result.length || result.width || result.height);
        
        // 计算体积（如果所有尺寸都有）
        if (result.length && result.width && result.height) {
            result.volume = result.length * result.width * result.height;
            result.volumeUnit = 'cm³';
            console.log('计算体积:', (result.volume/1000), 'cm³');
        }

        return result;
        
    } catch (error) {
        console.error('提取商品尺寸信息出错:', error);
        return result;
    }
}

/**
 * 从background.js迁移的函数 - 获取商品规格信息
 * @param {Object} productItem - 商品数据对象
 * @returns {Object} 完整的商品规格信息
 */
function getProductSpecifications(productItem) {
    
    const dimensions = extractProductDimensions(productItem);
    
    // 添加更多有用信息
    const specifications = {
        ...dimensions,
        variantId: productItem.variant_id || null,
        name: productItem.name || '',
        description: productItem.description || '',
        
        // 提取其他有用属性
        barcode: null,
        color: null,
        material: null,
        country: null
    };

    // 提取其他属性
    try {
        if (productItem.attributes && Array.isArray(productItem.attributes)) {
            productItem.attributes.forEach(attr => {
                const key = attr.key;
                const value = attr.value;

                switch (key) {
                    case '9048': // 可能是条码/型号
                        if (value && value.trim() !== '') {
                            specifications.barcode = value;
                        }
                        break;
                        
                    case '10097': // 颜色
                        if (value && value.trim() !== '') {
                            specifications.color = value;
                        }
                        break;
                        
                    case '4389': // 原产国
                        if (value && value.trim() !== '') {
                            specifications.country = value;
                        } else if (attr.collection && attr.collection.length > 0) {
                            specifications.country = attr.collection.join(', ');
                        }
                        break;
                        
                    case '8229': // 商品类型/材质
                        if (value && value.trim() !== '') {
                            specifications.material = value;
                        }
                        break;
                }
            });
        }
    } catch (error) {
        console.error('提取其他属性时出错:', error);
    }

    return specifications;
}
// 添加新的URL输入框函数
function addNewUrlInput() {
    const urlInputs = document.querySelectorAll('.sourceUrlInput');
    const inputCount = urlInputs.length;

    // 创建新的URL输入框容器
    const urlInputContainer = document.createElement('div');
    urlInputContainer.className = 'sourceUrlInputContainer url-input-group';

    // 创建新的URL输入框
    const newUrlInput = document.createElement('input');
    newUrlInput.type = 'text';
    newUrlInput.className = 'sourceUrlInput';
    newUrlInput.placeholder = `链接${inputCount + 1}`;

    // 创建删除按钮
    const deleteBtn = document.createElement('button');
    deleteBtn.type = 'button';
    deleteBtn.className = 'deleteUrlBtn';
    deleteBtn.textContent = '删除';
    deleteBtn.onclick = function () {
        sourceUrlsContainer.removeChild(urlInputContainer);
        // 更新剩余输入框的placeholder
        updateUrlPlaceholders();
    };

    // 将输入框和删除按钮添加到容器
    urlInputContainer.appendChild(newUrlInput);
    urlInputContainer.appendChild(deleteBtn);

    // 将容器添加到主容器
    sourceUrlsContainer.appendChild(urlInputContainer);
}

// 更新URL输入框的placeholder序号
function updateUrlPlaceholders() {
    const urlInputs = document.querySelectorAll('.sourceUrlInput');
    urlInputs.forEach((input, index) => {
        input.placeholder = `链接${index + 1}`;
    });
}


/**
 * 根据UNI物流渠道配置计算利润
 * @param {Object} config - UNI物流渠道配置（即您提供的JSON数据）
 * @param {number} productWeight - 产品重量（克）
 * @param {number} salePrice - 销售价格
 * @param {number} purchasePrice - 进货价格
 * @returns {Object} 计算结果，包含适用渠道、各项费用和利润
 */
function calculateUNIProfit(config, productWeight, salePrice, purchasePrice) {
    // 验证输入参数
    if (!config || !config.data || !config.data.items) {
        throw new Error('无效的物流配置');
    }
    
    if (productWeight <= 0 || salePrice <= 0 || purchasePrice < 0) {
        throw new Error('参数必须为正值');
    }
    
    // 查找适用的物流渠道
    const applicableChannels = config.data.items.filter(channel => {
        return productWeight >= channel.weight.min && 
               productWeight <= channel.weight.max &&
               salePrice >= channel.price.min && 
               salePrice <= channel.price.max;
    });
    
    if (applicableChannels.length === 0) {
        return {
            success: false,
            message: `没有找到适用的物流渠道。重量: ${productWeight}g, 价格: ${salePrice}`
        };
    }
    
    // 计算每个适用渠道的利润
    const results = applicableChannels.map(channel => {
        // 计算佣金
        const commission = salePrice * channel.commission;
        
        // 计算物流费
        const logisticFee = parseFloat(channel.logistic_fee.base) + 
                           (productWeight * parseFloat(channel.logistic_fee.growth));
        
        // 总费用
        const totalFees = commission + channel.package_fee + logisticFee;
        
        // 利润 = 售价 - 成本 - 总费用
        const profit = salePrice - purchasePrice - totalFees;
        
        // 利润率
        const profitMargin = salePrice > 0 ? (profit / salePrice) * 100 : 0;
        
        // 成本构成
        const costComposition = {
            productCost: purchasePrice,
            commission: commission,
            packageFee: channel.package_fee,
            logisticFee: logisticFee,
            totalFees: totalFees
        };
        
        return {
            channelName: channel.name,
            isApplicable: true,
            profit: parseFloat(profit.toFixed(2)),
            profitMargin: parseFloat(profitMargin.toFixed(2)),
            totalFees: parseFloat(totalFees.toFixed(2)),
            costComposition: costComposition,
            channelDetails: {
                weightRange: `${channel.weight.min}-${channel.weight.max}g`,
                priceRange: `${channel.price.min}-${channel.price.max}`,
                commissionRate: `${(channel.commission * 100).toFixed(1)}%`,
                packageFee: channel.package_fee,
                logisticFeeFormula: `基础: ${channel.logistic_fee.base} + 重量×${channel.logistic_fee.growth}/g`
            }
        };
    });
    
    // 找出利润最高的渠道
    const bestChannel = results.reduce((max, current) => 
        current.profit > max.profit ? current : max, results[0]);
    
    return {
        success: true,
        productInfo: {
            weight: productWeight,
            salePrice: salePrice,
            purchasePrice: purchasePrice
        },
        applicableChannels: results,
        recommendedChannel: bestChannel,
        summary: {
            maxProfit: bestChannel.profit,
            maxProfitMargin: bestChannel.profitMargin,
            bestChannel: bestChannel.channelName,
            totalApplicableChannels: results.length
        }
    };
}

/**
 * 批量计算利润的辅助函数
 * @param {Object} config - UNI物流渠道配置
 * @param {Array} products - 产品数组，每个产品包含weight, salePrice, purchasePrice
 * @returns {Array} 每个产品的计算结果
 */
function batchCalculateProfit(config, products) {
    return products.map(product => {
        const result = calculateUNIProfit(
            config, 
            product.weight, 
            product.salePrice, 
            product.purchasePrice
        );
        
        return {
            product: product,
            calculation: result
        };
    });
}

const simpleResult = calculateSimpleProfit(300, 1000, 400);
console.log('简化版本结果:', simpleResult);

/**
 * 计算利润的简化版本（如果需要快速使用）
 * @param {number} weight - 产品重量（克）
 * @param {number} salePrice - 销售价格
 * @param {number} purchasePrice - 进货价格
 * @returns {Object} 计算结果
 */
function calculateSimpleProfit(weight, salePrice, purchasePrice) {
    // 这里使用您提供的配置数据
    const uniConfig = {
        "status": "success",
        "data": {
            "name": "UNI默认配置",
            "items": [
                {
                    "name": "Extra Small",
                    "commission": 0.12,
                    "package_fee": 4,
                    "logistic_fee": {
                        "base": "3.04",
                        "growth": "0.03500"
                    },
                    "weight": {
                        "min": 1,
                        "max": 500
                    },
                    "price": {
                        "min": 1,
                        "max": 1500
                    }
                },
                {
                    "name": "Budget",
                    "commission": 0.12,
                    "package_fee": 6,
                    "logistic_fee": {
                        "base": "23.00",
                        "growth": "0.03300"
                    },
                    "weight": {
                        "min": 501,
                        "max": 25000
                    },
                    "price": {
                        "min": 1,
                        "max": 1500
                    }
                },
                {
                    "name": "Small",
                    "commission": 0.2,
                    "package_fee": 6,
                    "logistic_fee": {
                        "base": "16.03",
                        "growth": "0.02500"
                    },
                    "weight": {
                        "min": 1,
                        "max": 2000
                    },
                    "price": {
                        "min": 1501,
                        "max": 7000
                    }
                },
                {
                    "name": "Big",
                    "commission": 0.2,
                    "package_fee": 6,
                    "logistic_fee": {
                        "base": "36.00",
                        "growth": "0.03300"
                    },
                    "weight": {
                        "min": 2001,
                        "max": 25000
                    },
                    "price": {
                        "min": 1501,
                        "max": 7000
                    }
                },
                {
                    "name": "Premium small",
                    "commission": 0.2,
                    "package_fee": 6,
                    "logistic_fee": {
                        "base": "25.55",
                        "growth": "0.04500"
                    },
                    "weight": {
                        "min": 1,
                        "max": 5000
                    },
                    "price": {
                        "min": 7001,
                        "max": 250000
                    }
                },
                {
                    "name": "Premium Big",
                    "commission": 0.2,
                    "package_fee": 6,
                    "logistic_fee": {
                        "base": "62.00",
                        "growth": "0.03300"
                    },
                    "weight": {
                        "min": 5001,
                        "max": 25000
                    },
                    "price": {
                        "min": 7001,
                        "max": 250000
                    }
                }
            ]
        }
    };
    
    return calculateUNIProfit(uniConfig, weight, salePrice, purchasePrice);
}


// 获取CNY对RUB汇率
async function getCNY2RUBRate() {
    try {
        // 替换为无需API Key的免费汇率接口
        const res = await fetch('https://open.er-api.com/v6/latest/CNY');
        const data = await res.json();
        if (data && data.rates && data.rates.RUB) {
            CNY2RUBDetail = data.rates.RUB;
            return CNY2RUBDetail;
        }
    } catch (e) {
        console.error('获取汇率失败', e);
    }
    return CNY2RUBDetail;
}

// 显示加载
function showLoading() {
	document.getElementById('loading-overlay').classList.remove('hidden');
}

// 取消加载
function hideLoading() {
	document.getElementById('loading-overlay').classList.add('hidden');
}