//执行产品采集逻辑
function ExecuteProductAcquisitionLogic(url, tab, isVerifyDuplicate, isLinkCollect, issku = 0, isFloatButtonTriggered = false, packageDimensions = null) {
    try {
        var platformData = MatchingPlatform(url);
        if (url == "https://www.wish.com/") {
            sendMessageToContentScript({ "Type": "Alter", "MessageType": "error", "Message": '当前地址不支持产品采集' }, tab, function (response) { });
            return;
        }
        
        var platformId = platformData.PlatformId;
        var platformName = platformData.PlatformName;

        if (platformId > 0) {
			// 只有在非悬浮按钮触发的情况下才修改按钮状态
            if(!isFloatButtonTriggered) {
                if(issku){
                    sendMessageToContentScript({ "Type": "CheckCollectionSKUBtnDisabled", "Disabled": true }, tab, function (response) { });
                }else{
                    sendMessageToContentScript({ "Type": "CheckCollectionGoodsBtnDisabled", "Disabled": true }, tab, function (response) { });
                }
            }
            
            if (isVerifyDuplicate && !issku) {
                function ExecuteVerifyDuplicate(processedUrl)
                {
                    VerifyDuplicate(processedUrl,
                        function (parentSku) {
                            if (parentSku !== "" && parentSku != null) {
                                if(!isFloatButtonTriggered) {
                                    sendMessageToContentScript({ "Type": "CheckCollectionGoodsBtnDisabled", "Disabled": false }, tab, function (response) { });
                                }
                                sendMessageToContentScript({ "Type": "ConfirmAcquisition", "MessageType": "warning", "Message": "该产品在系统中已有采集记录，ParentSku:【" + parentSku + "】，是否继续采集？", "Url": processedUrl }, tab, function (response) { });
                            }
                            else {
                                sendMessageToContentScript({ "Type": "Get" + platformName + "Text", "MessageType": "", "Message": "", "isLinkCollect": isLinkCollect, "sourceUrl": processedUrl }, tab, function (response) {
                                    if (response !== null) {
                                        ApplyCapturedOzonPackageDimensions(response, packageDimensions);
                                        AnalyticalProducts(platformId, response, tab, processedUrl, sendMessageToContentScript, issku, isFloatButtonTriggered);
                                    }
                                });
                            }
                        },
                        function (msg) {
                            sendMessageToContentScript({ "Type": "Alter", "MessageType": "error", "Message": msg }, tab, function (response) { });
                        }
                    );
                }

                //验证前对URL的特殊处理
                if (url.indexOf('dj.1688.com') != -1) {
                    request(url, {
                        method: "GET",
                        responseType: "text"
                    }).then(detailResult => {
                        if (detailResult && detailResult.indexOf('b2c_auction=') > -1) {
                            var offerId = detailResult.split('b2c_auction=')[1].split('&')[0];
                            url = 'https://detail.1688.com/offer/' + offerId + '.html';
                        }
                        ExecuteVerifyDuplicate(url);
                    }).catch(reason => {
                        ExecuteVerifyDuplicate(url);
                    });
                }
                else {
                    ExecuteVerifyDuplicate(url);
                }
            }
            else {
                sendMessageToContentScript({ "Type": "Get" + platformName + "Text", "MessageType": "", "Message": "", "isLinkCollect": isLinkCollect,"sourceUrl": url }, tab, function (response) {
                    if (response !== null) {
                        ApplyCapturedOzonPackageDimensions(response, packageDimensions);
                        AnalyticalProducts(platformId, response, tab, url, sendMessageToContentScript, issku, isFloatButtonTriggered);
                    }
                });
            }
        }
        else {
            throw new Error("当前地址：[" + url + "]暂不支持产品采集");
        }
    } catch (error) {
        chrome.notifications.create("51selling_tip" + new Date(), {
            type: 'basic',
            iconUrl: 'img/icon_128.png',
            title: '熊猫ERP',
            message: "产品采集失败！" + error.message
        });
    }
}

// 商品卡分析面板已经读取到了 seller-prototype 的真实物流规格。
// 一键上货时把这份同一 SKU 的数据并入采集对象，避免后续再次请求失败后丢失尺寸。
function ApplyCapturedOzonPackageDimensions(content, packageDimensions) {
    if (!content || typeof content !== 'object' || !packageDimensions || typeof packageDimensions !== 'object') return;
    function positive(value) {
        var number = Number(value);
        return Number.isFinite(number) && number > 0 ? number : 0;
    }
    var dimensions = {
        length: positive(packageDimensions.length || packageDimensions.depth),
        width: positive(packageDimensions.width),
        height: positive(packageDimensions.height),
        weight: positive(packageDimensions.weight),
        unit: 'mm',
        dimension_unit: 'mm',
        weight_unit: 'g',
        source: packageDimensions.source || 'ozon-seller-prototype'
    };
    if (!(dimensions.length || dimensions.width || dimensions.height || dimensions.weight)) return;
    content.PackageDimensions = dimensions;
    if (dimensions.length) content.depth = dimensions.length;
    if (dimensions.width) content.width = dimensions.width;
    if (dimensions.height) content.height = dimensions.height;
    if (dimensions.weight) content.weight = dimensions.weight;
}

