// 数据抓取层已移到 product/ozon-api.js

const showOzonPageGoodsData=()=>{
    showSkuShelfGoods();
    showSkuGridSimple();
    showSearchResultsV2();
    //showTileGridDesktop();
}

if(location.href.indexOf('/product/') != -1){
	
}else{
	setInterval(function(){
			showTileGridDesktop_2();	
		},500);
}
		
	function tiddp(msg, t = 1500) {
    let m = document.createElement('div');
	m.style.cssText = 'display: inline-block;padding: 12px 24px;color: #fff;text-align: center;border-radius: 12px; position: fixed;top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 999999999; background: linear-gradient(135deg, #1e7bff, #005bff);font-size: 14px; font-weight: 600; box-shadow: 0 16px 48px rgba(10, 12, 20, 0.18), 0 0 0 1px rgba(10, 12, 20, 0.04);transition: opacity 0.3s ease;'
    m.innerHTML = msg;document.body.appendChild(m); setTimeout(() => {document.body.removeChild(m);}, t);
}	

// controlPanelHtml 已移到 product/ozon-templates.js

var vad = $(controlPanelHtml);
(function() {
  var href = location.href;
  var isOzon = (href.includes('ozon.ru') || href.includes('ozon.kz') || href.includes('ozon.by'));
  var isSeller = (href.includes('seller.ozon.ru') || href.includes('seller.ozon.kz') || href.includes('seller.ozon.by'));
  var isProduct = href.includes('/product/');
  if (!isOzon || isSeller || isProduct) return;

  var tewceds = setInterval(function() {
    if ($('#xq-login-main')[0]) {
      clearInterval(tewceds);
      $('#xq-login-main').append(vad);
      vad.find('#pocacewew').click(function() {
        window.open('https://air.1688.com/app/ctf-page/trade-order-list/buyer-order-list.html?tradeStatus=waitbuyerreceive&spm=a260k.home2025.topmenu.dmyorder&page=1&pageSize=10', '_blank');
      });
      vad.find('#ptbewew').click(function() {
        window.open('https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?action=itemlist%2FBoughtQueryAction&event_submit_do_query=1&tabCode=waitConfirm', '_blank');
      });
      vad.find('#pddewew').click(function() {
        window.open('https://mobile.yangkeduo.com/orders.html?type=3&comment_tab=1&combine_orders=1&main_orders=1&refer_page_name=personal&refer_page_id=10001_1772429674380_916ca2luxr&refer_page_sn=10001', '_blank');
      });
    }
  }, 500);
})();
  let boysew = 0,boyecw=0,xuaweew = 0;
  
  let offs,tmoce=0,opacewe;
vad.find('#poacewew').click(function(){
		  if(offs){
			  offs=!1;
			  $(this).text('自动滚动').removeClass('active');
			  clearTimeout(tmoce);
		  }else{
			 offs=!0;
			$(this).text('停止滚动').addClass('active'); 
			opacewe = 10000;	
			poacwewe();
		  }
});
function poacwewe(){
	if(offs){
		 tmoce = setInterval(function(){
				$('body').animate({scrollTop: $('body')[0].scrollHeight}, opacewe-300);
				boysew = document.querySelector("body").scrollTop;
				if(boysew && boysew == boyecw){
					xuaweew++;
					if(xuaweew>5){
						$('#poacewew').click();
					}
				}else{
					xuaweew = 0;
				}
				boyecw = boysew;
				
			},opacewe);
	}
};
function gyuhtml(item,sku){
    const cardStyles = `
        <style>
            .ozonhelper-card-good {
                background: #ffffff;
                color: #0a0c14;
                border-radius: 12px;
                padding: 16px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
                margin-top: 10px;
                border: 1px solid #e9ebef;
                text-align: left;
                font-size: 14px;
                line-height: 1.4;
                box-shadow: 0 16px 48px rgba(10, 12, 20, 0.18), 0 0 0 1px rgba(10, 12, 20, 0.04);
            }
            .ozonhelper-card-good h4 {
                color: #005bff;
                margin: 0 0 12px 0;
                padding-bottom: 10px;
                border-bottom: 1px solid #e9ebef;
                font-size: 16px;
                font-weight: 700;
            }
            .ozonhelper-card-good h4 span {
                font-weight: 400;
                color: #3a3e47;
            }
            .ozonhelper-card-body .layui-form-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 6px 0;
                border-bottom: 1px solid #e9ebef;
            }
             .ozonhelper-card-body .layui-form-item:last-child {
                border-bottom: none;
            }
            .ozonhelper-card-body .item-label {
                color: #6b7280;
                font-size: 13px;
            }
            .ozonhelper-card-body .item-value {
                color: #0a0c14;
                font-weight: 500;
                font-family: "SF Mono", "Fira Code", "Fira Mono", "Roboto Mono", monospace;
                font-size: 13px;
            }
            .ozonhelper-card-body .item-value.highlight {
                color: #005bff;
                font-weight: 600;
            }
            .getacewewce {
                cursor: pointer;
                color: #005bff !important;
                font-weight: 600;
            }
            .getacewewce:hover {
                text-decoration: underline;
            }
        </style>
    `;

    const items = [
        { label: '卖家ID', key: 'sellerId', highlight: true },
        { label: '卖家名称', key: 'sellerName', highlight: true },
        { label: '品牌', key: 'brand' },
        { label: '一级类目', key: 'category1' },
        { label: '三级类目', key: 'category3' },
        { label: '30天销量', key: 'soldCount', highlight: true },
        { label: '30天销售额', key: 'soldSum', highlight: true, unit: '₽' },
        { label: '30天销售变化', key: 'salesDynamics', suffix: '%' },
        { label: '平均售价', key: 'avgPrice', unit: '₽' },
        { label: '最低售价', key: 'minSellerPrice', unit: '₽' },
        { label: '加购率', key: 'convToCartPdp', highlight: true, suffix: '%' },
        { label: '浏览量', key: 'views' },
        { label: '体积/公斤', key: 'volume' },
        { label: '发货模式', key: 'salesSchema' },
        { label: '配送天数', key: 'avgDeliveryDays' },
        { label: '库存', key: 'stock' },
        { label: '出售时间', key: 'nullableCreateDate', highlight: true }
    ];

    let itemsHtml = items.map(i => {
        let value = rscwevrr(item[i.key]);
        let valueClass = 'item-value' + (i.highlight ? ' highlight' : '');
        
        let displayValue = value;
        if (value !== '无') {
            if (i.suffix) {
                displayValue = `${value}${i.suffix}`;
            }
            if (i.unit) {
                displayValue = `${value} ${i.unit}`;
            }
        }

        return `
            <div class="layui-form-item">
                <span class="item-label">${i.label}</span>
                <span class="${valueClass}">${displayValue}</span>
            </div>
        `;
    }).join('');

    const weightHtml = `
        <div class="layui-form-item">
            <span class="item-label">包裹重量</span>
            <span data-sku="${sku}" class="getacewewce item-value">${item['zwews'] || '点击获取'}</span>
        </div>
    `;

    return cardStyles +
        `<div class="ozonhelper-card ozonhelper-card-good">
            <div class="ozonhelper-card-header">
                <h4>SKU: <span>${sku}</span></h4>
            </div>
            <div class="ozonhelper-card-body">
                <div class="layui-form">
                    ${itemsHtml}
                    ${weightHtml}
                </div>
            </div>
        </div>`;
}
$(document).on('click','.getacewewce',function(){ 
	let self = $(this);
    self.text('↻ 查询中...');
	setTimeout(async () =>{
		let suk = self.attr('data-sku');
        const weightValue = ((await getWaith(suk))||'无').replace('гр','g').replace('кг','kg');
		
		if(location.href.indexOf('ozon.ru/product/') != -1 || location.href.indexOf('ozon.kz/product/') != -1){
			self.text(weightValue);
		}else{
			// 确保SKUDATA[suk]存在
			if(!SKUDATA[suk]) {
			    SKUDATA[suk] = {};
			}
			// 更新SKUDATA中的重量值
			SKUDATA[suk].zwews = weightValue;
			console.log(`已更新SKUDATA[${suk}].zwews = ${weightValue}`);
			
			// 更新DOM显示
			self.text(weightValue);
			// 更新数据表格中对应行的重量显示（列索引因新增跟卖数量列后变为5）
			$(`#data-table-body tr[data-sku="${suk}"] td:eq(5)`).html(weightValue);
            // 新增：刷新物流费和利润
            await updateProfitCell(suk);
            // 如果已经选择了物流分组，重新加载物流方式
            const groupId = $('#logistics-group').val();
            if (groupId) {
                console.log('重量已获取，重新加载物流方式');
                // window.loadOzonLogisticsMethods(groupId);
            }
		}
	},0)
});
async function getWaith(sku) {
    const cartItemIds = [];
    
    try {
        // Step 1: Get current cart items
        const summaryResponse = await $.ajax({
            url: 'https://www.ozon.ru/api/composer-api.bx/_action/summary',
            method: 'GET',
            dataType: 'json'
        });

        // Collect item IDs
        $.each(summaryResponse, function(index, 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 $.ajax({
                url: 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fcart%3Fpage_changed%3Dtrue',
                type: 'POST',
                data: JSON.stringify(clearCartData),
                contentType: 'application/json'
            });
        }

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

        const addResponse = await $.ajax({
            url: 'https://www.ozon.ru/api/composer-api.bx/_action/v2/addToCart',
            type: 'POST',
            data: JSON.stringify(addToCartData),
            contentType: 'application/json'
        });

        const addResponselast = await $.ajax({
            url: 'https://www.ozon.ru/cart?tab=0',
            type: 'GET',
            //contentType: 'application/json'
        });
        //console.log(addResponselast)
        const match = addResponselast.match(/"info":"[^•]+•\s*([^"]+)/);
        const weight = match ? match[1].trim() : null;
     
        return weight;
        
        

    } catch (error) {
        console.error('Operation failed:', error);
        return '无 ';
    }
}
const extractProductIdFromString1 = (inputString) => {
    // 移除查询参数和末尾可能存在的斜杠
    const cleanPath = inputString.split('?')[0].replace(/\/+$/, '');

    // 匹配包含数字结尾的路径格式，支持product和category页面
    const regex = /-(\d+)$/;
    const match = cleanPath.match(regex);
    return match ? match[1] : null;
}
// 配置格式化选项
const formatter1 = new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  timeZone: 'Asia/Shanghai',
});
//sku	商家id 30天销量	30天销售额	价格	划线价	促销比例	sku,卖价	产品名称	星级	评论数	品牌	一级类目	三级类目	30天销售变化	平均售价	最低售价	加购率	浏览量	重量	体积/公斤	发货模式	配送天数	库存	出售时间
function rscwevrr(b){
	return b?b:'无'
};
vad.find('#bsoacewew').click(function(){
	showDataExportModal();
});


