// product/ozon-api.js
// OZON 数据抓取层（纯 API/网络调用，无 DOM 操作）。
// 从 product/ozon.js 前 216 行抽出，const/let → var 以便跨 content script 共享。
// 加载顺序：此文件必须在 product/ozon.js 之前（manifest.json 已配置）。

// 获取物流缓存
var whCache = null;
// 获取token的辅助函数 - 添加缓存功能
var tokenCache = null;
var tokenLastUpdated = 0;
var TOKEN_CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

var grabOzonProduct = (purl) => {
    const url = 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=' + purl;
    return fetch(url).then(r => r.text());
};

// 添加图片预览弹窗的HTML
// imagePreviewHtml 已移到 product/ozon-templates.js

var grabProductContent = (purl) => {
    const url = 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=' + purl;
    return fetch(url).then(r => r.text());
};

var grabOtherGoodsLink=(url)=>{
    return new Promise(resolve => {
        grabOzonProduct(url).then((res)=>{
            let base = JSON.parse(res);
            let contentObj;
            let content_url = "";
            if(base.seo&&base.seo.script){
                let primary = JSON.parse(base.seo.script[0].innerHTML);
                for (var item in base.widgetStates) {
                    if (item.indexOf("paginator-") > -1) {
                        contentObj = JSON.parse(base.widgetStates[item]);
                        content_url = contentObj["nextPage"];
                    }
                }
            }
            grabProductContent(content_url).then((res)=>{
                let content = JSON.parse(res);
                let linkObj;
                let linkArr=[];
                for (var item in content.widgetStates) {
                    if (item.indexOf("skuShelfGoods-") > -1) {
                        linkObj = JSON.parse(content.widgetStates[item]);
                        linkObj.productContainer.products.forEach((link)=>{
                            linkArr.push({sku:link.skuId,url:link.link});
                        });
                    }
                }
                resolve(linkArr);
            });
        });
    });

}

var generateCombinationsOld = (aspects) => {

    let links = [];
    aspects.map(item=>{
        item.variants.map(v=>{
            links.push(v.link)
        });
    });
    return links;
}

var generateCombinations = (aspects) => {
    return new Promise(resolve => {
        const promises = aspects.map(item=>{
            return new Promise(async (resolveItem) => {
                let tmpLink = [];
                if(item.aspectModalInfo!=undefined){
                    const res = await grabOzonProduct(item.aspectModalInfo.link);
                    const base = JSON.parse(res);
                    for (const item in base.widgetStates) {
                        if (item.includes("webAspectsModal-")) {
                            const aspectsObj = JSON.parse(base.widgetStates[item]);
                            aspectsObj.aspects.forEach((tmp)=>{
                                tmp.variants.map(v=>{
                                    tmpLink.push(v.link)
                                });
                            });
                        }
                    }
                }else{
                    item.variants.map(v=>{
                        tmpLink.push(v.link)
                    });
                }
                resolveItem(tmpLink);
            });
        });
        Promise.all(promises)
            .then(results => {
                const validResults = results.filter(Boolean);
                resolve(validResults);
            })
            .catch(error => {
                console.error("全局错误:", error);
                resolve([]);
            });
    });
}

// 主抓取函数
var grabVariantsGoods = (aspects) => {
    return new Promise(resolve => {
        generateCombinations(aspects).then((linkRes)=>{
            let links = [];
            linkRes.map(item=>{
                links = links.concat(item);
            });
            grabDetailOtherGoods(links).then(res=>{
                resolve(res);
            });
        });

    });
}
var grabDetailOtherGoods = (links) => {
    return new Promise(resolve => {
        if (links.length === 0) {
            resolve({ data: [], sku_str: "" });
            return;
        }

        const promises = links.map(link => {
            return new Promise(async (resolveItem) => {
                try {
                    const res = await grabOzonProduct(link);
                    const base = JSON.parse(res);
                    let sku = "";
                    let content_url = "";

                    // 提取SKU
                    if (base.seo && base.seo.script) {
                        const primary = JSON.parse(base.seo.script[0].innerHTML);
                        sku = primary.sku;
                    }

                    // 提取内容URL
                    for (const item in base.widgetStates) {
                        if (item.includes("paginator-")) {
                            const contentObj = JSON.parse(base.widgetStates[item]);
                            content_url = contentObj.nextPage;
                            break; // 找到第一个符合条件即可退出
                        }
                    }

                    // 获取内容数据
                    const contentRes = await grabProductContent(content_url);
                    const content = JSON.parse(contentRes);

                    resolveItem({ sku, base, content });
                } catch (error) {
                    console.error(`处理链接 ${link} 失败:`, error);
                    resolveItem(null); // 失败时返回null保持数组结构
                }
            });
        });

        Promise.all(promises)
            .then(results => {
                const validResults = results.filter(Boolean);
                const skuList = validResults.map(item => item.sku);

                resolve({
                    data: validResults,
                    sku_str: skuList.join(",")
                });
            })
            .catch(error => {
                console.error("全局错误:", error);
                resolve({ data: [], sku_str: "" });
            });
    });
};

var grabDetailOtherGoodsOld = (links)=>{
    return new Promise(resolve => {
        if(links.length>0){
            let sku_str = "";
            let data = [];
            links.forEach((link)=>{
                grabOzonProduct(link).then((res)=>{
                    let base = JSON.parse(res);
                    let contentObj;
                    let content_url = "";
                    let sku = "";

                    if(base.seo&&base.seo.script){
                        let primary = JSON.parse(base.seo.script[0].innerHTML);
                        sku = primary.sku;
                        sku_str += sku_str!=""?","+sku:sku;

                    }
                    for (var item in base.widgetStates) {
                        if (item.indexOf("paginator-") > -1) {
                            contentObj = JSON.parse(base.widgetStates[item]);
                            content_url = contentObj["nextPage"];
                        }
                    }

                    //获取content
                    grabProductContent(content_url).then((res)=>{
                        let content = JSON.parse(res);
                        data.push({sku,base,content});
                    });
                });
            });
            resolve({data,sku_str});
        }
    });

};


