//监听backgroud的消息
NotificationList = []

chrome.runtime.onMessage.addListener(receiveMessages);

// 当文档加载完成时执行  
document.addEventListener('DOMContentLoaded', function () {
    //引入JS
    let jsArr = ["js/config.js", "js/requestapi.js", "js/sendmessage.js", "js/callserver.js", "js/analyticalproducts.js", "js/productacquisition.js"];
    jsArr.forEach((item) => {
        let script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', item);
        document.getElementsByTagName('head')[0].appendChild(script);
    });
    // 从本地存储中获取数据  
    chrome.storage.local.get('urls', function (result) {

        // 如果找到了数据  
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError);
        } else {

            let datas = result.urls;
            let dataText = '';
            if (Array.isArray(datas)) {
                for (let data of datas) {
                    dataText += data + '\n'.trim();
                }
                dataText = dataText.slice(0, -'\n'.length);
            }
            // 找到页面上的文本元素并更新其内容  
            let textElement = document.getElementById('urlCollect');
            let urlBtn = document.getElementById('urlCollectBtn');
            if (textElement) {
                textElement.textContent = dataText;
                if (dataText && dataText.length > 0) {
                    //触发点击事件
                    urlBtn.click();
                }

                //清除本地缓存
                chrome.storage.local.remove(["urls"], function () {});
            }
        }
    });
});

async function executeRequestsInBatches(dimensionToAsinMap, request, batchSize = 10) {
    const objArr = [];
    const entries = Object.entries(dimensionToAsinMap);
    const parser = new DOMParser();

    for (let i = 0; i < entries.length; i += batchSize) {
        const batch = entries.slice(i, i + batchSize);

        const promises = batch.map(async ([key, value]) => {
            const newUrl = request.sourceUrl.replace(/(dp\/)([^\/]+)(\/)/, `$1${value}$3`);

            try {
                const response = await fetch(newUrl);
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const html = await response.text();
                const doc = parser.parseFromString(html, 'text/html');

                let Price = "0", Size = "", Color = "";

                let priceDiv = doc.getElementById('corePriceDisplay_desktop_feature_div');
                let priceSpan = priceDiv?.querySelector('span.a-price-whole');
                if (priceSpan) {
                    let allPrice = priceSpan.textContent.replace(/[^0-9]/g, '');
                    let fractionPriceSpan = priceDiv.querySelector('.a-price-fraction');
                    if (fractionPriceSpan) allPrice += "." + fractionPriceSpan.textContent;
                    Price = allPrice;
                } else {
                    let priceSpan2 = doc.getElementById('corePrice_desktop')?.querySelector('.a-offscreen');
                    if (priceSpan2) Price = priceSpan2.textContent;
                }

                Size = doc.getElementById('twisterContainer')?.querySelector('.a-dropdown-prompt')?.textContent || "";
                Color = doc.getElementById('variation_color_name')?.querySelector('.selection')?.textContent.trim() || "";

                objArr.push({ Price, Size, Color, Id: value });
            } catch (error) {
                console.error(`Error fetching ${newUrl}:`, error);
            }
        });

        await Promise.all(promises);
    }

    return objArr;
}