let visibleSkus = [];
function updateVisibleSkus() {
    visibleSkus = [];
    $('#data-table-body tr:visible').each(function() {
        const sku = $(this).attr('data-sku');
        if (sku) visibleSkus.push(sku);
    });
}
$(document).on('tableContentChanged', updateVisibleSkus);

// 汇率全局变量
let CNY2RUB = 10.93; // 默认1，实际用接口值覆盖
let priceAdjustCount = 0; // 批量调价计数器

// 从background.js迁移的函数 - 获取Ozon卖家平台的cookie
// 走 background 的 getCookie 消息（带 scripting 兜底），Chrome 147+ chrome.cookies.get 空返回时仍可用
async function getCookiesoz() {
    let resPromise = new Promise(function (resolve, reject) {
        try {
            config.getCookie({"url": "https://seller.ozon.ru", "name": 'sc_company_id'}, function (cookie) {
                if (cookie && cookie.value) {
                    resolve({ token: cookie.value, sc_company_id: cookie.value });
                } else {
                    resolve({ token: "", sc_company_id: "" });
                }
            });
        } catch (error) {
            console.error('getCookiesoz函数出错:', error);
            resolve({token: "", sc_company_id: ""});
        }
    });
    return resPromise;
}

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

// 5.19 新增：按 SKU 反查商品基础信息（用于上报 SpiderOzon）。content script → bg httpRequest。
function getProductDetaisearch(headers, sku) {
    if (!sku) return Promise.resolve(null);
    const body = OzAnalytics.buildSearchRequestBody(headers['x-o3-company-id'], sku);
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({
            action: "httpRequest",
            method: "POST",
            url: OzAnalytics.SEARCH_URL,
            headers: headers,
            params: body
        }, (response) => {
            if (response && !response.error) resolve(response);
            else resolve(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);
    }
}

// 通过 background 转发分析数据请求；body/headers/响应整形均走共享模块。
// 返回 Promise，方便批量场景 await
async function httpPostoz(url, params = {}, callback = () => {}) {
    return new Promise(async (resolve, reject) => {
        const done = function(result) {
            callback(result);
            resolve(result);
        };
        try {
            const {token, sc_company_id} = await getCookiesoz();
            const headers = OzAnalytics.buildHeaders(sc_company_id, false);
            const sku = params.sku || OzAnalytics.ggetSkuFromurl(params.url);
            const requestBody = OzAnalytics.buildRequestBody(sku);
            const pourl = OzAnalytics.ANALYTICS_URL;

            chrome.runtime.sendMessage({
                action: "httpRequest",
                method: "POST",
                url: pourl,
                headers: headers,
                params: requestBody
            }, function(response) {
                if (!response || response.error) {
                    console.error('请求失败:', response);
                    done({ error: true, message: (response && response.error) || '请求失败' });
                    return;
                }
                const firstData = response;

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

                (async () => {
                    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) {
                        done(OzAnalytics.shapeMergedWithDetail(firstData, productDetail));
                    } else {
                        done(OzAnalytics.shapeFallbackWithoutDetail(firstData));
                    }
                })();
            });
        } catch (error) {
            console.error('httpPostoz请求失败:', error);
            done({ error: true, message: error.message });
        }
    });
}

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 requestBody = {
            "company_id": "" + headers['x-o3-company-id'] + "",
            "variant_id": "" + sku + "",
            "source": "SOURCE_UI_COPY_MERGED"
        };
        console.log('搜索商品详情，SKU:', sku);

        return new Promise((resolve) => {
            chrome.runtime.sendMessage({
                action: "httpRequest",
                method: "POST",
                url: pourl,
                headers: headers,
                params: requestBody
            }, function(response) {
                if (response && !response.error) {
                    const data = response;
                    if (data && data.item) {
                        const firstItem = data.item;
                        const specs = getProductSpecifications(firstItem);
                        firstItem.specifications = specs;
                        resolve(firstItem);
                    } else {
                        console.log('未找到相关商品或请求失败');
                        resolve(null);
                    }
                } else {
                    console.log('请求失败:', response);
                    resolve(null);
                }
            });
        });
    } catch (error) {
        console.error('获取商品详情失败:', error);
        return null;
    }
}

// 从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 requestBody = {name: sku, limit: "10"};

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

        // 使用 Chrome runtime API 发送跨域请求
        return new Promise((resolve) => {
            chrome.runtime.sendMessage({
                action: "httpRequest",
                method: "POST",
                url: pourl,
                params: requestBody,
                headers: headers
            }, function(data) {
                if (data && !data.error) {
                    //console.log('商品搜索API返回数据');

                    if (data && 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;
                        resolve(firstItem);
                    } else {
                        console.log('未找到相关商品');
                        resolve(null);
                    }
                } else {
                    console.error('商品详情请求失败:', data);
                    resolve(null);
                }
            });
        });
    } catch (error) {
        console.error('获取商品详情失败:', error);
        return null;
    }
}