//匹配平台
function MatchingPlatform(url) {
    var platformId = 0;
    var platformName = '';
    var type = "detail";
    var isDetail=true;
    
    for (let i = 0; i < config.platformArr.length; i++) {
        const platform = config.platformArr[i];
        for (let j = 0; j < platform.MatchingURLs.length; j++) {
            const item = platform.MatchingURLs[j];
    
            if (item.indexOf('*') !== -1) {
                const itemUrls = item.split('*');
    
                let matched = true;
                for (let index = 0; index < itemUrls.length; index++) {
                    if (url.indexOf(itemUrls[index]) < 0) {
                        matched = false;
                        break;
                    }
                }
    
                if (matched) {
                    platformId = platform.PlatformId;
                    platformName = platform.PlatformName;
                    break;
                }
            } else if (url.indexOf(item) !== -1) {
                platformId = platform.PlatformId;
                platformName = platform.PlatformName;
                break;
            }
        }
    
        if (platformId > 0) {
            // 判断是明细页还是类目页面
            for (const item in platformLinkRule) {
                if (url.indexOf(item) !== -1) {
                    type = platformLinkRule[item].getType(url);
                    isDetail = platformLinkRule[item].detail(url);
                    break;
                }
            }
            break;
        }
    }
    return { "PlatformId": platformId, "PlatformName": platformName, "CrawlType": type,"isDetail":isDetail };
}
//验证是否登录
function VerifyLogin(successfulCallBack, failedCallBack) {
    // 在 background service worker 上下文（importScripts 导入时）直接调用
    // readCookieWithFallback，避免 sendMessage 给自身造成死循环/无响应。
    // 在 content script 上下文时 readCookieWithFallback 未定义，走 config.getCookie。
    function readCookie(url, name, cb) {
        if (typeof readCookieWithFallback === 'function') {
            readCookieWithFallback(url, name, function(val) {
                console.log('[VerifyLogin] readCookieWithFallback result for', name, 'at', url, ':', val ? 'found' : 'not found');
                cb(val ? { value: val, name: name } : null);
            });
        } else {
            console.log('[VerifyLogin] readCookieWithFallback not defined, using config.getCookie for', name);
            config.getCookie({ url: url, name: name }, cb);
        }
    }

    readCookie(config.url.domain(), config.cookieName11, function(cookie) {
        console.log('[VerifyLogin] token cookie check:', cookie);
        if (cookie && cookie.value) {
            successfulCallBack();
        } else {
            readCookie(config.url.domainz(), config.cookieName1, function(cookie2) {
                console.log('[VerifyLogin] usrid cookie check:', cookie2);
                if (cookie2 && cookie2.value) {
                    successfulCallBack();
                } else {
                    console.log('[VerifyLogin] 登录验证失败，两个 cookie 都未找到');
                    failedCallBack();
                }
            });
        }
    });
}
//重复采集
function ExecuteRepeateProduct(url, tab,failedCallBack){
       var platformData = MatchingPlatform(url);
       var platformId = platformData.PlatformId;
       if(platformId>0){
               sendMessageToContentScript({ "Type": "RepeateCollect"}, tab, function (response) {
                    if (response !== null) {
                        ExecuteProductDetail(url,platformId, false, function(res){
                            failedCallBack(res);
                        });
                    }
                });
       }else{
         failedCallBack({MessageType:"error",Message:"当前url地址不支持采集"});
       }
}
//验证版本号
function VerifyVersion(successfulCallBack, failedCallBack) {
    successfulCallBack();
 
}
// 类目采集
function categoryCrawlProcess(platformId, platformName, url,tab, sendResponse) {
    VerifyVersion(function () {
        VerifyLogin(function () {
            try {
                sendResponse('');
                sendMessageToContentScript({ "Type": "CheckCategoryBtnDisabled", "Disabled": true }, tab, function (response) { });
                sendMessageToContentScript({ "Type": platformName + "CategoryCrawl", "MessageType": "", "Message": "" }, tab, function (response) {
                    if (response !== null) {
                        AnalyticalCategory(platformId, response, tab, sendMessageToContentScript);
                    }
                });

            } catch (e) {
                sendMessageToContentScript({ "Type": "CheckCategoryBtnDisabled", "Disabled": false }, tab, function (response) { });
                chrome.notifications.create("51selling_tip" + new Date(), {
                    type: 'basic',
                    iconUrl: 'img/icon_128.png',
                    title: '熊猫ERP',
                    message: "类目采集失败！" + error.message
                });
            }
        }, function () {
            sendMessageToContentScript({ "Type": "RedirectSite", "MessageType": "warning", "Message": "当前无登录用户，点击确认前往登录！", "Site": "https://sczfai.com" }, tab, function (response) {

             });
        })
    }, function (latestVersion, latestUrl) {
        sendMessageToContentScript({ "Type": "RedirectSite", "MessageType": "warning", "Message": "检测到最新插件版本为" + latestVersion + "，点击确认前往下载最新版本", "Site": "https://sczfai.com" }, tab, function (response) { });
    })
}

//根据获取符号获取对应货币简码
function GetcurrencyCode(price, defaultCode) {
    var currencyCode = "";
    if (defaultCode)
        currencyCode = defaultCode;
    if (price.indexOf("$") >= 0) {
        currencyCode = "USD";
    } else if (price.indexOf("₽") >= 0){
        currencyCode = "RUB";
    } else if (price.indexOf("BYN") >= 0) {
        currencyCode = "BYN";
    } else if (price.indexOf("₸") >= 0) {
        currencyCode = "KZT";
    } else if (price.indexOf("₪") >= 0) {
        currencyCode = "ILS";
    } else if (price.indexOf("֏") >= 0) {
        currencyCode = "AMD";
    } else if (price.indexOf("kr") >= 0) {
        currencyCode = "DKK";
    } else if (price.indexOf("C$") >= 0) {
        currencyCode = "CAD";
    } else if (price.indexOf("с") >= 0) {
        currencyCode = "KGS";
    } else if (price.indexOf("¥") >= 0) {
        currencyCode = "CNY";
    }
    return currencyCode;
}