function receiveMessages(request, sender, sendResponse) {
    {
        if (request.Type === 'GetWishText') {
            let path = window.location.pathname.substring(window.location.pathname.indexOf('/product'));
            url = window.location.protocol + '//' + window.location.host + path;
            if (request.isLinkCollect) {
                url = request.sourceUrl;
            }

            sendResponse({"isLinkCollect": true, "cookies": document.cookie, "url": url});
        } else if (request.Type === 'GetAliexpressText') {
            let boxObj = {};
            //笛卡尔积
            function cartesianProduct(input) {
                // 提取所有属性的值
                const keys = input.map(item => item.key);
                const values = input.map(item => item.values);
            
                // 递归计算笛卡尔积
                function calculateCartesian(arr) {
                    return arr.reduce((acc, current) => {
                        return acc.flatMap(x => current.map(y => [...x, y]));
                    }, [[]]);
                }
            
                // 计算所有组合
                const combinations = calculateCartesian(values);
            
                // 将组合转换为目标格式
                const result = combinations.map(combination => {
                    // 找到第一个有 imgUrl 的属性作为 VariantImageUrl
                    const variantImageUrl = combination.find(item => item.imgUrl)?.imgUrl || "";
            
                    // 构建 Property 数组
                    const property = combination.map((item, index) => ({
                        Key: keys[index],
                        Value: item.key
                    }));
            
                    return {
                        VariantImageUrl: variantImageUrl,
                        Property: property
                    };
                });
            
                return result;
            }
            //提取价格
            function extractNumbersAndSingleDot(str) {
                // 提取数字和第一个小数点
                const result = str.replace(/[^0-9.]/g, '');
                const firstDotIndex = result.indexOf('.');
            
                // 如果存在小数点，只保留第一个
                if (firstDotIndex !== -1) {
                    return result.slice(0, firstDotIndex + 1) + result.slice(firstDotIndex + 1).replace(/\./g, '');
                }
            
                return result;
            }
            try{
                if(document.getElementById("root") && request.sourceUrl.indexOf("www.aliexpress.com") < 0 && request.sourceUrl.indexOf("www.aliexpress.us") < 0 ){
                    let pageHtmlStr = document.getElementById("root").innerHTML;
                    let dom = new DOMParser();
                    let doc = dom.parseFromString(pageHtmlStr, 'text/html');

                    let Title = doc.querySelector('h1[data-pl="product-title"]')?.textContent.trim() || ''; //产品标题
                    if(!Title)
                    {
                        Title = doc.querySelector('div[class^="title--wrap"] h1')?.textContent.trim() || '';
                    }
                    let VideoUrl = doc.querySelector('div[class^="video--wrap"] source')?.getAttribute('src') || ''; //产品视频

                    let DetailedDescription = doc.querySelector('div.detailmodule_html')?.innerHTML.trim() || ''; //产品富文本描述
                    let BriefDescription = "";  //产品文字描述
                    let ImageUrl = [];  //产品图片
                    let Price = 0; //产品价格
                    let PriceStr = doc.querySelector('div.price--current--I3Zeidd')?.textContent.trim();
                    PriceStr = extractNumbersAndSingleDot(PriceStr);
                    Price = parseFloat(PriceStr);

                    let pdpInfoDiv = doc.querySelector('.pdp-info-left');
                    if (pdpInfoDiv) {
                        pdpImageUrls = Array.from(pdpInfoDiv.querySelectorAll('img'))
                            .map(img => img.getAttribute('src'))
                            .filter(src => src); // 过滤掉 null 或空值
                        
                        ImageUrl.push(...pdpImageUrls);
                    }
                    
                    let Parameters = []; //产品属性
                    let specificationList = doc.querySelector('[class^="specification--list"]');
                    if (specificationList) {
                        let props = specificationList.querySelectorAll('[class^="specification--prop"]');
                        
                        props.forEach(prop => {
                            let key = prop.querySelector('[class^="specification--title"] span')?.textContent.trim();
                            let value = prop.querySelector('[class^="specification--desc"] span')?.textContent.trim();

                            if (key && value) {
                                Parameters.push({ "Key": key, "Value": value });
                            }
                        });
                    }

                    ///////////

                    // 1. 获取变体属性的名称
                    let variants = [];
                    let propertyNames = [];
                    let porpList = [];

                    doc.querySelectorAll('.sku-item--property--HuasaIz').forEach((propertyDiv) => {
                        let porpTitle = propertyDiv.querySelector('.sku-item--title--Z0HLO87')?.textContent.trim() || "";
                        porpTitle = porpTitle.split(":")[0].trim().replace(/\([^()]*\)/g, '');;
                        
                        propertyNames.push(porpTitle)
                        
                        let porpValueArr = [];
                        // 2. 遍历 skus 的 div
                        propertyDiv.querySelectorAll('.sku-item--skus--StEhULs > div').forEach((skuDiv) => {
                            let img = skuDiv.querySelector('img'); // 获取 img 标签
                            if (img) {
                                let porpAlt = img.alt.trim();
                                let porpImgUrl = img.src.trim();
                                let porpValue = {
                                    "key" : porpAlt,
                                    "imgUrl" : porpImgUrl
                                }
                                porpValueArr.push(porpValue);
                            } else {
                                let porpAlt =  skuDiv.textContent.trim();
                                let porpValue = {
                                    "key" : porpAlt,
                                    "imgUrl" : ""
                                }
                                porpValueArr.push(porpValue);
                            }
                        });

                        let porpObj = {
                            "key" : porpTitle,
                            "values" : porpValueArr
                        }
                        porpList.push(porpObj);
                    });
                    variants = cartesianProduct(porpList);

                    variants.forEach(item => {
                        item.Property = JSON.stringify(item.Property);
                        item.Price = Price;
                        let jpgIndex = item.VariantImageUrl.indexOf(".jpg");
                        if (jpgIndex !== -1) 
                        {
                            item.VariantImageUrl = item.VariantImageUrl.slice(0, jpgIndex + 4); // +4 是为了包含 .jpg
                        }
                        if(ImageUrl.indexOf(item.VariantImageUrl) < 0)
                        {
                            ImageUrl.push(item.VariantImageUrl);
                        }
                    });

                    if(doc.querySelector('div.detailmodule_html'))
                    {
                        let detailModuleDiv = doc.querySelector('div.detailmodule_html');
                        BriefDescription = detailModuleDiv?.textContent.trim() || '';
                        // 提取 div 中的所有 img 标签的 src 并存入数组
                        let descImageUrls = Array.from(detailModuleDiv?.querySelectorAll('img') || [])
                            .map(img => img.getAttribute('src'))
                            .filter(src => src); // 过滤掉 null 或空值

                        ImageUrl.push(...descImageUrls);
                    }
                    for(var i=0;i<ImageUrl.length;i++){
                        let jpgIndex = ImageUrl[i].indexOf(".jpg");
                        if (jpgIndex !== -1) 
                        {
                            ImageUrl[i] = ImageUrl[i].slice(0, jpgIndex + 4); // +4 是为了包含 .jpg
                        }
                    }

                    let boxInfo = {
                                "Title":Title,
                                "DetailedDescription": btoa(encodeURI(DetailedDescription)),
                                "BriefDescription": BriefDescription,
                                "ImageUrl": ImageUrl.join("|"),
                                "PropertyName": propertyNames.length > 0 ? JSON.stringify(propertyNames) : "[]",
                                "SourceUrl": request.sourceUrl,
                                "VideoUrl": VideoUrl,
                                "IsClaimed": false,
                                "SourcePlatform": 3,
                                "Tags": [],
                                "Remark": "",
                                "CreateTime": "1900-01-01 00:00:00",
                                "Parameters": JSON.stringify(Parameters)
                            };

                    boxObj =
                    {
                        boxInfo,
                        variants
                    }
                    sendResponse(
                        {
                            "isLinkCollect": request.isLinkCollect,
                            "box" :boxObj
                        }
                    );
                    console.log(boxObj);
                }
            }catch(e){
                sendResponse({"isLinkCollect": request.isLinkCollect});
            }
            return true;
        } else if (request.Type === 'GetBanggoodText') {
            sendResponse({"isLinkCollect": request.isLinkCollect});
            return true;
        } else if (request.Type === "GetWalmartText") {
            sendResponse({"isLinkCollect": request.isLinkCollect});
            return true;
        } else if (request.Type === 'GetTemuText') {
            let docType = 'type_0_type';
            if (window._LiSellingTemuSign_ !== undefined && window._LiSellingTemuRequestData_ !== undefined) {
                docType = 'type_1_type';
                let ajaxData = null;
                if (window._LiSellingTemuRequestData_.data) {//获取请求参数
                    try {
                        ajaxData = typeof window._LiSellingTemuRequestData_.data === 'string' ? JSON.parse(window._LiSellingTemuRequestData_.data) : window._LiSellingTemuRequestData_.data;
                    } catch (e) {
                        ajaxData = null;
                    }
                }

                let jsondata = "none";
                $.ajax({
                    type: 'POST',
                    headers: window._LiSellingTemuSign_,
                    withCredentials: true,
                    url: window._LiSellingTemuRequestData_.url,
                    async: false,
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify(ajaxData),
                    success: function (results) {
                        //把得到的数据放到html字段里面
                        results.DocType = docType;
                        jsondata = JSON.stringify(results);
                    },
                    error: function () {
                    }
                });
                sendResponse({"isLinkCollect": request.isLinkCollect, "DocType": docType, "Ext": jsondata});
            } else {
                sendResponse({
                    "isLinkCollect": request.isLinkCollect,
                    "DocType": docType,
                    "Ext": document.documentElement.outerHTML
                });
            }

            return true;
        } else if (request.Type === 'GetAliexpressRusText') {
            sendResponse({"isLinkCollect": request.isLinkCollect});
            return true;
        } else if (request.Type === 'GetAmazonText') {

            var scripts = document.querySelectorAll("script");
            var dimensionToAsinMap = {};
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('dimensionToAsinMap') !== -1) {
                    var scriptContent = scripts[i].innerHTML;
                    var originalString = scriptContent.toString();
                    const regex = /"dimensionToAsinMap"\s*:\s*({[^}]*})/;
                    const match = originalString.match(regex);
                    if (match && match[1]) {
                        dimensionToAsinMap = JSON.parse(match[1]);
                    } else {
                        console.error('dimensionToAsinMap not found');
                        throw new Error('dimensionToAsinMap not found');
                    }

                }
            }
            let objArr = [];
            executeRequestsInBatches(dimensionToAsinMap, request)
                .then(result => {
                    sendResponse({ "isLinkCollect": true, variantData: result });
                    return true;
                })
                .catch(error => {
                    sendResponse({ "isLinkCollect": true, variantData: [] });
                });
            return true;
        } else if (request.Type === 'GetJF91Text') {
            sendResponse({ "isLinkCollect": true });
            return true;
        } else if (request.Type === 'GetAlibabaText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetAlibabaInternationText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetJoomText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetTaoBaoText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetPinDuoDuoText') {
            var jsonStr = "none";
            //判断当前页面域名是否为"https://pifa.pinduoduo.com/*",
            if (document.URL.indexOf('pifa.pinduoduo.com') >= 0) {
                var jsondata = "none";
                let url = document.URL;
                let data = {};
                data.url = document.URL;
                let param = url;
                if (url.indexOf("&") > -1) {
                    param = param.substring(url.indexOf("=") + 1, url.indexOf("&"));
                } else {
                    param = param.substring(url.indexOf("=") + 1);
                }
                let antiContent = "0arAfxndGylBYgEhgv4SUxfUg2Dfdk48vhhLuJuEP6bHozEP9v5TjXOhIzNrhFjcpOH5HSF2TzQTPOgqwQTU4tZ4x7Z4eP8x9dFwDISiRTvSbMwW9l9eEshpRAp8rg5HGoa3tzK_eEon1S5UsswmtLqwzYNosjOCoT6XVd1atOuse_tyt7gmqal6lN5gKzJob-6t4diu8aUPbNbs27wQLwEu-pmX1PIzLM0c3fsclrqMal7XihpyNIDjh50xywy5FtDbdkgcPaxv1_GaGvfUAv9Whx0rvIqNzpFw-T1loX7c1EhvwCtqf9n4JYrcwJFmQrTgVhexq96cGXXGLCq0rhBVGPVp8uvZVFygAzoHsHNIlYOos0yfkqPuFRQoJyAI9m_gRGLF7qCsNgwHWS5BwAke14DNFEzjh7px9TLqEjzjOJmWALdxYXA4q8X1c8SDGyxNuRX-b-RNTux1gj4wtZxriZNRuhKAGyANaO69mL3wigSIwqqBZy8_3zL1TuoQWQqaixqNTfAfxei9TqOUkMlyPqkR";
                if (window._LiSellingPinDuoDuoSign_ != null) {
                    antiContent = window._LiSellingPinDuoDuoSign_['Anti-Content'];
                }
                var propertyInfo = "";
                var Detail = "";
                $.ajax({
                    type: "POST",
                    headers: {
                        "anti-content": antiContent
                    },
                    withCredentials: true,
                    url: "https://pifa.pinduoduo.com/pifa/goods/queryGoodsPropertyInfo",
                    data: JSON.stringify({"goodsId": param}),
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (results) {
                        propertyInfo = JSON.stringify(results);
                    },
                    error: function (results) {
                    }
                });
                $.ajax({
                    type: "POST",
                    headers: {
                        "anti-content": antiContent
                    },
                    withCredentials: true,
                    url: "https://pifa.pinduoduo.com/pifa/goods/queryGoodsDetail",
                    data: JSON.stringify({"goodsId": param}),
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (results) {
                        Detail = JSON.stringify(results);

                    },
                    error: function (results) {
                    }
                });
                data.html = Detail;
                data.propertyInfo = propertyInfo;
                sendResponse(data);
                // sendResponse({ "isLinkCollect": true });
                return true;
            }
            var scripts = document.querySelectorAll("body > script");
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('window.rawData=') != -1)
                    jsonStr = scripts[i].innerHTML.replace("window.rawData=", "var jsonData=");
                if (jsonStr != "none")
                    i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
            }
            if (jsonStr != "none") {
                jsonData = undefined;
                let interpreter = new eval5.Interpreter(window);
                let result = interpreter.evaluate(jsonStr);
                if (typeof (jsonData) != 'undefined') {
                    sendResponse(jsonData);
                } else {
                    sendResponse("none");
                }
            } else {
                sendResponse("none");
            }

            return true;
        } else if (request.Type === 'GetOzonText') {
            var jsonStr = "none";
            varnameArr = [];
            var scripts = document.querySelectorAll("body > script");

            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('window.__NUXT__') != -1) {
                    jsonStr = scripts[i].innerHTML.split("window.__NUXT__")[1];
                }
                if (jsonStr != "none")
                    i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
            }
            var breadCrumbs = $(".e4h").children();
            var categoryName = '';
            if (breadCrumbs.length > 0) {
                categoryName = breadCrumbs[breadCrumbs.length - 1].innerText
            }
            url = window.location.pathname;
            var data;
            // 兼容两种页面json读取方式
            if (jsonStr.indexOf('={}') == 0 || jsonStr == "none") {
                for (var i = 0; i < scripts.length; i++) {
                    if (scripts[i].innerHTML.indexOf('window.__NUXT__.state') != -1) {
                        jsonStr = scripts[i].innerHTML.replace("window.__NUXT__.state", "var jsonData");
                    }
                    if (jsonStr != "none")
                        i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
                }
                varnameArr.push("jsonData");
            } else {
                jsonStr = 'jsondata' + jsonStr;
                varnameArr.push("jsondata");
            }

            if (jsonStr != "none") {
                jsonData = undefined;
                let interpreter = new eval5.Interpreter(window);
                let result = interpreter.evaluate(jsonStr);
                if (jsonData) {
                    data = JSON.parse(jsonData).seo;
                }
                if (jsondata) {
                    data = jsondata.state.seo;
                }

                // 主数据：页面结构变更（OZON 改版）或非标准商品页时 data.script 可能不存在，先兜底
                if (!data || !data.script || !data.script[0]) {
                    sendResponse("none");
                    return true;
                }
                var obj = JSON.parse(data.script[0].innerHTML);

                //获取变体参数
                var aspectsModel = null;
                var PropertyName = [];
                var parameters = [];
                var skuLinks = [];
                var skus = [];
                var imageUrls = [];
                var aspectsJson = $("div[id^='state-webAspects-']").attr("data-state");
                var webGalleryJson = $("div[id^='state-webGallery-']").attr("data-state");

                var videoUrl = "";
                if (aspectsJson) {//多变体
                    aspectsModel = JSON.parse(aspectsJson);
                    var webGalleryModel = JSON.parse(webGalleryJson);

                    //变体参数名
                    //PropertyName = aspectsModel.aspects.map(x => x.descriptionRs[0].content.replace(": ", "").replace(":", ""));

                    //当前页面sku、sku链接
                    var selfSku = {};
                    aspectsModel.aspects.forEach(x => {
                        var key = "";
                        if (x.descriptionRs && x.descriptionRs.length > 0) {
                            key = x.descriptionRs[0].content.replace(": ", "").replace(":", "");
                        }
                        x.variants.forEach(variant => {
                            if (variant.sku == webGalleryModel.sku) {
                                var property = [];
                                if (selfSku.Property) {
                                    property = JSON.parse(selfSku.Property);
                                }
                                if (key) {
                                    property.push({Key: key, Value: variant.data.searchableText});
                                }

                                var currency = GetcurrencyCode(variant.data.price, "RUB");

                                selfSku.Price = variant.data.price.replaceAll(",", ".").replace(/[^\d^.]/g, "");
                                selfSku.SkuCode = variant.sku;
                                selfSku.Property = JSON.stringify(property);
                                selfSku.Currency = currency;
                            }

                            if (!skuLinks.some(y => y.SkuCode == variant.sku)) {
                                skuLinks.push({
                                    SkuCode: variant.sku,
                                    Link: variant.link,
                                    ImageUrls: null,
                                });
                            }
                        });
                    });
                    selfSku.VariantImageUrl = webGalleryModel.images.map(x => x.src);
                    skus.push(selfSku);
                    skuLinks.forEach(x => {
                        if (x.SkuCode == webGalleryModel.sku) {
                            x.ImageUrls = selfSku.VariantImageUrl;
                        }
                    });

                    //获取视频链接
                    if (webGalleryModel.videoCover && webGalleryModel.videoCover.url) {
                        videoUrl = webGalleryModel.videoCover.url;
                    }
                } else if (webGalleryJson) {//单变体
                    var webGalleryModel = JSON.parse(webGalleryJson);

                    //获取视频链接
                    if (webGalleryModel.videoCover && webGalleryModel.videoCover.url) {
                        videoUrl = webGalleryModel.videoCover.url;
                    }

                    skus.push({
                        Price: 0,
                        SkuCode: webGalleryModel.sku,
                        Property: "[]",
                        Currency: "RUB",
                        VariantImageUrl: webGalleryModel.images.map(x => x.src),
                    });
                }

                if (obj != undefined) {
                    sendResponse({
                        Info: obj,
                        //PropertyName: PropertyName,
                        Parameters: parameters,
                        SkuLinks: skuLinks,
                        Skus: skus,
                        Url: url,
                        VideoUrl: videoUrl,
                        CategoryName: categoryName
                    });
                } else {
                    sendResponse("none");
                }

            } else {
                sendResponse("none");
            }
            return true;
        } else if (request.Type === 'GetLazadaText') {
            sendResponse({"isLinkCollect": true});
            return true;
           
        } else if (request.Type === 'GetEbayText') {
            var jsonStr = "none";
            var scripts = document.querySelectorAll("script");
            var productJs = "";
            var scriptKeyword = "$MC=(window.$MC||[]).concat(";
            for (var i = 0; i < scripts.length; i++) {
                var script = scripts[i];
                if (script.innerHTML.indexOf(scriptKeyword) > -1) {
                    productJs = script.innerHTML.split(scriptKeyword)[1].slice(0, -1);
                    break;
                }
            }
            var breadCrumbs = $($(".breadcrumbs")[0]).find("ul").children();
            var categoryName = '';
            if (breadCrumbs.length > 0) {
                categoryName = breadCrumbs[breadCrumbs.length - 1].innerText
            }
           
            var productData = JSON.parse(productJs);
            productData = productData.o.w;
            let htmldesurl = ''
            if (document.getElementById('desc_ifr'))
                htmldesurl = document.getElementById('desc_ifr').src

            if (productData) {
                sendResponse(
                    {
                        "htmldesurl": htmldesurl,
                        "productData": productData,
                        'categoryName': categoryName
                    });
            } else {
                sendResponse("none");
            }

            return true;
        } else if (request.Type === 'GetCouPangText') {
            var jsonStr = "none";
            var scripts = document.querySelectorAll("head > script");

            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('exports.sdp') >= 0 && scripts[i].innerHTML.indexOf('exports.sdp') < 50)
                    jsonStr = scripts[i].innerHTML.split("exports.sdp")[1].split("exports.sdpIssueTypes")[0];
                if (jsonStr != "none")
                    i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
            }
            jsondata = undefined;
            let interpreter = new eval5.Interpreter(window);
            let result = interpreter.evaluate('jsondata ' + jsonStr);
            if (result) {
                sendResponse(result);
            } else {
                sendResponse("none");
            }
            return true;
        } else if (request.Type === 'GetShopeeText') {
            var shopeeApiUrlObj = getShopeeHtmlUrl(request.sourceUrl)
            if (window._LiSellingShopeeSign_ != undefined) {
                var jsondata = "none";
                var headObj = window._LiSellingShopeeSign_;
                var shopeeV4Url = headObj.shopeeV4Url ? headObj.shopeeV4Url : shopeeApiUrlObj.v4Url;
                var shopeeHeadersObj = {
                    'anti-content': '0aoAfaNddyhYY9T8kxVCQC0_P2EfPw_tuZL8SiH1_tdWSZQK47TOPFLHwaLLv5eaBh6SdUl8G5o1yUtsxbPSqu3Xiinw5lOsC9o99LmfaecBR9PG1hzeoAP5c7f8UP39qRVPhHaDa1qWcObKHVZya_IusQkmfnx3AvF-k3Nv0vaSDy8Ae6jZgr0wICTCuNNhvLy22nmcK__T6_stNaRiI7tv2jelsAwOubfPrt0Cs0f2BXi5VVQHgraqT2J0Q7m9EbYo9g9GjBVMCuX2K5pII9VmQWnMedw56YedQ99q-mlA959tL5dZ6BHWGrIA4oFqy_mKPqJHRC8pijT0nx6vuGkjD_QDp19joS428x05kIQx8jVuAaas3Qja23Chsj5ZqgZjXv6x2EglYfDoTbw8aZOf-Sjt2IQGce_Cu100iQqETWKE16TAbdHxUnYX1RGKWtU6ACxP1UItD1XHLCcRIK92iLzLkFfea1WFvXqj-Sq11e2aGiBvloc1tF4WqT-KR7KjwuKyeh-5NIUFmDbuHI6y7Tm7vRLgajA0fWVKLdRhngrj8J7J9zHH3WRA_1J2rYBCBmo85xK53icGUMomuXMt8UmvcB9LWObIRmGovBEho'
                };

                delete headObj['shopeeV4Url'];//删除URL路径

                shopeeHeadersObj = $.extend(shopeeHeadersObj, headObj);
                $.ajax({ //调用Shopee的获取数据的接口
                    type: "GET",
                    headers: shopeeHeadersObj,
                    withCredentials: true,
                    url: shopeeV4Url,
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (results) {
                        results.version = "4";
                        //把得到的数据放到html字段里面
                        jsondata = JSON.stringify(results);
                        ;
                    },
                    error: function (results) {
                    }
                });

                sendResponse(jsondata);
            } else {
                sendResponse({isBathCollect: true});
            }
            return true;
        } else if (request.Type === 'GetTmallText') {
            var id = '';
            if ($('#aliww-click-trigger') && $('#aliww-click-trigger').length > 0)
                id = $('#aliww-click-trigger').attr('data-item');

            sendResponse({"isLinkCollect": true, "id": id});
            return true;
        } else if (request.Type === 'GetJDText') {
            var price = 0.00;
            if (window._LiSellingJDSign_ != undefined) {
                var option = {
                    headers: { //请求头
                        'x-referer-page': window.location.href,
                        'x-rp-client': 'h5_1.0.0'
                    },
                    //请求参数
                    data: null
                };
                var url = window._LiSellingJDSign_;
                var fetchOptions = {
                    method: 'GET', // *GET, POST, PUT, DELETE, etc.
                    cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
                    credentials: 'include', // include, *same-origin, omit
                    redirect: 'follow', // manual, *follow, error
                    referrerPolicy: 'strict-origin-when-cross-origin'
                };
                if (option) {
                    Object.assign(fetchOptions, option);
                }
                if (option.headers) {
                    fetchOptions['headers'] = option.headers;
                }
                fetchOptions.body = option.data;

                fetch(url, fetchOptions).then(function (data) {
                    return data.json();
                }).then(function (data) {
                    sendResponse({"isLinkCollect": true, "price": data.price.p});
                }).catch(function (error) {
                    sendResponse({"isLinkCollect": true, "price": 0.00});
                });
            } else {
                sendResponse({"isLinkCollect": true, "price": 0.00});
            }
            return true;
           
        } else if (request.Type === 'GetCdiscountText') {
            var jsonStr = "none";
            if (document.getElementById("fpZnPrdMain")) {
                //Cdiscount旧版
                var title = document.getElementsByClassName("fpDesCol")[0].getElementsByTagName("h1")[0].innerText;
                // var title = $('*[itemprop="name"]').text;//标题
                var price = document.querySelector("span[itemprop='price']").getAttribute("content");
                // var price = $('*[itemprop="price"]').getAttribute('content'); //价格
                var vantList = [];
                var mainImg = [];
                var descStr = [];
                var vantStyleFlag = 1;
                var vantTitles = document.getElementsByClassName("fpVariationGroupTitleContainer");
                var vantVals = document.getElementsByClassName("fpVariationGroupOptionsContainer");
                var descHtml = document.getElementsByClassName("testSep")[2].innerHTML;
                var desclable = document.getElementsByClassName("testSep")[2].getElementsByTagName("tr");
                var mainImgLi = document.getElementsByClassName("jsFpZoomPic")[0].getElementsByTagName("li");

                if (vantTitles == null || vantTitles.length == 0) {
                    vantStyleFlag = 2;
                    //服装单变体
                    vantTitles = document.getElementsByClassName("fpSizeSelector");
                    vantVals = document.getElementsByClassName("jsSltSize");
                }
                //[0].getElementsByTagName("img")[0].getAttribute("src");

                //[0].getElementsByClassName("fpVariationGroupTitle")[0].innerText
                var scripts = document.querySelectorAll("head > script");

                // for (var i = 0; i < scripts.length; i++) {
                //     if (scripts[i].innerHTML.indexOf('\"@type\":\"Product\"') >= 0)
                //         jsonStr = scripts[i].innerHTML;
                //     if (jsonStr != "none")
                //         i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
                // }

                //获取主图
                for (var i = 0; i < mainImgLi.length; i++) {
                    if (mainImgLi[i].getElementsByTagName("img").length > 0) {
                        var imgStr = mainImgLi[i].getElementsByTagName("img")[0].getAttribute("src");
                        var imgStrList = imgStr.split("/");
                        var sizeStr = imgStrList.find(x => x.indexOf("x") > -1 && x.length == 7);
                        if (sizeStr != null) {
                            imgStr = imgStr.replace(sizeStr, "700x700");
                        }
                        mainImg.push(imgStr);
                    }
                }

                //多变体，电子产品变体
                //获取变体title
                for (var i = 0; i < vantTitles.length; i++) {
                    var vanrs = [];
                    var vantName = (vantStyleFlag == 1 ? vantTitles[i].getElementsByClassName("fpVariationGroupTitle")[0].innerText : vantTitles[i].innerText).split(':')[0].trim();

                    //变体内容
                    if (vantVals.length > i) {
                        var vantval = vantStyleFlag == 1 ? vantVals[i].getElementsByTagName("div") : vantVals[i].getElementsByTagName("option");
                        var vantImg = vantVals[i].getElementsByTagName("img"); //变体图片

                        //变体详细子集
                        for (var j = 0; j < vantval.length; j++) {
                            var proval = vantStyleFlag == 1 ? vantval[j].getAttribute("data-message") : vantval[j].innerText;
                            var img = "";
                            if (vantImg && vantImg.length > j) {
                                img = vantImg[j].getAttribute("src");
                                var imgStrList = img.split("/");
                                var sizeStr = imgStrList.find(x => x.indexOf("x") > -1 && x.length == 7);
                                if (sizeStr != null) {
                                    img = img.replace(sizeStr, "700x700");
                                }
                            }
                            if (proval && proval != null && proval != '' && proval != 'Choisissez votre taille')
                                vanrs.push({"option": proval, "imageUrl": img});
                        }

                        if (vanrs.length > 0)
                            vantList.push({key: vantName, value: vanrs});
                    }
                }

                //获取参数
                if (desclable != null) {
                    //获取参数
                    for (let i = 0; i < desclable.length; i++) {
                        if (desclable[i].getElementsByTagName("td") != null && desclable[i].getElementsByTagName("td").length > 0) {
                            var paramVal = desclable[i].getElementsByTagName("td")[0].innerText;
                            paramVal = paramVal.replace(/[\\n]/g, "").replace('"', '');
                            var strObj = {Key: desclable[i].getElementsByTagName("th")[0].innerText, Value: paramVal};
                            descStr.push(strObj);
                        }
                    }
                }
                var breads = $(".o-breadcrumb").children("li");
                var categoryName = '';
                if (breads != null && breads.length > 0) {
                    var categroy = breads[breads.length - 2];
                    categoryName = categroy.innerText.trim();
                }
                sendResponse({
                    "title": title,
                    "price": price,
                    "mainImg": mainImg,
                    "vantList": vantList,
                    "descHtml": descHtml,
                    "descStr": descStr,
                    "categoryName": categoryName
                });
            } else {
                //Cdiscount新版
                //标题
                var title = document.getElementById("fpMain").getElementsByTagName("h1")[0].innerText;
                //价格
                var price = document.querySelector("#BuyboxTabs span[itemprop='price']").getAttribute("content").replaceAll(",", ".");
                //图片
                var mainImg = [];
                var imgDivs = document.querySelectorAll(".js-productViewer__thumbnails > div");
                for (var i = 0; i < imgDivs.length; i++) {
                    if (imgDivs[i].getElementsByTagName("img").length > 0) {
                        var imgStr = imgDivs[i].getElementsByTagName("img")[0].getAttribute("src");
                        var imgStrList = imgStr.split("/");
                        var sizeStr = imgStrList.find(x => x.indexOf("x") > -1 && x.length == 7);
                        if (sizeStr != null) {
                            imgStr = imgStr.replace(sizeStr, "700x700");
                        }
                        mainImg.push(imgStr);
                    }
                }

                //属性
                var descStr = [];
                var desclable = document.querySelectorAll("#ProductSheetAccordion-content-2 table tbody tr");
                if (desclable.length > 0) {
                    //获取参数
                    for (let i = 0; i < desclable.length; i++) {
                        if (desclable[i].getElementsByTagName("td") != null && desclable[i].getElementsByTagName("td").length > 0) {
                            var paramVal = desclable[i].getElementsByTagName("td")[0].innerText;
                            paramVal = paramVal.replace(/[\\n]/g, "").replace('"', '');
                            var strObj = {Key: desclable[i].getElementsByTagName("th")[0].innerText, Value: paramVal};
                            descStr.push(strObj);
                        }
                    }
                }

                //分类
                var categoryLis = document.querySelectorAll("#bc li");
                var categoryName = '';
                if (categoryLis != null && categoryLis.length > 0) {
                    var categroy = categoryLis[categoryLis.length - 2];
                    categoryName = categroy.innerText.trim();
                }

                //描述
                var descHtml = document.querySelector("#ProductSheetAccordion-content-2").innerHTML;

                //变体
                var vantList = [];
                var vantDivs = document.querySelectorAll(".c-productHighlights__cell .c-productHightlights__criteria");
                if (vantDivs && vantDivs.length > 0) {
                    for (var i = 0; i < vantDivs.length; i++) {
                        var vantName = vantDivs[i].querySelector("p strong").innerHTML.replace(":", "").trim();
                        var vants = [];
                        var vantLis = vantDivs[i].querySelectorAll("li");
                        if (vantLis && vantLis.length > 0) {
                            for (var j = 0; j < vantLis.length; j++) {
                                var option = vantLis[j].querySelector(".js-variant__label").innerHTML.trim();
                                var imageUrl = "";
                                if (vantLis[j].querySelector("img")) {
                                    var imageUrl = vantLis[j].querySelector("img").getAttribute("src").trim();
                                    var imgStrList = imageUrl.split("/");
                                    var sizeStr = imgStrList.find(x => x.indexOf("x") > -1 && x.length == 7);
                                    if (sizeStr != null) {
                                        imageUrl = imageUrl.replace(sizeStr, "700x700");
                                    }
                                }
                                vants.push({"option": option, "imageUrl": imageUrl});
                            }
                        }
                        if (vants.length > 0)
                            vantList.push({key: vantName, value: vants});
                    }
                }
                sendResponse({
                    "title": title,
                    "price": price,
                    "mainImg": mainImg,
                    "vantList": vantList,
                    "descHtml": descHtml,
                    "descStr": descStr,
                    "categoryName": categoryName
                });
            }
            return true;
        } else if (request.Type === 'GetMercadoliText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetYiwugoText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetVVicText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetSooxieText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetDunhuangText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetTuGouText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetWSYText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetETSYText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetOnBuyText') {
            sendResponse({"isLinkCollect": true, "currency": "GBP"});
            return true;
        } else if (request.Type === 'GetTiktokText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetWildberriesText') {
            let videoUrl = "";
            try{
                videoUrl = document.querySelector('video.j-video-thumb-preview').getAttribute('src');
            }catch(e){}
            sendResponse({"isLinkCollect": true, "videoUrl" :videoUrl});
            return true;
        } else if (request.Type === 'GetFruugoText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetSheinText') {
            sendResponse({"isLinkCollect": true});
            return true;
        } else if (request.Type === 'GetYandexText') {
            sendResponse({"isLinkCollect": true});
            return true;
        }else if (request.Type === 'GetSaleyeeText') {
            sendResponse({"isLinkCollect": true});
            return true;
        }else if (request.Type === 'Alter') {
            if (request.Url && request.Url != null && request.Url != '') {
                GrowlNotification.notify({
                    title: '温馨提示',
                    description: request.Message,
                    type: request.MessageType,
                    position: 'top-right',
                    closeTimeout: 7000,
                    closeWith: "button",
                    image: {visible: true, customImage: config.logoBase64},
                    showButtons: true,
                    buttons: {
                        action: {
                            text: request.ActionBtnText && request.ActionBtnText != null && request.ActionBtnText != '' ? request.ActionBtnText : '是',
                            callback: function () {
                                window.open(request.Url, "_blank");
                            }
                        },
                        cancel: {
                            text: '取消',
                            callback: function () {
                            }
                        }
                    }
                });
            } else {
                GrowlNotification.notify({
                    title: '温馨提示',
                    description: request.Message,
                    type: request.MessageType,
                    position: 'top-right',
                    closeTimeout: 3000,
                    image: {visible: true, customImage: config.logoBase64},
                });
            }
            sendResponse('');
            return true;
        } else if (request.Type === 'NotificationShow') {
            if (!request.Key || NotificationList.find(x => x.Key == request.Key)) {
                sendResponse('');
                return true;
            }

            options = {
                title: '温馨提示',
                description: request.Message,
                type: request.MessageType,
                position: 'top-right',
                closeTimeout: 0,
                image: {visible: true, customImage: config.logoBase64},
            }

            gn = new GrowlNotification(options)
            gn.show();
            NotificationList.push({Key: request.Key, Growl: gn})

            sendResponse('');
            return true;
        } else if (request.Type === 'NotificationClose') {
            if (!request.Key || !NotificationList.find(x => x.Key == request.Key)) {
                sendResponse('');
                return true;
            }

            let notificationIndex = NotificationList.findIndex(x => x.Key == request.Key)
            if (notificationIndex > -1) {
                notificationModel = NotificationList[notificationIndex]
                NotificationList.splice(notificationIndex, 1)
                notificationModel.Growl.close()

                //对于外部库引用类型,以防万一,手动释放.使用延时是因为Notification库在关闭时有延时,不能立刻赋空
                setTimeout(() => {
                    if (notificationModel && notificationModel.Growl)
                        notificationModel.Growl = null;
                    if (notificationModel)
                        notificationModel = null;
                }, 5000);
            }

            sendResponse('');
            return true;
        } else if (request.Type === 'ConfirmAcquisition') {

            GrowlNotification.notify({
                title: '温馨提示',
                description: request.Message,
                type: request.MessageType,
                position: 'top-center',
                closeTimeout: 0,
                closeWith: "button",
                image: {visible: true, customImage: config.logoBase64},
                showButtons: true,
                buttons: {
                    action: {
                        text: '是',
                        callback: function () {
                            sendMessageToBackgroudScript({
                                "Type": "CollectionGoods",
                                "IsVerifyDuplicate": false,
                                "sourceUrl": request.Url
                            }, function (response) {
                            });
                        }
                    },
                    cancel: {
                        text: '否',
                        callback: function () {
                        }
                    }
                }
            });
            sendResponse('');
            return true;
        } else if (request.Type === 'RedirectSite') {
            if (window.__QYDZ_AI_LINK_SCRAPE__) {
                sendResponse('');
                return true;
            }
            try {
                var qydzAiTs = parseInt(sessionStorage.getItem('__qydz_ai_link_scrape') || '0', 10);
                if (qydzAiTs && Date.now() - qydzAiTs < 5 * 60 * 1000) {
                    sendResponse('');
                    return true;
                }
            } catch (e) {}
            ShowRedirectSiteBox(request.Message, request.MessageType, request.Site);
            sendResponse('');
            return true;
        } else if (request.Type === 'SaveKey') {//存储数据到网页中
            try {
                window[request.Key] = request.Value;
                if ($('[data-action="shopeebatch"]').length) {
                    $('[data-action="shopeebatch"]').click();
                }
            } catch (e) {
            }
            sendResponse('');
            return true;
        } else if (request.Type === 'CheckCollectionGoodsBtnDisabled') {
            if (request.Disabled && $("#selling_collectiongoods") && $("#selling_collectiongoods").length > 0) {
                if ($("#selling_collectiongoods").text() != "处理中3") {
                    $("#selling_collectiongoods").attr({"disabled": "disabled"});
                    $("#selling_collectiongoods").text("处理中2");
                }
            } else {
                if ($("#selling_collectiongoods").text() == "处理中1") {
                    $("#selling_collectiongoods").removeAttr("disabled");
                    $("#selling_collectiongoods").text("开始采集");
                }
            }

            sendResponse('');
            return true;
        }else if (request.Type === 'CheckCollectionSKUBtnDisabled') {
            if (request.Disabled && $("#collectiongoodsku") && $("#collectiongoodsku").length > 0) {
                if ($("#collectiongoodsku").text() != "处理中") {
                    $("#collectiongoodsku").attr({"disabled": "disabled"});
                    $("#collectiongoodsku").text("处理中");
                }
            } else {
                if ($("#collectiongoodsku").text() == "处理中") {
                    $("#collectiongoodsku").removeAttr("disabled");
                    $("#collectiongoodsku").text("采集SKU");
                }
            }

            sendResponse('');
            return true;
        } else if (request.Type === 'ShowTmallVerifyBox') {//天猫验证码展示
            if ($('#wyys-TmallVericodeModal').length <= 0) {
                let tmallVericodeModal = $('<div class="wyys-modal center middle" id="wyys-TmallVericodeModal">' +
                    '<div class="wyys-modal-dialog" style="width:500px;"><div class="wyys-modal-content" style="width:500px;margin-top:100px;">' +
                    '<div id="wyys-TmallVericodeModalContent" class="wyys-modal-body repeat-crawl-modal-content" style="padding:10px">' +
                    '</div></div></div>');

                $('<div></div>').append(tmallVericodeModal).appendTo('body');
            }

            let htmlStr = request.BoxHtml;
            $('#wyys-TmallVericodeModalContent').html(htmlStr);
            wyysModal.show('#wyys-TmallVericodeModal');

            sendResponse('');
            return true;
        } else if (request.Type === 'HideTmallVerifyBox') {//天猫验证码隐藏
            if ($('#wyys-TmallVericodeModal').length > 0) {
                $('#wyys-TmallVericodeModalContent').empty();
                wyysModal.hide('#wyys-TmallVericodeModal');
                GrowlNotification.notify({
                    title: '温馨提示',
                    description: "验证完成！请重新点击采集",
                    type: "success",
                    position: 'top-right',
                    closeTimeout: 3000,
                    image: {visible: true, customImage: config.logoBase64},
                });

                //这里调用下接口，触发重新获取token
                try {
                    $.ajax({
                        url: "https://h5api.m.tmall.com/h5/mtop.taobao.pcdetail.data.get/1.0/?jsv=2.6.1&&appKey=12574478",
                        type: 'get',
                        async: true,
                        dataType: "html",
                        success: function (res) {
                        },
                        error: function (data, status, e) {
                        }
                    })
                } catch (e) {

                }

            }

            sendResponse('');
            return true;
        } 
        else if (request.Type === 'ShowYandexVerifyBox') 
        {   
            //Yandex验证展示
            if ($('#wyys-YandexVericodeModal').length <= 0) {
                let yandexVericodeModal = $('<div class="wyys-modal center middle" id="wyys-YandexVericodeModal">' +
                    '<div class="wyys-modal-dialog" style="width:500px;"><div class="wyys-modal-content" style="width:500px;margin-top:100px;">' +
                    '<div id="wyys-YandexVericodeModalContent" class="wyys-modal-body repeat-crawl-modal-content" style="padding:10px">' +
                    '</div></div></div>');

                $('<div></div>').append(yandexVericodeModal).appendTo('body');
            }

            let htmlStr = request.BoxHtml;
            $('#wyys-YandexVericodeModalContent').html(htmlStr);
            wyysModal.show('#wyys-YandexVericodeModal');

            sendResponse('');
            return true;
        }
        else if (request.Type === 'HideYandexVerifyBox') 
        {
            //Yandex验证码隐藏
            if ($('#wyys-YandexVericodeModal').length > 0) {
                $('#wyys-YandexVericodeModalContent').empty();
                wyysModal.hide('#wyys-YandexVericodeModal');
                GrowlNotification.notify({
                    title: '温馨提示',
                    description: "验证完成！请重新点击采集",
                    type: "success",
                    position: 'top-right',
                    closeTimeout: 3000,
                    image: {visible: true, customImage: config.logoBase64},
                });

                // //这里调用下接口，触发重新获取token
                // try {
                //     $.ajax({
                //         url: "https://h5api.m.tmall.com/h5/mtop.taobao.pcdetail.data.get/1.0/?jsv=2.6.1&&appKey=12574478",
                //         type: 'get',
                //         async: true,
                //         dataType: "html",
                //         success: function (res) {
                //         },
                //         error: function (data, status, e) {
                //         }
                //     })
                // } catch (e) {

                // }
            }

            sendResponse('');
            return true;
        }
        else if (request.Type === 'CheckCategoryBtnDisabled') {
            if (request.Disabled && $("#51selling_collectioncategory") && $("#51selling_collectioncategory").length > 0) {
                if ($("#51selling_collectioncategory").text() != "处理中") {
                    $("#51selling_collectioncategory").attr({"disabled": "disabled"});
                    $("#51selling_collectioncategory").text("处理中");
                }
            } else {
                if ($("#51selling_collectioncategory").text() == "处理中") {
                    $("#51selling_collectioncategory").removeAttr("disabled");
                    $("#51selling_collectioncategory").text("开始采集");
                }
            }

            sendResponse('');
            return true;
        } else if (request.Type === "AlibabaCategoryCrawl") {//1688类目采集产品id
            var pageNum = 0;
            if (request.pageNum) {
                pageNum = request.pageNum;
            }
            pageNum += 1;
            if (request.data) {
                Crawl.categoryDataList.push(...request.data);
                Crawl.categoryCrawlCountNum += request.data.length;
                $('.wyysTotalNum').text(Crawl.categoryCrawlCountNum);
            }
            if (request.totalCount) {
                Crawl.categoryCrawlTotalNum = request.totalCount;

            }
            //获取cookie
            var h5_tk = getCookie('_m_h5_tk')
            var contend = {token: h5_tk, pageNum: pageNum, url: window.location.href, next: '', platformId: 5};
            if (pageNum == 1) {
                sendResponse(contend);
            } else if (pageNum > 1) {
                if (Crawl.categoryCrawlTotalNum > Crawl.categoryCrawlCountNum)
                    contend.next = '1';

                contend.data = [];
                if (request.data)
                    contend.data = request.data;
                sendResponse(contend);
            }
            return true;
        } else if (request.Type === "SetCategoryProgress") {//设置采集进度条
            var totalCount = Crawl.categoryCrawlTotalNum;
            $('.wyysTotalNum').text(totalCount);
            var $msgModal = $('#wyysCategoryCollectMsgModal');
            if (request.ProcessType === 1) {//重复采集
                Crawl.CarwlDetailExcuteNum += 1;
                Crawl.repeatDataList.push(request.data)
            } else if (request.ProcessType === 2) { //采集成功
                Crawl.CarwlDetailSuccessNum += 1;
                Crawl.CarwlDetailExcuteNum += 1;
            } else if (request.ProcessType === 3) {//采集失败
                Crawl.CarwlDetailErrorNum += 1;
                Crawl.CarwlDetailExcuteNum += 1;
                Crawl.CarwlDetailErrorUrl.push(request.url);
            }

            $msgModal.find('.completionNum').text(Crawl.CarwlDetailExcuteNum);
            $msgModal.find('.wyys-f-blue').text(Crawl.CarwlDetailSuccessNum);
            $msgModal.find('.wyysFail').text(Crawl.CarwlDetailErrorNum);
            if (totalCount > 0) {
                $msgModal.find('.crawProgressBar').css('width', (Crawl.CarwlDetailExcuteNum / totalCount) * 100 + '%')

            }
            sendResponse('');
            return true;
        } else if (request.Type === "SetCategoryResult") {
            if (Crawl.repeatDataList.length > 0) {
                Crawl.repeatDataList.forEach(function (item) {
                    var html = '<tr class="content"><td class="has-ipt">' +
                        '<input name="sourceUrlRepeat" type="checkbox" value="' + item.SourceUrl + '">' +
                        '</td><td class="img-box"><div class="img-out">' +
                        '<img class="imgCss" src="' + item.ImageUrl.split("|")[0] +
                        '" width="50px" height="50px"/></div></td>' +
                        '<td><a href="' + item.SourceUrl + '" target="_blank">' + item.Title + '</a></td></tr>';
                    $("#wyysCategoryCollectRepeatCrawlModal").find('#repeatValue').append(html);
                    $('#wyysCategoryCollectRepeatCrawlModal').find('input[name = "sourceUrlRepeat"]').prop('checked', false);
                })
                wyysModal.show("#wyysCategoryCollectRepeatCrawlModal");
            } else {
                //采集完成
                GrowlNotification.notify({
                    title: '温馨提示',
                    description: '采集完成',
                    type: 'Alter',
                    position: 'top-right',
                    closeTimeout: 3000,
                    image: {visible: true, customImage: config.logoBase64},
                });
            }
            sendResponse('');
            return true;
        } else if (request.Type === "GetAjaxResult") {//请求接口，有些接口不适用于在backgroud里做请求，会有校验
            $.ajax({
                type: request.RequestMethod,
                headers: request.RequestHeaders,
                xhrFields: {
                    withCredentials: true
                },
                url: request.RequestUrl,
                async: request.Async ? true : false,
                contentType: request.RequestContentType,
                dataType: request.RequestDataType,
                data: request.RequestData,
                success: function (data) {
                    sendResponse({IsSuccess: true, Data: data});
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    sendResponse({IsSuccess: false, Data: jqXHR});
                }
            });
            return true;
        } else if (request.Type === "GetDocumentCookies") {
            var resultData = {};
            for (var i = 0; i < request.NeedNameArr.length; i++) {
                resultData[request.NeedNameArr[i]] = getCookie(request.NeedNameArr[i]);
            }
            sendResponse(resultData);
            return true;
        } else if (request.Type === "GetOnbuyVariationsInfo") {
            let skuFirstImage = '';
            let price = 0;

            try {
                let dom = new DOMParser();
                let imageDoc = dom.parseFromString(request.HtmlStr, 'text/html');
                let imagesElement = imageDoc.querySelector("#image-gallery").querySelectorAll("a");
                skuFirstImage = imagesElement[0].attributes["href"].value;
                let priceString = imageDoc.querySelector(".q-p").querySelector(".price").innerText;
                price = parseFloat(priceString.replace(/[^\d.]/g, ''));
            } catch (e) {}

            sendResponse(
                {
                    SkuFirstImage: skuFirstImage,
                    Price: price
                });
            return true;
        } else if (request.Type === "GetOnbuyProductInfo") {
            let desc = '';
            let title = '';
            let categoryId = '';
            let categoryName = '';
            let productId = '';

            let skus = [];
            let parameters = [];
            let imageList = [];
            let propertyNames = [];

            let price = 0;
            let hasMoreSku = false;

            try {
                let parser = new DOMParser();
                let doc = parser.parseFromString(request.HtmlStr, 'text/html');
                title = doc.querySelectorAll(".product-name")[0].innerHTML;
                desc = doc.querySelector("#product-description").outerHTML;
                let topModel = JSON.parse(doc.querySelector(".top-info").querySelector('script').textContent)
                let divElement = doc.createElement('div');
                divElement.innerHTML = topModel.itemListElement[topModel.itemListElement.length - 2].name;
                categoryName = divElement.textContent;

                if (doc.querySelector(".product-features")) {
                    var lis = doc.querySelector(".product-features").querySelectorAll("li");
                    lis.forEach(element => {
                        var text = element.textContent.trim();
                        var match = text.match(/(.+):(.+)/);
                        if (match) {
                            var key = match[1].trim();
                            var value = match[2].trim();
                            if (!parameters.some(z => z.Key == key)) {
                                parameters.push({
                                    Key: key,
                                    Value: value,
                                });
                            }

                        }

                    })
                }

                categoryId = doc.querySelector(".product-code").attributes["data-category_id"].value;
                var priceString = doc.querySelector(".q-p").querySelector(".price").innerText;
                price = parseFloat(priceString.replace(/[^\d.]/g, ''));

                //产品主图
                var images = doc.querySelector("#image-gallery").querySelectorAll("a");
                images.forEach(element => {
                    imageList.push(element.attributes["href"].value)
                });

                if (doc.querySelector(".product-options div")) {
                    hasMoreSku = true;
                    productId = doc.querySelector(".product-options").attributes["data-product_id"].value;
                    let attributes = doc.querySelector(".product-options").querySelectorAll("div");
                    var properties = []
                    attributes.forEach(element => {
                        var name = element.querySelector("label").textContent;
                        propertyNames.push(name.replace(":", ""));
                        var options = element.querySelector("select").querySelectorAll("option");
                        var values = []
                        options.forEach(option => {
                            var id = option.attributes["value"].value;
                            if (id) {
                                values.push({ id: id, value: option.textContent });
                            }
                        })
                        properties.push({ key: name, value: values });
                    });
                    var setSku = function generateCombinations(properties) {
                        const combinations = [];

                        function helper(index, combination) {
                            if (index === properties.length) {
                                combinations.push(combination);
                                return;
                            }

                            const property = properties[index];
                            const values = property.value;

                            for (const value of values) {
                                const newCombination = { ...combination };
                                newCombination[`attributeKey${index + 1}`] = property.key.replace(":", '');
                                newCombination[`attributeValue${index + 1}`] = value.value;
                                newCombination[`attribute${index + 1}Id`] = value.id;
                                newCombination['price'] = content.price;
                                newCombination['imageUrl'] = '';
                                newCombination['hasStock'] = 0;
                                helper(index + 1, newCombination);
                            }
                        }

                        helper(0, {});

                        return combinations;
                    }

                    //多属性
                    skus = setSku(properties);
                    //拿到页面有库存的变体
                    doc.querySelector(".variant-list").querySelectorAll(".variant").forEach(element => {
                        var attributeLable = element.querySelectorAll(".detail");
                        var attributeValue1 = '';
                        var attributeValue2 = '';
                        if (attributeLable.length > 0) {
                            attributeValue1 = attributeLable[0].querySelector(".value").textContent;
                        }
                        if (attributeLable.length > 1 && attributeLable[1].querySelector(".value")) {
                            attributeValue2 = attributeLable[1].querySelector(".value").textContent;
                        }
                        for (i = 0; i < skus.length; i++) {
                            var sku = skus[i];
                            var attr1 = '';
                            var attr2 = '';
                            if (sku.attribute1Id) attr1 = sku.attributeValue1;
                            if (sku.attribute2Id) attr2 = sku.attributeValue2;
                            if (attributeValue1 == attr1 && attributeValue2 == attr2) {
                                skus[i].hasStock = 1;
                                break;
                            }
                        }
                    });
                }

            } catch (e) {}

            sendResponse(
                {
                    Title: title,
                    Desc: desc,
                    CategoryId: categoryId,
                    CategoryName: categoryName,
                    ProductId: productId,
                    Price: price,
                    HasMoreSku: hasMoreSku,
                    Skus: skus,
                    Parameters: parameters,
                    ImageList: imageList,
                    PropertyNames: propertyNames
                });
            return true;
        }
        else if(request.Type==='GetFruugoProductInfo'){
            let desc = '';
            let categoryId = '';
            let categoryName = '';
            let otherSkuIds=[];
            let skus = [];
            let parameters = [];
            let propertyNames = [];
            let imageList=[];
            let price = 0;
            let currency='';
            let skuAttr=[];
            let hasMoreSku = false;
            try{
                let parser = new DOMParser();
                let doc = parser.parseFromString(request.HtmlStr, "text/html");
                const skuInfo = extractAttributesAndValues(doc);
                var title=doc.querySelector('.js-product-title').innerHTML;
                const skuid = Number(
                    doc.querySelector('input[name="skuId"]').value
                );
                var descDiv= doc.querySelector("#description");
                desc = descDiv.querySelector("div:first-child").outerHTML;
                const lastItemLink = doc.querySelector(
                    "ol.breadcrumb > li.breadcrumb-item:last-child a"
                );
                categoryName = lastItemLink.textContent.trim();
                categoryId =
                    (lastItemLink.getAttribute("href").match(/\/a-(\d+)/) ||
                        [])[1] || "";
                // 选择所有属性列表项
                var spec = doc.querySelector(".product-description-spec-list");
                const items = spec.querySelectorAll("li");

                items.forEach((item) => {
                    const strong = item.querySelector("strong");
                    const valueElement = item.querySelector("a, span");
                    if (strong && valueElement) {
                        const key = strong.textContent.replace(":", "").trim();
                        const value = valueElement.textContent.trim();
                        parameters.push({ key, value });
                    }
                });
                // 获取图片 .Product__Gallery 元素
                let scripts = doc.querySelectorAll('script');
                let matchingScripts = Array.from(scripts).filter(script => script.textContent.includes('window.skuInfo'));
                if(matchingScripts.length>0)
                {
                    let scriptContent = matchingScripts[0].textContent;
                    let jsonMatch = scriptContent.match(/window\.skuInfo\s*=\s*({.*?});/);

                    if (jsonMatch) {
                        // 解析 JSON 对象
                        let skuInfoJson = JSON.parse(jsonMatch[1]);
                        imageList=skuInfoJson.images.urls;
                        var attrs = skuInfoJson.attributes;
                        if (attrs && attrs.length > 1)
                            skuInfoJson.attributes.filter(item => item.type !== "OTHER");

                        skuAttr = attrs.map(item => ({
                            key: item.title,
                            value: item.value
                        }));
                    }
                }
                // 价格
                let pricemetaTag = doc.querySelector('meta[property="product:sale_price:amount"]');

                price = pricemetaTag ? pricemetaTag.getAttribute('content') : 0;
                if (price===0) {
                    pricemetaTag = doc.querySelector('meta[property="product:price:amount"]');
                    price = pricemetaTag ? pricemetaTag.getAttribute('content') : 0;
                }
                let currencyMetaTag = doc.querySelector('meta[property="product:sale_price:currency"]');
                if(!currencyMetaTag){
                    currencyMetaTag = doc.querySelector('meta[property="product:price:currency"]');
                }
                currency = currencyMetaTag ? currencyMetaTag.getAttribute('content') :'USD';

                if (skuInfo !== null) {
                    propertyNames = skuInfo.propertyName;
                    hasMoreSku = true;
                    //排除当前sku
                    otherSkuIds = skuInfo.uniqueIds.filter(
                        (item) => item !== skuid
                    );
                }
            }catch(e) {}
            sendResponse(
                {
                    Currency:currency,
                    Desc: desc,
                    CategoryId: categoryId,
                    CategoryName: categoryName,
                    Price: price,
                    HasMoreSku: hasMoreSku,
                    Skus: skus,
                    OtherSkuids:otherSkuIds,
                    Parameters: parameters,
                    ImageList: imageList,
                    PropertyNames: propertyNames,
                    SkuAttr:skuAttr,
                    Title:title
                });
            return true;
        } else if(request.Type==='GetFruugoVariationsInfo'){
            let imageList=[];
            let price = 0;
            let currency='';
            let skuAttr=[];
            try{
                let parser = new DOMParser();
                let doc = parser.parseFromString(request.HtmlStr, "text/html");
                const skuInfo = extractAttributesAndValues(doc);
                // 获取图片 .Product__Gallery 元素
                let scripts = doc.querySelectorAll('script');
                let matchingScripts = Array.from(scripts).filter(script => script.textContent.includes('window.skuInfo'));
                if(matchingScripts.length>0)
                {
                    let scriptContent = matchingScripts[0].textContent;
                    let jsonMatch = scriptContent.match(/window\.skuInfo\s*=\s*({.*?});/);

                    if (jsonMatch) {
                        // 解析 JSON 对象
                        let skuInfoJson = JSON.parse(jsonMatch[1]);
                        imageList=skuInfoJson.images.urls;
                        var attrs = skuInfoJson.attributes;
                        if (attrs && attrs.length > 1)
                            skuInfoJson.attributes.filter(item => item.type !== "OTHER");

                        skuAttr = attrs.map(item => ({
                            key: item.title,
                            value: item.value
                        }));
                    }
                }
                // 价格
                let pricemetaTag = doc.querySelector('meta[property="product:sale_price:amount"]');

                price = pricemetaTag ? pricemetaTag.getAttribute('content') : 0;
                if (price===0) {
                    pricemetaTag = doc.querySelector('meta[property="product:price:amount"]');
                    price = pricemetaTag ? pricemetaTag.getAttribute('content') : 0;
                }
                let currencyMetaTag = doc.querySelector('meta[property="product:sale_price:currency"]');
                if(!currencyMetaTag){
                    currencyMetaTag = doc.querySelector('meta[property="product:price:currency"]');
                }
                currency = currencyMetaTag ? currencyMetaTag.getAttribute('content') :'USD';
            }catch(e) {}
            sendResponse(
                {
                    Currency:currency,
                    Price: price,
                    ImageList: imageList,
                    SkuAttr:skuAttr
                });
            return true;
        }
        else if(request.Type==='GetSaleyeeProductInfo'){
            let desc = '';
            let categoryUrl = '';
            let categoryName = '';
            let skus = [];
            let parameters = [];
            let propertyNames = [];
            let imageList=[];
            let price = 0;
            let stockNum=0;
            let currency='';
            let skuAttr=[];
            let spuCode='';
            let allProductIds=[];
            let productId=0;
            let width2=0;
            let weight2=0;
            let height2=0;
            let length2=0;
            try{
                let parser = new DOMParser();
                let doc = parser.parseFromString(request.HtmlStr, "text/html");
                const skuInfoJson = doc.querySelector(".hideAttrListData").innerText;
                var title=doc.querySelector('.choose_h3').innerText.trim();
                var productInfo=JSON.parse(doc.querySelector(".hideDefaultSkuData").innerText);
                var skuId='';
                if(productInfo&&productInfo.ProductDetailRegionLogisticsProductList!=null&&productInfo.ProductDetailRegionLogisticsProductList.length>0){
                    var product=productInfo.ProductDetailRegionLogisticsProductList[0];
                    //库存
                    stockNum=product.StockQty;
                    if(product.ProductDetailLogisticsProductList&&product.ProductDetailLogisticsProductList.length>0){
                         //价格
                         price=product.ProductDetailLogisticsProductList[0].Price_d;
                         currency=product.ProductDetailLogisticsProductList[0].Price.split(" ")[0];
                    }
                    skuId=productInfo.PlatformGoodsCode;
                    spuCode=productInfo.SPU;
                    productId=productInfo.Id,
                    title=productInfo.ProductNameUS;
                    width2=productInfo.Spec.SpecWidth;
                    weight2=productInfo.Spec.SpecWeight/1000;
                    height2=productInfo.Spec.SpecHeight;
                    length2=productInfo.Spec.SpecLength;
                   
                }
                // 获取图片 
                if(productInfo.PictureModels&&productInfo.PictureModels.length>0){
                    imageList=productInfo.PictureModels.map(x=>x.ImageUrl)
                }
                var attrs=doc.querySelectorAll('.li_attr');
                if(attrs&&attrs.length>0){
                  //多属性
                  var skuInfos = JSON.parse(skuInfoJson);
                  allProductIds=[...new Set(skuInfos.map(x => x.PlatformGoodsCode))];
                  propertyNames=Array.from(attrs).map((attr)=>attr
                  .querySelector("span")
                  .textContent.replace("：", "")
                  .trim())
                  // 获取所有属性的值
                  const attributes = Array.from(
                    attrs
                  ).map((attr) => {
                    const attrName = attr
                      .querySelector("span")
                      .textContent.replace("：", "")
                      .trim();
                    const attrCode = attr.getAttribute("data-attrcode");
                    const values = Array.from(
                      attr.querySelectorAll(".em_attr")
                    ).map((em) => ({
                      code: attrCode,
                      name:attrName,
                      value: em.getAttribute("data-attrval"),
                    }));
                    return { attrName, values };
                  });

                  // 生成笛卡尔积
                  function cartesianProduct(arr) {
                    return arr.reduce(
                      (acc, curr) => {
                        return acc.flatMap((d) =>
                          curr.values.map((v) => [...d, { v }])
                        );
                      },
                      [[]]
                    );
                  }
                  // 获取 SKU 的笛卡尔积组合
                  const skuCombinations = cartesianProduct(attributes);
                  skuCombinations.forEach((item) => {
                        skus.push({
                        SkuId:'',
                        Price:price,
                        Property:item.map(item => ({
                            key: item.v.name,
                            value: item.v.value,
                            code: item.v.code
                          })),
                        Currency: currency,
                        VariantImageUrl:imageList[0],
                       });
                  });
                }else{
                    skus.push({
                        SkuId:skuId,
                        Price:price,
                        Property: [],
                        Currency: currency,
                        VariantImageUrl:imageList[0],
                    });
                }
                desc = doc.querySelector(".layui-tab-item").outerHTML;
                const lastItemLink = doc.querySelector(
                    ".location p a:last-of-type"
                );
                categoryName = lastItemLink.textContent.trim();
                categoryUrl = lastItemLink.href;
            }catch(e) {}
            sendResponse(
                {
                    allProductIds,
                    SpuCode:spuCode,
                    Currency:currency,
                    Desc: desc,
                    CategoryId: categoryUrl,
                    CategoryName: categoryName,
                    Price: price,
                    Skus: skus,
                    Parameters: parameters,
                    ImageList: imageList,
                    PropertyNames: propertyNames,
                    Title:title,
                    productId,
                     width2,
                     weight2,
                     height2,
                     length2
                });
            return true;
        }else if(request.Type==='GetSaleyeeCategory'){
            let categoryId =0
            try{
                let parser = new DOMParser();
                let doc = parser.parseFromString(request.HtmlStr, "text/html");
                var scriptText=doc.querySelector(".headtopmargin").querySelector("script").innerText;
                const cate3Match = scriptText.match(/cate3:\s*(\d+)/);
                categoryId = cate3Match ? parseInt(cate3Match[1], 10) : null;
            }catch(e) {}
            sendResponse({
                id:categoryId
            })
        }else if(request.Type==='GetSaleyeeDesc'){
            let parser = new DOMParser();
            let doc = parser.parseFromString(request.HtmlStr, "text/html");
            doc.querySelector(".choose_description").innerHTML=request.desc;
            sendResponse({
                desc:doc.querySelector(".layui-tab-item").outerHTML
            })
        } else if (request.Type === 'GetJF91ProductInfo') {
            let goodsId = "";
            let specData = [];
            let dataIds = [];

            const parser = new DOMParser();
            const doc = parser.parseFromString(request.HtmlStr, 'text/html');

            const specDiv = doc.querySelector('div[name="init[]"][type="specs"]');
            const specContent = specDiv.textContent.trim(); 
            specData = JSON.parse(specContent); 
        
            const goodsIdDiv = doc.querySelector('div[name="init[]"][type="goodsid"]');
            const goodsIdContent = goodsIdDiv.textContent.trim(); 
            goodsId = JSON.parse(goodsIdContent); 

            const specPicListDiv = doc.querySelector('div.spec_pic_list');

            if (specPicListDiv) {
                // 在 spec_pic_list 内找到所有 sp_div 中的 a 标签，并提取 data-id 属性
                dataIds = Array.from(specPicListDiv.querySelectorAll('div.sp_div a[data-id]'))
                    .map(anchor => anchor.getAttribute('data-id')) // 提取 data-id 属性值
                    .filter((dataId, index, self) => self.indexOf(dataId) === index); // 去重
            }

            let data = {
                goodsId: goodsId, 
                specs: specData, 
                dataIds
            }
            sendResponse({IsSuccess: true, Data: data});
        } else if (request.Type === "GetTiktokData") {
            let resData = {};
            try {
                let dom = new DOMParser();
                let doc = dom.parseFromString(request.HtmlStr, 'text/html');
                let element = doc.querySelector("#__MODERN_ROUTER_DATA__");
                let jsonObj = element.innerText;
                let productData1 = JSON.parse(jsonObj);
                let productData2 = productData1.loaderData;
                resData = productData2["(shop$)/(pdp)/(name$)/(id)/page"].initialData.productInfo;
                productData2 = jsonObj;
            } catch (e) {}

            sendResponse(
                {
                    data: resData
                });

            return true;

        }     
        else if (request.Type === "GetYandexProductInfo") {
            let resData = {};
            let dom = new DOMParser();
            let doc = dom.parseFromString(request.HtmlStr, 'text/html');
            try {
                const content = Array.from(doc.querySelectorAll('noframes[data-apiary="patch"]'))
                .find(tag => {
                    const text = tag.textContent || tag.innerHTML;
                    return text.includes("oskuId") && text.includes("businessId");
                })
                ?.textContent || "";

                if(content && content != "")
                {
                    let contentObj = JSON.parse(content);
                    let argument = contentObj.widgets["@light/ToggleWishlist"]["/content/page/fancyPage/defaultPage/wishlist/wishlistToggle"];
                    resData.CardBusinessId = argument.businessId;
                    resData.CardOskuId =  argument.oskuId;
                    resData.CardProductId = argument.productId;
                }
            } catch (e) {}

            sendResponse({data: resData});
            return true;
        }
        else if (request.Type === "GetYandexData") {
            let resData = {};
            // try {
            //     console.log(request.HtmlStr);

            //     let matchSk = request.HtmlStr.match(/"sk":"([^"]+)"/);

            //     if (matchSk) {
            //         let skValue = matchSk[1];  // match[1] 是捕获的 sk 值
            //         console.log("sk 的值是:", skValue);
            //     } else {
            //         console.log("未找到 sk 的值");
            //     }

            //     let dom = new DOMParser();
            //     let doc = dom.parseFromString(request.HtmlStr, 'text/html');
            //     let noframesElements = doc.querySelectorAll('noframes[data-apiary="patch"]');
            //     let matchedElement = Array.from(noframesElements).find(element => {
            //         return element.innerHTML.includes('/content/page/fancyPage/defaultPage/productRating');
            //     });
            //     let jsonData = JSON.parse(matchedElement.textContent.trim());
                
            //     // let element = doc.querySelector(".disableOverscroll");
            //     // let zoneData = element ? element.getAttribute("data-zone-data") : null;
            //     // let productData1 = JSON.parse(zoneData);

            //     productData2 = jsonObj;
            // } catch (e) {}
            
            try {
                $.ajax({
                    url: "https://market.yandex.ru/manifest.json",
                    method: 'GET',
                    async: false, // 异步请求
                    success: function (html) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(`Error fetching`, jqXHR);
                        let responseText = jqXHR.responseText;
                        console.log(`responseText`, responseText);

                        const regex = /window\.state\s*=\s*(\{.*\});/;
                        const match = responseText.match(regex);
                        if (match) {
                            resData = JSON.parse(match[1]);
                            console.log(resData);  
                        } else {
                            console.log("Yandex未找到有效的对象");
                        }
                    }
                });
            } catch (e) {}
            
            sendResponse({data: resData});
            return true;

        } 
    }
}