// 从background.js迁移的函数 - 从商品属性中提取尺寸和重量信息
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迁移的函数 - 获取商品规格信息
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;
}

// 新增函数：为多个SKU发送第一个API请求并处理响应
async function processMultipleSkus(skus) {
    console.log('开始处理多个SKU的API请求，SKU数量:', skus.length);
    
    for (const sku of skus) {
        console.log('处理SKU:', sku);
        // 构建请求参数，直接传递SKU值
        const params = {
            url: window.location.href,
            sku: sku // 直接传递SKU值
        };
        // 发送API请求并处理响应
        await httpPostoz('https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3', params, function(response) {
            console.log('SKU', sku, '的API请求响应:', response);
            
            // 将返回的数据与SKUDATA中的信息对应
            if (SKUDATA[sku] && !response.error) {
                // 存储完整的API响应数据
                SKUDATA[sku].apiData = response;
                
                // 从response中提取所需属性并更新SKUDATA
                if (response.items && Array.isArray(response.items) && response.items.length > 0) {
                    const item = response.items[0];
                    console.log('items:',item)
                    // // 更新SKUDATA中的字段
                    // if (item.soldCount !== undefined) {
                    //     SKUDATA[sku].soldCount = item.soldCount;
                    // }
                    // if (item.gmvSum !== undefined) {
                    //     SKUDATA[sku].soldSum = item.gmvSum;
                    // }
                    // if (item.brand !== undefined) {
                    //     SKUDATA[sku].brand = item.brand;
                    // }
                    // if (item.salesSchema !== undefined) {
                    //     SKUDATA[sku].salesSchema = item.salesSchema;
                    // }
                    // if (item.pdpToCartConversion !== undefined) {
                    //     SKUDATA[sku].convToCartPdp = item.pdpToCartConversion;
                    // }
                    SKUDATA[sku].soldCount = item.soldCount;
                    SKUDATA[sku].soldSum = item.gmvSum;
                    SKUDATA[sku].brand = item.brand;
                    SKUDATA[sku].salesSchema = item.salesSchema;
                    SKUDATA[sku].convToCartPdp = item.pdpToCartConversion;
                    // 新增字段
                    SKUDATA[sku].category1 = item.category1;
                    SKUDATA[sku].category3 = item.category3;
                    SKUDATA[sku].salesDynamics = item.salesDynamics;
                    SKUDATA[sku].avgPrice = item.avgPrice;
                    // 直接保存跟卖最低价的原始值
                    if (item.minSellerPrice != null) {
                        SKUDATA[sku].minSellerPrice = item.minSellerPrice;
                    }
                    SKUDATA[sku].views = item.views;
                    SKUDATA[sku].stock = item.stock;
                    SKUDATA[sku].photo = item.photo;
                    // 出售时间：优先从 item 取 nullableCreateDate，否则尝试 response.productDetail
                    if (item.nullableCreateDate) {
                        SKUDATA[sku].nullableCreateDate = item.nullableCreateDate;
                        SKUDATA[sku].pCreateDate = item.nullableCreateDate.split('T')[0];
                    } else if (response.productDetail && response.productDetail.created_at) {
                        SKUDATA[sku].nullableCreateDate = response.productDetail.created_at;
                        SKUDATA[sku].pCreateDate = response.productDetail.created_at.split('T')[0];
                    } else if (response.productDetail && response.productDetail.createDate) {
                        SKUDATA[sku].nullableCreateDate = response.productDetail.createDate;
                        SKUDATA[sku].pCreateDate = response.productDetail.createDate.split('T')[0];
                    }
                    
                    // 自动提取重量、长宽高并同步到快速核价
                    if (response.productDetail) {
                        const specs = getProductSpecifications(response.productDetail);
                        if (specs.weight) {
                            SKUDATA[sku].zwews = specs.weight;
                            console.log('自动提取到重量:', specs.weight, 'g');
                            
                            // 更新表格中的重量单元格，添加单位（列索引因新增跟卖数量列后变为5）
                            const weightCell = $(`#data-table-body tr[data-sku="${sku}"] td:eq(5)`);
                            if (weightCell.length > 0) {
                                weightCell.html(`${specs.weight} g`);
                            }
                        }
                        // 保存到 chrome.storage.local 供快速核价读取（mm → cm）
                        try {
                            const dimL = specs.length ? +(specs.length / 10).toFixed(1) : 0;
                            const dimW = specs.width  ? +(specs.width  / 10).toFixed(1) : 0;
                            const dimH = specs.height ? +(specs.height / 10).toFixed(1) : 0;
                            const storageKey = 'jz_calc_sku_specs_v1';
                            chrome.storage.local.get([storageKey], (res) => {
                                const all = res[storageKey] || {};
                                all[sku] = {
                                    weight: specs.weight || 0,
                                    dimL: dimL,
                                    dimW: dimW,
                                    dimH: dimH,
                                    ts: Date.now()
                                };
                                chrome.storage.local.set({ [storageKey]: all });
                            });
                        } catch (e) {
                            console.log('同步规格到 storage 失败:', e);
                        }
                    }
                    
                    console.log('已更新SKUDATA中的字段:', {
                        soldCount: SKUDATA[sku].soldCount,
                        soldSum: SKUDATA[sku].soldSum,
                        brand: SKUDATA[sku].brand,
                        salesSchema: SKUDATA[sku].salesSchema,
                        convToCartPdp: SKUDATA[sku].convToCartPdp,
                        category1: SKUDATA[sku].category1,
                        category3: SKUDATA[sku].category3,
                        salesDynamics: SKUDATA[sku].salesDynamics,
                        avgPrice: SKUDATA[sku].avgPrice,
                        minSellerPrice: SKUDATA[sku].minSellerPrice,
                        views: SKUDATA[sku].views,
                        stock: SKUDATA[sku].stock,
                        photo: SKUDATA[sku].photo,
                        weight: SKUDATA[sku].zwews
                    });
                    
                    // 检查成本是否为0或未填写，如果是则计算利润
                    const cost = parseFloat(SKUDATA[sku].cost) || 0;
                    if (cost === 0 || !SKUDATA[sku].cost) {
                        console.log(`成本为0或未填写，开始计算SKU ${sku} 的利润`);
                         updateProfitCell(sku);
                    }
                    
                    // 更新表格中对应行的单元格
                    const tableRow = $(`#data-table-body tr[data-sku="${sku}"]`);
                    if (tableRow.length > 0) {
                        // 更新30天销量 (第11列，索引11，因新增跟卖数量列后偏移)
                        if (SKUDATA[sku].soldCount !== undefined) {
                            tableRow.find('td:eq(11)').text(SKUDATA[sku].soldCount);
                        }
                        // 更新30天销售额 (第12列，索引12，因新增跟卖数量列后偏移)
                        if (SKUDATA[sku].soldSum !== undefined) {
                            tableRow.find('td:eq(12)').text(`${SKUDATA[sku].soldSum} ₽`);
                        }
                        // 更新品牌 (第14列，索引14，因新增跟卖数量列后偏移)
                        if (SKUDATA[sku].brand !== undefined) {
                            tableRow.find('td:eq(14)').text(SKUDATA[sku].brand);
                        }
                        // 更新发货模式 (第15列，索引15，因新增跟卖数量列后偏移)
                        if (SKUDATA[sku].salesSchema !== undefined) {
                            tableRow.find('td:eq(15)').text(SKUDATA[sku].salesSchema);
                        }
                        // 更新加购率 (第16列，索引16，因新增跟卖数量列后偏移)
                        if (SKUDATA[sku].convToCartPdp !== undefined) {
                            tableRow.find('td:eq(16)').text(`${SKUDATA[sku].convToCartPdp}%`);
                        }
                        // 更新出售时间 (第13列，索引13)
                        if (SKUDATA[sku].pCreateDate && SKUDATA[sku].pCreateDate !== '未知') {
                            tableRow.find('td:eq(13)').text(SKUDATA[sku].pCreateDate);
                        } else if (SKUDATA[sku].nullableCreateDate) {
                            tableRow.find('td:eq(13)').text(SKUDATA[sku].nullableCreateDate.split('T')[0]);
                        }
                        console.log('已更新表格中对应行的单元格');
                    }
                }
                
                // 更新表格中对应行的显示
                // 这里可以根据实际需要，更新表格中的数据显示
            }
        });
        
        // 添加短暂延迟，避免请求过于频繁
        await new Promise(resolve => setTimeout(resolve, 500));
    }
    
    console.log('多个SKU的API请求处理完成');
    
    // 主动触发 SpiderOzon 批量发送
    chrome.runtime.sendMessage({ action: "spiderPostFlush" }, function(res) {
        console.log('SpiderOzon 批量 flush 结果:', res);
    });
}