function extractAttributesAndValues(doc) {
    const form = doc.querySelector("form.Product__Configurable");
    if (!form) {
        return null;
    }

    const attributes = [];
    const allIds = new Set();
    const propertyName=[];
    // 获取下拉框的数据
    const formGroups = form.querySelectorAll(".form-group");

    formGroups.forEach((group) => {
        const select = group.querySelector("select");

        if (select) {
            const attributeKey = select.getAttribute("id");
            const options = select.querySelectorAll("option");
            const values = Array.from(options).map((option) => {
                const valueText = option.textContent.trim();
                const match = option.value.match(/\[(.*?)\]/);
                if (match) {
                    match[1].split(", ").forEach((id) => allIds.add(Number(id)));
                }
                return valueText;
            });
            propertyName.push(attributeKey);
            attributes.push({
                key: attributeKey,
                value: values,
            });
        }
    });

    return {
        propertyName:propertyName,
        attributes: attributes,
        uniqueIds: Array.from(allIds),
    };
}
var Crawl = {
    categoryCrawlTotalNum: 0, //分类采集的产品总数
    categoryCrawlCountNum: 0, //分类采集已经采集的数量
    categoryDataList: [], //分类采集需要采集的产品数据集合
    CarwlDetailSuccessNum: 0,// 详情采集成功数量
    CarwlDetailExcuteNum: 0,//当前进度数量
    CarwlDetailErrorNum: 0,//详情采集失败数量
    CarwlDetailErrorUrl: [], //详情采集失败url
    repeatDataList: [],//重复采集数据
}

function getShopeeHtmlUrl(url) {
    var siteUrl = url,
        urlHost = '',
        shopIdAndItemId = '',
        shopId = '',
        itemId = '';

    if (siteUrl.indexOf('https://') !== -1) {
        // if(siteUrl.indexOf('mall.shopee.') !== -1){
        //     urlHost = siteUrl.substring(siteUrl.indexOf('https://') + 13);
        // }else {
        urlHost = siteUrl.substring(siteUrl.indexOf('https://') + 8);
        // }
        urlHost = urlHost.substring(0, urlHost.indexOf('/'));
    } else if (siteUrl.indexOf('http://') !== -1) {
        // if(siteUrl.indexOf('mall.shopee.') !== -1){
        //     urlHost = siteUrl.substring(siteUrl.indexOf('http://') + 12);
        // }else {
        urlHost = siteUrl.substring(siteUrl.indexOf('http://') + 7);
        // }
        urlHost = urlHost.substring(0, urlHost.indexOf('/'));
    }
    if (siteUrl.indexOf('-i.') !== -1) {
        shopIdAndItemId = siteUrl.substring(siteUrl.indexOf('-i.') + 3);
        if (shopIdAndItemId.indexOf('/') !== -1) {
            shopIdAndItemId = shopIdAndItemId.substring(0, shopIdAndItemId.indexOf('/'));
        }
        shopId = shopIdAndItemId.substring(0, shopIdAndItemId.indexOf('.'));
        itemId = shopIdAndItemId.substring(shopIdAndItemId.indexOf('.') + 1);
    } else if (siteUrl.indexOf('/product/') !== -1) {
        shopIdAndItemId = siteUrl.substring(siteUrl.indexOf('/product/') + 9);
        shopId = shopIdAndItemId.substring(0, shopIdAndItemId.indexOf('/'));
        itemId = shopIdAndItemId.substring(shopIdAndItemId.indexOf('/') + 1);
        if (itemId.indexOf('/') !== -1) {
            itemId = itemId.replace('/', '');
        }
    }
    if (itemId.indexOf('?') !== -1) {
        itemId = itemId.split('?')[0];
    }
    var v2Url = 'https://' + urlHost + '/api/v2/item/get?itemid=' + itemId + '&shopid=' + shopId,
        v4Url = 'https://' + urlHost + '/api/v4/item/get?itemid=' + itemId + '&shopid=' + shopId,
        v0Url = 'https://' + urlHost + '/api/v0/shop/' + shopId + '/item/' + itemId + '/shipping_info_to_address';
    return {
        v4Url: v4Url,
        v2Url: v2Url,
        v0Url: v0Url
    }
}