// 获取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) {
            CNY2RUB = data.rates.RUB;
            return CNY2RUB;
        }
    } catch (e) {
        console.error('获取汇率失败', e);
    }
    return CNY2RUB;
}


// ─────────────────────────────────────────────────────────────────────
// 数据导出弹窗模块已迁移到 product/ozon-export.js
// (showDataExportModal / initializeDataTable / createDataRow / bindModalEvents /
//  applyFilters / clearFilters / exportSelectedData / exportAllData /
//  exportDataToExcel / copyDataToClipboard / logisticsTiers / exportExcel)
// ─────────────────────────────────────────────────────────────────────


const SKUDATA = {};	
const SKUDATA_pic = {};		
const showTileGridDesktop_2=()=>{
	// 不在seller.ozon.ru上执行
	if(location.href.indexOf('seller.ozon.ru') != -1) return;
	
	$('div[data-index][pose!="1"]').each(function(i){
		// 新增：过滤"您可能喜欢"区域
		if ($(this).closest('[data-widget="skuGrid"]').length > 0) return;
		
		let item = $(this).attr('pose',1);
		let iaoe = $(this);
		if($(this).contents('a')[0]){
		//if(i==0){
		let aTag = this.querySelector('a');
			//if(i==0){
			let suk = extractProductIdFromString1(aTag.href);
			// 尝试获取商品信息元素
			let hs = $(this).find('a').eq(0).next();
			let use = hs.find('.tile-clickable-element').eq(0).next();
			
			// 获取标题信息
			let title = hs.find('.tile-clickable-element').eq(0).text();
			if(!title) {
				title = hs.find('.tile-title').text();
			}
			
			// 如果标题为空，说明不是有效的商品元素，跳过
			if (!title) return;
			
			let price = hs.find('span').eq(0).text().replace(',','.').replace('¥','');
			let originalPrice = hs.find('span').eq(1).text().replace(',','.').replace('¥','');
			let promotion = hs.find('span').eq(2).text();
			let rating = use.find('span>span').eq(0).text();
			let reviews = parseFloat(use.find('span>span').eq(1).text().replace(' ',''));
			let miniapp = location.href.split('miniapp=seller_')[1];
			
			// 填充SKUDATA_pic对象
			SKUDATA_pic[suk] = [price, originalPrice, promotion, title, rating, reviews, miniapp];
			
			// 打印获取到的商品基本信息
			console.log('获取到商品基本信息:', {
				sku: suk,
				basicInfo: SKUDATA_pic[suk]
			});
			
			}
		});
};
		
const showTileGridDesktop=()=>{
    const skuShelfGoods = $("#layoutPage").find("div[data-widget='tileGridDesktop']").children("div").filter(function () {
        return ($(this).attr("class"))
    });
    for(let index = 0; index < skuShelfGoods.length; index++){
        const item = skuShelfGoods.eq(index);
        const isLoad = item.data("isLoad");
        const hrefObj = item.find("a")[0];

        if (!isLoad) {
            item.data("isLoad", true);
            if(hrefObj!=undefined){
					console.log(77)
                sendMessageToBackgroudScript("getGoodsInfo",{ url: hrefObj.href,type:'Ozon' }, function (response) {
					if (chrome.runtime.lastError || !response) {
						console.log(chrome.runtime.lastError ? chrome.runtime.lastError.message : "无有效响应");
						return;
					}
                    // console.log(response);
                    if(response.code==200){
                        item.css("flex-direction","column");
                        item.append(response.data.html);
                    }
                });
            }
        }
    }
}

const showSkuShelfGoods=()=>{
    const skuShelfGoods = $("#layoutPage").find("div[data-widget='skuShelfGoods']").children("div:nth-last-of-type(1)").children("div").children("div").children("div").filter(function () {
        return ($(this).attr("class"))
    });
    for(let index = 0; index < skuShelfGoods.length; index++){
        const item = skuShelfGoods.eq(index);
        const isLoad = item.data("isLoad");
        const hrefObj = item.find("a")[0];
        // console.log(hrefObj.href);
        if (!isLoad) {
            item.data("isLoad", true);
            if(hrefObj!=undefined){
                sendMessageToBackgroudScript("getGoodsInfo",{ url: hrefObj.href,type:'Ozon' }, function (response) {
					if (chrome.runtime.lastError || !response) {
						console.log(chrome.runtime.lastError ? chrome.runtime.lastError.message : "无有效响应");
						return;
					}
                    // console.log(response);
                    if(response.code==200){
                        item.css("flex-direction","column");
                        item.append(response.data.html);
                    }
                });
            }
        }

    };
}
const showSkuGridSimple=()=>{
    const skuShelfGoods = $("#layoutPage").find("div[data-widget='skuGridSimple']").children("div:nth-last-of-type(1)").children("div").filter(function () {
        return ($(this).attr("class"))
    });
    // console.log(skuShelfGoods);
    for(let index = 0; index < skuShelfGoods.length; index++){
        const item = skuShelfGoods.eq(index);
        const isLoad = item.data("isLoad");
        const hrefObj = item.find("a")[0];
        if (!isLoad) {
            item.data("isLoad", true);
            if(hrefObj!=undefined){
                sendMessageToBackgroudScript("getGoodsInfo",{ url: hrefObj.href,type:'Ozon' }, function (response) {
					if (chrome.runtime.lastError || !response) {
						console.log(chrome.runtime.lastError ? chrome.runtime.lastError.message : "无有效响应");
						return;
					}
                    // console.log(response);
                    if(response.code==200){
                        item.css("flex-direction","column");
                        item.append(response.data.html);
                    }
                });
            }
        }

    };
}
const showSearchResultsV2=()=>{
    const skuShelfGoods = $("#layoutPage").find("div[data-widget='searchResultsV2']").children("div:nth-last-of-type(1)").children("div").children("div").filter(function () {
        return ($(this).attr("class"))
    });
    for(let index = 0; index < skuShelfGoods.length; index++){
        const item = skuShelfGoods.eq(index);
        const isLoad = item.data("isLoad");
        const hrefObj = item.find("a")[0];

        if (!isLoad) {
            item.data("isLoad", true);
            if(hrefObj!=undefined){
                sendMessageToBackgroudScript("getGoodsInfo",{ url: hrefObj.href,type:'Ozon' }, function (response) {
					if (chrome.runtime.lastError || !response) {
						console.log(chrome.runtime.lastError ? chrome.runtime.lastError.message : "无有效响应");
						return;
					}
                    // console.log(response);
                    if(response.code==200){
                        item.css("flex-direction","column");
                        item.append(response.data.html);
                    }
                });
            }
        }

    };
}