function getshopeeSiteImage(id) {
    var site = "";
    if (window.location.host.indexOf("xiapibuy") !== -1) {
        site = window.location.host.split(".")[0];
    } else {
        site = window.location.host.split(".").pop();
    }
    let url = "";
    if (site === "sg" || site === "ph" || site === "vn" || site === "cl" || site === "es") {
        url = `https://cf.shopee.${site}/file/${id}`;
    } else if (site === "tw" || site === 'xiapi') {
        url = `https://s-cf-tw.shopeesz.com/file/${id}`;
    } else if (site === "id" || site === "th") {
        url = `https://cf.shopee.co.${site}/file/${id}`;
    } else if (site === "my" || site === "br" || site === "mx" || site === "ar" || site === "co") {
        url = `https://cf.shopee.com.${site}/file/${id}`;
    }
    return url;
}

function findWidgetId(obj, widgetId, keyValue) {
    for (var key in obj) {
        if (key === widgetId && obj[key].indexOf(keyValue) > -1) {
            return obj;
        } else if (typeof obj[key] === 'object') {
            var result = findWidgetId(obj[key], widgetId, keyValue);
            if (result) {
                return result;
            }
        }
    }
    return null;
}

//AI精铺上架功能获取主图方法
function GetPlatformImageUrl(platformId, platformName) {
    let getImage = new Promise((resolve, reject) => {
        var imageUrl = "";
        if (platformId == 1) {
            var imgArr = Array.from($('div[data-box-name="showoffer.gallery"] button[tabindex] img').map(function () {
                return $(this).attr('src')
            }));
            //这里使用for循环，forEach只有抛异常才能中断循环
            for (var i = 0; i < imgArr.length; i++) {
                var element = imgArr[i];
                if (imageUrl != "")
                    resolve(imageUrl);
                else
                    reject();
            }
            reject();
        } else if (platformId == 2) {
            var images = [];
            if ($("img.ProductImageContainer__StripImage-sc-1gow8tc-7")) {
                images = $("img.ProductImageContainer__StripImage-sc-1gow8tc-7").map(function () {
                    return $(this).attr('src')
                });
            }
            if (images.length > 0) {
                var image = images[0].replace("-small", "-original").replace("-large", "-original").replace("-tiny", "-original").split('?')[0];
                resolve(image);
            } else {
                throw new Error("未能成功获取产品主图，请重试！");
            }
            // receiveMessages({ "Type": "Get" + platformName + "Text" }, null, function (content) {
            //     if (content != "none") {
            //         var images = [];
            //         if (content != "none" && content.Images != null && content.Images != undefined && content.Images.length > 0) {
            //             Array.from(content.Images).forEach(function (image) {
            //                 images.push(image.replace("-small", "-original").replace("-large", "-original").replace("-tiny", "-original").split('?')[0]);
            //             });
            //         } else if (content != "none" && content.Data) {
            //             var productInfo = JSON.parse(content.Data);
            //             images.push(productInfo.productPagePicture.split('?')[0].replace("-large", "-original"));//主图
            //             if (productInfo.hasOwnProperty("extraPhotoUrls") && productInfo["extraPhotoUrls"] != null && productInfo["extraPhotoUrls"] != undefined) {
            //                 Object.keys(productInfo.extraPhotoUrls).forEach(function (key) {
            //                     images.push(productInfo.extraPhotoUrls[key].replace("-small", "-original"));
            //                 });
            //             }
            //         }

            //         if (images.length > 0) {
            //             resolve(images[0]);
            //         }
            //         else {
            //             reject();
            //         }
            //     }
            //     else {
            //         reject();
            //     }
            // });
        } else if (platformId == 3) {

            meta = document.querySelector('meta[property="og:image"]');
            if (meta && meta.content) {
                imageUrl = meta.content;
                resolve(imageUrl);
            } else {
                var jsonStr = "none";
                var scripts = document.querySelectorAll("body > script");

                for (var i = 0; i < scripts.length; i++) {
                    if (scripts[i].innerHTML.indexOf('window.runParams') != -1)
                        jsonStr = scripts[i].innerHTML.split("window.runParams")[1];
                    if (jsonStr != "none")
                        i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
                }

                if (jsonStr == "none") {
                    scripts = document.querySelectorAll("head > script");
                    for (var i = 0; i < scripts.length; i++) {
                        if (scripts[i].innerHTML.indexOf('window._dida_config_._init_data_') != -1)
                            jsonStr = scripts[i].innerHTML.split("window._dida_config_._init_data_")[1];
                        if (jsonStr != "none")
                            i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
                    }
                }

                if (jsonStr == "none") {
                    throw new Error("未能成功获取产品主图，请重试！");
                } else {
                    let interpreter = new eval5.Interpreter(window);
                    let result = interpreter.evaluate('jsondata' + jsonStr);
                    if (result && result.data) {
                        if (result.data.hasOwnProperty("imageModule") && result.data.imageModule != undefined && result.data.imageModule.imagePathList != undefined) {
                            imageUrl = result.data.imageModule.imagePathList[0];
                        } else if (result.data.hasOwnProperty("data")
                            && result.data.data.hasOwnProperty("imageView_2247")
                            && result.data.data.imageView_2247.hasOwnProperty("fields")
                            && result.data.data.imageView_2247.fields.hasOwnProperty("imagePathList")
                            && result.data.data.imageView_2247.fields.imagePathList.length > 0) {
                            resolve(result.data.data.imageView_2247.fields.imagePathList[0]);
                        } else {
                            throw new Error("未能成功获取产品主图，请重试！");
                        }
                    } else {
                        throw new Error("未能成功获取产品主图，请重试！");
                    }
                }
            }
        } else if (platformId == 4) {

            let images = [];
            var divImages = document.querySelectorAll(".imgTagWrapper")
            if (divImages.length > 0) {
                for (let img of divImages) {
                    if (img.querySelector("img")) {
                        images.push(img.querySelector("img").src);
                        break;
                    }

                }
            }
            if (images.length == 0) {
                let imageElement = document.querySelector("#imageBlock_feature_div>script");

                if (imageElement !== null) {
                    let json = imageElement.textContent;
                    let match = json.match(/var\s+data\s*=\s*({.*?});/s);

                    if (match !== null) {
                        let jsonData = match[1];
                        let jsonDataWithDoubleQuotes = jsonData.replace(/'/g, "\"")
                            .replace("\"imageBlockRenderingStartTime\": Date.now(),", "")
                            .replace(/A\.\$\.parseJSON\(\"/g, "")
                            .replace(/\"\)/g, "");

                        let jsonModel = JSON.parse(jsonDataWithDoubleQuotes);

                        if (jsonModel !== null && jsonModel.colorImages !== null && jsonModel.colorImages.initial !== null) {
                            for (let item of jsonModel.colorImages.initial) {
                                if (item.large !== null && !images.some(c => item.large.value === c)) {
                                    images.push(item.large);
                                }
                            }
                        }
                    }
                }
            }


            if (images.length > 0) {
                resolve(images[0]);
            } else {
                reject();
            }
        } else if (platformId == 5) {
            var images = $("#dt-tab ul li").map(function () {
                if ($(this).attr('data-imgs') != undefined) return JSON.parse($(this).attr('data-imgs')).original
            });
            if (images == null || images == undefined || images.length <= 0) {
                var jsonStr = "none";
                scripts = document.querySelectorAll("body script");
                for (var i = 0; i < scripts.length; i++) {
                    if (scripts[i].innerHTML.indexOf('window.__INIT_DATA=') != -1) {
                        jsonStr = scripts[i].innerHTML.split("window.__INIT_DATA=")[1];
                    }
                    if (jsonStr != "none")
                        i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
                }
                if (jsonStr != "none") {
                    var jsonObj = JSON.parse(jsonStr);
                    if (jsonObj != null
                        && jsonObj != undefined
                        && jsonObj.hasOwnProperty("globalData")) {
                        images = jsonObj.globalData.images.map(n => "https://cbu01.alicdn.com/" + n.imageURI);
                    }
                }
            }

            if (images != null && images != undefined && images.length > 0) {
                resolve(images[0]);
            } else {
                try{
                    const srcValue = document.getElementById('gallery')
                        .querySelector('div.od-gallery-turn-item-wrapper:not(.prepic-video) img').src;
                    resolve(srcValue);
                }catch(e){
                    reject();
                }
            }
        } else if (platformId == 6) {
            var jsonStr = "none";
            var images = [];
            var scripts = document.querySelectorAll("body > lint > script, body > script");
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('window.detailData = ') != -1)
                    jsonStr = scripts[i].innerHTML.split("window.detailData = ")[1];
                if (jsonStr != "none")
                    i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
            }

            if (jsonStr != "none") {
                if (jsonStr.indexOf('window.') != -1)
                    jsonStr = jsonStr.substring(0, jsonStr.indexOf('window.'));
                var obj = JSON.parse(jsonStr);
                if (obj.hasOwnProperty("globalData")) {
                    var productInfo = obj.globalData;

                    if (productInfo.product.hasOwnProperty("mediaItems")
                        && productInfo.product.mediaItems != null
                        && productInfo.product.mediaItems.length > 0) {
                        productInfo.product.mediaItems.forEach(function (item) {
                            if (item.hasOwnProperty("type")) {
                                if (item.type = "image"
                                    && item.hasOwnProperty("imageUrl")
                                    && item.imageUrl.hasOwnProperty("big")
                                    && !item.imageUrl.hasOwnProperty("fileName")) {
                                    images.push(item.imageUrl.big);
                                }
                            }
                        });
                    }
                }
            }

            if (images != null && images != undefined && images.length > 0) {
                resolve(images[0]);
            } else {
                reject();
            }
        } else if (platformId == 7) {
            //主图，橱窗图
            var picture = [];
            if ($('div.scroller___gCiAJ ul.items___MT9MW img') && $('div.scroller___gCiAJ ul.items___MT9MW img').length > 0) {
                for (var i = 0; i < $('div.scroller___gCiAJ ul.items___MT9MW img').length; i++) {
                    picture.push($($('div.scroller___gCiAJ ul.items___MT9MW img')[i]).attr('src'));
                }
            } else if ($('.gallery___KYLUJ .content___OJbKT img') && $('.gallery___KYLUJ .content___OJbKT img').length > 0) {
                for (var i = 0; i < $('.gallery___KYLUJ .content___OJbKT img').length; i++) {
                    picture.push($($('.gallery___KYLUJ .content___OJbKT img')[i]).attr('src'));
                }
            }
            if (picture.length > 0) {
                resolve(picture[0]);
            } else {
                reject();
            }
        } else if (platformId == 8) {
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none" && content.Info && content.Info.image && content.Info.image != null) {
                    resolve(content.Info.image);
                } else {
                    reject();
                }
            });
        } else if (platformId == 9) {
            receiveMessages({
                "Type": "Get" + platformName + "Text",
                "sourceUrl": window.location.href
            }, null, function (content) {
                if (content != "none") {
                    if (content.isBathCollect) {
                        resolve(window.location.href);
                    } else {
                        var product = JSON.parse(content);
                        if (product && product.data.product_images != null && product.data.product_images.images != null) {
                            var imageId = product.data.product_images.images[0]
                            var image = getshopeeSiteImage(imageId)
                            if (image && image != "") {
                                resolve(image);
                            } else {
                                throw new Error("未能成功获取产品主图，请重试！");
                            }
                        } else {
                            throw new Error("未能成功获取产品主图，请重试！");
                        }
                    }

                } else {
                    reject();
                }
            });
        } else if (platformId == 10) {

            var jsonStr = "none";
            var scripts = document.querySelectorAll("body > script");
            // lazada
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].innerHTML.indexOf('__moduleData__') != -1) {
                    jsonStr = scripts[i].innerHTML.split("__moduleData__ =")[1].split("};")[0];
                }

                if (jsonStr != "none")
                    i = scripts.length;//都取到值直接跳出循环，retrun中断循环会影响消息回传
            }
            var jsondata = JSON.parse(jsonStr + "}");

            if (jsondata != undefined && jsondata.data != undefined && jsondata.data.root != undefined && jsondata.data.root.fields != undefined) {
                var content = jsondata.data.root.fields;
                if (content.skuGalleries && content.skuGalleries != null) {
                    var images = [];
                    var skuGalleries = [];
                    if (Array.isArray(content.skuGalleries)) {
                        skuGalleries.push(content.skuGalleries[0]); //首页轮播主图
                    } else {
                        for (var skuKey in content.skuGalleries) {
                            for (let i = 0; i < content.skuGalleries[skuKey].length; i++) {
                                skuGalleries.push(content.skuGalleries[skuKey][i]);
                            }
                            if (skuGalleries.length > 0)
                                break;
                        }
                    }
                    images = skuGalleries.map(x => {
                        if (x.poster.indexOf("https:") == -1)
                            return "https:" + x.poster;
                        else
                            return x.poster;
                    });
                    resolve(images[0]);
                } else {
                    reject();
                }
            } else {
                reject();
            }


        } else if (platformId == 11) {
            if ($('img[class*="PicGallery--thumbnailPic--"]') && $('img[class*="PicGallery--thumbnailPic--"]').length > 0) {
                imageUrl = $('img[class*="PicGallery--thumbnailPic--"]').attr('src').split('.jpg')[0] + ".jpg";
                if (imageUrl.indexOf('http') == -1)
                    imageUrl = 'https:' + imageUrl;
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 12) {
            if (document.URL.indexOf('pifa.pinduoduo.com') >= 0) {
                var imageUrls = [];
                var imgs = document.getElementsByClassName("goods-img");
                //循环获取imgs中的src属性，并Push到imageUrl中
                for (var i = 0; i < imgs.length; i++) {
                    imageUrl = imgs[i].getAttribute("src");
                    imageUrls.push(imageUrl);
                }
                if (imageUrls.length > 0)
                    resolve(imageUrls[0]);
                else
                    reject();
            } else if (document.URL.indexOf('mobile.yangkeduo.com') >= 0) {
                var imageUrls = [];
                var divList = document.getElementsByClassName("_1bq9lpD4");
                var imgs = document.getElementsByClassName("_1bq9lpD4")[0].getElementsByTagName("img");
                if (divList.length > 0) {
                    imgs = document.getElementsByClassName("_1bq9lpD4")[1].getElementsByTagName("img");
                }
                //循环获取imgs中的src属性，并Push到imageUrl中
                for (var i = 0; i < imgs.length; i++) {
                    imageUrl = imgs[i].getAttribute("src");
                    imageUrls.push(imageUrl);
                }
                if (imageUrls.length > 0)
                    resolve(imageUrls[0]);
                else
                    reject();
            } else {
                meta = document.querySelector('meta[property="og:image"]');
                if (meta && meta.content) {
                    imageUrl = meta.content;
                    resolve(imageUrl);
                } else {
                    reject();
                }
            }
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none"
                    && content.store
                    && content.store.initDataObj
                    && content.store.initDataObj.goods) {
                    //图片
                    var imageUrls = [];
                    if (content.store.initDataObj.goods.viewImageData
                        && content.store.initDataObj.goods.viewImageData != null
                        && content.store.initDataObj.goods.viewImageData.length > 0)
                        imageUrls = content.store.initDataObj.goods.viewImageData;

                    if (content.store.initDataObj.goods.detailGallery
                        && content.store.initDataObj.goods.detailGallery != null
                        && content.store.initDataObj.goods.detailGallery.length > 0) {
                        content.store.initDataObj.goods.detailGallery.map(x => {
                            if (imageUrls.indexOf(x.url) < 0)
                                imageUrls.push(x.url);
                        });
                    }

                    if (imageUrls.length > 0)
                        resolve(imageUrls[0]);
                    else
                        reject();
                } else {
                    reject();
                }
            });
        } else if (platformId == 13) {
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none"
                    && content.PicturePanelData
                    && content.PicturePanelData.fsImgList
                    && content.PicturePanelData.fsImgList != null
                    && content.PicturePanelData.fsImgList.length > 0) {
                    //图片
                    var imageUrls = [];
                    for (let PicturePanel of content.PicturePanelData.fsImgList) {
                        if (PicturePanel.maxImageUrl)
                            imageUrls.push(PicturePanel.maxImageUrl)
                        else if (PicturePanel.displayImgUrl)
                            imageUrls.push(PicturePanel.displayImgUrl)
                    }

                    if (imageUrls.length > 0)
                        resolve(imageUrls[0]);
                    else
                        reject();
                } else {
                    reject();
                }
            });
        } else if (platformId == 14) {
            var jsonStr = "none";
            var images = [];
            var rusJs = document.getElementById('__AER_DATA__');

            jsonStr = rusJs.innerHTML;
            let interpreter = new eval5.Interpreter(window);
            let result = interpreter.evaluate('jsondata = ' + jsonStr);
            if (result != null && result.widgets != null && result.widgets.length > 0) {
                findImage: for (var i = 0; i < result.widgets.length; i++) {
                    if (result.widgets[i].widgetId.indexOf('bx/PhoneInputContextWidget/') > -1) {
                        for (let children1 of result.widgets[i].children[0].children) {
                            if (children1.widgetId.indexOf('bx/SnowStoreContextWidget/') > -1) {
                                for (let children2 of children1.children) {
                                    if (children2.widgetId.indexOf('bx/SnowProductContextWidget/0.4.20') > -1
                                        && children2.props
                                        && children2.props.gallery
                                        && children2.props.gallery != null
                                        && children2.props.gallery.length > 0) {
                                        children2.props.gallery.forEach(x => {
                                            if (images.find(item => item == x.imageUrl) == undefined)
                                                images.push(x.imageUrl);
                                        });
                                        break findImage;
                                    }


                                }
                            }
                        }
                    } else {
                        var widgetObj = findWidgetId(result.widgets[i], 'widgetId', 'bx/SnowProductContextWidget');
                        if (widgetObj != null) {
                            widgetObj.props.gallery.forEach(x => {
                                if (images.find(item => item == x.imageUrl) == undefined)
                                    images.push(x.imageUrl);
                            });
                            break findImage;
                        }
                    }
                }
            }

            if (images && images.length > 0) {
                resolve(images[0]);
            } else {
                reject();
            }
        } else if (platformId == 15) {
            if ($('img[class^="PicGallery--thumbnailPic"]') && $('img[class^="PicGallery--thumbnailPic"]').length > 0) {
                imageUrl = $('img[class^="PicGallery--thumbnailPic"]').attr('src').split('.jpg')[0] + ".jpg";
                if (imageUrl.indexOf('http') == -1)
                    imageUrl = 'https:' + imageUrl;
                resolve(imageUrl);
            } else if ($('#J_ImgBooth') && $('#J_ImgBooth').length > 0) {
                imageUrl = $('#J_ImgBooth').attr('src').split('.jpg')[0] + ".jpg";
                if (imageUrl.indexOf('http') == -1)
                    imageUrl = 'https:' + imageUrl;
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 16) {
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none"
                    && content.images
                    && content.images != null
                    && content.images.length > 0) {
                    //图片
                    var imageUrls = content.images.map(x => {
                        if (x.origin.indexOf("https:") != 0)
                            return "https:" + x.origin;
                        else
                            return x.origin;
                    });

                    if (imageUrls.length > 0)
                        resolve(imageUrls[0]);
                    else
                        reject();
                } else {
                    reject();
                }
            });
        } else if (platformId == 17) {
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none" && content.mainImg != undefined && content.mainImg != null && content.mainImg.length > 0) {
                    resolve(content.mainImg[0]);
                } else {
                    reject();
                }
            });
        } else if (platformId == 18) {
            receiveMessages({"Type": "Get" + platformName + "Text"}, null, function (content) {
                if (content != "none" && content.product && content.product.imageList && content.product.imageList != null && content.product.imageList.length > 0) {
                    var imageUrls = content.product.imageList.map(x => {
                        if (x.indexOf("https://img13.360buyimg.com/n1/s350x467_") != 0)
                            return "https://img13.360buyimg.com/n1/s350x467_" + x;
                        else
                            return x;
                    });
                    resolve(imageUrls[0]);
                } else {
                    reject();
                }
            });
        } else if (platformId == 19) {
            let jsondata = JSON.parse($(document).find("#__NEXT_DATA__")[0].innerText);
            if (jsondata
                && jsondata != null
                && jsondata.props
                && jsondata.props.pageProps
                && jsondata.props.pageProps.initialData
                && jsondata.props.pageProps.initialData.data
                && jsondata.props.pageProps.initialData.data.product
                && jsondata.props.pageProps.initialData.data.product.imageInfo
                && jsondata.props.pageProps.initialData.data.product.imageInfo.allImages
                && jsondata.props.pageProps.initialData.data.product.imageInfo.allImages.length > 0) {
                resolve(jsondata.props.pageProps.initialData.data.product.imageInfo.allImages[0].url);
            } else {
                reject();
            }

        } else if (platformId == 20) {
            meta = document.querySelector('meta[property="og:image"]');
            if (meta && meta.content) {
                imageUrl = meta.content;
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 21) {
            if (document.querySelector('._2AOclWz7')) {
                imageUrl = document.querySelector('._2AOclWz7').children[0].firstChild.attributes.src.value
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 23) {
            resolve(window.location.href)
            // const swiperWrapper = document.querySelector('.swiper-wrapper');
            // if (swiperWrapper) {
            //  const images = swiperWrapper.querySelectorAll('img');
            //    for (let i = 0; i < images.length; i++) {
            //        const image = images[i];
            //       if (image.attributes.ytimg) {
            //         const imageUrl = image.attributes.ytimg.value;
            //         break;
            //       }
            //    }
            //    if(imageUrl.indexOf("http")!=0){
            //      imageUrl="https:"+imageUrl;
            //    }
            //    resolve(imageUrl);
            //   }  
            // else{
            //  reject();
            //  }
        } else if (platformId == 24) {
            if (document.querySelector('.tb-thumb-item')) {
                if (document.querySelector('.tb-thumb-item > a').children[0].attributes.big) {
                    imageUrl = document.querySelector('.tb-thumb-item > a').children[0].attributes.big.value
                } else {
                    imageUrl = document.querySelector('.tb-thumb-item > a').children[0].attributes.src.value
                }
                if (imageUrl.indexOf("http") != 0) {
                    imageUrl = "https:" + imageUrl;
                }
                resolve(imageUrl);
            } else {
                reject();
            }

        } else if (platformId == 25) {
            resolve(window.location.href)
            //             if(document.querySelector('#photoSmall')){
            //                 if($(document.querySelector('#photoSmall')).find("img")[0].attributes.alt){
            // imageUrl = $(document.querySelector('#photoSmall')).find("img")[0].attributes.alt.value
            //                 }else{
            // imageUrl = $(document.querySelector('#photoSmall')).find("img")[0].attributes.src.value
            //                 }
            //                if(imageUrl.indexOf("http")!=0){
            //                  imageUrl="https:"+imageUrl;
            //                }

            //                resolve(imageUrl);
            //             }else{
            //                   reject();
            //             }

        } else if (platformId == 26) {
            if (document.querySelector('.bimg-inner')) {
                const images = document.querySelectorAll('.bimg-inner');
                for (let i = 0; i < images.length; i++) {
                    const image = images[i];
                    if (image.attributes["data-imgurl"]) {
                        imageUrl = image.attributes["data-imgurl"].value;
                        break;
                    }
                }
                if (imageUrl.indexOf("http") != 0) {
                    imageUrl = "https:" + imageUrl;
                }
                resolve(imageUrl);
            } else {
                reject();
            }

        } else if (platformId == 27) {
            if (document.querySelector('#image-gallery')) {
                const images = document.querySelectorAll('#image-gallery')[0].querySelectorAll("a");
                for (let i = 0; i < images.length; i++) {
                    const image = images[i];
                    if (image.attributes["href"]) {
                        imageUrl = image.attributes["href"].value;
                        break;
                    }
                }
                if (imageUrl.indexOf("http") != 0) {
                    imageUrl = "https:" + imageUrl;
                }
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 22) {
            if (document.querySelector('.ui-pdp-gallery__column')) {
                const galleryColumns = document.querySelector('.ui-pdp-gallery__column');

                const wrapper = galleryColumns.querySelector('.ui-pdp-gallery__wrapper');
                if (wrapper) {
                    const figure = wrapper.querySelector('figure');
                    if (figure) {
                        const img = figure.querySelector('img');
                        if (img) {
                            imageUrl = img.getAttribute('src');
                        }
                    }
                }
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 28) {
            if (document.querySelector('.small-img-item')) {
                const imagesli = document.querySelectorAll('.small-img-item');
                for (let i = 0; i < imagesli.length; i++) {
                    const image = imagesli[i].querySelector('a');
                    if (image && image.attributes["href"]) {
                        imageUrl = image.attributes["href"].value;
                        break;
                    }
                    const imageLable = imagesli[i].querySelector('img');
                    if (imageLable && imageLable.attributes['data-url']) {
                        imageUrl = imageLable.attributes["data-url"].value;
                        break;
                    }

                }
                if (imageUrl.indexOf("http") != 0) {
                    imageUrl = "https:" + imageUrl;
                }
                resolve(imageUrl);
            } else {
                reject();
            }

        } else if (platformId == 29) {
            resolve(window.location.href)
        } else if (platformId == 30) {
            var picElement = document.querySelector(".image-carousel-container");
            if (picElement) {
                imageUrl = picElement.querySelectorAll("li")[0].querySelector("img").getAttribute("src")
                resolve(imageUrl);
            } else {
                reject();
            }
        } else if (platformId == 35) {
            var imgElement = document.querySelector(".j-zoom-image");
            if (imgElement) {
                var imgArr = Array.from($('.j-zoom-image').map(function () {
                    return $(this).attr('src')
                }));
                resolve(imgArr[0].replace("/c246x328/", "/big/").replace(".webp", ".jpg"));
            } else {
                reject();
            }
        } else if (platformId == 32) {
            var tiktokImgElement = document.querySelector(".slick-slide.slick-active.slick-current");
            if (tiktokImgElement) {
                let tiktokImgUrl = tiktokImgElement.querySelector('img').getAttribute("src");
                resolve(tiktokImgUrl);
            } else {
                reject();
            }
        } else if (platformId == 36) {
            let gigab2bImgElement = document.querySelector("#image-show .el-image img");
            if (gigab2bImgElement) {
                let gigab2bImgUrl = gigab2bImgElement.getAttribute("src");
                resolve(gigab2bImgUrl);
            } else {
                reject();
            }
        } else if(platformId == 39){
            let scripts = document.querySelectorAll('script');
            let matchingScripts = Array.from(scripts).filter(script => script.textContent.includes('window.skuInfo'));
            if(matchingScripts.length>0)
            {
                let scriptContent = matchingScripts[0].textContent;
                let jsonMatch = scriptContent.match(/window\.skuInfo\s*=\s*({.*?});/);

                if (jsonMatch) {
                    // 解析 JSON 对象
                    let skuInfoJson = JSON.parse(jsonMatch[1]);
                    imageList=skuInfoJson.images.urls;
                    let decodedUrl = decodeURIComponent(imageList[0]);
                    resolve(decodedUrl);
                }
            }else{ reject();}
        } else if (platformId == 38) {
            let sheinImgBoxElement = document.querySelector(".crop-image-container");
            let sheinImgElement = sheinImgBoxElement.querySelector('img');
            if (sheinImgElement) {
                let sheinImgUrl = "https:" + sheinImgElement.getAttribute("src");
                resolve(sheinImgUrl);
            } else {
                reject();
            }
        } else if(platformId == 41){
            let images = document.querySelector('.proimg-container').querySelectorAll("img");
            if(images.length>0){
                resolve(images[0].getAttribute("src"));
            }else{
                reject();
            }

        } else if(platformId == 42){
            var imgElement = document.querySelector('button._2AXg-._2nLTP._355_d img');
            if (imgElement) {
                var imgSrc = imgElement.src;
                resolve(imgSrc);
            } else {
                reject();
            }   
        } else if (platformId == 43) {
            var imgElement = document.querySelector("#zoom img");
            if (imgElement) {
                var imgSrc = imgElement.getAttribute('src');
                resolve(imgSrc);
            } else {
                reject();
            }
        }  
        else if (platformId == 44) {
            let images = document.querySelector('.swiper-slide').querySelectorAll("img");
            if(images.length>0){
                resolve(images[0].getAttribute("src"));
            }else{
                reject();
            }
        } 
        else {
            GrowlNotification.notify({
                title: '温馨提示',
                description: "未能成功获取产品主图，请重试！",
                type: "error",
                position: 'top-right',
                closeTimeout: 3000,
                image: {visible: true, customImage: config.logoBase64},
            });
        }
    });
    getImage.then(imageUrl => {
        findGoods(platformId, platformName, imageUrl);
    }).catch(e => {
        if ($("#51selling_findgoods").attr('disabled'))
            $("#51selling_findgoods").removeAttr("disabled");
        $("#51selling_findgoods").text('AI精铺上品');
        GrowlNotification.notify({
            title: '温馨提示',
            description: '发生错误！未能成功获取图片地址，请稍后重试！',
            type: 'error',
            position: 'top-right',
            closeTimeout: 3000,
            image: {visible: true, customImage: config.logoBase64},
        });
    });
}

if (document.contentType === 'text/html') {
    if (window.location.href.indexOf('shopee.') !== -1 || window.location.href.indexOf('tw.shopeesz.com') !== -1 || window.location.href.indexOf('xiapibuy.com') !== -1) {
        $(document).off('DOMNodeInserted', '#main')
            .on('DOMNodeInserted', '#main', function () {
                ShowBottomMenu();
            });
    }
}
var CONFIG, OPTIONS = {}, isshowBox = true;
var crawlShow = null;
//调用方法创建悬浮窗
ShowBottomMenu();

function ShowBottomMenu() {
    var hrefUrl = window.location.href;
    var platformInfo = MatchingPlatform(hrefUrl);
    var downloadHtml = '';
    var width = '238px';
    if (hrefUrl.indexOf('detail.1688.com') > 0) {
        // downloadHtml = '<button type="button" id="wyysDownLoadVideo" style="font-size:13px;background-color: #0037ff3d;border-color: #0037ff3d;color: #FFF;font-weight: 300;text-decoration: none;text-align: center;line-height: 30px;height: 30px;padding: 0 20px;display: inline-block;appearance: none;cursor: pointer;border: none;border-radius:30px;margin-left: 5px;" >下载视频</button>';
        width = '238px';
    }
    if (platformInfo.PlatformId > 0) {
        if (platformInfo.CrawlType == "detail") {
            if (platformInfo.PlatformId == 9) {
                if (hrefUrl.indexOf('product/') == -1 && hrefUrl.indexOf('-i.') == -1) {
                    isshowBox = false
                    if (crawlShow != null) {
                        crawlShow.close();
                        crawlShow = null;
                    }
                    return;
                } else {
                    isshowBox = true
                }
            }
            // if (platformInfo.PlatformId === 21) {
            //     if (/-g-[0-9]*\.html/.test(hrefUrl) || hrefUrl.indexOf('goods.html') !== -1 || hrefUrl.indexOf('psurl.html') !== -1 || hrefUrl.indexOf('goods_id') !== -1) {
            //         isshowBox = true
            //     } else {
            //         isshowBox = false
            //     }
            // }
            // if(hrefUrl.includes('ozon.ru')){
            // 	if (platformInfo.PlatformId == 29 || platformInfo.PlatformId == 30 || platformInfo.PlatformId == 27) {
            // 		isshowBox = platformInfo.isDetail
            // 	}
            // }else{
            // 	isshowBox = false
            // }
            if (isshowBox && crawlShow == null) {
                crawlShow = GrowlNotification.notify({
                    description: '<button type="button" id="51selling_findgoods" title="进入AI精铺上品" style="width:132px;height:36px;padding:0 16px;display:inline-flex;align-items:center;justify-content:center;appearance:none;cursor:pointer;border:0;border-radius:8px;background:#f59e0b;color:#fff;font-size:13px;font-weight:700;line-height:1;white-space:nowrap;box-shadow:0 2px 6px rgba(245,158,11,.24);transition:background-color .15s ease,box-shadow .15s ease,transform .15s ease;">AI精铺上品</button>' + downloadHtml,
					position: 'bottom-left',
                    closeWith: "button",
                    image: {visible: true, customImage: config.logoBase64},
                    width: width,
                    type: "info"
                });
                crawlShow.getContent().addClass('panda-ai-entry-notification');
                var aiEntryNode = crawlShow.getContent().get();
                aiEntryNode.style.width = '228px';
                aiEntryNode.style.minHeight = '64px';
                var aiEntryBody = aiEntryNode.querySelector('.growl-notification__body');
                var aiEntryImage = aiEntryNode.querySelector('.growl-notification__image');
                var aiEntryContent = aiEntryNode.querySelector('.growl-notification__content');
                var aiEntryDesc = aiEntryNode.querySelector('.growl-notification__desc');
                if (aiEntryBody) { aiEntryBody.style.minHeight = '64px'; aiEntryBody.style.padding = '9px 18px'; }
                if (aiEntryImage) aiEntryImage.style.marginRight = '14px';
                if (aiEntryContent) { aiEntryContent.style.flex = '1'; aiEntryContent.style.minWidth = '0'; }
                if (aiEntryDesc) { aiEntryDesc.style.display = 'flex'; aiEntryDesc.style.alignItems = 'center'; }
            }


        } else {
            GrowlNotification.notify({
                description: '<button platformId=' + platformInfo.PlatformId + ' platformName="' + platformInfo.PlatformName + '" type="button" style="margin-right:3px;font-size:13px; background-color: #1B9AF7;border-color: #1B9AF7;color: #FFF;font-weight: 300;text-decoration: none;text-align: center;line-height: 30px;height: 30px;padding: 0 20px;display: inline-block;appearance: none;cursor: pointer;border: none;border-radius:30px;" id="51selling_collectioncategory">开始采集</button>',
                position: 'bottom-left',
                closeWith: "button",
                image: {visible: true, customImage: config.logoBase64},
                width: '300px',
                type: "info"
            });
        }

        //if ($('#51selling_sandbox').length <= 0) {
        //    var htmlPath = chrome.runtime.getURL('/html/sandbox.html');
        //    var iframeStr = `<iframe src="${htmlPath}" id="51selling_sandbox" style="display: none"></iframe>`;
        //    $('body').append(iframeStr);
        //}
    }
}

if (document.contentType === 'text/html') {
    chrome.storage.sync.get({}, function (data) {
        OPTIONS = data;
        preload();
    });
}

function preload() {
    //匹配平台
    var linkrule = getLinkRule(location.href);
    try {
        CONFIG = linkrule;
        handleLinks(CONFIG.detail);
        $(window).scroll(debounceHandleLinks);
    } catch (e) {
        return;
    }
}

var debounceHandleLinks = debounce(function () {
    if (CONFIG && CONFIG.detail) {
        handleLinks(CONFIG.detail);
    }
}, 500);

//过滤超链接，将满足条件的图片上加上采集按钮
//fnBody 过滤方法的方法体
function handleLinks(fnBody) {
    //嵌套方法处理单个链接
    function handleLink(index, a) {
        if (a.dataset.wyysStatus === 'ready') return;
        var href = a.href;
        //如果是相对地址，浏览器会自动变成完整地址。
        //getAttribute获取的是原始地址
        if (!href && location.href.indexOf("aliexpress.") !== -1 && $(a).attr('data-href') !== undefined)
            href = 'https:' + $(a).attr('data-href');
        if (!href) return;
        if (a.getAttribute('href') === '#' || a.getAttribute('href') === '#none') return;
        if (href.indexOf('javascript:') === 0) return;
        // if (href.indexOf('//') === 0) href = location.protocol + href;
        if (href.indexOf('/') === 0) href = location.protocol + href;
        if (href.indexOf('item-img') !== -1) return;
        if (href.indexOf('bid=') !== -1 && href.indexOf("/product") == -1) return;

        try {
            //将链接与后台返回的规则进行匹配
            var test = fnBody(href);
            var localHref = window.location.href;
            if ((localHref.indexOf('joom.com') !== -1 || localHref.indexOf('temu.com') !== -1 || localHref.indexOf('alibaba.com') !== -1 || localHref.indexOf('tmall.com') !== -1) && test) {
                var $a = $(a);
                insertFetchBtn($a, href, '', localHref);
                a.dataset.wyysStatus = 'ready';
            } else if (test && localHref.indexOf('walmart.com') !== -1) {
                var $a = $(a);
                if ($a.parent().attr("data-item-id")) {
                    insertFetchBtn($a, href, '', localHref);
                    a.dataset.wyysStatus = 'ready';
                }
            } else if (test && localHref.indexOf("shopee.")) {
                if (href.indexOf('help.tw.shopeesz.com') !== -1 || href.indexOf('seller.tw.shopeesz.com') !== -1 || href.indexOf("seller.shopee.com") !== -1) return;
                var $a = $(a);
                insertFetchBtn($a, href, '', localHref);
                a.dataset.wyysStatus = 'ready';
            } else if (test && (validArea(a) || (href.indexOf("banggood.com") !== -1 && href.indexOf("pid=") === -1))) {
                var $a = $(a);
                insertFetchBtn($a, href, '', localHref);
                a.dataset.wyysStatus = 'ready';
            }

        } catch (e) {
            //console.log(e);
        }
    }

    //遍历页面所有的链接,如果满足条件，则加上导入按钮
    $.each(document.links, handleLink);

    //速卖通需要处理href属性隐藏且列表异步加载的特殊情况
    if (location.href.indexOf("aliexpress.") !== -1)
        $.each(document.querySelectorAll('a:not([href])'), handleLink);


}

/*
 根据a自动插入采集按钮
 $a 超链接元素
 url 超链接地址
 */

function setUrl(href) {

}

function insertFetchBtn($a, url, status, localHref) {
    var $body = $('body'), $crawl;
    $a.addClass('wyys-link'); //头部悬浮01
    //$a.parent().addClass('wyys-link-box');
    $crawl = $('<span class="wyys-link-next" data-url=""><span class="wyys-link-con-box wyysLinkConBox"><span class="wyys-link-con wyysLinkCon">采到无忧</span></span></span>').insertAfter($body);

    var mouseenterFn = function (event) {
        var $firstImg = /*$a.find('img:first-child') */getCrawlANode($a),
            href = '',
            crawlTop, crawlLeft, firstImgTop, firstImgLeft,
            pos, top, left;
        if (status === 'hy') $firstImg = $a;
        href = $a.attr('href');
        if (localHref.indexOf('walmart.com') != -1 || localHref.indexOf('temu.com') != -1 || localHref.indexOf('yiwugo.com') != -1 || localHref.indexOf('vvic.com') != -1 || localHref.indexOf('wsy.com') != -1 || localHref.indexOf('onbuy.com') != -1) {
            href = CONFIG.setUrl(href)
        }
        if ((href.indexOf("/gp/") != -1 || href.indexOf("/dp/") != -1) && href.indexOf("www.amazon.") == -1 && localHref.indexOf("www.amazon.") != -1) {
            var siteUrl = localHref.substring(localHref.indexOf("https://") + 8);
            siteUrl = "https://" + siteUrl.substring(0, siteUrl.indexOf("/") + 1);
            href = siteUrl.substring(0, siteUrl.length - 1) + href;
        }
        if (location.href.indexOf("shopee.") !== -1 && href.indexOf("shopee.") === -1) {
            href = 'https://' + location.host + href;
        } else if (location.href.indexOf("tw.shopeesz.com") !== -1 && href.indexOf("tw.shopeesz.com") === -1) {
            href = 'https://tw.shopeesz.com' + href;
        } else if (location.href.indexOf("xiapibuy.com") !== -1 && href.indexOf("xiapibuy.com") === -1) {
            href = 'https://' + location.host + href;
        } else if (!href && location.href.indexOf("aliexpress.") !== -1 && $a.attr('data-href') !== undefined) {
            href = 'https:' + $a.attr('data-href');
        } else if (location.href.indexOf("pifa.pinduoduo.com") !== -1) {
            href = 'https://pifa.pinduoduo.com' + href;
        }else if(location.href.indexOf("fruugo.") !== -1||location.href.indexOf("fruugoaustralia.") !== -1){
            href=location.origin+href;
        }else if(location.href.indexOf("saleyee.") !== -1){
            href=location.origin+href;
        }
        else if(location.href.indexOf("91jf.") !== -1){
            href = "https://detail.91jf.com" + href;
        }

        crawlTop = $crawl.offset().top;
        crawlLeft = $crawl.offset().left;
        if ($firstImg.length > 0) {
            firstImgTop = $firstImg.offset().top;
            firstImgLeft = $firstImg.offset().left;
            if ($firstImg.width() > 50)
                firstImgLeft += 20;
        } else {
            firstImgTop = $a.offset().top;
            firstImgLeft = $a.offset().left;
            if ($a.width() > 50)
                firstImgLeft += 20;
        }
        firstImgLeft ? left = firstImgLeft : left = crawlLeft;
        firstImgTop ? top = firstImgTop - 21 : top = crawlTop - 21;
        if (window.location.host.indexOf('temu.com') != -1) {
            top = $a.offset().top;
        }
        if ($crawl.attr('data-url') !== href) {
            $crawl.removeClass('success').attr({'data-url': href}).find('.wyysLinkCon').text('采到无忧');
        }

        $crawl.css({
            'top': top,
            'left': left,
            'opacity': 1,
            'transition': 'opacity 0.1s',
            '-moz-transition': 'opacity 0.1s',
            '-webkit-transition': 'opacity 0.1s',
            '-o-transition': 'opacity 0.1s',
            'pointer-events': 'auto'
        });
    };

    var mouseleaveFn = function (event) {
        $crawl.css({
            'opacity': 0,
            'transition': 'opacity .5s',
            '-moz-transition': 'opacity .5s',
            '-webkit-transition': 'opacity .5s',
            '-o-transition': 'opacity .5s',
            'pointer-events': 'none'
        });
    };

    if (localHref.indexOf('temu.com') !== -1) {
        $a.closest('.goods-container').on('mouseenter', function () {
            mouseenterFn();
        });
        $a.closest('.goods-container').on('mouseleave', function () {
            mouseleaveFn();
        });
    }
    $a.on('mouseenter', function () {
        mouseenterFn();
    });
    $a.on('mouseleave', function () {
        mouseleaveFn();
    });

    //列表页的单个产品图片上的采集按钮
    $crawl.click(function () {
        if ($('.wyys-notify').length > 0) $('.wyys-notify').remove();
        var $span = $(this);

        var fastCrawl = function () {
            if ($('[data-action="shopeebatch"]').length) $('[data-action="shopeebatch"]').removeAttr('data-action');

            sendMessageToBackgroudScript({
                "Type": "CollectionGoods",
                "IsVerifyDuplicate": true,
                "link": url
            }, function (response) {
                setTimeout(() => {
                    $span.find('.wyysLinkConBox .wyysLinkCon').text('采到无忧');
                }, 2000)
            });
        }

        if (!$span.hasClass('success')) {
            if (url.indexOf('haiyingshuju.com') == -1 && url.indexOf("detail.tmall.com") == -1)
                url = $span.attr('data-url');

            if (url.indexOf('http') == -1) {
                if(window.location.host == "www.gigab2b.com" || window.location.host.indexOf("shein.") !== -1){
                    url = window.location.origin + "/" + url
                } else if (window.location.host == "www.wish.com" || window.location.host == "www.joom.com" || window.location.host == "www.joom.ru" || window.location.host == "www.go2.cn") {
                    url = window.location.origin + url
                } else if (window.location.host.indexOf("yandex.ru") > -1) {
                    url = window.location.origin + url
                } else {
                    url = "https:" + url
                }
            }
            $span.find('.wyysLinkConBox .wyysLinkCon').text('采集中...');
            if ((url.indexOf('shopee.') !== -1 || url.indexOf('xiapibuy.') !== -1) && !$('[data-action="shopeebatch"]').length) {
                $span.attr('data-action', 'shopeebatch');
                if ($('#shopeeIframeBox').length) {
                    $('#shopeeIframeBox').attr('src', url);
                } else {
                    $('<iframe id="shopeeIframeBox" src="' + url + '"' +
                        ' style="width: 100%; height: 300px;" scrolling="auto" frameborder="0"></iframe>').appendTo('body');
                    setTimeout(() => {
                        if (!window['_LiSellingShopeeSign_']) {
                            fastCrawl();
                        }
                    }, 2000)
                }
            } else {
                fastCrawl();
            }
        }
    });
}

var getCrawlANode = function ($a) {
    var $imgNode = $a.find('img').first();

    if (window.location.href.indexOf('www.chinavasion.com') > -1) {
        if ($a.children('img').length) {
            $imgNode = $a.children('img');
        } else {
            $imgNode = $a.children('span');
        }
    }
    if (window.location.href.indexOf('www.walmart.com') > -1) {
        $imgNode = $a.parent();
    }

    //修复一些用背景代替图片的情况
    if (!$imgNode.length && $a.find('div').prop('style') && $a.find('div').prop('style').background) $imgNode = $a.find('div');

    return $imgNode;
};

//当前链接是否为有效链接
function validArea(a) {
    var $a = $(a);
    return $a.find('img').length || $a.css('background-image') !== 'none' || $a.html().indexOf('background') !== -1;
}

function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}


//重定向框
function ShowRedirectSiteBox(message, messageType, site) {
    GrowlNotification.notify({
        title: '温馨提示',
        description: message,
        type: messageType,
        position: 'top-center',
        closeTimeout: 0,
        closeWith: "button",
        image: {visible: true, customImage: config.logoBase64},
        showButtons: true,
        buttons: {
            action: {
                text: '确认',
                callback: function () {
                    window.open(site);
                }
            },
            cancel: {
                text: '取消',
                callback: function () {
                }
            }
        }
    });
}

//单个采集
$(document).off('click', '#collectiongoodsku').on('click', '#collectiongoodsku', function () {
    $("#collectiongoodsku").attr({"disabled": "disabled"}).text("处理中");
    sendMessageToBackgroudScript({
        "Type": "CollectionGoodsku",
        "IsVerifyDuplicate": true,
        "link": window.location.href
    }, function (response) {
        if (chrome.runtime.lastError) {
            $("#collectiongoodsku").removeAttr("disabled").text("采集SKU");
            ShowRedirectSiteBox("采集SKU失败：" + chrome.runtime.lastError.message + "，请重新加载插件后重试", "error", config.url.domain());
        }
    });
});

$(document).off('click', '#selling_collectiongoods').on('click', '#selling_collectiongoods', function () {
    sendMessageToBackgroudScript({
        "Type": "CollectionGoods",
        "IsVerifyDuplicate": true,
        "link": window.location.href
    }, function (response) {
    });
});
$(document).off('click', '#checkUrl').on('click', '#checkUrl', function () {
    if (Crawl.CarwlDetailErrorUrl.length > 0) {
        $('#wyysCopyUrl').val(Crawl.CarwlDetailErrorUrl.join('\n'));
        $('#wyysCopyUrl').select();
        document.execCommand('copy');
    }
});
$(document).off('click', 'input[name="curPage"]').on('click', 'input[name="curPage"]', function () {
    if (this.checked) {
        $("input[name='sourceUrlRepeat']").each(function () {
            $(this).prop("checked", true);
        });
    } else {
        $("input[name='sourceUrlRepeat']").each(function () {
            $(this).prop("checked", false);
        });
    }
});
//跳过采集
$(document).off('click', '.repeatCrawDefaultBtn').on('click', '.repeatCrawDefaultBtn', function () {
    wyysModal.hide('#wyysCategoryCollectRepeatCrawlModal');
});
$(document).off('click', '#collected').on('click', '#collected', function () {

    let localSite = config.url.domain() + '/main#/collectbox';
    window.open(localSite, "_blank");
});
//重复采集
$(document).off('click', '#submitRepeatCrawl').on('click', '#submitRepeatCrawl', function () {
    var sourceUrls = getCheckBoxValByName("sourceUrlRepeat");
    if (!sourceUrls) {
        receiveMessages({
            "Type": "Alter",
            "Message": "请至少选择一个产品进行采集",
            "MessageType": "error"
        }, null, function (res) {
        })
        return;
    } else {
        wyysModal.hide('#wyysCategoryCollectRepeatCrawlModal');
        var data = sourceUrls.split(",");
        //重置进度条和结果显示,发起请求
        Crawl.categoryCrawlTotalNum = data.length;
        Crawl.CarwlDetailErrorNum = 0;
        Crawl.CarwlDetailErrorUrl = [];
        Crawl.CarwlDetailSuccessNum = 0;
        Crawl.CarwlDetailExcuteNum = 0;
        Crawl.repeatDataList = [];
        receiveMessages({"Type": "SetCategoryProgress", "ProcessType": 0}, null, function (res) {
        })
        data.forEach(function (item) {
            sendMessageToBackgroudScript({
                "Type": "CollectionRepeatGoods",
                "IsVerifyDuplicate": false,
                "link": item
            }, function (response) {
                if (response.MessageType && response.MessageType == "success") {//采集成功
                    receiveMessages({"Type": "SetCategoryProgress", "ProcessType": 2}, null, function (response) {
                    });

                } else {
                    receiveMessages({
                        "Type": "SetCategoryProgress",
                        "ProcessType": 3,
                        "url": item
                    }, null, function (response) {
                    });
                }
            });
        })

    }
});