// 应用价格调整
function applyPriceAdjustment() {
    const adjustType = $('#price-adjust-type').val();
    const adjustValue = parseFloat($('#price-adjust-value').val());
    const adjustDirection = $('#price-adjust-direction').val();
    
    if (!adjustValue || adjustValue <= 0) {
        tiddp('请输入有效的调整数值');
        return;
    }
    
    // 确认操作
    const type = adjustDirection === 'up' ? 'success' : 'danger';
    priceAdjustCount = priceAdjustCount + 1;
    const adjustMainMsg = `<div style='text-align:center;'>确定要对所有可见产品的价格进行${adjustDirection === 'up' ? '上涨' : '下降'}操作吗？</div>`;
    const adjustTypeMsg = `<div style='text-align:left;margin-top:10px;'>调整方式: <b>${adjustType === 'percentage' ? '比例' : '固定价格'}</b></div>`;
    const adjustValueMsg = `<div style='text-align:left;'>调整数值: <b>${adjustValue}${adjustType === 'percentage' ? '%' : '₽'}</b></div>`;
    const adjustCountMsg = `<div style='text-align:left;margin-top:8px;'><span style="color:#FF3B30;font-weight:bold;font-size:16px;">第${priceAdjustCount}次调价</span></div>`;
    const message = `${adjustMainMsg}${adjustTypeMsg}${adjustValueMsg}${adjustCountMsg}`;

    // showCustomConfirm({
    //     message,
    //     type,
    //     onConfirm: () => {
            let adjustedCount = 0;
            let totalCount = 0;
            // 先保存原价（只在第一次调价时保存）
            $('#data-table-body tr:visible .row-checkbox:checked').closest('tr').each(function() {
                const row = $(this);
                const sku = row.attr('data-sku');
                const picData = SKUDATA_pic[sku];
                const skuData = SKUDATA[sku];
                if (picData && skuData) {
                    if (typeof skuData._originPrice === 'undefined') {
                        skuData._originPrice = picData[0];
                    }
                }
            });

            $('#data-table-body tr:visible .row-checkbox:checked').closest('tr').each(function() {
                const row = $(this);
                const sku = row.attr('data-sku');
                const picData = SKUDATA_pic[sku];
                const skuData = SKUDATA[sku];

                if (picData && picData[0]) {
                    const currentPrice = parseFloat(picData[0]);
                    if (!isNaN(currentPrice) && currentPrice > 0) {
                        let newPrice;

                        if (adjustType === 'percentage') {
                            if (adjustDirection === 'up') {
                                newPrice = currentPrice * (1 + adjustValue / 100);
                            } else {
                                newPrice = currentPrice * (1 - adjustValue / 100);
                            }
                        } else {
                            if (adjustDirection === 'up') {
                                newPrice = currentPrice + adjustValue;
                            } else {
                                newPrice = currentPrice - adjustValue;
                            }
                        }

                        newPrice = Math.max(0, newPrice);
                        const newPriceStr = newPrice.toFixed(2);

                        picData[0] = newPriceStr;
                        if (skuData) {
                            skuData.price = newPriceStr;
                        }
                        row.find('.price-input').val(newPriceStr);
                        updateProfitCell(sku);
                        adjustedCount++;
                    }
                }
                totalCount++;
            });
            
            if (adjustedCount > 0) {
                tiddp(`成功调整了 ${adjustedCount} 个产品的价格`);
                updateSelectedCount();
            } else {
                tiddp('没有找到可调整价格的产品');
            }
        // }
    // });
}