function getCheckBoxValByName(name) {
    var s = "";
    $("input[name='" + name + "']:checked").each(function () {
        var v = $(this).val();
        if (v.indexOf(",") > -1) v = v.replace(/,/g, "");
        if (s != "") s = s + ",";
        s = s + v;
    });
    return s;
}

//类目批量采集
$("#51selling_collectioncategory").click(function () {
    Crawl.categoryCrawlTotalNum = 0;
    Crawl.categoryCrawlCountNum = 0;
    Crawl.CarwlDetailErrorNum = 0;
    Crawl.CarwlDetailErrorUrl = [];
    Crawl.CarwlDetailSuccessNum = 0;
    Crawl.categoryDataList = [];
    Crawl.repeatDataList = [];
    let localSite = config.url.domain() + '/main#/collectbox';
    //显示采集结果框
    var bodyDom = '<div class="wyys-modal-body" style="padding:0 10px;overflow:hidden;height:115px;min-height:115px;">',
        linkUrlDom = '<a class="wyys-m-left20 wyys-aLable" id="checkUrl" href="javascript:"><span class="copy-icon wyys-m-right10">' +
            '</span>复制失败链接</a><textarea id="wyysCopyUrl" style="position:relative;top:-3000px;width:100px;height:10px;"></textarea>';
    var collectionProgressModal = '<div class="wyys-modal msg-modal" style="margin-right:40px;margin-bottom:10px;" id="wyysCategoryCollectMsgModal">' +
        '<span class="wyysCount wyys-hide">0</span><span class="wyysTotalCount wyys-hide"></span>' +
        '<div class="wyys-modal-dialog">' +
        '<div class="wyys-modal-content">' +
        '<div class="wyys-modal-head">' +
        '<span class="wyys-modal-head-title">采集分类</span>' +
        '<span class="wyys-modal-head-close">&times;</span></div>' +
        bodyDom +
        '<div class="wyys-m-top10"><span class="craw-progress"><span class="craw-progress-bar progress-bar-success crawProgressBar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0;"></span></span><span class="craw-progress-info"><span class="completionNum">0</span>&nbsp;/&nbsp;<span class="wyysTotalNum">0</span></span></div>' +
        '<div class="wyys-m-top10 wyys-m-bottom10 wyysCategoryCrawlNumBox">采集成功：<span class="wyys-f-blue ">0</span></div>' +
        '<div class="wyys-m-top10 wyys-m-bottom10 wyysCategoryCrawlNumBox">采集失败：<span class="wyys-f-red wyysFail ">0</span>' +
        linkUrlDom +
        '</div>' +
        '</div><div class="wyys-modal-foot"><button type="button" class="wyys-btn wyys-btn-primary"><a id="collected" class="wyys-white" style="color: #fff !important;">查看已采集数据</a></button></div></div></div></div>';
    $('<div></div>').html(collectionProgressModal).appendTo('body');
    //重复产品采集弹框
    var repeatCrawlModal = $('<div class="wyys-modal center middle repeat-crawl-pro" id="wyysCategoryCollectRepeatCrawlModal"><div class="wyys-modal-dialog"><div class="wyys-modal-content"><div class="wyys-modal-head"><span class="wyys-modal-head-title">重复采集</span><span class="wyys-modal-head-close repeatCrawDefaultBtn">&times;</span></div><div id="repeatCrawlModalContent" class="repeatCrawlModalContent wyys-modal-body wyys-p10 repeat-crawl-modal-content"><div class="repeat-crawl-warn wyys-f15" id="repeatCrawlWarn"><span class="wyys-gray-c">重复采集提示：以下产品在系统中已有采集记录，若需要再次采集请手动勾选。</span></div><div class="wyys-m-top10 wyys-table-modal-box"><table class="wyys-table-modal"></table></div></div><div class="wyys-modal-foot"><div class="craw-fr"><button type="button" class="wyys-btn wyys-btn-primary" id="submitRepeatCrawl">确认采集</button><button type="button" class="wyys-btn wyys-btn-default wyys-m-left10 repeatCrawDefaultBtn">跳过</button></div></div></div></div>');
    var tableThead = '<thead><tr><th class="has-ipt"><input name="curPage" id="wyys_checkbox" type="checkbox" onclick=""/></th><th class="img-box">图片</th><th class="wyys-f-left">标题</th></tr></thead>';
    var tableTbody = '<tbody id="repeatValue"><tbody>';
    var tableCon = tableThead + tableTbody;
    repeatCrawlModal.find('.wyys-table-modal').append(tableCon);
    $('<div></div>').append(repeatCrawlModal).appendTo('body');

    var platformId = Number($(this).attr("platformId"));
    var platformName = $(this).attr("platformName");
    sendMessageToBackgroudScript({
        "Type": "CollectionCategory",
        "PlatformId": platformId,
        "PlatformName": platformName
    }, function (response) {
        $(".growl-notification__close").click();
        var $msgModal = $('#wyysCategoryCollectMsgModal');
        $msgModal.find('.wyys-f-blue').text(0);
        $msgModal.find('.wyysFail').text(0);
        $msgModal.find('.wyysCount').text();
        $msgModal.find('.wyystotalCount').text();
        wyysModal.show('#wyysCategoryCollectMsgModal');
    });
});
$('#wyysDownLoadVideo').click(function () {
    var $video = $('video'),
        videoSrc = $video.length ? $video[0].src : '';
    if (videoSrc) {
        window.open(videoSrc, '_blank');
    } else {
        notify('当前商品无视频！', 'error');
    }
});
(function syncPandaMerchantAuth() {
    try {
        var host = location.hostname.toLowerCase();
        if (host !== 'sczfai.com' && host !== 'www.sczfai.com' && host !== '8.137.211.255') return;
        if (!chrome || !chrome.runtime || !chrome.runtime.sendMessage) return;
        var lastToken = '';
        function readUser() {
            try { return JSON.parse(localStorage.getItem('current_user') || 'null'); } catch (error) { return null; }
        }
        function sync() {
            var token = localStorage.getItem('token') || localStorage.getItem('panda_admin_token') || '';
            if (token === lastToken) return;
            lastToken = token;
            chrome.runtime.sendMessage({
                action: 'pandaAuthSync',
                token: token,
                user: readUser(),
                source_url: location.href
            }, function() { void chrome.runtime.lastError; });
        }
        sync();
        setInterval(sync, 3000);
        window.addEventListener('storage', sync);
    } catch (error) {}
})();

function isPandaAi1688Source(url) {
    try {
        var parsed = new URL(String(url || ''));
        var hostname = parsed.hostname.toLowerCase().replace(/^www\./, '');
        return (hostname === '1688.com' || hostname.endsWith('.1688.com')) && /\/offer\/\d+/i.test(parsed.pathname);
    } catch (error) {
        return false;
    }
}

function openPandaAiListingFromCurrentPage() {
    var currentUrl = document.URL || window.location.href || '';
    var aiUrl = config.url.domain() + '/pages/ai-premium-listing.html';
    if (isPandaAi1688Source(currentUrl) && typeof window.__QYDZ_1688_AI_PREMIUM_COLLECT__ === 'function') {
        window.__QYDZ_1688_AI_PREMIUM_COLLECT__();
        return;
    }
    try {
        var target = new URL(aiUrl);
        target.searchParams.set('entry', 'plugin');
        if (isPandaAi1688Source(currentUrl)) target.searchParams.set('source_url', currentUrl);
        else target.searchParams.set('from_url', currentUrl);
        window.open(target.href, '_blank');
    } catch (error) {
        window.open(aiUrl, '_blank');
    }
}

$(document).off('click', '#51selling_findgoods').on('click', '#51selling_findgoods', function () {
    try {
        $("#51selling_findgoods").text('打开中');
        openPandaAiListingFromCurrentPage();
    } catch (e) {
        GrowlNotification.notify({
            title: '温馨提示',
            description: '打开熊猫AI精铺上品失败，请前往sczfai.com/pages/ai-premium-listing.html',
            type: 'error',
            position: 'top-right',
            closeTimeout: 3000,
            image: {visible: true, customImage: config.logoBase64},
        });
    } finally {
        setTimeout(function () {
            $("#51selling_findgoods").text('AI精铺上品');
        }, 500);
    }
});


function findGoods(platformId, platformName, imageUrl) {
    var needUploadPlatform = [1, 2, 4, 7, 8, 10, 13, 16, 17, 19, 20, 22, 27, 37, 39, 41, 42];
    var notImageUrls = [9, 23, 25, 29, 30];
    if (imageUrl == null || imageUrl == undefined || imageUrl == "")
        throw new Error("");
    var pattern = /http(?:s?):\/\/[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
    if ((needUploadPlatform.indexOf(platformId) == -1 && imageUrl.IsPicture()) || notImageUrls.indexOf(platformId) !== -1) {
        //var parameter = imageUrl.replace(pattern, "");
        //var domain = imageUrl.match(pattern)[0].replace(/http(?:s?):\/\//, '');//去除https
        //var goodsUrl = "https://kj.1688.com/pdt_tongkuan.html?imgUrl=" + encodeURIComponent(imageUrl);

        var goodsUrl = "https://s.1688.com/youyuan/index.htm?tab=imageSearch&imageAddress=" + encodeURIComponent(imageUrl);
        window.open(goodsUrl);
    } else {
        //因这个接口调用时间比较长，点击一次禁用按钮且提示处理中，回调方法后再启用按钮
        $("#51selling_findgoods").attr({"disabled": "disabled"});
        $("#51selling_findgoods").text('处理中');
        GrowlNotification.notify({
            title: '温馨提示',
            description: '图片处理中，请稍后.....',
            type: 'info',
            position: 'top-right',
            closeTimeout: 5000,
            image: {visible: true, customImage: config.logoBase64},
        });

        sendMessageToBackgroudScript({"Type": "VerifyVersion"}, function (response) {
            if (response != '' && response != undefined && response != "") {
                ShowRedirectSiteBox("检测到最新插件版本为" + response.LatestVersion + "，点击确认前往下载最新版本", "warning", response.LatestUrl);
            } else {
                sendMessageToBackgroudScript({"Type": "UploadImage", "ImageUrl": imageUrl}, function (response) {
                    //启用按钮
                    $("#51selling_findgoods").removeAttr("disabled");
                    $("#51selling_findgoods").text('AI精铺上品');

                    if (!response || response == '' || response == imageUrl) {
                        //var parameter = response.replace(pattern, "");
                        //var domain = response.match(pattern)[0].replace(/http(?:s?):\/\//, '');//去除https
                        //var goodsUrl = "https://kj.1688.com/pdt_tongkuan.html?imgUrl=" + imageUrl;

                        var goodsUrl = "https://s.1688.com/youyuan/index.htm?tab=imageSearch&imageAddress=" + imageUrl;
                        ShowRedirectSiteBox("图片处理失败，请前往sczfai.com检查登录状态，是否继续使用未经处理的图片进行AI精铺上品（可能导致查找失败）？", "warning", goodsUrl);
                    } else {
                        //var parameter = response.replace(pattern, "");
                        //var domain = response.match(pattern)[0].replace(/http(?:s?):\/\//, '');//去除https
                        //var goodsUrl = "https://kj.1688.com/pdt_tongkuan.html?imgUrl=" + response;

                        var goodsUrl = "https://s.1688.com/youyuan/index.htm?tab=imageSearch&imageAddress=" + response;
                        window.open(goodsUrl);
                    }

                });
            }
        });
    }
}

var getCookie = function (name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]);
    return null
};

function getLinkRule(url) {
    if (!url) {
        return "Invalid url...";
    }
    var rule = "";
    if (url.indexOf('aliexpress.us') !== -1) {//速卖通美国站点使用.com规则,全局有两个地方要改，需要改这里记得全局搜索下域名
        rule = platformLinkRule['aliexpress.com'];
    } else {
        $.each(platformLinkRule, function (key, value) {
            if (url.indexOf(key) !== -1) {
                rule = value;
                return false;
            }
        });
    }

    if (!rule) {
        return "The platform does not support the collection, we will deal with as soon as possible";
    }
    return rule;
}

// 增加一个名为 IsPicture 的函数作为String 构造函数的原型对象的一个方法
String.prototype.IsPicture = function () {
    //判断是否是图片 - strFilter必须是小写列举
    var strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|"
    if (this.indexOf(".") > -1) {
        var p = this.lastIndexOf(".");
        var strPostfix = this.substring(p, this.length) + '|';
        strPostfix = strPostfix.toLowerCase();
        if (strFilter.indexOf(strPostfix) > -1) {
            return true;
        }
    }
    return false;
}

//计算表达式的值
//function myeval(data, callback) {
//    var pwd = guid();
//    data.LiSellingTempPwd = pwd;
//    const iframe = document.getElementById('51selling_sandbox');
//    window.addEventListener('message', (event) => {
//        try {
//            var res = JSON.parse(event.data.data);
//            if (event.data.LiSellingTempPwd && event.data.LiSellingTempPwd == data.LiSellingTempPwd) {
//                callback(res);
//            }
//        } catch (e) { }

//    });

//    iframe.contentWindow.postMessage(data, "*");
//}

//生成一个GUID
function guid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

//构建异步方法按顺序执行的队列
//function queue(arr) {
//    var sequeue = Promise.resolve();
//    arr.forEach(function (item) {
//        sequeue = sequeue.then(item);
//    });
//    return sequeue;
//}


$(function () {
    $(document).ready(function () {
        var num = 0;
        var timer = setInterval(function () {
            if (num > 10) {
                clearInterval(timer);
            }
            num++;

            if ($('#selling_collectiongoods') && $("#selling_collectiongoods").length > 0) {
                let element = $('#selling_collectiongoods').closest('.growl-notification__body').get(0);
                let doc = element.ownerDocument;
                let {x, y, width, height} = element.getBoundingClientRect();
                x |= 0;
                y |= 0;
                width |= 0;
                height |= 0;
                let elements = [
                    doc.elementFromPoint(x, y),
                    doc.elementFromPoint(x + width, y),
                    doc.elementFromPoint(x, y + height),
                    doc.elementFromPoint(x + width, y + height)
                ];
                var eles = elements.filter((el) => el !== null && el !== element);

                for (var i = 0; i < eles.length; i++) {
                    if ($($(eles[i])[0]).attr('class') == 'mango-fetch')
                        $($(eles[i])[0]).css({'z-index': '2147483646'});
                }
            }
        }, 1000);

        if (location.href.indexOf("aliexpress.")) {//速卖通有异步加载的情况，持续15秒，每秒检测一次
            var aliexpressNum = 0;
            var aliexpressTimer = setInterval(function () {
                if (aliexpressNum > 15)
                    clearInterval(aliexpressTimer);
                aliexpressNum++;
                preload();
            }, 1000);
        }
    });

})