// 批量获取重量
async function batchGetWeight() {
    // 获取选中的SKU
    const selectedSkus = [];
    $('#data-table-body tr:visible .row-checkbox:checked').each(function() {
        const sku = $(this).closest('tr').attr('data-sku');
        selectedSkus.push(sku);
    });
    
    if (selectedSkus.length === 0) {
        tiddp('请先选择要获取重量的产品');
        return;
    }
    
    // 过滤出需要获取重量的SKU（跳过已有重量数据的）
    const skusToProcess = [];
    const skusToSkip = [];
    
    selectedSkus.forEach(sku => {
        const skuData = SKUDATA[sku];
        const hasWeight = skuData && skuData.zwews && skuData.zwews !== '点击获取' && skuData.zwews !== '无';
        
        if (hasWeight) {
            skusToSkip.push(sku);
        } else {
            skusToProcess.push(sku);
        }
    });
    
    if (skusToProcess.length === 0) {
        tiddp(`选中的 ${selectedSkus.length} 个产品都已具有重量数据，无需重复获取`);
        return;
    }
    
    // 确认操作
    const skipMessage = skusToSkip.length > 0 ? `\n其中 ${skusToSkip.length} 个产品已有重量数据将被跳过` : '';
    const message = `确定要为选中的 ${selectedSkus.length} 个产品批量获取重量信息吗？\n需要获取重量：${skusToProcess.length} 个${skipMessage}\n此操作可能需要较长时间，请耐心等待。`;

    showCustomConfirm({
        message,
        onConfirm: async () => {
            const button = $('#batch-get-weight');
            const originalText = button.text();
            button.text('获取中...').prop('disabled', true);
            
            // 显示进度条
            const progressContainer = $('#weight-progress-container');
            const progressText = $('#weight-progress-text');
            const progressBar = $('#weight-progress-bar');
            
            progressContainer.show();
            progressText.text(`0/${skusToProcess.length}`);
            progressBar.css('width', '0%');
            
            let successCount = 0;
            let failCount = 0;
            let skipCount = skusToSkip.length;
            
            try {
                // 先清空购物车一次，避免每次都清空
                const cartItemIds = [];
                const summaryResponse = await $.ajax({
                    url: 'https://www.ozon.ru/api/composer-api.bx/_action/summary',
                    method: 'GET',
                    dataType: 'json'
                });
                
                $.each(summaryResponse, function(index, item) {
                    cartItemIds.push(item.id);
                });
                
                if (cartItemIds.length > 0) {
                    const clearCartParams = {
                        items: cartItemIds
                    };
                    const str = JSON.stringify(clearCartParams);
                    const clearCartData = {
                        name: "deleteItems",
                        params: str
                    };
                    
                    await $.ajax({
                        url: 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fcart%3Fpage_changed%3Dtrue',
                        type: 'POST',
                        data: JSON.stringify(clearCartData),
                        contentType: 'application/json'
                    });
                }
                
                // 串行处理每个SKU
                for (let i = 0; i < skusToProcess.length; i++) {
                    const sku = skusToProcess[i];
                    
                    // 更新进度显示
                    const currentProgress = i + 1;
                    const progressPercent = (currentProgress / skusToProcess.length) * 100;
                    
                    button.text(`获取中... (${currentProgress}/${skusToProcess.length})`);
                    progressText.text(`${currentProgress}/${skusToProcess.length}`);
                    progressBar.css('width', `${progressPercent}%`);
                    
                    try {
                        // 添加商品到购物车
                        const addToCartData = [{
                            id: Number(sku),
                            quantity: 1
                        }];
                        
                        await $.ajax({
                            url: 'https://www.ozon.ru/api/composer-api.bx/_action/v2/addToCart',
                            type: 'POST',
                            data: JSON.stringify(addToCartData),
                            contentType: 'application/json'
                        });
                        
                        // 获取重量
                        const addResponselast = await $.ajax({
                            url: 'https://www.ozon.ru/cart?tab=0',
                            type: 'GET'
                        });
                        
                        // 改进正则表达式，提高匹配成功率
                        let weightValue = null;
                        let match = addResponselast.match(/"info":"[^•]+•\s*([^"]+)/);
                        if (match) {
                            weightValue = match[1].trim();
                        } else {
                            // 尝试其他可能的匹配模式
                            match = addResponselast.match(/•\s*([^•"]+)\s*•/);
                            if (match) {
                                weightValue = match[1].trim();
                            } else {
                                match = addResponselast.match(/重量[:\s]*([^\s<"']+)/);
                                if (match) {
                                    weightValue = match[1].trim();
                                }
                            }
                        }
                        const formattedWeight = weightValue ? weightValue.replace('гр','g').replace('кг','kg') : '无';
                        
                        // 更新SKUDATA
                        if (SKUDATA[sku]) {
                            SKUDATA[sku].zwews = formattedWeight;
                        }
                        
                        // 更新表格显示（列索引因新增跟卖数量列后变为5）
                        const weightCell = $(`#data-table-body tr[data-sku="${sku}"] td:eq(5)`);
                        weightCell.html(formattedWeight);
                        
                        // 新增：调用updateProfitCell统一更新物流费和利润
                        updateProfitCell(sku);
                        successCount++;
                        
                        // 每处理完一个商品就清空购物车
                        const clearCartParams = {
                            items: [Number(sku)]
                        };
                        const str = JSON.stringify(clearCartParams);
                        const clearCartData = {
                            name: "deleteItems",
                            params: str
                        };
                        
                        await $.ajax({
                            url: 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fcart%3Fpage_changed%3Dtrue',
                            type: 'POST',
                            data: JSON.stringify(clearCartData),
                            contentType: 'application/json'
                        });
                        
                        // 添加较短的延迟，避免请求过于频繁
                        if (i < skusToProcess.length - 1) {
                            await new Promise(resolve => setTimeout(resolve, 300));
                        }
                        
                    } catch (error) {
                        console.error(`获取SKU ${sku} 重量失败:`, error);
                        failCount++;
                        
                        // 更新表格显示为错误状态（列索引因新增跟卖数量列后变为5）
                        const weightCell = $(`#data-table-body tr[data-sku="${sku}"] td:eq(5)`);
                        weightCell.html('<span style="color: #c82333;">获取失败</span>');
                    }
                }
                
                // 完成后的提示
                let resultMessage = `批量获取完成：`;
                if (successCount > 0) resultMessage += `成功 ${successCount} 个，`;
                if (failCount > 0) resultMessage += `失败 ${failCount} 个，`;
                if (skipCount > 0) resultMessage += `跳过 ${skipCount} 个（已有数据）`;
                
                tiddp(resultMessage);
                
            } catch (error) {
                console.error('批量获取重量失败:', error);
                tiddp('批量获取重量失败: ' + error.message);
            } finally {
                // 恢复按钮状态
                button.text(originalText).prop('disabled', false);
                
                // 延迟隐藏进度条
                setTimeout(() => {
                    progressContainer.hide();
                }, 3000);
            }
        }
    });
}

// 一键跟卖功能
async function batchFollowSell() {
    // 获取选中的SKU
    const selectedSkus = [];
    $('#data-table-body tr:visible .row-checkbox:checked').each(function() {
        const sku = $(this).closest('tr').attr('data-sku');
		
        selectedSkus.push(sku);
    });
	
    // 确定要处理的SKU列表
    let skusToProcess = [];
    if (selectedSkus.length > 0) {
        skusToProcess = selectedSkus;
    } else {
		tiddp('请选择跟卖SKU');
		return
        // 没有选中，处理所有可见SKU
        $('#data-table-body tr:visible').each(function() {
            const sku = $(this).attr('data-sku');
            if (sku) skusToProcess.push(sku);
        });
    }
    
    if (skusToProcess.length === 0) {
        tiddp('没有数据可处理');
        return;
    }
    var appid = $('#store').val();
    if(!appid) { tiddp('请先选择要跟卖的店铺'); return; }
    // 确认操作
    const message = `确定要对 ${skusToProcess.length} 个产品进行一键跟卖吗？`;
    
    showCustomConfirm({
        message,
        onConfirm: async () => {
            const button = $('#batch-follow-sell');
            const originalText = button.text();
            button.text('处理中...').prop('disabled', true);
            
            try {
                // 构建要传输的数据
                const data = {
                    list: [],
                    copyInfo: {
                        appid: appid || '', // 获取所选店铺ID，不是必选
                        flowOrCopy: $('#flow-or-copy').val(),
                        noBrand: $('#noBrand').val()
                        
                    }
                };
                
                // 遍历SKU，收集数据
                for (const sku of skusToProcess) {
                    const skuData = SKUDATA[sku];
                    const picData = SKUDATA_pic[sku];
                    
                    if (skuData && picData) {
                        // 构建list项
                        const listItem = {
                            item: null, // response.items[0]
                            specifications: null, // response.productDetail.specifications
                            tableData: {
                                sku: sku,
                                price: picData[0],
                                weight: skuData.zwews,
                                cost: skuData.cost || 0,
                                soldCount: skuData.soldCount,
                                soldSum: skuData.soldSum,
                                brand: skuData.brand,
                                salesSchema: skuData.salesSchema,
                                convToCartPdp: skuData.convToCartPdp
                            }
                        };
                        
                        // 这里需要获取API响应数据，如果有的话
                        // 假设已经有存储的API响应数据
                        if (skuData.apiData) {
                            const response = skuData.apiData;
                            if (response.items && response.items[0]) {
                                listItem.item = response.items[0];
                            }
                            if (response.productDetail && response.productDetail.specifications) {
                                listItem.specifications = response.productDetail.specifications;
                            }
                        }
                        
                        data.list.push(listItem);
                    }
                }
                
                // 发送数据到 config.url.itemList()
                console.log('发送一键跟卖数据:', data);
                
                const response = await fetch(config.url.itemList(), {
                    method: 'POST',
                    headers: {
                        'Authorization': tokenCache,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                console.log('一键跟卖API响应:', result);
                
                if (result.status === 'success') {
                    tiddp(`一键跟卖成功，处理了 ${skusToProcess.length} 个产品`);
                } else {
                    tiddp(`一键跟卖失败: ${result.message || '未知错误'}`);
                }
                
            } catch (error) {
                console.error('一键跟卖失败:', error);
                tiddp('一键跟卖失败: ' + error.message);
            } finally {
                // 恢复按钮状态
                button.text(originalText).prop('disabled', false);
            }
        }
    });
}

// 自定义确认弹窗
function showCustomConfirm(options) {
    // 移除已存在的确认弹窗
    $('#custom-confirm-modal').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>
    `;

    $('body').append(modalHtml);
    const modal = $('#custom-confirm-modal');
    
    // Trigger animations
    setTimeout(() => {
        modal.css('opacity', '1');
        modal.find('> div').css('transform', 'scale(1)');
    }, 10);

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

    $('#confirm-ok').click(() => {
        closeModal();
        if (onConfirm && typeof onConfirm === 'function') {
            onConfirm();
        }
    });

    $('#confirm-cancel').click(closeModal);
    
    modal.click((e) => {
        if (e.target.id === 'custom-confirm-modal') {
            closeModal();
        }
    });
}


// ─────────────────────────────────────────────────────────────────────
// calcLogisticsFee 已迁移到 product/ozon-export.js
// ─────────────────────────────────────────────────────────────────────


// 添加SKU图片预览功能
function bindSkuImagePreview() {
    // 确保modal只添加一次
    if (!$('#sku-image-modal').length) {
        $('body').append(imagePreviewHtml);
    }

    const modal = $('#sku-image-modal');
    const modalImg = modal.find('img');
    const skuInfo = $('#sku-info');
    let currentIndex = -1;
    let visibleSkus = [];

    // 获取所有可见的SKU
    function updateVisibleSkus() {
        visibleSkus = [];
            $('#data-table-body tr:visible').each(function() {
            const sku = $(this).attr('data-sku');
            if (sku) {
                visibleSkus.push(sku);
            }
        });
    }

    // 显示指定SKU的图片
    function showImage(sku, visibleSkus) {
        // 显示弹窗
        $('#sku-image-modal').fadeIn(200).css('display', 'flex');
        
        let imgUrl = '';
        
        // 使用SKUDATA中的photo字段
        const skuData = SKUDATA[sku];
        console.log('SKUDATA photo:',skuData);
        if (skuData && skuData.photo) {
            imgUrl = skuData.photo;
            
            // 确保图片URL是高分辨率版本
            imgUrl = imgUrl.replace(/\/wc\d+/, '/wc1000');
        } else {
            // 如果SKUDATA中没有photo字段，使用Ozon的商品图片API获取图片
            imgUrl = `https://www.ozon.ru/multimedia/api/v1/content/file/data/${sku}/`;
        }

        // 显示加载提示
        modalImg.hide();
        $('#image-loading').fadeIn(200).show();
        
        // 确保图片容器有合适的尺寸
        const imgContainer = modalImg.parent();
        imgContainer.css({
            'min-width': '500px',
            'min-height': '300px',
            'display': 'flex',
            'align-items': 'center',
            'justify-content': 'center'
        });
        
        // 更新导航按钮状态
        currentIndex = visibleSkus.indexOf(sku);
        window._currentVisibleSkus = visibleSkus; // 全局存一份，供箭头用
        $('#prev-image').css('opacity', currentIndex > 0 ? '1' : '0.3');
        $('#next-image').css('opacity', currentIndex < visibleSkus.length - 1 ? '1' : '0.3');

        // 获取商品数据
        const picData = SKUDATA_pic[sku] || [];
        const hasData = skuData && skuData !== 1;
        
        // 格式化函数
        const formatCNY = (price) => {
            if (!price) return '无';
            return `¥${price}`;
        };
        const formatRUB = (price) => {
            if (!price) return '无';
            return `${price} ₽`;
        };
        const formatPercent = (value) => {
            if (!value) return '无';
            return `${value}%`;
        };
        const formatValue = (value) => {
            if (!value || value === '点击获取') return '无';
            return value;
        };
        const tierFromPrice = (p) => {
            if (!p || p <= 0) return null;
            if (p <= 135) return 1;
            if (p <= 437) return 2;
            return 3;
        };
        const TIER_RATE = { 1: 13, 2: 15, 3: 17 };

        // 更新标题和SKU
        $('#product-title').text(picData[3] || '无标题');
        $('#product-sku').text(`SKU: ${sku}`);

        // 计算快速核价佣金
        const priceCNY = parseFloat(picData[0]) || 0;
        const tier = tierFromPrice(priceCNY);
        const commRate = tier ? TIER_RATE[tier] : 15;
        const commission = priceCNY > 0 ? (priceCNY * (commRate / 100)).toFixed(2) : '—';

        // 从 apiData 取长宽高（mm → cm）
        let dimL = '—', dimW = '—', dimH = '—';
        if (skuData && skuData.apiData && skuData.apiData.productDetail) {
            const specs = getProductSpecifications(skuData.apiData.productDetail);
            if (specs.length) dimL = (specs.length / 10).toFixed(1) + ' cm';
            if (specs.width)  dimW = (specs.width  / 10).toFixed(1) + ' cm';
            if (specs.height) dimH = (specs.height / 10).toFixed(1) + ' cm';
        }

        // 创建详细信息HTML，包含所有要求的字段
        const details = [
            { label: 'SKU', value: sku },
            { label: '商家ID', value: hasData ? formatValue(skuData.sellerId) : '无' },
            { label: '30天销量', value: hasData ? formatValue(skuData.soldCount) : '无' },
            { label: '30天销售额', value: hasData ? formatRUB(skuData.soldSum) : '无' },
            { label: '价格', value: formatCNY(picData[0]) },
            { label: '划线价', value: formatCNY(picData[1]) },
            { label: '促销比例', value: formatValue(picData[2]) },
            { label: 'SKU卖价', value: formatCNY(picData[0]) },
            { label: '产品名称', value: formatValue(picData[3]) },
            { label: '星级', value: formatValue(picData[4]) },
            { label: '品牌', value: hasData ? formatValue(skuData.brand) : '无' },
            { label: '一级类目', value: hasData ? formatValue(skuData.category1) : '无' },
            { label: '三级类目', value: hasData ? formatValue(skuData.category3) : '无' },
            { label: '30天销售变化', value: hasData ? formatPercent(skuData.salesDynamics) : '无' },
            { label: '平均售价', value: hasData ? formatRUB(skuData.avgPrice) : '无' },
            { label: '最低售价', value: hasData ? formatCNY(skuData.minSellerPrice) : '无' },
            { label: '加购率', value: hasData ? formatPercent(skuData.convToCartPdp) : '无' },
            { label: '浏览量', value: hasData ? formatValue(skuData.views) : '无' },
            { label: '体积/公斤', value: hasData ? formatValue(skuData.volume) : '无' },
            { label: '发货模式', value: hasData ? formatValue(skuData.salesSchema) : '无' },
            { label: '重量', value: hasData ? formatValue(skuData.zwews) : '无' },
            { label: '长', value: dimL },
            { label: '宽', value: dimW },
            { label: '高', value: dimH },
            { label: '配送天数', value: hasData ? formatValue(skuData.avgDeliveryDays) : '无' },
            { label: '库存', value: hasData ? formatValue(skuData.stock) : '无' },
            { label: '出售时间', value: hasData ? formatValue(skuData.nullableCreateDate) : '无' },
            { label: '佣金(T' + (tier || '?') + ')', value: priceCNY > 0 ? '−¥' + commission + ' (' + commRate + '%)' : '—' },
            { label: '物流费', value: hasData ? (function() { const logisticsInfo = calcLogisticsFee({price: picData[0], weight: skuData.zwews, type: $('#logistics-type').val() || 'E邮宝'}); return formatCNY(parseFloat(logisticsInfo.fee) || 0); })() : '无', tooltip: hasData ? skuData.zwews === '无' || skuData.zwews === '点击获取' ? '' : calcLogisticsFee({price: picData[0], weight: skuData.zwews, type: $('#logistics-type').val() || 'E邮宝'}).formulaStr : '' }
        ];

        const detailsHtml = details.map(item => `
            <div style="
                padding: 4px 0;
                border-bottom: 1px solid rgba(58, 90, 138, 0.1);
                display: flex;
                justify-content: space-between;
                align-items: center;
            ">
                <div style="color: #666666; font-size: 13px; font-weight: 600; min-width: 100px;">${item.label}</div>
                <div style="
                    
                    font-size: 13px;
                    font-weight: 600;
                    text-align: right;
                    flex: 1;
                    margin-left: 8px;
                    ${item.tooltip ? 'cursor: help;' : ''}
                " ${item.tooltip ? `title="${item.tooltip}"` : ''}>${item.value}</div>
            </div>
        `).join('');

        $('#product-details').html(detailsHtml);
        
        // 插入成本输入框和利润显示的基础HTML
        let costVal = (skuData && typeof skuData.cost !== 'undefined') ? parseFloat(skuData.cost) : 0;
        let commissionRate = parseFloat($('#commission-rate').val()) || 20;
        let packingFeeInput = $('#packing-fee').val();
        let packingFee = packingFeeInput !== '' ? parseFloat(packingFeeInput) : 5;
        
        let costAndProfitHtml = `
            <div id="cost-profit-container" style="
                margin-top: 12px;
                padding: 8px;
                background: #eeeeee;
                border-radius: 4px;
                border: 1px solid #FFFFFF;
            ">
                <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
                    <span style="color: #151515; font-size: 13px; font-weight: 600; min-width: 35px;">成本：</span>
                    <input type="number" id="cost-input-modal" data-sku="${sku}" value="${costVal}" min="0" step="0.01" style="
                        width: 70px;
                        background: #ffffff;
                        border: 1px solid #eaeaea;
                        color: #151515;
                        border-radius: 3px;
                        padding: 3px 5px;
                        font-size: 13px;
                        font-weight: 600;
                    ">
                    <span style="color: #666666; font-size: 13px;">→</span>
                    <div id="profit-info-modal" style="
                        font-size: 13px;
                        font-weight: 700;
                        flex: 1;
                        line-height: 1.2;
                    ">
                        <div>利润：计算中...</div>
                        <div>利润率：计算中...</div>
                    </div>
					<div id="whType-info-modal" style="
					    color: #151515;
					    font-size: 13px;
					    font-weight: 700;
					    flex: 1;
					    line-height: 1.2;
					">
					    <option value="">-- 加载中 --</option>
					</div>
                </div>
                <!-- <div style="
                    font-size: 11px;
                    color: #666666;
                    line-height: 1.2;
                ">
                    计算公式：售价 - 成本 - 佣金(售价*${commissionRate}%) - 物流费 - 打包费(${packingFee}元)
                </div> -->
            </div>
        `;
        $('#cost-profit-container').remove();
        $('#product-details').after(costAndProfitHtml);
        
        // 调用updateProfitCell获取正确的利润数据，确保与表格一致
        updateProfitCell(sku);
        // 监听弹窗成本输入框变化，实时同步到SKUDATA和表格
        $('#cost-input-modal').off('input').on('input', function() {
            const val = $(this).val();
            if (!SKUDATA[sku]) return;
            SKUDATA[sku].cost = val;
            $(`#cost-input-${sku}`).val(val);
            
            // 显示计算中动画效果
            $('#profit-info-modal').html(`
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 16px; height: 16px; border: 2px solid #1e88e5; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                    <div>计算中...</div>
                </div>
                <div>利润率：计算中...</div>
                <style>
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
            `);
            // 显示计算中动画效果
            $('#whType-info-modal').html(`
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 16px; height: 16px; border: 2px solid #1e88e5; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                    <div>计算中...</div>
                </div>
                <div>物流方式：计算中...</div>
                <style>
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
            `);
            // 刷新该SKU的利润计算
             updateProfitCell(sku);
            
            // 如果已经选择了物流分组，重新加载物流方式
            const groupId = $('#logistics-group').val();
            if (groupId) {
                console.log('模态框成本已修改，重新加载物流方式');
                // window.loadOzonLogisticsMethods(groupId);
            }
        });
        
        // 处理图片加载和布局调整
        if (imgUrl) {
            // 有图片，显示正常布局
            $('#image-container').css('display', 'flex');
            $('#image-container').css('width', '450px');
            
            // 创建新的图片对象来预加载
            const tempImg = new Image();
            tempImg.onload = function() {
                // 图片加载完成，设置src并显示
                modalImg.attr('src', imgUrl);
                modalImg.fadeIn(300);
                $('#image-loading').fadeOut(200);
            };
            tempImg.onerror = function() {
                // 图片加载失败，显示默认信息
                modalImg.attr('src', 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="%23f5f5f5"/><text x="50%25" y="50%25" font-size="16" text-anchor="middle" dominant-baseline="middle" fill="%23666666">无可用图片</text></svg>');
                modalImg.fadeIn(300);
                $('#image-loading').fadeOut(200);
            };
            tempImg.src = imgUrl;
        } else {
            // 没有图片，调整布局
            // 设置图片容器为最小宽度
            $('#image-container').css('width', '200px');
            
            // 显示默认信息
            modalImg.attr('src', 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="%23f5f5f5"/><text x="50%25" y="50%25" font-size="16" text-anchor="middle" dominant-baseline="middle" fill="%23666666">无可用图片</text></svg>');
            modalImg.fadeIn(300);
            $('#image-loading').fadeOut(200);
        }

    }

    // 点击SKU显示图片
    $(document).off('click', '.sku-cell').on('click', '.sku-cell', function() {
        // 每次点击时，动态获取所有可见SKU
        const allVisibleSkus = [];
        $('#data-table-body tr:visible').each(function() {
            const sku = $(this).attr('data-sku');
            if (sku) allVisibleSkus.push(sku);
        });
        const sku = String($(this).data('sku')); // 转换为字符串
        
    
        
        if ($('#sku-image-modal').is(':visible')) {
            const currentSku = $('#product-sku').text().replace('SKU: ', '');
            if (currentSku == sku) return;
        }
        if (sku) {
            showImage(sku, allVisibleSkus);
            $('#sku-image-modal').fadeIn(200).css('display', 'flex');
        }
    });
	
    // 上一张图片
    $('#prev-image').off('click').on('click', function(e) {
        e.stopPropagation();
        if (typeof currentIndex === 'number' && currentIndex > 0 && window._currentVisibleSkus) {
            showImage(window._currentVisibleSkus[currentIndex - 1], window._currentVisibleSkus);
        }
    });

    // 下一张图片
    $('#next-image').off('click').on('click', function(e) {
        e.stopPropagation();
        if (typeof currentIndex === 'number' && window._currentVisibleSkus && currentIndex < window._currentVisibleSkus.length - 1) {
            showImage(window._currentVisibleSkus[currentIndex + 1], window._currentVisibleSkus);
        }
    });

    // 键盘导航
    $(document).keydown(function(e) {
        if (modal.is(':visible')) {
            if (e.key === 'ArrowLeft' && currentIndex > 0 && window._currentVisibleSkus) {
                showImage(window._currentVisibleSkus[currentIndex - 1], window._currentVisibleSkus);
            } else if (e.key === 'ArrowRight' && currentIndex < window._currentVisibleSkus.length - 1 && window._currentVisibleSkus) {
                showImage(window._currentVisibleSkus[currentIndex + 1], window._currentVisibleSkus);
            } else if (e.key === 'Escape') {
                modal.fadeOut(200);
            }
        }
    });

    // 鼠标悬停效果
    $('.nav-arrow').hover(
        function() {
            $(this).css({
                'background': 'rgba(58, 90, 138, 0.5)',
                'transform': 'translateY(-50%) scale(1.1)'
            });
        },
        function() {
            $(this).css({
                'background': '#FFFFFF',
                'transform': 'translateY(-50%) scale(1)'
            });
        }
    );

    // 点击关闭按钮
    $('#close-image-modal').click(function(e) {
        e.stopPropagation();
        modal.fadeOut(200);
    });

    // 点击背景关闭
    modal.click(function(e) {
        if (e.target === this) {
            modal.fadeOut(200);
        }
    });

    // 点击图片跳转到OZON详情页
    modal.find('img').off('click').on('click', function(e) {
        e.stopPropagation();
        const currentSku = $('#product-sku').text().replace('SKU: ', '');
        if (currentSku) {
            const ozonUrl = `https://www.ozon.ru/product/${currentSku}`;
            window.open(ozonUrl, '_blank');
        }
    });

    // 图片悬停效果
    modal.find('img').hover(
        function() {
            $(this).css('transform', 'scale(1.02)');
        },
        function() {
            $(this).css('transform', 'scale(1)');
        }
    );
}

// ─────────────────────────────────────────────────────────────────────
// 利润计算模块已迁移到 product/ozon-profit.js
// (allLogisticsMethods / getToken / loadOzonShops / loadOzonLogisticsGroups /
//  loadOzonLogisticsMethods / processLogisticsMethods / updateAllProfitCells /
//  ProfitCalculator / debounce / getWhType / updateProfitCell /
//  calculateProfitWithFallback / updateProfitDisplay + 事件监听)
// ─────────────────────────────────────────────────────────────────────

