const SERVER_HOST = 'https://sczfai.com';
const dldomain = 'https://sczfai.com';
const AI_SCRAPE_CACHE_KEY = 'qydz_ai_pending_scraped_products';
const AI_DRAFT_CONTEXT_KEY = 'qydz_ai_draft_collection_contexts';
const PANDA_AUTH_KEY = 'qydz_panda_auth';
const OZON_VISUAL_CATEGORY_TASKS_KEY = 'qydz_ozon_visual_category_tasks';

importScripts("common/js/ozon-analytics.js", "js/config.js", "js/requestapi.js", "js/sendmessage.js", "js/callserver.js", "js/analyticalproducts.js", "js/productacquisition.js");
let main = chrome.runtime.getURL('html/main.html');
let isFloatButtonTriggered = false;

function appendAiScrapeFlag(url) {
    var value = String(url || '').trim();
    if (!value) return '';
    if (value.indexOf('_qydz_scrape=1') !== -1) return value;
    return value + (value.indexOf('?') >= 0 ? '&' : '?') + '_qydz_scrape=1';
}

function cacheAiScrapeData(info, callback) {
    if (!info || !info.name) {
        if (callback) callback(0);
        return;
    }
    chrome.storage.local.get([AI_SCRAPE_CACHE_KEY], function(result) {
        var items = Array.isArray(result[AI_SCRAPE_CACHE_KEY]) ? result[AI_SCRAPE_CACHE_KEY] : [];
        var key = info.sku || info.url || info.name;
        items = items.filter(function(item) {
            return (item.sku || item.url || item.name) !== key;
        });
        items.push(Object.assign({}, info, { cachedAt: new Date().toISOString() }));
        if (items.length > 100) items = items.slice(-100);
        var payload = {};
        payload[AI_SCRAPE_CACHE_KEY] = items;
        chrome.storage.local.set(payload, function() {
            if (callback) callback(items.length);
        });
    });
}

function syncCachedAiScrapeData(sendResponse) {
    chrome.storage.local.get([AI_SCRAPE_CACHE_KEY], function(result) {
        var pending = Array.isArray(result[AI_SCRAPE_CACHE_KEY]) ? result[AI_SCRAPE_CACHE_KEY] : [];
        if (!pending.length) {
            sendResponse({ success: true, count: 0, remaining: 0 });
            return;
        }

        var synced = 0;
        var failed = [];

        function postNext(index) {
            if (index >= pending.length) {
                var payload = {};
                payload[AI_SCRAPE_CACHE_KEY] = failed;
                chrome.storage.local.set(payload, function() {
                    sendResponse({
                        success: failed.length === 0,
                        count: synced,
                        remaining: failed.length
                    });
                });
                return;
            }

            var item = pending[index];
            fetch(SERVER_HOST + '/api/scrape-from-extension', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(item)
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.code === 1) {
                    synced++;
                } else {
                    failed.push(item);
                }
                postNext(index + 1);
            })
            .catch(function() {
                failed.push(item);
                postNext(index + 1);
            });
        }

        postNext(0);
    });
}

function openAiScrapeTabs(urls, sendResponse) {
    var list = Array.isArray(urls) ? urls.map(appendAiScrapeFlag).filter(Boolean) : [];
    if (!list.length) {
        sendResponse({ success: false, count: 0, message: '没有可打开的链接' });
        return;
    }

    list.forEach(function(url, index) {
        setTimeout(function() {
            chrome.tabs.create({ url: url, active: false });
        }, index * 350);
    });
    sendResponse({ success: true, count: list.length });
}

function draftScrapeUrl(url, draftId) {
    try {
        var parsed = new URL(String(url || ''));
        parsed.searchParams.set('_qydz_scrape', '1');
        parsed.searchParams.set('qydz_draft_id', String(draftId));
        return parsed.href;
    } catch (error) {
        return '';
    }
}

function openAiDraftScrape(request, sender, sendResponse) {
    var draftId = String(request.draft_id || '').trim();
    var targetUrl = draftScrapeUrl(request.url, draftId);
    if (!draftId || !targetUrl) {
        sendResponse({ success: false, message: '草稿或1688链接无效' });
        return;
    }
    chrome.storage.local.get([AI_DRAFT_CONTEXT_KEY], function(result) {
        var contexts = result[AI_DRAFT_CONTEXT_KEY] && typeof result[AI_DRAFT_CONTEXT_KEY] === 'object' ? result[AI_DRAFT_CONTEXT_KEY] : {};
        contexts[draftId] = {
            token: String(request.token || ''),
            page_tab_id: sender.tab && sender.tab.id ? sender.tab.id : null,
            page_frame_id: typeof sender.frameId === 'number' ? sender.frameId : null,
            source_url: String(request.url || ''),
            created_at: Date.now(),
            expires_at: Date.now() + 15 * 60 * 1000
        };
        var payload = {};
        payload[AI_DRAFT_CONTEXT_KEY] = contexts;
        chrome.storage.local.set(payload, function() {
            chrome.tabs.create({ url: targetUrl, active: false }, function(tab) {
                if (chrome.runtime.lastError) {
                    sendResponse({ success: false, message: chrome.runtime.lastError.message });
                    return;
                }
                sendResponse({ success: true, draft_id: draftId, tab_id: tab && tab.id });
            });
        });
    });
}

function notifyAiDraftPage(context, message) {
    if (!context || !context.page_tab_id) return;
    var options = typeof context.page_frame_id === 'number' ? { frameId: context.page_frame_id } : undefined;
    chrome.tabs.sendMessage(context.page_tab_id, message, options, function() {
        void chrome.runtime.lastError;
    });
}

function aiPremiumDraftUrl(draftId) {
    var url = SERVER_HOST + '/pages/ai-premium-listing.html?entry=plugin';
    if (draftId) url += '&draft_id=' + encodeURIComponent(String(draftId));
    return url;
}

function pandaLoginUrl() {
    return SERVER_HOST + '/login.html?redirect=' + encodeURIComponent('/pages/ai-premium-listing.html');
}

function syncPandaAuth(request, sendResponse) {
    var token = String(request.token || '').trim();
    var user = request.user && typeof request.user === 'object' ? request.user : null;
    if (!token) {
        chrome.storage.local.remove([PANDA_AUTH_KEY], function() {
            sendResponse({ success: true, cleared: true });
        });
        return;
    }
    var payload = {};
    payload[PANDA_AUTH_KEY] = {
        token: token,
        user: user,
        source_url: String(request.source_url || ''),
        updated_at: Date.now()
    };
    chrome.storage.local.set(payload, function() {
        sendResponse({ success: true });
    });
}

function getPandaToken(callback) {
    chrome.storage.local.get([PANDA_AUTH_KEY], function(result) {
        var auth = result[PANDA_AUTH_KEY] && typeof result[PANDA_AUTH_KEY] === 'object' ? result[PANDA_AUTH_KEY] : {};
        callback(String(auth.token || '').trim(), auth);
    });
}

function sendAiDraftSnapshot(info, context, callback) {
    function runWithToken(token) {
        if (!token) {
            callback({
                success: false,
                message: '未检测到熊猫登录状态，请先登录熊猫商家后台后重试',
                login_url: pandaLoginUrl()
            });
            return;
        }
        var controller = new AbortController();
        var timer = setTimeout(function() { controller.abort(); }, 25000);
        fetch(SERVER_HOST + '/api/ai-listing/ingest/extension', {
            method: 'POST',
            signal: controller.signal,
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({
                draft_id: info.draft_id || undefined,
                collector_version: info.collector_version || '5.2.30',
                product: info
            })
        })
        .then(function(response) {
            return response.json().then(function(data) { return { status: response.status, data: data }; });
        })
        .then(function(result) {
            clearTimeout(timer);
            var data = result.data && result.data.data ? result.data.data : {};
            var draftId = data.draft && data.draft.id ? data.draft.id : info.draft_id;
            if (result.data && result.data.code === 1) {
                callback({
                    success: true,
                    draft_id: draftId,
                    snapshot_id: data.snapshot ? data.snapshot.id : null,
                    open_url: SERVER_HOST + (data.open_url || ('/pages/ai-premium-listing.html?entry=plugin&draft_id=' + encodeURIComponent(String(draftId || '')))),
                    auto_created: Boolean(data.auto_created),
                    draft_reused: Boolean(data.draft_reused),
                    message: result.data.msg || '货源快照已保存'
                });
            } else {
                callback({ success: false, draft_id: draftId, status: result.status, message: result.data && result.data.msg ? result.data.msg : '服务器拒绝采集结果' });
            }
        })
        .catch(function(error) {
            clearTimeout(timer);
            callback({ success: false, draft_id: info.draft_id, message: error && error.name === 'AbortError' ? '回传超时，请重试' : '无法连接熊猫服务器' });
        });
    }
    if (context && context.token) runWithToken(context.token);
    else getPandaToken(function(token) { runWithToken(token); });
}

function forwardAiDraftSnapshot(info, sendResponse) {
    var draftId = String(info && (info.draft_id || info.draftId) || '').trim();
    if (!draftId) {
        sendAiDraftSnapshot(info, null, sendResponse);
        return;
    }
    chrome.storage.local.get([AI_DRAFT_CONTEXT_KEY], function(result) {
        var contexts = result[AI_DRAFT_CONTEXT_KEY] && typeof result[AI_DRAFT_CONTEXT_KEY] === 'object' ? result[AI_DRAFT_CONTEXT_KEY] : {};
        var context = contexts[draftId];
        if (!context || context.expires_at < Date.now()) {
            sendResponse({ success: false, message: '采集任务已过期，请从AI上品页面重新开始' });
            return;
        }
        sendAiDraftSnapshot(info, context, function(response) {
            notifyAiDraftPage(context, { action: 'aiDraftCollectionComplete', response: response });
            if (response.success) {
                delete contexts[draftId];
                var payload = {};
                payload[AI_DRAFT_CONTEXT_KEY] = contexts;
                chrome.storage.local.set(payload);
            }
            sendResponse(response);
        });
    });
}
//监听来自外部扩展和网页的消息
chrome.runtime.onMessageExternal.addListener(function (request, sender, sendResponse) {
    // OZON API代理请求（优先级高）
    if (request && request.action === 'ozonApiProxy') {
        const { path, method, body, appid, apikey } = request;
        if (!path || !appid || !apikey) {
            sendResponse({ error: '缺少参数' });
            return true;
        }

        const apiUrl = 'https://api.ozon.ru' + path;
        const fetchOptions = {
            method: method || 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Client-Id': appid,
                'Api-Key': apikey,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': 'application/json'
            }
        };
        if (body && method !== 'GET') {
            fetchOptions.body = JSON.stringify(body);
        }

        fetch(apiUrl, fetchOptions)
            .then(function(response) {
                return response.text().then(function(text) {
                    return { status: response.status, text: text, headers: Object.fromEntries(response.headers.entries()) };
                });
            })
            .then(function(result) {
                // 尝试解析JSON
                try { result.data = JSON.parse(result.text); } catch(e) { result.data = null; }
                sendResponse({ success: true, result: result });
            })
            .catch(function(err) {
                sendResponse({ success: false, error: err.message });
            });
        return true;
    }

    // 原来的采集链接逻辑
    if (request && request.urls) {
        chrome.storage.local.set({ urls: request.urls }, function () {});
        chrome.tabs.create({ url: main }, function (mainTab) {
            chrome.storage.local.set({ _TabId: mainTab.id, urls: request.urls });
        });
    }
});

// ===== OZON API 代理 - 轮询任务 + 心跳 =====
// 每隔5秒轮询服务器，处理待办的 OZON API 请求
const OZON_PROXY_HOST = 'https://sczfai.com';
const WORKER_ID = 'ext-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6);

function ozonAuthHeaders(token) {
  return {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + token
  };
}

function saveProductSelectionSnapshot(snapshot, callback) {
    getPandaToken(function(token) {
        if (!token) {
            callback({ success: false, auth_required: true, message: '请先登录熊猫店长后台' });
            return;
        }
        var controller = new AbortController();
        var timer = setTimeout(function() { controller.abort(); }, 20000);
        fetch(SERVER_HOST + '/api/product-selection/items', {
            method: 'POST',
            signal: controller.signal,
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify(snapshot || {})
        })
        .then(function(response) {
            return response.json().then(function(data) { return { status: response.status, data: data }; });
        })
        .then(function(result) {
            clearTimeout(timer);
            if (result.status >= 200 && result.status < 300 && result.data && result.data.code === 1) {
                callback({
                    success: true,
                    created: Boolean(result.data.data && result.data.data.created),
                    item: result.data.data && result.data.data.item,
                    message: result.data.msg || '已加入选品池'
                });
                return;
            }
            callback({ success: false, auth_required: result.status === 401, message: result.data && result.data.msg ? result.data.msg : '加入选品池失败' });
        })
        .catch(function(error) {
            clearTimeout(timer);
            callback({ success: false, message: error && error.name === 'AbortError' ? '请求超时，请重试' : '无法连接熊猫店长服务器' });
        });
    });
}

function ozonVisualTaskId(draftId) {
    return 'ozon-category-' + String(draftId || '') + '-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
}

function readOzonVisualTasks(callback) {
    chrome.storage.local.get([OZON_VISUAL_CATEGORY_TASKS_KEY], function(result) {
        var tasks = result[OZON_VISUAL_CATEGORY_TASKS_KEY] && typeof result[OZON_VISUAL_CATEGORY_TASKS_KEY] === 'object'
            ? result[OZON_VISUAL_CATEGORY_TASKS_KEY]
            : {};
        var now = Date.now();
        Object.keys(tasks).forEach(function(taskId) {
            if (!tasks[taskId] || Number(tasks[taskId].expires_at || 0) < now) delete tasks[taskId];
        });
        callback(tasks);
    });
}

function writeOzonVisualTasks(tasks, callback) {
    var payload = {};
    payload[OZON_VISUAL_CATEGORY_TASKS_KEY] = tasks || {};
    chrome.storage.local.set(payload, callback || function() {});
}

function notifyOzonVisualCategoryPage(task, response) {
    if (!task || !task.page_tab_id) return;
    var options = typeof task.page_frame_id === 'number' ? { frameId: task.page_frame_id } : undefined;
    chrome.tabs.sendMessage(task.page_tab_id, {
        action: 'ozonVisualCategoryComplete',
        response: response || { success: false, message: 'Ozon visual category search failed' }
    }, options, function() {
        void chrome.runtime.lastError;
    });
}

function sendOzonVisualTaskToTab(task, delayMs) {
    if (!task || !task.ozon_tab_id) return;
    setTimeout(function() {
        chrome.tabs.sendMessage(task.ozon_tab_id, {
            action: 'runOzonVisualCategorySearch',
            task_id: task.task_id,
            draft_id: task.draft_id,
            image_url: task.image_url,
            stage: task.stage || 'submit'
        }, function() {
            void chrome.runtime.lastError;
        });
    }, Math.max(0, Number(delayMs) || 0));
}

function finishOzonVisualTask(taskId, response) {
    readOzonVisualTasks(function(tasks) {
        var task = tasks[taskId];
        if (!task) return;
        delete tasks[taskId];
        writeOzonVisualTasks(tasks, function() {
            notifyOzonVisualCategoryPage(task, response);
            if (task.created_tab && task.ozon_tab_id) {
                chrome.tabs.remove(task.ozon_tab_id, function() { void chrome.runtime.lastError; });
            }
        });
    });
}

function openOzonVisualCategorySearch(request, sender, sendResponse) {
    var draftId = String(request.draft_id || '').trim();
    var imageUrl = String(request.image_url || '').trim();
    if (!draftId || !/^https?:\/\//i.test(imageUrl)) {
        sendResponse({ success: false, message: '缺少可用于 Ozon 以图搜索的商品主图 URL' });
        return;
    }
    readOzonVisualTasks(function(tasks) {
        Object.keys(tasks).forEach(function(taskId) {
            if (String(tasks[taskId].draft_id || '') === draftId) delete tasks[taskId];
        });
        var taskId = ozonVisualTaskId(draftId);
        var task = {
            task_id: taskId,
            draft_id: draftId,
            image_url: imageUrl,
            token: String(request.token || ''),
            page_tab_id: sender.tab && sender.tab.id ? sender.tab.id : null,
            page_frame_id: typeof sender.frameId === 'number' ? sender.frameId : null,
            ozon_tab_id: null,
            created_tab: true,
            stage: 'submit',
            created_at: Date.now(),
            expires_at: Date.now() + 3 * 60 * 1000
        };
        tasks[taskId] = task;
        writeOzonVisualTasks(tasks, function() {
            chrome.tabs.create({ url: 'https://www.ozon.ru/', active: false }, function(tab) {
                if (chrome.runtime.lastError || !tab || !tab.id) {
                    finishOzonVisualTask(taskId, {
                        success: false,
                        message: chrome.runtime.lastError ? chrome.runtime.lastError.message : '无法打开 Ozon 搜索页'
                    });
                    sendResponse({ success: false, message: '无法打开 Ozon 搜索页' });
                    return;
                }
                task.ozon_tab_id = tab.id;
                tasks[taskId] = task;
                writeOzonVisualTasks(tasks, function() {
                    sendResponse({ success: true, task_id: taskId, tab_id: tab.id });
                });
            });
        });
    });
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (!request || request.action !== 'openOzonVisualCategorySearch') return;
    openOzonVisualCategorySearch(request, sender, sendResponse);
    return true;
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (!request || (request.action !== 'ozonVisualCategoryNavigationStarted' && request.action !== 'ozonVisualCategoryResults')) return;
    var taskId = String(request.task_id || '').trim();
    readOzonVisualTasks(function(tasks) {
        var task = tasks[taskId];
        if (!task || (sender.tab && task.ozon_tab_id && sender.tab.id !== task.ozon_tab_id)) {
            if (sendResponse) sendResponse({ success: false, message: 'Ozon visual category task not found' });
            return;
        }
        if (request.action === 'ozonVisualCategoryNavigationStarted') {
            task.stage = 'collect';
            task.updated_at = Date.now();
            tasks[taskId] = task;
            writeOzonVisualTasks(tasks, function() {
                sendOzonVisualTaskToTab(task, 2500);
                if (sendResponse) sendResponse({ success: true });
            });
            return;
        }
        var evidence = Array.isArray(request.evidence) ? request.evidence : [];
        finishOzonVisualTask(taskId, request.success === false || !evidence.length
            ? { success: false, message: request.message || 'Ozon 以图搜索没有返回可用的同类商品' }
            : { success: true, evidence: evidence, task_id: taskId });
        if (sendResponse) sendResponse({ success: true });
    });
    return true;
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
    if (changeInfo.status !== 'complete') return;
    readOzonVisualTasks(function(tasks) {
        Object.keys(tasks).forEach(function(taskId) {
            var task = tasks[taskId];
            if (Number(task.ozon_tab_id) === Number(tabId)) sendOzonVisualTaskToTab(task, 400);
        });
    });
});

chrome.tabs.onRemoved.addListener(function(tabId) {
    readOzonVisualTasks(function(tasks) {
        Object.keys(tasks).forEach(function(taskId) {
            var task = tasks[taskId];
            if (Number(task.ozon_tab_id) !== Number(tabId)) return;
            delete tasks[taskId];
            notifyOzonVisualCategoryPage(task, { success: false, message: 'Ozon 以图搜索页面已关闭' });
        });
        writeOzonVisualTasks(tasks);
    });
});

function ozonHeartbeat() {
  getPandaToken(function(token) {
    if (!token) return;
    fetch(OZON_PROXY_HOST + '/api/ozon-api-proxy/heartbeat', {
      method: 'POST',
      headers: ozonAuthHeaders(token),
      body: JSON.stringify({ workerId: WORKER_ID })
    }).catch(function() {});
  });
}

function ozonSubmitTaskResult(token, taskId, payload) {
  return fetch(OZON_PROXY_HOST + '/api/ozon-tasks/' + taskId + '/result', {
    method: 'POST',
    headers: ozonAuthHeaders(token),
    body: JSON.stringify(payload)
  }).catch(function() {});
}

async function executeSellerMarketRankingTask(task) {
  var tabs = await chrome.tabs.query({ url: 'https://seller.ozon.ru/*' });
  if (!tabs.length) throw new Error('请先打开 seller.ozon.ru 并完成登录');
  var targetTab = tabs.find(function(tab) { return tab.active; })
    || tabs.find(function(tab) { return tab.url && tab.url.indexOf('/app/') !== -1; })
    || tabs[0];
  var companyId = await getSellerCompanyId(targetTab);
  var results = await chrome.scripting.executeScript({
    target: { tabId: targetTab.id },
    world: 'MAIN',
    func: async function(scCompanyId, body, pageCount, collectionPolicy) {
      var allItems = [];
      var seen = {};
      var pagesLoaded = 0;
      var stoppedReason = 'page_limit';
      var policy = collectionPolicy || {};
      var limit = Math.max(1, Math.min(100, Number(body && body.limit) || 50));
      var maxPages = Math.max(1, Math.min(20, Number(policy.maxPages || pageCount) || 1));
      var minPages = Math.max(1, Math.min(maxPages, Number(policy.minPages) || 1));
      var targetMatchCount = Math.max(0, Number(policy.targetMatchCount) || 0);
      function numberValue(item, keys) {
        for (var i = 0; i < keys.length; i++) {
          var value = item && item[keys[i]];
          if (value !== '' && value != null && isFinite(Number(value))) return Number(value);
        }
        return null;
      }
      function textValue(item, keys) {
        for (var i = 0; i < keys.length; i++) {
          var value = item && item[keys[i]];
          if (value != null && String(value).trim()) return String(value).trim();
        }
        return '';
      }
      function prefilterMatches(item) {
        var profile = policy.profile || {};
        var price = numberValue(item, ['avgPrice', 'minSellerPrice', 'price']);
        var sellers = numberValue(item, ['sellerCount', 'seller_count']);
        var growth = numberValue(item, ['salesDynamics', 'sales_dynamics']);
        var category = textValue(item, ['category3', 'category2', 'category1', 'categoryName', 'category3Id', 'category2Id', 'category1Id']);
        var preferred = Array.isArray(profile.preferred_categories) ? profile.preferred_categories : [];
        var excluded = Array.isArray(profile.excluded_categories) ? profile.excluded_categories : [];
        if (profile.target_price_min != null && (price == null || price < Number(profile.target_price_min))) return false;
        if (profile.target_price_max != null && (price == null || price > Number(profile.target_price_max))) return false;
        if (preferred.length && (!category || preferred.indexOf(category) === -1)) return false;
        if (excluded.length && (!category || excluded.indexOf(category) !== -1)) return false;
        if (profile.max_seller_count != null && (sellers == null || sellers > Number(profile.max_seller_count))) return false;
        if (profile.min_sales_growth != null && (growth == null || growth < Number(profile.min_sales_growth))) return false;
        return true;
      }
      for (var page = 0; page < maxPages; page++) {
        var controller = new AbortController();
        var timer = setTimeout(function() { controller.abort(); }, 30000);
        try {
          var pageBody = Object.assign({}, body || {}, { limit: limit, offset: page * limit });
          var response = await fetch('https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3', {
            method: 'POST',
            signal: controller.signal,
            credentials: 'include',
            headers: {
              accept: 'application/json, text/plain, */*',
              'content-type': 'application/json',
              'x-o3-app-name': 'seller-ui',
              'x-o3-company-id': scCompanyId,
              'x-o3-language': 'zh-Hans',
              'x-o3-page-type': 'products-other'
            },
            body: JSON.stringify(pageBody)
          });
          var text = await response.text();
          var data = null;
          try { data = JSON.parse(text); } catch (error) {}
          if (!response.ok) throw new Error('Ozon Seller HTTP ' + response.status + ': ' + text.slice(0, 180));
          var items = data && Array.isArray(data.items) ? data.items
            : data && data.data && Array.isArray(data.data.items) ? data.data.items : [];
          pagesLoaded++;
          items.forEach(function(item) {
            var key = String(item && (item.variantId || item.variant_id || item.sku || item.productId || item.product_id) || '');
            if (!key || seen[key]) return;
            seen[key] = true;
            allItems.push(item);
          });
          if (items.length < limit) { stoppedReason = 'source_exhausted'; break; }
          var prefilterMatchCount = allItems.filter(prefilterMatches).length;
          if (!policy.forceMaxPages && targetMatchCount > 0 && pagesLoaded >= minPages && prefilterMatchCount >= targetMatchCount) {
            stoppedReason = 'target_reached';
            break;
          }
        } finally {
          clearTimeout(timer);
        }
      }
      var enrichedCount = 0;
      if (policy.enrichDetails && Number(policy.enrichmentLimit) > 0) {
        var candidates = allItems.filter(prefilterMatches).slice(0, Math.min(60, Number(policy.enrichmentLimit) || 0));
        async function enrichItem(item) {
          var variantId = textValue(item, ['variantId', 'variant_id', 'sku', 'productId', 'product_id']);
          if (!variantId) return false;
          try {
            var response = await fetch('https://seller.ozon.ru/api/site/seller-prototype/create-bundle-by-variant-id', {
              method: 'POST',
              credentials: 'include',
              headers: {
                accept: 'application/json, text/plain, */*',
                'content-type': 'application/json',
                'x-o3-app-name': 'seller-ui',
                'x-o3-company-id': scCompanyId,
                'x-o3-language': 'zh-Hans'
              },
              body: JSON.stringify({ company_id: String(scCompanyId), variant_id: String(variantId), source: 'SOURCE_UI_COPY_MERGED' })
            });
            if (!response.ok) return false;
            var data = await response.json();
            var detail = data && data.item;
            if (!detail) return false;
            var attributes = Array.isArray(detail.attributes) ? detail.attributes : [];
            function attributeNumber(key) {
              var attr = attributes.find(function(value) { return String(value && value.key) === String(key); });
              var raw = attr && (attr.value != null ? attr.value : attr.values && attr.values[0] && attr.values[0].value);
              var match = String(raw == null ? '' : raw).replace(',', '.').match(/-?\d+(?:\.\d+)?/);
              return match ? Number(match[0]) : null;
            }
            var weight = numberValue(detail, ['weight']) || attributeNumber('4497');
            var length = numberValue(detail, ['depth']) || attributeNumber('9454');
            var width = numberValue(detail, ['width']) || attributeNumber('9455');
            var height = numberValue(detail, ['height']) || attributeNumber('9456');
            if (weight != null && weight > 0) item.weightG = weight;
            if (length > 0 && width > 0 && height > 0) item.volumeCm3 = Math.round((length * width * height) / 1000 * 100) / 100;
            if (item.weightG != null || item.volumeCm3 != null) { enrichedCount++; return true; }
          } catch (error) {}
          return false;
        }
        for (var index = 0; index < candidates.length; index += 3) {
          await Promise.all(candidates.slice(index, index + 3).map(enrichItem));
        }
      }
      return { status: 200, data: { items: allItems, pages_loaded: pagesLoaded, prefilter_match_count: allItems.filter(prefilterMatches).length, stopped_reason: stoppedReason, enriched_count: enrichedCount } };
    },
    args: [companyId, task.body || {}, task.meta && task.meta.pageCount, task.meta && task.meta.collectionPolicy]
  });
  var result = results && results[0] && results[0].result;
  if (!result) throw new Error('Ozon Seller 页面未返回榜单数据');
  return result;
}

function competitorReviewText(item) {
  var content = item && item.content;
  var parts = [
    typeof content === 'string' ? content : '',
    content && typeof content === 'object' ? content.comment : '',
    content && typeof content === 'object' ? content.positive : '',
    content && typeof content === 'object' ? content.negative : '',
    item && item.text,
    item && item.comment,
    item && item.reviewText,
    item && item.review_text,
    item && item.negative
  ].map(function(value) { return String(value || '').trim(); }).filter(Boolean);
  return Array.from(new Set(parts)).join('\n').slice(0, 6000);
}

function extractCompetitorReviews(payload) {
  var reviews = [];
  var seen = {};
  var visited = 0;
  function visit(value, depth) {
    if (value == null || depth > 10 || visited > 60000) return;
    visited++;
    if (typeof value === 'string') {
      if ((value.charAt(0) === '{' || value.charAt(0) === '[') && value.length < 2000000) {
        try { visit(JSON.parse(value), depth + 1); } catch (error) {}
      }
      return;
    }
    if (Array.isArray(value)) {
      value.forEach(function(item) { visit(item, depth + 1); });
      return;
    }
    if (typeof value !== 'object') return;
    var rating = Number(value.rating != null ? value.rating : value.score != null ? value.score : value.stars);
    var text = competitorReviewText(value);
    if (Number.isFinite(rating) && rating >= 1 && rating <= 5 && text) {
      var id = String(value.reviewId || value.review_id || value.id || value.uuid || '').trim();
      var key = id || rating + '|' + text.slice(0, 300);
      if (!seen[key]) {
        seen[key] = true;
        reviews.push({
          reviewId: id,
          rating: rating,
          content: text,
          authorName: String(value.authorName || (value.author && value.author.name) || '').slice(0, 300),
          publishedAt: String(value.publishedAt || value.published_at || value.createdAt || value.created_at || '').slice(0, 100)
        });
      }
    }
    Object.keys(value).slice(0, 200).forEach(function(key) { visit(value[key], depth + 1); });
  }
  visit(payload, 0);
  return reviews;
}

async function executeCompetitorReviewTask(task) {
  var body = task.body || {};
  var productId = String(body.productId || '').trim();
  if (!/^\d{5,}$/.test(productId)) throw new Error('竞品 Ozon SKU 无效');
  var pageCount = Math.max(1, Math.min(5, Number(body.pageCount) || 4));
  var pageSize = Math.max(10, Math.min(50, Number(body.pageSize) || 30));
  var all = [];
  var seen = {};
  for (var page = 1; page <= pageCount; page++) {
    var targetPath = '/product/' + encodeURIComponent(productId) + '/reviews/?page=' + page + '&page_size=' + pageSize + '&sort=published_at_desc';
    var controller = new AbortController();
    var timer = setTimeout(function() { controller.abort(); }, 30000);
    try {
      var response = await fetch('https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=' + encodeURIComponent(targetPath), {
        method: 'GET',
        signal: controller.signal,
        credentials: 'include',
        headers: {
          accept: 'application/json, text/plain, */*',
          'x-o3-app-name': 'ozon-front'
        }
      });
      var text = await response.text();
      if (!response.ok) throw new Error('Ozon 评论接口 HTTP ' + response.status + ': ' + text.slice(0, 180));
      var payload = null;
      try { payload = JSON.parse(text); } catch (error) { throw new Error('Ozon 评论接口未返回JSON'); }
      var pageReviews = extractCompetitorReviews(payload);
      pageReviews.forEach(function(review) {
        var key = String(review.reviewId || '') || review.rating + '|' + String(review.content || '').slice(0, 300);
        if (seen[key]) return;
        seen[key] = true;
        all.push(review);
      });
      if (!pageReviews.length) break;
    } finally {
      clearTimeout(timer);
    }
  }
  return { status: 200, data: { items: all, pages_requested: pageCount } };
}

function ozonPollTasks() {
  getPandaToken(function(token) {
    if (!token) return;
    fetch(OZON_PROXY_HOST + '/api/ozon-tasks/pending?worker=extension', {
      headers: { 'Authorization': 'Bearer ' + token }
    })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data && data.tasks && data.tasks.length > 0) {
          data.tasks.forEach(function(task) {
            if (task.kind === 'competitor_reviews') {
              executeCompetitorReviewTask(task)
                .then(function(result) {
                  return ozonSubmitTaskResult(token, task.id, { success: true, result: result });
                })
                .catch(function(err) {
                  return ozonSubmitTaskResult(token, task.id, { success: false, error: err.message || String(err) });
                });
              return;
            }
            if (task.kind === 'seller_market_ranking') {
              executeSellerMarketRankingTask(task)
                .then(function(result) {
                  return ozonSubmitTaskResult(token, task.id, { success: true, result: result });
                })
                .catch(function(err) {
                  return ozonSubmitTaskResult(token, task.id, { success: false, error: err.message || String(err) });
                });
              return;
            }
            var apiUrl = 'https://api.ozon.ru' + task.path;
            var fetchOptions = {
              method: task.method || 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Client-Id': task.appid,
                'Api-Key': task.apikey,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
              }
            };
            if (task.body && task.method !== 'GET') {
              fetchOptions.body = JSON.stringify(task.body);
            }
            fetch(apiUrl, fetchOptions)
              .then(function(response) {
                return response.text().then(function(text) {
                  var result = { status: response.status, text: text };
                  try { result.data = JSON.parse(text); } catch(e) {}
                  return result;
                });
              })
              .then(function(result) {
                ozonSubmitTaskResult(token, task.id, { success: true, result: result });
              })
              .catch(function(err) {
                ozonSubmitTaskResult(token, task.id, { success: false, error: err.message });
              });
          });
        }
      })
      .catch(function() {});
  });
}

// 注册定期任务
var OZON_POLL_INTERVAL = 5000; // 5秒轮询一次
setInterval(ozonPollTasks, OZON_POLL_INTERVAL);
setInterval(ozonHeartbeat, 10000); // 10秒心跳一次
ozonHeartbeat(); // 立即发一次心跳

// 进入mian.html
chrome.action.onClicked.addListener((tab) => {
    // 当扩展图标被点击时，这里的代码将被执行
    chrome.tabs.create({url: "html/main.html"});
});
// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 处理订单数据
  if (message.type === 'ORDER_DATA') {
    console.log('收到订单数据:', message.data);
    
    // 存储订单数据到本地存储
    chrome.storage.local.set({
      [`orders_${message.platform}`]: message.data,
      lastUpdateTime: new Date().getTime()
    }, () => {
      sendResponse({ success: true, message: '订单数据已保存' });
    });
    
    return true; // 保持消息通道开放
  }
  
  // 响应用户点击获取订单的请求
  else if (message.type === 'FETCH_ORDERS') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs.length > 0) {
        const url = tabs[0].url;
        if (url.includes('taobao.com')) {
          chrome.tabs.sendMessage(tabs[0].id, { type: 'GET_TAOBAO_ORDERS' }, sendResponse);
        } else if (url.includes('pinduoduo.com')) {
          chrome.tabs.sendMessage(tabs[0].id, { type: 'GET_PINDUODUO_ORDERS' }, sendResponse);
        } else {
          sendResponse({ error: '请先打开淘宝或拼多多订单页面' });
        }
      }
    });
    
    return true;
  }
});

// 监听标签页更新，自动注入脚本
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url) {
    // 可以在这里添加自动执行的逻辑
  }
});
chrome.runtime.onInstalled.addListener(function () {
    //创建页面右键菜单
    chrome.contextMenus.create({
        type: 'normal',
        title: '采集此产品',
        id: '51Selling_CollectProductsMenu',
        contexts: ['all']
    }, function () {
    });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'PRODUCT_WEIGHT_DATA') {
        console.log('PRODUCT_WEIGHT_DATA-bac:', message);
        // 直接发送回来源标签页
        if (sender.tab?.id) {
            chrome.tabs.sendMessage(sender.tab.id, {
                type: 'FORWARDED_WEIGHT_DATA',
                data: message
            });
        } else {
            console.error('无法获取来源标签页ID');
        }
    }
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "openAiDraftScrape") {
        openAiDraftScrape(request, sender, sendResponse);
        return true;
    }
    if (request.action === "pandaAuthSync") {
        syncPandaAuth(request, sendResponse);
        return true;
    }
    if (request.action === "getPandaAuth") {
        chrome.storage.local.get([PANDA_AUTH_KEY], function(result) {
            var auth = result[PANDA_AUTH_KEY] && typeof result[PANDA_AUTH_KEY] === 'object' ? result[PANDA_AUTH_KEY] : {};
            sendResponse({
                success: Boolean(String(auth.token || '').trim()),
                token: String(auth.token || '').trim(),
                user: auth.user || null,
                updated_at: auth.updated_at || ''
            });
        });
        return true;
    }
    if (request.action === "openAiScrapeTabs") {
        openAiScrapeTabs(request.urls, sendResponse);
        return true;
    }
    if (request.action === "syncCachedScrapeData") {
        syncCachedAiScrapeData(sendResponse);
        return true;
    }
    if (request.action === "cacheScrapeData") {
        cacheAiScrapeData(request.data, function(count) {
            sendResponse({ success: true, cached: true, count: count });
        });
        return true;
    }
    if (request.action === "spiderPost") {
        // 转发到 bg 的 sendToSpiderOzon（5.19 引入的 SpiderOzon 上报）
        try { sendToSpiderOzon(request.dataObj || {}, request.sku); } catch (e) { console.error(e); }
        sendResponse({ ok: true });
        return true;
    }
    if (request.action === "forwardScrapeData") {
        // 内容脚本采集到的产品数据，由background.js代为发送到服务器（解决HTTPS混合内容问题）
        const info = request.data;
        if (!info || !info.name) { sendResponse({ success: false }); return true; }
        if (info.draft_id || request.draft_id) {
            info.draft_id = info.draft_id || request.draft_id;
            forwardAiDraftSnapshot(info, sendResponse);
            return true;
        }

        fetch(SERVER_HOST + '/api/scrape-from-extension', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(info)
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data && data.code === 1) {
                sendResponse({ success: true });
            } else {
                cacheAiScrapeData(info, function(count) {
                    sendResponse({
                        success: false,
                        cached: true,
                        count: count,
                        message: data && data.msg ? data.msg : 'server rejected scrape data'
                    });
                });
            }
        })
        .catch(function() {
            cacheAiScrapeData(info, function(count) {
                sendResponse({ success: false, cached: true, count: count });
            });
        });
        return true;
    }
    if (request.action === "spiderPostFlush") {
        var count = spiderOzonBatchQueue.length;
        flushSpiderOzonBatch();
        sendResponse({ ok: true, sentCount: count });
        return true;
    }
    if (request.action === "httpRequest") {
        fetch(request.url, {
            method: request.method,
            headers: request.headers,
            body: request.params ? JSON.stringify(request.params) : undefined
        })
        .then(response => {
            // 检查响应是否为HTML
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('text/html')) {
                return response.text(); // 返回HTML文本
            } else {
                return response.json(); // 返回JSON
            }
        })
        .then(data => {
            // 统一返回格式，方便前端处理
            if (typeof data === 'string') {
                // HTML响应
                sendResponse({ data: data });
            } else {
                // JSON响应
                sendResponse(data);
            }
        })
        .catch(error => sendResponse({ error: error.message }));
        
        return true; // 保持消息通道开放
    } 
    else if (request.action === "getTrackingNumber1688" || request.action === "getTrackingNumberTB") {
    // 生成唯一请求ID
    const requestId = Math.random().toString(36).substr(2, 9);
    
    // 打开后台标签页获取快递单号
    chrome.tabs.create({
        url: request.url,
        active: false // 在后台打开
    }, function(tab) {
        // 等待页面加载完成（减少到 800ms）
        setTimeout(function() {
            // 注入脚本到页面中获取快递单号，传递 requestId
            chrome.scripting.executeScript({
                target: { tabId: tab.id },
                args: [requestId, request.action],
                func: (requestId, action) => {
                    // 等待页面元素加载完成（减少超时时间）
                    function waitForElement(selector, timeout = 5000) {
                        return new Promise((resolve) => {
                            let element = null;
                            let startTime = Date.now();
                                
                            const checkElement = () => {
                                element = document.querySelector(selector);
                                if (element || Date.now() - startTime > timeout) {
                                    resolve(element);
                                    return;
                                }
                                setTimeout(checkElement, 300); // 加快检查频率
                            };
                                
                            checkElement();
                        });
                    }
                        
                    // 处理 1688 的快递单号提取
                    async function process1688() {
                        try {
                            // 查找并激活物流信息标签
                            await activateLogisticsInfo1688();
                                
                            // 等待物流信息加载完成（减少到 500ms）
                            await new Promise(resolve => setTimeout(resolve, 500));
                                
                            // 提取快递单号
                            let trackingNumber = await extractTrackingNumber1688();
                            return trackingNumber;
                        } catch (error) {
                            throw error;
                        }
                    }
                    
                    // 处理淘宝的快递单号提取
                    async function processTB() {
                        try {
                            // 淘宝页面的快递单号提取逻辑
                            return await extractTrackingNumberTB();
                        } catch (error) {
                            throw error;
                        }
                    }
                    
                    // 1688物流信息标签激活
                    function activateLogisticsInfo1688() {
                        return new Promise((resolve) => {
                            // 查找物流信息标签
                            const findAndActivateLogisticsTab = () => {
                                console.log('🔍 开始查找物流信息标签');
                                
                                // 方法1：直接查找detail-tabs元素
                                let detailTabs = document.querySelector('detail-tabs');
                                console.log('🔍 detailTabs direct:', detailTabs);
                                
                                if (detailTabs && detailTabs.shadowRoot) {
                                    console.log('✅ 找到detail-tabs及其Shadow DOM');
                                    // 查找tabs容器
                                    let tabsContainer = detailTabs.shadowRoot.querySelector('.tabs-container');
                                    console.log('🔍 tabsContainer:', tabsContainer);
                                    
                                    if (tabsContainer) {
                                        // 查找tabs元素
                                        let tabs = tabsContainer.querySelector('.tabs');
                                        console.log('🔍 tabs:', tabs);
                                        
                                        if (tabs) {
                                            // 查找所有tab-item
                                            let tabItems = tabs.querySelectorAll('.tab-item');
                                            console.log('🔍 找到', tabItems.length, '个tab-item');
                                            
                                            // 遍历tab-item，找到物流信息标签
                                            for (let tabItem of tabItems) {
                                                let tabContent = tabItem.textContent || '';
                                                console.log('🔍 tab内容:', tabContent);
                                                
                                                if (tabContent.includes('物流信息')) {
                                                    // 检查是否已经是激活状态
                                                    if (!tabItem.classList.contains('active')) {
                                                        tabItem.click();
                                                        console.log('✅ 已激活物流信息标签');
                                                    } else {
                                                        console.log('✅ 物流信息标签已处于激活状态');
                                                    }
                                                    resolve();
                                                    return;
                                                }
                                            }
                                            
                                            // 如果没有找到包含"物流信息"的标签，尝试点击第二个标签
                                            if (tabItems.length >= 2) {
                                                tabItems[1].click();
                                                console.log('✅ 已激活第二个标签（作为备选）');
                                                resolve();
                                                return;
                                            }
                                        }
                                    }
                                } else {
                                    // 方法2：尝试通过app-root和q-theme查找
                                    console.log('🔍 尝试通过app-root和q-theme查找');
                                    
                                    let appRoot = document.querySelector('app-root');
                                    console.log('🔍 appRoot:', appRoot);
                                    
                                    if (appRoot && appRoot.shadowRoot) {
                                        console.log('✅ 找到app-root及其Shadow DOM');
                                        
                                        let mainContainer = appRoot.shadowRoot.querySelector('main.main-container');
                                        console.log('🔍 mainContainer:', mainContainer);
                                        
                                        if (mainContainer) {
                                            let qTheme = mainContainer.querySelector('q-theme');
                                            console.log('🔍 qTheme:', qTheme);
                                            
                                            if (qTheme) {
                                                console.log('✅ 找到q-theme元素');
                                                
                                                // 方法1：直接在q-theme的light DOM中查找detail-tabs（适用于通过slot插入的元素）
                                                let detailTabsFromLightDOM = qTheme.querySelector('detail-tabs') || Array.from(qTheme.children).find(child => child.tagName.toLowerCase() === 'detail-tabs');
                                                console.log('🔍 detailTabsFromLightDOM:', detailTabsFromLightDOM);
                                                
                                                if (detailTabsFromLightDOM && detailTabsFromLightDOM.shadowRoot) {
                                                    console.log('✅ 从q-theme的light DOM中找到detail-tabs及其Shadow DOM');
                                                    let tabsContainer = detailTabsFromLightDOM.shadowRoot.querySelector('.tabs-container');
                                                    console.log('🔍 tabsContainer:', tabsContainer);
                                                    
                                                    if (tabsContainer) {
                                                        let tabs = tabsContainer.querySelector('.tabs');
                                                        console.log('🔍 tabs:', tabs);
                                                        
                                                        if (tabs) {
                                                            let tabItems = tabs.querySelectorAll('.tab-item');
                                                            console.log('🔍 找到', tabItems.length, '个tab-item');
                                                            
                                                            for (let tabItem of tabItems) {
                                                                let tabContent = tabItem.textContent || '';
                                                                console.log('🔍 tab内容:', tabContent);
                                                                
                                                                if (tabContent.includes('物流信息')) {
                                                                    if (!tabItem.classList.contains('active')) {
                                                                        tabItem.click();
                                                                        console.log('✅ 已激活物流信息标签');
                                                                    } else {
                                                                        console.log('✅ 物流信息标签已处于激活状态');
                                                                    }
                                                                    resolve();
                                                                    return;
                                                                }
                                                            }
                                                            
                                                            if (tabItems.length >= 2) {
                                                                tabItems[1].click();
                                                                console.log('✅ 已激活第二个标签（作为备选）');
                                                                resolve();
                                                                return;
                                                            }
                                                        }
                                                    }
                                                }
                                                
                                                // 方法2：如果q-theme有shadowRoot，通过slot穿透查找
                                                if (qTheme.shadowRoot) {
                                                    console.log('✅ 访问q-theme的Shadow DOM');
                                                    
                                                    // 查找q-theme的shadowRoot中的所有slot元素
                                                    let slots = qTheme.shadowRoot.querySelectorAll('slot');
                                                    console.log('🔍 qTheme的Shadow DOM中有', slots.length, '个slot');
                                                    
                                                    // 遍历所有slot，获取通过slot插入的节点
                                                    for (let slot of slots) {
                                                        // 获取slot的分配节点（包括嵌套slot的内容）
                                                        let assignedNodes = slot.assignedNodes({ flatten: true });
                                                        console.log('🔍 slot assignedNodes:', assignedNodes.length, '个节点');
                                                        
                                                        // 在分配节点中查找detail-tabs
                                                        let slotDetailTabs = assignedNodes.find(node => node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() === 'detail-tabs');
                                                        console.log('🔍 slotDetailTabs:', slotDetailTabs);
                                                        
                                                        if (slotDetailTabs && slotDetailTabs.shadowRoot) {
                                                            console.log('✅ 从slot中找到detail-tabs及其Shadow DOM');
                                                            let tabsContainer = slotDetailTabs.shadowRoot.querySelector('.tabs-container');
                                                            console.log('🔍 tabsContainer:', tabsContainer);
                                                            
                                                            if (tabsContainer) {
                                                                let tabs = tabsContainer.querySelector('.tabs');
                                                                console.log('🔍 tabs:', tabs);
                                                                
                                                                if (tabs) {
                                                                    let tabItems = tabs.querySelectorAll('.tab-item');
                                                                    for (let tabItem of tabItems) {
                                                                        let tabContent = tabItem.textContent || '';
                                                                        if (tabContent.includes('物流信息')) {
                                                                            if (!tabItem.classList.contains('active')) {
                                                                                tabItem.click();
                                                                                console.log('✅ 已激活物流信息标签');
                                                                            } else {
                                                                                console.log('✅ 物流信息标签已处于激活状态');
                                                                            }
                                                                            resolve();
                                                                            return;
                                                                        }
                                                                    }
                                                                    
                                                                    if (tabItems.length >= 2) {
                                                                        tabItems[1].click();
                                                                        console.log('✅ 已激活第二个标签（作为备选）');
                                                                        resolve();
                                                                        return;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                
                                // 如果所有方法都失败，继续检查
                                console.log('⏳ 未找到所需元素，500ms后重试');
                                setTimeout(findAndActivateLogisticsTab, 500);
                            };
                            
                            findAndActivateLogisticsTab();
                        });
                    }
                    
                    // 1688提取快递单号
                    function extractTrackingNumber1688() {
                        return new Promise((resolve, reject) => {
                            console.log('🔍 开始提取快递单号');
                            
                            let startTime = Date.now();
                            const timeout = 10000; // 10秒超时
                            
                            // 按照图片中的DOM结构顺序查找
                            const findTrackingNumber = () => {
                                // 检查是否超时
                                if (Date.now() - startTime > timeout) {
                                    console.error('❌ 提取快递单号超时');
                                    reject(new Error('提取快递单号超时'));
                                    return;
                                }
                                
                                try {
                                    console.log('🔍 步骤1: 查找app-root');
                                    let appRoot = document.querySelector('app-root');
                                    
                                    if (!appRoot) {
                                        console.warn('⚠️ 未找到app-root元素');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到app-root');
                                    
                                    // 步骤2: 进入app-root的Shadow DOM
                                    if (!appRoot.shadowRoot) {
                                        console.warn('⚠️ app-root没有shadowRoot');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 访问app-root的Shadow DOM');
                                    
                                    // 步骤3: 查找main.main-container
                                    let mainContainer = appRoot.shadowRoot.querySelector('main.main-container');
                                    if (!mainContainer) {
                                        console.warn('⚠️ 未找到main.main-container');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到main.main-container');
                                    
                                    // 步骤4: 查找q-theme
                                    let qTheme = mainContainer.querySelector('q-theme');
                                    if (!qTheme) {
                                        console.warn('⚠️ 未找到q-theme元素');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到q-theme元素');
                                    console.log('🔍 q-theme是否有shadowRoot:', !!qTheme.shadowRoot);
                                    
                                    // 步骤5: 进入q-theme的Shadow DOM
                                    if (!qTheme.shadowRoot) {
                                        console.warn('⚠️ q-theme没有shadowRoot');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 访问q-theme的Shadow DOM');
                                    
                                    // 步骤6: 在q-theme的Shadow DOM中查找detail-tabs
                                    // 注意: 根据图片，detail-tabs是通过slot插入的
                                    let detailTabs = null;
                                    
                                    // 先尝试直接查找
                                    detailTabs = qTheme.shadowRoot.querySelector('detail-tabs');
                                    console.log('🔍 直接查找detail-tabs:', detailTabs);
                                    
                                    // 如果没找到，尝试通过slot查找
                                    if (!detailTabs) {
                                        const slots = qTheme.shadowRoot.querySelectorAll('slot');
                                        console.log(`🔍 找到 ${slots.length} 个slot元素`);
                                        
                                        for (let slot of slots) {
                                            const assignedElements = slot.assignedElements();
                                            console.log(`🔍 slot "${slot.name}" 分配了 ${assignedElements.length} 个元素`);
                                            
                                            for (let el of assignedElements) {
                                                if (el.tagName.toLowerCase() === 'detail-tabs') {
                                                    detailTabs = el;
                                                    console.log('✅ 从slot中找到detail-tabs');
                                                    break;
                                                }
                                            }
                                            if (detailTabs) break;
                                        }
                                    }
                                    
                                    if (!detailTabs) {
                                        console.warn('⚠️ 在q-theme的Shadow DOM中未找到detail-tabs');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到detail-tabs');
                                    
                                    // 现在detail-tabs已经在light DOM中，我们需要进入它的Shadow DOM
                                    if (!detailTabs.shadowRoot) {
                                        console.warn('⚠️ detail-tabs没有shadowRoot');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 进入detail-tabs的Shadow DOM');
                                    
                                    // 步骤7: 查找tabs容器
                                    let tabsContainer = detailTabs.shadowRoot.querySelector('.tabs-container');
                                    if (!tabsContainer) {
                                        console.warn('⚠️ 未找到.tabs-container');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到.tabs-container');
                                    
                                    // 步骤8: 查找tabs
                                    let tabs = tabsContainer.querySelector('.tabs');
                                    if (!tabs) {
                                        console.warn('⚠️ 未找到.tabs');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log('✅ 找到.tabs');
                                    
                                    // 步骤9: 查找tab-item
                                    let tabItems = tabs.querySelectorAll('.tab-item');
                                    if (tabItems.length === 0) {
                                        console.warn('⚠️ 未找到.tab-item');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    console.log(`✅ 找到 ${tabItems.length} 个.tab-item`);
                                    
                                    // 步骤10: 查找并点击物流信息标签
                                    let logisticsTabClicked = false;
                                    for (let tabItem of tabItems) {
                                        let tabContent = tabItem.textContent || '';
                                        console.log('🔍 检查tab:', tabContent.trim());
                                        
                                        if (tabContent.includes('物流信息')) {
                                            if (!tabItem.classList.contains('active')) {
                                                tabItem.click();
                                                console.log('✅ 已点击物流信息标签');
                                            } else {
                                                console.log('✅ 物流信息标签已是激活状态');
                                            }
                                            logisticsTabClicked = true;
                                            break;
                                        }
                                    }
                                    
                                    if (!logisticsTabClicked && tabItems.length >= 2) {
                                        tabItems[1].click();
                                        console.log('✅ 已点击第二个标签（备选）');
                                        logisticsTabClicked = true;
                                    }
                                    
                                    if (!logisticsTabClicked) {
                                        console.warn('⚠️ 未找到物流信息标签且无法点击备选标签');
                                        setTimeout(findTrackingNumber, 500);
                                        return;
                                    }
                                    
                                    // 等待物流信息加载
                                    console.log('⏳ 等待物流信息加载...');
                                    
                                    // 给一些时间让物流信息加载
                                    setTimeout(() => {
                                        // 现在查找物流信息区域
                                        findLogisticsInfo();
                                    }, 1000);
                                    
                                    // 查找物流信息区域的函数
                                    function findLogisticsInfo() {
                                        console.log('🔍 开始查找物流信息区域');
                                        
                                        // 步骤11: 查找logistics-info（自定义元素）
                                        // 根据您的说明，logistics-info应该是通过slot插入的
                                        let logisticsInfoElement = null;
                                        
                                        // 尝试在detail-tabs的Shadow DOM中查找
                                        if (detailTabs.shadowRoot) {
                                            logisticsInfoElement = detailTabs.shadowRoot.querySelector('logistics-info');
                                            console.log('🔍 在detail-tabs的Shadow DOM中查找logistics-info:', logisticsInfoElement);
                                        }
                                        
                                        // 如果没找到，尝试在q-theme的light DOM中查找
                                        if (!logisticsInfoElement) {
                                            logisticsInfoElement = qTheme.querySelector('logistics-info');
                                            console.log('🔍 在q-theme的light DOM中查找logistics-info:', logisticsInfoElement);
                                        }
                                        
                                        // 如果还没找到，尝试在document中直接查找
                                        if (!logisticsInfoElement) {
                                            logisticsInfoElement = document.querySelector('logistics-info');
                                            console.log('🔍 在document中直接查找logistics-info:', logisticsInfoElement);
                                        }
                                        
                                        if (!logisticsInfoElement) {
                                            console.warn('⚠️ 未找到logistics-info元素');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到logistics-info元素');
                                        console.log('🔍 logistics-info是否有shadowRoot:', !!logisticsInfoElement.shadowRoot);
                                        
                                        // 步骤12: 进入logistics-info的Shadow DOM
                                        if (!logisticsInfoElement.shadowRoot) {
                                            console.warn('⚠️ logistics-info没有shadowRoot');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 进入logistics-info的Shadow DOM');
                                        
                                        // 步骤13: 查找.logistics-info-container
                                        let logisticsInfoContainer = logisticsInfoElement.shadowRoot.querySelector('.logistics-info-container');
                                        if (!logisticsInfoContainer) {
                                            console.warn('⚠️ 未找到.logistics-info-container');
                                            
                                            // 如果没有.logistics-info-container，尝试直接查找.logistics-info-items
                                            let logisticsInfoItems = logisticsInfoElement.shadowRoot.querySelector('.logistics-info-items');
                                            if (logisticsInfoItems) {
                                                console.log('✅ 直接找到.logistics-info-items');
                                                processLogisticsInfoItems(logisticsInfoItems);
                                                return;
                                            }
                                            
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.logistics-info-container');
                                        
                                        // 步骤14: 查找.logistics-info-items
                                        let logisticsInfoItems = logisticsInfoContainer.querySelector('.logistics-info-items');
                                        if (!logisticsInfoItems) {
                                            console.warn('⚠️ 未找到.logistics-info-items');
                                            
                                            // 如果没有.logistics-info-items，尝试在容器中查找.logistics-info-content
                                            let logisticsInfoContent = logisticsInfoContainer.querySelector('.logistics-info-content');
                                            if (logisticsInfoContent) {
                                                console.log('✅ 直接找到.logistics-info-content');
                                                processLogisticsInfoContent(logisticsInfoContent);
                                                return;
                                            }
                                            
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.logistics-info-items');
                                        processLogisticsInfoItems(logisticsInfoItems);
                                    }
                                    
                                    // 处理.logistics-info-items
                                    function processLogisticsInfoItems(logisticsInfoItems) {
                                        console.log('🔍 处理.logistics-info-items');
                                        
                                        // 步骤15: 查找.logistics-info-content
                                        let logisticsInfoContent = logisticsInfoItems.querySelector('.logistics-info-content');
                                        if (!logisticsInfoContent) {
                                            console.warn('⚠️ 未找到.logistics-info-content');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.logistics-info-content');
                                        processLogisticsInfoContent(logisticsInfoContent);
                                    }
                                    
                                    // 处理.logistics-info-content
                                    function processLogisticsInfoContent(logisticsInfoContent) {
                                        console.log('🔍 处理.logistics-info-content');
                                        
                                        // 步骤16: 查找logistics-info-message（自定义标签）
                                        let logisticsInfoMessage = logisticsInfoContent.querySelector('logistics-info-message');
                                        if (!logisticsInfoMessage) {
                                            console.warn('⚠️ 未找到logistics-info-message元素');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到logistics-info-message');
                                        console.log('🔍 logistics-info-message是否有shadowRoot:', !!logisticsInfoMessage.shadowRoot);
                                        
                                        // 步骤17: 进入logistics-info-message的Shadow DOM
                                        if (!logisticsInfoMessage.shadowRoot) {
                                            console.warn('⚠️ logistics-info-message没有shadowRoot');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 进入logistics-info-message的Shadow DOM');
                                        
                                        // 步骤18: 查找.info-message-content
                                        let infoMessageContent = logisticsInfoMessage.shadowRoot.querySelector('.info-message-content');
                                        if (!infoMessageContent) {
                                            console.warn('⚠️ 未找到.info-message-content');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.info-message-content');
                                        
                                        // 步骤19: 查找.item-list
                                        let itemList = infoMessageContent.querySelector('.item-list');
                                        if (!itemList) {
                                            console.warn('⚠️ 未找到.item-list');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.item-list');
                                        
                                        // 步骤20: 查找所有.info-item
                                        let infoItems = itemList.querySelectorAll('.info-item');
                                        if (infoItems.length < 4) {
                                            console.warn(`⚠️ 只有 ${infoItems.length} 个.info-item，需要至少4个`);
                                            
                                            // 调试：查看所有info-item的内容
                                            infoItems.forEach((item, index) => {
                                                const title = item.querySelector('.info-item-tit')?.textContent?.trim() || '无标题';
                                                const value = item.querySelector('.info-item-val')?.textContent?.trim() || '无值';
                                                console.log(`  info-item[${index}]: ${title} = ${value}`);
                                            });
                                            
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log(`✅ 找到 ${infoItems.length} 个.info-item`);
                                        
                                        // 步骤21: 获取第四个info-item（索引3）
                                        const fourthInfoItem = infoItems[3];
                                        console.log('✅ 第四个info-item:', fourthInfoItem);
                                        
                                        // 步骤22: 获取.info-item-val
                                        const infoItemVal = fourthInfoItem.querySelector('.info-item-val');
                                        if (!infoItemVal) {
                                            console.warn('⚠️ 第四个info-item中没有.info-item-val');
                                            
                                            // 查看第四个info-item的内部结构
                                            console.log('🔍 第四个info-item的innerHTML:', fourthInfoItem.innerHTML);
                                            console.log('🔍 第四个info-item的textContent:', fourthInfoItem.textContent);
                                            
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        console.log('✅ 找到.info-item-val');
                                        
                                        // 步骤23: 获取快递单号
                                        const trackingNumber = infoItemVal.textContent.trim();
                                        console.log('✅ 获取到快递单号:', trackingNumber);
                                        
                                        if (!trackingNumber) {
                                            console.warn('⚠️ 快递单号为空');
                                            setTimeout(findTrackingNumber, 500);
                                            return;
                                        }
                                        
                                        resolve(trackingNumber);
                                    }
                                    
                                } catch (e) {
                                    console.error('❌ 提取快递单号出错:', e);
                                    setTimeout(findTrackingNumber, 500);
                                }
                            };
                            
                            findTrackingNumber();
                        });
                    }
                    
                    // 淘宝提取快递单号
                    function extractTrackingNumberTB() {
                        return new Promise((resolve, reject) => {
                            console.log('� 开始提取淘宝快递单号');
                            
                            let startTime = Date.now();
                            const timeout = 10000; // 10秒超时
                            
                            // 淘宝页面查找快递单号
                            const findTrackingNumber = () => {
                                // 检查是否超时
                                if (Date.now() - startTime > timeout) {
                                    console.error('❌ 提取快递单号超时');
                                    reject(new Error('提取快递单号超时'));
                                    return;
                                }
                                
                                try {
                                    // 方法1：查找.expressId--zegtKfpq类
                                    let expressIdElements = document.querySelectorAll('.expressId--zegtKfpq');
                                    if (expressIdElements.length > 0) {
                                        let trackingNumber = expressIdElements[0].textContent.trim();
                                        if (trackingNumber) {
                                            console.log('✅ 从.expressId--zegtKfpq获取到快递单号:', trackingNumber);
                                            resolve(trackingNumber);
                                            return;
                                        }
                                    }
                                    
                                    // 方法2：查找包含快递单号的元素
                                    let allElements = document.querySelectorAll('*');
                                    for (let element of allElements) {
                                        let textContent = element.textContent || '';
                                        let trackingMatch = textContent.match(/快递单号[:：]\s*(\d{12,})/);
                                        if (trackingMatch && trackingMatch[1]) {
                                            console.log('✅ 从文本匹配获取到快递单号:', trackingMatch[1]);
                                            resolve(trackingMatch[1]);
                                            return;
                                        }
                                    }
                                    
                                    // 方法3：查找物流信息区域
                                    let logisticsElements = document.querySelectorAll('.logisticPopoverContent--MaLWhCj9');
                                    for (let logisticsElement of logisticsElements) {
                                        let trackingNumber = logisticsElement.querySelector('.expressId--zegtKfpq');
                                        if (trackingNumber) {
                                            let number = trackingNumber.textContent.trim();
                                            if (number) {
                                                console.log('✅ 从物流弹窗获取到快递单号:', number);
                                                resolve(number);
                                                return;
                                            }
                                        }
                                    }
                                    
                                    console.log('⏳ 未找到快递单号，500ms后重试');
                                    setTimeout(findTrackingNumber, 500);
                                    
                                } catch (e) {
                                    console.error('❌ 提取快递单号出错:', e);
                                    setTimeout(findTrackingNumber, 500);
                                }
                            };
                            
                            findTrackingNumber();
                        });
                    }
                    
                    // 执行整个流程
                    async function getTrackingNumber() {
                        try {
                            console.log('🔄 开始获取快递单号');
                            // 等待页面加载完成
                            await new Promise(resolve => setTimeout(resolve, 2000));
                            
                            let trackingNumber;
                            if (action === 'getTrackingNumberTB') {
                                // 处理淘宝
                                trackingNumber = await processTB();
                            } else {
                                // 处理1688
                                trackingNumber = await process1688();
                            }
                            
                            // 将结果发送回background脚本，包含requestId
                            chrome.runtime.sendMessage({ action: 'trackingNumberResult', requestId: requestId, trackingNumber: trackingNumber });
                        } catch (error) {
                            console.error('❌ 获取快递单号失败:', error);
                            chrome.runtime.sendMessage({ action: 'trackingNumberResult', requestId: requestId, error: error.message });
                        }
                    }
                    
                    // 启动流程
                    getTrackingNumber();
                }
            }).then(() => {
                // 监听来自注入脚本的响应，检查requestId
                const listener = (message, sender) => {
                    if (message.action === 'trackingNumberResult' && message.requestId === requestId) {
                        // 移除监听器
                        chrome.runtime.onMessage.removeListener(listener);
                        // 返回结果
                        if (message.error) {
                            sendResponse({ error: message.error });
                        } else {
                            sendResponse({ trackingNumber: message.trackingNumber });
                        }
                        // 关闭标签页
                        chrome.tabs.remove(tab.id);
                    }
                };
                chrome.runtime.onMessage.addListener(listener);
            });
        }, 3000); // 等待3秒，确保页面加载完成
    });
    
    return true; // 保持消息通道开放
}
    else if (request.type === 'FLOAT_BUTTON_CLICKED') {
        console.log('接收到悬浮按钮点击消息');
        // 标记这是由悬浮按钮触发的采集
        isFloatButtonTriggered = true;
        // 发送响应
        sendResponse({});
        return true;
    }
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
        GenericOnClick(info, tab);
    
});
var tabId = '';

// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    tabId = request.tabId + '';
    if (request.Type === "CollectionGoodsku") {
        let itemUrl = sender.url;
        if (request.sourceUrl != null && request.sourceUrl !== '') {
            itemUrl = request.sourceUrl;
        }
        const specPlatform = ['yangkeduo.com'];
        if (specPlatform.find(x => sender.url.indexOf(x) > 0)) {
            itemUrl = sender.tab.url;
        }
        let isLinkCollect = false;
        if (request.link) {
            itemUrl = request.link;
            isLinkCollect = true;
        }
        GenericOnClick({"pageUrl": itemUrl}, sender.tab, request.IsVerifyDuplicate, true, isLinkCollect, 1, request.packageDimensions || null);
        sendResponse('');
    }else if (request.Type === "CollectionOzonAllVariants") {
        // Ozon 的全部变体必须与当前源商品合并走 SKU 采集接口。
        // AnalyticalOzonProducts 会将当前 SKU 和所有 SkuLinks 去重后写入同一 skulist。
        let itemUrl = request.sourceUrl || sender.url;
        GenericOnClick({"pageUrl": itemUrl}, sender.tab, request.IsVerifyDuplicate, true, false, 1);
        sendResponse('');
    }else if (request.Type === "CollectionGoods") {
        let itemUrl = sender.url;
        if (request.sourceUrl != null && request.sourceUrl !== '') {
            itemUrl = request.sourceUrl;
        }
        const specPlatform = ['yangkeduo.com'];
        if (specPlatform.find(x => sender.url.indexOf(x) > 0)) {
            itemUrl = sender.tab.url;
        }
        let isLinkCollect = false;
        if (request.link) {
            itemUrl = request.link;
            isLinkCollect = true;
        }
        GenericOnClick({"pageUrl": itemUrl}, sender.tab, request.IsVerifyDuplicate, true, isLinkCollect,0);
        sendResponse('');
    } else if (request.Type === "UploadImage") {
        var imageUrl = request.ImageUrl;
        UploadImageToOss(imageUrl, sendResponse);
    } else if (request.Type === "VerifyVersion") {
        VerifyVersion(
            function () {
                sendResponse('');
            },
            function (latestVersion, latestUrl) {
                sendResponse({
                    "LatestVersion": latestVersion,
                    "LatestUrl": "https://www.51selling.com/HelpDocument/ShowHelpDocument/8"
                });
            }
        );
    } else if (request.Type === "CollectionCategory") {
        categoryCrawlProcess(request.PlatformId, request.PlatformName, sender.url, sender.tab, sendResponse);
    } else if (request.Type === "CollectionRepeatGoods") {
        ExecuteRepeateProduct(request.link, sender.tab, sendResponse)
    }
    return true;
});

//监听系统通知后用户点击按钮
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
    if (notificationId.indexOf("51selling_login") > -1 && buttonIndex === 0) {
        chrome.tabs.create({
            url: dldomain
        });
    } else if (notificationId.indexOf("51selling_update") > -1 && buttonIndex === 0) {
        chrome.tabs.create({
            url: dldomain
        });
    }
});


//监听Shopee页面所有请求消息
chrome.webRequest.onBeforeSendHeaders.addListener(
    (function (details) {
        if ((-1 !== details.url.indexOf("shopee") || -1 !== details.url.indexOf("xiapibuy")) && details.requestHeaders && details.requestHeaders.length && details.tabId != -1) {
            var shopeeHeadersData = {shopeeHeaders: true};

            var requestHeaders = details.requestHeaders;

            for (var i = 0; i < requestHeaders.length; i++) {
                var header = requestHeaders[i];
                shopeeHeadersData[header.name] = header.value;

                // 判断是否为最后一个请求头
                if (i + 1 === requestHeaders.length) {
                    shopeeHeadersData['shopeeV4Url'] = details.url;
                    sendMessageToContentScript({
                        "Type": "SaveKey",
                        "Key": "_LiSellingShopeeSign_",
                        "Value": shopeeHeadersData
                    }, {"id": details.tabId}, function (response) {
                    });
                    break;
                }
            }

        }
    }),
    {
        urls: [
            "*://*/api/v4/item/get?*",
            "*://*/api/v4/search/search_items?*",
            "*://*/api/v4/pdp/get_pc?*"
        ]
    }, ["requestHeaders"]);

//监听Temu页面请求头
chrome.webRequest.onBeforeSendHeaders.addListener(
    (function (details) {
        var requestHeaders = details.requestHeaders,
            temuCrawlUrl = details.url,
            lastIndex = temuCrawlUrl ? temuCrawlUrl.lastIndexOf('/') : -1,
            apiName = lastIndex > -1 ? temuCrawlUrl.substr(lastIndex + 1) : '';

        if (requestHeaders && requestHeaders.length && apiName && apiName === 'render') {
            var temuHeadersData = {temuHeaders: true};

            //循环请求头
            for (var i = 0; i < requestHeaders.length; i++) {
                temuHeadersData[requestHeaders[i].name] = requestHeaders[i].value;//把value返回到前台页面，用来请求temu获取数据

                //判断是否为最后一个请求头
                if (i + 1 === requestHeaders.length) {
                    sendMessageToContentScript({
                        "Type": "SaveKey",
                        "Key": "_LiSellingTemuSign_",
                        "Value": temuHeadersData
                    }, {"id": details.tabId}, function (response) {
                    });
                }
            }
        }
    }),
    {
        urls: [
            "*://www.temu.com/*/api/oak/integration/*",
            "*://www.temu.com/api/oak/integration/*"
        ]
    }, ["requestHeaders"]);

//监听Temu页面请求Body
chrome.webRequest.onBeforeRequest.addListener(
    (function (details) {
        var requestBody = details.requestBody,
            requestBodyType = 'formData';

        if (requestBody && (requestBody.formData && requestBody.formData.data || requestBody.raw)) {
            if (requestBody && requestBody.raw && !requestBody.formData)
                requestBodyType = 'raw';
            requestBody = requestBodyType === 'formData' ? requestBody.formData.data[0] : requestBody.raw[0].bytes;

            if (requestBodyType === 'raw') {
                requestBody = decodeURIComponent(String.fromCharCode.apply(null, new Uint8Array(requestBody)));
            }

            sendMessageToContentScript({
                "Type": "SaveKey",
                "Key": "_LiSellingTemuRequestData_",
                "Value": {'url': details.url, 'data': requestBody, 'type': requestBodyType}
            }, {"id": details.tabId}, function (response) {
            });
        }
    }),
    {
        urls: [
            "*://www.temu.com/*/api/oak/integration/*",
            "*://www.temu.com/api/oak/integration/*"
        ]
    }, ["requestBody"]);
// 监听拼多多批发页面所有请求消息
chrome.webRequest.onBeforeSendHeaders.addListener(
    (function (details) {
        var PinDuoDuoHeadersData = {PinDuoDuoHeaders: true};

        var requestHeaders = details.requestHeaders;
        for (var i = 0; i < requestHeaders.length; i++) {
            var header = requestHeaders[i];
            PinDuoDuoHeadersData[header.name] = header.value;

            // 判断是否为最后一个请求头
            if (i + 1 === requestHeaders.length) {
                sendMessageToContentScript({
                    "Type": "SaveKey",
                    "Key": "_LiSellingPinDuoDuoSign_",
                    "Value": PinDuoDuoHeadersData
                }, {"id": details.tabId}, function (response) {
                });
                break;
            }
        }
    }),
    {
        urls: [
            "*://pifa.pinduoduo.com/pifa/goods/queryGoodsShareInfo*"
        ]
    }, ["requestHeaders"]);

chrome.webRequest.onBeforeRequest.addListener(function (details) {
        if (details.method === 'GET') {
            setTimeout(function () {
                sendMessageToContentScript({
                    "Type": "SaveKey",
                    "Key": "_LiSellingJDSign_",
                    "Value": details.url
                }, {"id": details.tabId}, function (response) {
                });
            }, 1000);
        }
    },
    {
        urls: [
            "*://api.m.jd.com/?appid=pc-item-soa*",
            "*://api.m.jd.com/description/channel?appid=i-item_fe*"
        ]
    },
    ["requestBody"]);
//监听天猫页面所有请求消息，隐藏验证码
chrome.webRequest.onHeadersReceived.addListener(function (details) {
        //如果当前请求地址上带有slide?字段，那么就是天猫的滑动条验证码事件触发
        if (details.url.indexOf('slide?') !== -1 ||
            details.url.indexOf('https://h5api.m.tmall.com/h5/mtop.taobao.pcdetail.data.get/1.0/_____tmd_____/page/mtoph5_close_iframe_page') !== -1 ||
            details.url.indexOf('https://item.taobao.com/item.htm/_____tmd_____/page/close_iframe_page') !== -1 ||
            (details.url.indexOf('https://item.taobao.com/item.htm/_____tmd_____/report') !== -1 && details.url.indexOf('setCookieSuccess') !== -1)
            || details.url.indexOf('newslidevalidate?') !== -1) 
        {
            //隐藏验证码
            sendMessageToContentScript({"Type": "HideTmallVerifyBox"}, {"id": details.tabId}, function (response) {
            });
        }
        
        if(details.url.indexOf('market.yandex.ru/product--') !== -1 || details.url.indexOf('market.yandex.ru/card') !== -1){
            //隐藏验证
            sendMessageToContentScript({"Type": "HideYandexVerifyBox"}, {"id": details.tabId}, function (response) {});
        }
    },
    {
        urls: [
            "*://h5api.m.tmall.com/h5/mtop.taobao.detail.getdesc/*", //天猫新版页面的滑动条验证监听
            "*://h5api.m.tmall.com/h5/mtop.taobao.pcdetail.data.get/*", //天猫新版页面的滑动条验证监听
            "*://h5api.m.tmall.hk/h5/mtop.taobao.pcdetail.data.get/*", //天猫新版页面的滑动条验证监听
            "*://detail.tmall.com/item_o.htm/_____tmd_____/slide*",//天猫旧版页面的滑动条验证监听
            "*://item.taobao.com/item.htm/_____tmd_____/slide*",//天猫旧版页面的滑动条验证监听
            "*://h5api.m.taobao.com/h5/mtop.taobao.detail.getdesc/*", //淘宝新版滑动条验证监听
            "*://h5api.m.taobao.com/h5/mtop.taobao.pcdetail.data.get/*", //淘宝新版页面的滑动条验证监听
            "*://h5api.m.taobao.hk/h5/mtop.taobao.pcdetail.data.get/*", //淘宝新版页面的滑动条验证监听
            "*://item.taobao.com/item.htm/_____tmd_____/slide*", //淘宝滑动条验证监听
            "*://market.yandex.ru/*" 
        ]
    });
// background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.Type === "GetProductInfo") {
        const url = request.url;
        
        // 获取标签页ID
        chrome.tabs.query({url: url}, function(tabs) {
            if (tabs && tabs.length > 0) {
                const tab = tabs[0];
                
                // 向内容脚本发送消息获取页面内容
                sendMessageToContentScript({
                    "Type": "GetPageContent"
                }, tab, function(response) {
                    if (response && response.content) {
                        // 返回页面内容
                        sendResponse({
                            content: response.content,
                            tab: tab
                        });
                    } else {
                        sendResponse({error: "无法获取页面内容"});
                    }
                });
            } else {
                sendResponse({error: "未找到匹配的标签页"});
            }
        });
        
        return true; // 保持sendResponse可用
    }
});
//cookie变更监听
chrome.cookies.onChanged.addListener((changeInfo) => {
    if (!changeInfo.removed && changeInfo.cookie) {
        if (changeInfo.cookie.name == '_m_h5_tk') {
            var value = changeInfo.cookie.value;
            if (value.indexOf('_') > -1)
                value = value.split('_')[0];

            //存储数据到本地
            if (value && value.length > 0) {
                if (changeInfo.cookie.domain == '.taobao.com') {
                    chrome.storage.local.set({ wyystaobaoh5tk: value }, function () { });
                } else if (changeInfo.cookie.domain == '.tmall.com') {
                    chrome.storage.local.set({ wyystmallh5tk: value }, function () { });
                } else if (changeInfo.cookie.domain == '.aliexpress.com') {
                    chrome.storage.local.set({ wyysaliexpressh5tk: value }, function () { });
                } else if (changeInfo.cookie.domain == '.aliexpress.ru') {
                    chrome.storage.local.set({ wyysaliexpressruh5tk: value }, function () { });
                }
            }
        } else if (changeInfo.cookie.name == 'aep_usuc_f') {
            var value = changeInfo.cookie.value;
            //存储数据到本地
            if (value && value.length > 0) {
                if (changeInfo.cookie.domain == '.aliexpress.com') {
                    chrome.storage.local.set({ wyysaliexpressh5aepusucf: value }, function () { });
                } else if (changeInfo.cookie.domain == '.aliexpress.ru') {
                    chrome.storage.local.set({ wyysaliexpressruh5aepusucf: value }, function () { });
                }
            }
        }
    }
});

//上传图片到OSS
function UploadImageToOss(imageUrl, sendResponse) {
    VerifyLogin(
        function () {
            UploadImage(imageUrl, function (image) {
                sendResponse(image);
            });
        },
        function () {
            sendResponse(imageUrl);//这里没登录也不报错，直接返回原图URL
        }
    );
}

//采集产品点击事件
function GenericOnClick(info, tab, isVerifyDuplicate = true, isContent = false, isLinkCollect = false, issku = 0, packageDimensions = null) {
    //isContent表示是否来源于Content，用于判断应该给什么类型的弹窗，右键点击采集的，有可能页面没有注入脚本，无法弹出自定义弹窗
    VerifyVersion(//验证插件版本
        function () {
            VerifyLogin(//验证是否登录
                function () {
                    let fnBody;
                    let url;
                    if (info.linkUrl === undefined) {
                        url = info.pageUrl;
                    } else {
                        url = info.linkUrl;
                        isLinkCollect = true;
                        let isSupportSite = false;
                        let isSupportUrl = false;
                        if (url.indexOf('aliexpress.us') !== -1) {
                            fnBody = platformLinkRule['aliexpress.com'].detail;
                            isSupportSite = true;
                            if (fnBody(url)) {
                                isSupportUrl = true;
                            }
                        } else {
                            for (let item in platformLinkRule) {
                                if (url.indexOf(item) !== -1) {
                                    fnBody = platformLinkRule[item].detail;
                                    isSupportSite = true;
                                    if (fnBody(url)) {
                                        isSupportUrl = true;
                                    }
                                }
                            }
                        }

                        if (!isSupportSite) {
                            sendMessageToContentScript({
                                "Type": "Alter",
                                "MessageType": "error",
                                "Message": "该平台暂不支持快速采集!"
                            }, tab, function (response) {
                            });
                            return;
                        }
                        if (!isSupportUrl) {
                            sendMessageToContentScript({
                                "Type": "Alter",
                                "MessageType": "error",
                                "Message": "该链接不支持采集!"
                            }, tab, function (response) {
                            });
                            return;
                        }
                    }
                    const currentFloatButtonTriggered = isFloatButtonTriggered === true;
                    isFloatButtonTriggered = false;
                    console.log('isFloatButtonTriggered:', currentFloatButtonTriggered);
                    ExecuteProductAcquisitionLogic(url, tab, isVerifyDuplicate, isLinkCollect, issku, currentFloatButtonTriggered, packageDimensions);
                },
                function () {
                    if (isContent) {
                        sendMessageToContentScript({
                            "Type": "RedirectSite",
                            "MessageType": "warning",
                            "Message": "当前无登录用户，点击确认前往登录！",
                            "Site": dldomain
                        }, tab, function (response) {
                        });
                    } else {
                        chrome.notifications.create("51selling_login" + new Date(), {
                            type: 'basic',
                            iconUrl: 'img/icon_128.png',
                            title: '熊猫ERP',
                            message: "当前无登录用户，请先前往"+dldomain+"进行登录！",
                            buttons: [{title: "立即前往"}]
                        });
                    }
                }
            );
        },
        function (latestVersion, latestUrl) {
            if (isContent) {
                sendMessageToContentScript({
                    "Type": "RedirectSite",
                    "MessageType": "warning",
                    "Message": "检测到最新插件版本为" + latestVersion + "，点击确认前往下载最新版本",
                    "Site": dldomain
                }, tab, function (response) {
                });
            } else {
                chrome.notifications.create("51selling_update" + new Date(), {
                    type: 'basic',
                    iconUrl: 'img/icon_128.png',
                    title: '熊猫ERP',
                    message: "检测到最新插件版本为" + latestVersion + "，请先前往" + dldomain + "升级最新版本！给您带来的不便，敬请谅解！",
                    buttons: [{title: "立即前往"}]
                });
            }

        }
    );

}

//分析相关方法



// chrome.cookies API 在 Chrome 147+ / 启用"阻止第三方 cookie"时可能返回空。
// 这个兜底从目标域已打开的标签页里用 scripting.executeScript 读 document.cookie，
// 解析出指定 name 的值。若仍拿不到（cookies.get 空 + 没开标签页），返回 null。
function parseCookieString(cookieStr, name) {
    if (!cookieStr) return null;
    const parts = cookieStr.split(';');
    for (let i = 0; i < parts.length; i++) {
        const p = parts[i].trim();
        const eq = p.indexOf('=');
        if (eq < 0) continue;
        if (p.slice(0, eq) === name) return p.slice(eq + 1);
    }
    return null;
}

function readCookieFromOpenTab(url, name, cb) {
    let urlObj;
    try { urlObj = new URL(url); } catch (e) { cb(null); return; }
    const candidates = [
        'https://' + urlObj.host + '/*',
        'http://' + urlObj.host + '/*',
    ];
    chrome.tabs.query({ url: candidates }, (tabs) => {
        if (!tabs || !tabs.length) { cb(null); return; }
        const tab = tabs[0];
        try {
            chrome.scripting.executeScript({
                target: { tabId: tab.id },
                func: () => document.cookie || '',
            }).then((results) => {
                const first = results && results[0];
                const val = first ? parseCookieString(first.result, name) : null;
                cb(val);
            }).catch(() => cb(null));
        } catch (e) { cb(null); }
    });
}

function readCookieWithFallback(url, name, cb) {
    console.log('[readCookieWithFallback] 开始读取 cookie:', name, 'from', url);
    try {
        chrome.cookies.get({ url: url, name: name }, (cookie) => {
            console.log('[readCookieWithFallback] chrome.cookies.get result:', cookie);
            if (cookie && cookie.value) {
                console.log('[readCookieWithFallback] 通过 chrome.cookies.get 找到 cookie');
                cb(cookie.value);
                return;
            }
            console.log('[readCookieWithFallback] chrome.cookies.get 为空，尝试 getAll');
            // 尝试 getAll，不限制 domain，直接按 name 过滤
            try {
                chrome.cookies.getAll({}, (cookies) => {
                    let found = cookies.find(c => c.name === name);
                    if (found && found.value) {
                        console.log('[readCookieWithFallback] 通过 getAll 找到 cookie, domain:', found.domain, 'path:', found.path);
                        cb(found.value);
                        return;
                    }
                    let allNames = cookies.map(c => c.name).join(', ');
                    console.log('[readCookieWithFallback] getAll 扫描了', cookies.length, '个cookie，名称列表:', allNames);
                    console.log('[readCookieWithFallback] 未找到目标 cookie:', name, '，尝试 fallback 到标签页');
                    readCookieFromOpenTab(url, name, cb);
                });
            } catch (e2) {
                readCookieFromOpenTab(url, name, cb);
            }
        });
    } catch (e) {
        console.log('[readCookieWithFallback] chrome.cookies.get 异常:', e);
        readCookieFromOpenTab(url, name, cb);
    }
}

function getCookies() {
    return new Promise((resolve) => {
        readCookieWithFallback(dldomain, 'token', (value) => {
            if (value) { token = value; resolve({ token: value }); }
            else resolve('');
        });
    });
}


async function httpPost(url, params = {}, callback = () => {
}) {
    getCookies().then(({token}) => {
        let headers = {"Access-Control-Allow-Origin": "*", "Content-Type": "application/json",};
        if (token) {
            headers["Authorization"] = token;
            headers["X-Token"] = token;
        }
		params.token = token;
        fetch(SERVER_HOST + url, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(params),
        }).then(function (res) {
            return res.json()
        }).then((response) => callback(response)).catch((error) => callback(error))
    })
}

function getCookiesoz() {
    return new Promise((resolve) => {
        readCookieWithFallback('https://seller.ozon.ru', 'sc_company_id', (value) => {
            if (value) resolve({ token: value, sc_company_id: value });
            else resolve('');
        });
    });
}

function readCookieValue(url, name) {
    return new Promise((resolve) => {
        readCookieWithFallback(url, name, (value) => resolve(value || ''));
    });
}

function normalizeCompanyId(value) {
    const text = String(value || '').trim();
    const match = text.match(/\d{3,}/);
    return match ? match[0] : '';
}

async function readSellerCompanyIdFromTab(tabId) {
    if (!tabId) return '';
    try {
        const results = await chrome.scripting.executeScript({
            target: { tabId },
            world: 'MAIN',
            func: () => {
                function clean(value) {
                    const text = String(value || '').trim();
                    const match = text.match(/\d{3,}/);
                    return match ? match[0] : '';
                }

                function readCookie(name) {
                    const pairs = String(document.cookie || '').split(';');
                    for (let i = 0; i < pairs.length; i++) {
                        const item = pairs[i].trim();
                        const eq = item.indexOf('=');
                        if (eq > 0 && item.slice(0, eq) === name) return clean(item.slice(eq + 1));
                    }
                    return '';
                }

                function scanText(text) {
                    const source = String(text || '');
                    const patterns = [
                        /sc_company_id["'\s:=]+(\d{3,})/i,
                        /company_id["'\s:=]+(\d{3,})/i,
                        /companyId["'\s:=]+(\d{3,})/i,
                        /"company_id"\s*:\s*"?(\d{3,})"?/i,
                        /"companyId"\s*:\s*"?(\d{3,})"?/i
                    ];
                    for (let i = 0; i < patterns.length; i++) {
                        const match = source.match(patterns[i]);
                        if (match && match[1]) return clean(match[1]);
                    }
                    return '';
                }

                const cookieValue = readCookie('sc_company_id');
                if (cookieValue) return cookieValue;

                const stores = [window.localStorage, window.sessionStorage];
                for (let s = 0; s < stores.length; s++) {
                    const store = stores[s];
                    try {
                        for (let i = 0; i < store.length; i++) {
                            const key = store.key(i) || '';
                            const val = store.getItem(key) || '';
                            const found = scanText(key + ':' + val);
                            if (found) return found;
                        }
                    } catch (e) {}
                }

                return '';
            }
        });
        return normalizeCompanyId(results && results[0] && results[0].result);
    } catch (e) {
        return '';
    }
}

async function getSellerCompanyId(targetTab) {
    let companyId = normalizeCompanyId(await readCookieValue('https://seller.ozon.ru', 'sc_company_id'));
    if (companyId) return companyId;

    companyId = normalizeCompanyId(await readCookieValue('https://www.ozon.ru', 'sc_company_id'));
    if (companyId) return companyId;

    companyId = await readSellerCompanyIdFromTab(targetTab && targetTab.id);
    if (companyId) return companyId;

    throw new Error('未检测到店铺 company_id：请在同一个 Chrome 里打开 seller.ozon.ru 店铺首页，刷新一次后回到 Ozon 前台点重新获取');
}

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

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

// 批量上报队列
var spiderOzonBatchQueue = [];
var spiderOzonBatchTimer = null;
const SPIDER_BATCH_DELAY = 3000;

function generateRandomString(length) {
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var result = '';
    for (var i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

function flushSpiderOzonBatch() {
    if (spiderOzonBatchQueue.length === 0) return;
    var batch = spiderOzonBatchQueue.splice(0);
    var payloads = batch.map(function(item) {
        return OzAnalytics.buildSpiderPayload(item.dataObj, item.sku);
    });
    getCookies().then(function({token}) {
        var headers = {"Access-Control-Allow-Origin": "*", "Content-Type": "application/json"};
        if (token) {
            headers["Authorization"] = token;
            headers["X-Token"] = token;
        }
        var jsonStr = JSON.stringify(payloads);
        var base64Data = btoa(encodeURIComponent(jsonStr));
        var randomPrefix = generateRandomString(33);
        var body = randomPrefix + base64Data;
        fetch(SERVER_HOST + OzAnalytics.SPIDER_PATH, {
            method: "POST",
            headers: headers,
            body: body
        }).then(function(res) {
            return res.json();
        }).then(function(response) {
            if (response && response.error) {
                console.error('批量发送到 SpiderOzon 失败:', response.message || response);
            } else {
                console.log('批量发送到 SpiderOzon 成功，条数:', payloads.length);
            }
        }).catch(function(error) {
            console.error('批量发送到 SpiderOzon 请求异常:', error);
        });
    });
}

// 5.19 新增：合并 analytics + search + detail 后上报到自家服务器 /SpiderOzon/adtoAll
// 改为批量收集模式：数据入队，debounce 后自动发送；业务层可主动调用 flushSpiderOzonBatch
function sendToSpiderOzon(dataObj, sku) {
    spiderOzonBatchQueue.push({ dataObj: dataObj, sku: sku });
    if (spiderOzonBatchTimer) clearTimeout(spiderOzonBatchTimer);
    spiderOzonBatchTimer = setTimeout(flushSpiderOzonBatch, SPIDER_BATCH_DELAY);
}

// 后台 service worker 直接 fetch；body/headers/响应整形均走共享模块。
async function httpPostoz(url, params = {}, callback = () => {}) {
    try {
        const {token, sc_company_id} = await getCookiesoz();
        const headers = OzAnalytics.buildHeaders(sc_company_id, true);
        const sku = OzAnalytics.ggetSkuFromurl(params.url);
        const requestBody = OzAnalytics.buildRequestBody(sku);
        const pourl = OzAnalytics.ANALYTICS_URL;

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

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

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

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

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

// ===== 定时抓取 SKU 列表并处理 =====
const SKU_LIST_URL = SERVER_HOST + '/SpiderOzon/getSpilist';
const SKU_LIST_FETCH_INTERVAL = 1 * 30 * 1000; // 5分钟

async function fetchSkuList() {
    try {
        const resp = await fetch(SKU_LIST_URL);
        if (!resp.ok) {
            console.error('[定时抓取] 获取SKU列表失败:', resp.status);
            return [];
        }
        const result = await resp.json();
        if (result.status !== 200 || !Array.isArray(result.data)) {
            console.error('[定时抓取] SKU列表格式异常:', result);
            return [];
        }
        return result.data.map(item => item.sku?.trim()).filter(Boolean);
    } catch (e) {
        console.error('[定时抓取] fetchSkuList 出错:', e);
        return [];
    }
}

async function processSkuList(skus) {
    for (const sku of skus) {
        const fakeUrl = `https://www.ozon.ru/product/any-${sku}`;
        await new Promise((resolve) => {
            httpPostoz(OzAnalytics.ANALYTICS_URL, { url: fakeUrl }, function(result) {
                console.log('[定时抓取] SKU处理完成:', sku);
                resolve();
            });
        });
        await new Promise(r => setTimeout(r, 1000)); // 间隔1秒，避免请求过快
    }
}

function startScheduledSkuFetch() {
    async function tick() {
        console.log('[定时抓取] 开始获取SKU列表...');
        const skus = await fetchSkuList();
        if (skus.length > 0) {
            console.log('[定时抓取] 获取到', skus.length, '个SKU');
            await processSkuList(skus);
            console.log('[定时抓取] 全部处理完成，进入休眠');
        } else {
            console.log('[定时抓取] 没有待处理的SKU');
        }
        setTimeout(tick, SKU_LIST_FETCH_INTERVAL);
    }
    tick();
}

// 启动定时任务
startScheduledSkuFetch();

async function getProductDetailnew(headers, sku) {
    if (!sku) {
        console.log('SKU为空，跳过商品详情搜索');
        return null;
    }

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

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

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

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

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

async function getProductDetail(headers, sku) {
    if (!sku) {
        console.log('SKU为空，跳过商品详情搜索');
        return null;
    }

    try {
        let pourl = 'https://seller.ozon.ru/api/v1/search';
        let paa = JSON.stringify({"company_id":""+headers['x-o3-company-id']+"","need_total":false,"filter":{"children_nodes":{"children_nodes":[{"input_leaf":{"sku":{"values":[""+sku+""]}}}],"operator":"AND"}},"pagination":{"limit":"50"},"is_copy_allowed":false});

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

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

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

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

        if (data.variants && Array.isArray(data.variants) && data.variants.length > 0) {
            const firstItem = data.variants[0];
            //console.log('找到商品详情:', firstItem);
			const specs = getProductSpecifications(firstItem);
			        //console.log('提取到的规格信息:', specs);
			        
			        // 如果需要，可以将规格信息添加到商品对象中
			        firstItem.specifications = specs;
            return firstItem;
        } else {
            console.log('未找到相关商品');
            return null;
        }
    } catch (error) {
        console.error('获取商品详情失败:', error);
        return null;
    }
}
/**
 * 从商品属性中提取尺寸和重量信息
 * @param {Object} productItem - 商品数据对象
 * @returns {Object} 包含尺寸和重量信息的对象
 */
function extractProductDimensions(productItem) {
    const result = {
        weight: productItem.weight,    // 重量
        length: productItem.depth,    // 长度
        width: productItem.width,     // 宽度
        height: productItem.height,     // 高度
        unit: 'g/mm',    // 默认单位（重量是克，尺寸是厘米）
        success: false
    };

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

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

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

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

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

/**
 * 优化的提取函数，包含单位转换和更多信息
 * @param {Object} productItem - 商品数据对象
 * @returns {Object} 完整的商品规格信息
 */
function getProductSpecifications(productItem) {
    const dimensions = extractProductDimensions(productItem);
    
    // 添加更多有用信息
    const specifications = {
        ...dimensions,
        variantId: productItem.variant_id || null,
        name: productItem.name || '',
        description: productItem.description || '',
        
        // 提取其他有用属性
        barcode: null,
        color: null,
        material: null,
        country: null
    };

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

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

    return specifications;
}

/**
 * 格式化显示商品规格信息
 * @param {Object} specs - 商品规格信息
 * @returns {String} 格式化后的字符串
 */
function formatProductSpecifications(specs) {
    const parts = [];
    
    if (specs.variantId) {
        parts.push(`商品ID: ${specs.variantId}`);
    }
    
    if (specs.name) {
        parts.push(`商品名称: ${specs.name.substring(0, 50)}${specs.name.length > 50 ? '...' : ''}`);
    }
    
    // 尺寸信息
    if (specs.length || specs.width || specs.height) {
        const dimParts = [];
        if (specs.length) dimParts.push(`长: ${specs.length}cm`);
        if (specs.width) dimParts.push(`宽: ${specs.width}cm`);
        if (specs.height) dimParts.push(`高: ${specs.height}cm`);
        
        if (dimParts.length > 0) {
            parts.push(`尺寸: ${dimParts.join(' × ')}`);
        }
        
        if (specs.volume) {
            parts.push(`体积: ${specs.volume}cm³`);
        }
    }
    
    if (specs.weight) {
        parts.push(`重量: ${specs.weight}g`);
    }
    
    if (specs.color) {
        parts.push(`颜色: ${specs.color}`);
    }
    
    if (specs.country) {
        parts.push(`产地: ${specs.country}`);
    }
    
    return parts.join('\n');
}


function getBlob(url) {
    let resPromise = new Promise(async function (resolve, reject) {
        fetch(url, {method: "GET", responseType: "blob",}).then(function (res) {
            return res.blob()
        }).then((response) => resolve(response)).catch((error) => reject(error))
    });
    return resPromise
}

async function alibabaPost(url, params, callback = () => {
}) {
    let headers = {"Access-Control-Allow-Origin": "*",};
    let blob = await getBlob(params);
    let formdata = new FormData();
    formdata.append("file", blob, "blob");
    fetch(url, {method: "POST", headers: headers, body: formdata,}).then(function (res) {
        return res.json()
    }).then((response) => callback(response)).catch((error) => callback(error))
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request["type"]) {
        case"panda:saveProductSelection":
            saveProductSelectionSnapshot(request.snapshot || {}, sendResponse);
            return true;

        case"goseller":
            if (request["params"]["fxout"] !== undefined && request["params"]["fxout"]!== '' && request["params"]["fxout"]== 1) {
                 httpPost(request["url"], request["params"], (res) => {
                     sendResponse(res)
                 });
            }else{
            	httpPostoz(request["url"], request["params"], (res) => {
            	    sendResponse(res)
            	});
            }
            break;
        case"1688":
            alibabaPost(request["url"], request["params"], (res) => {
                sendResponse(res)
            });
            break;

        case"getCookie":
            readCookieWithFallback(request.url, request.name, sendResponse);
            return true;

        case"panda:ozonInsights":
            {
                const sku = String(request.sku || '').trim();
                if (!sku) {
                    sendResponse({ ok: false, error: 'missing sku' });
                    break;
                }
                fetchPandaOzonInsights(sku)
                    .then((data) => sendResponse({ ok: true, data }))
                    .catch((e) => sendResponse({ ok: false, error: e.message || String(e) }));
                return true;
            }

        case"getGoodsInfo":
            {
                const prodUrl = (request.params || {}).url || '';
                if (!prodUrl) { sendResponse({ code: 0, msg: '无URL' }); break; }

                // 尝试通过打开的OZON页面的内容脚本获取数据
                chrome.tabs.query({ url: ['*://*.ozon.ru/*'] }, (tabs) => {
                    if (tabs && tabs.length > 0) {
                        // 找与请求URL匹配的标签页，或者用第一个
                        let targetTab = tabs.find(t => t.url && prodUrl.includes(t.url.split('/product/')[1]?.split('?')[0])) || tabs[0];
                        chrome.tabs.sendMessage(targetTab.id, {
                            action: 'fetchOzonProductData', url: prodUrl
                        }, function(resp) {
                            if (!chrome.runtime.lastError && resp && resp.success && resp.html) {
                                sendResponse({ code: 200, data: { html: resp.html } });
                            } else {
                                // fallback: 通过httpRequest获取
                                httpRequestOzonPage(prodUrl, sendResponse);
                            }
                        });
                    } else {
                        httpRequestOzonPage(prodUrl, sendResponse);
                    }
                });
                return true;
            }

        // 通过OZON页面API直接获取商品数据
        async function httpRequestOzonPage(url, sr) {
            try {
                const u = new URL(url);
                const resp = await fetch('https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=' + u.pathname, {
                    headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept': 'application/json' }
                });
                const text = await resp.text();
                const data = JSON.parse(text);
                if (data && data.seo && data.seo.script) {
                    const p = JSON.parse(data.seo.script[0].innerHTML);
                    const sku = p.sku || '';
                    const name = p.name || '';
                    const price = p.offers?.price || '';
                    var h = '<div class="ozonhelper-card-good" style="background:#fff;border-radius:12px;padding:16px;margin-top:10px;border:1px solid #e9ebef;text-align:left;font-size:14px;box-shadow:0 16px 48px rgba(10,12,20,.18)">'
                        + '<h4 style="color:#005bff;margin:0 0 12px 0;padding-bottom:10px;border-bottom:1px solid #e9ebef;font-size:16px;font-weight:700">SKU: <span style="font-weight:400;color:#3a3e47">' + sku + '</span></h4>'
                        + '<div class="layui-form-item" style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #e9ebef"><span style="color:#6b7280;font-size:13px">商品名称</span><span style="color:#0a0c14;font-weight:500;font-size:13px">' + (name.substring(0,50)||'无') + '</span></div>'
                        + '<div class="layui-form-item" style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #e9ebef"><span style="color:#6b7280;font-size:13px">价格</span><span style="color:#005bff;font-weight:600;font-size:13px">' + (price||'无') + ' ₽</span></div>'
                        + '<div class="layui-form-item" style="display:flex;justify-content:space-between;padding:6px 0"><span style="color:#6b7280;font-size:13px">卖家</span><span style="color:#0a0c14;font-weight:500;font-size:13px">' + (p.seller?.name || p.brand?.name || '无') + '</span></div>'
                        + '</div>';
                    sr({ code: 200, data: { html: h } });
                } else {
                    sr({ code: 200, data: { html: fallbackCard(prodUrl) } });
                }
            } catch(e) {
                sr({ code: 200, data: { html: fallbackCard(prodUrl) } });
            }
        }
        function fallbackCard(url) {
            var m = url.match(/-(\d+)(?:\?|$)/);
            var s = m ? m[1] : '';
            return '<div class="ozonhelper-card-good" style="background:#fff;border-radius:12px;padding:12px;margin-top:10px;border:1px solid #e9ebef"><h4 style="color:#005bff;margin:0;font-size:14px">SKU: ' + s + '</h4></div>';
        }

        case"jzc:searchVariants":
            {
                const sku = String(request.sku || '').trim();
                if (!sku) {
                    sendResponse({ ok: false, error: 'missing sku' });
                    break;
                }
                fetchSellerPortal('/search-variant-model', { name: sku, limit: '50' })
                    .then((data) => sendResponse({ ok: true, data: { items: data?.items || [] } }))
                    .catch((e) => sendResponse({ ok: false, error: e.message || String(e) }));
                return true;
            }
        default:
            break
    }
    return true
});

async function fetchPandaOzonInsights(sku) {
    const tabs = await chrome.tabs.query({ url: 'https://seller.ozon.ru/*' });
    if (!tabs.length) throw new Error('请先打开 seller.ozon.ru 并完成登录');

    const targetTab =
        tabs.find((t) => t.active) ||
        tabs.find((t) => t.url && t.url.includes('/app/')) ||
        tabs[0];

    const companyId = await getSellerCompanyId(targetTab);

    const analyticsBody = OzAnalytics.buildRequestBody(sku);
    const results = await chrome.scripting.executeScript({
        target: { tabId: targetTab.id },
        world: 'MAIN',
        func: async (productSku, scCompanyId, body) => {
            const headers = {
                accept: 'application/json, text/plain, */*',
                'content-type': 'application/json',
                'x-o3-app-name': 'seller-ui',
                'x-o3-company-id': scCompanyId,
                'x-o3-language': 'zh-Hans',
                'x-o3-page-type': 'products-other',
            };

            async function postJson(url, payload) {
                const ctrl = new AbortController();
                const timer = setTimeout(() => ctrl.abort(), 25000);
                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        signal: ctrl.signal,
                        credentials: 'include',
                        headers,
                        body: JSON.stringify(payload),
                    });
                    clearTimeout(timer);
                    if (response.redirected && /\/(signin|login)/.test(response.url)) {
                        throw new Error('seller.ozon.ru 登录状态已过期');
                    }
                    if (!response.ok) {
                        const text = await response.text().catch(() => '');
                        throw new Error('HTTP ' + response.status + ': ' + text.slice(0, 180));
                    }
                    return response.json();
                } catch (error) {
                    clearTimeout(timer);
                    if (error && error.name === 'AbortError') throw new Error('请求超时');
                    throw error;
                }
            }

            const analytics = await postJson(
                'https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3',
                body
            );
            const first = analytics && Array.isArray(analytics.items) ? analytics.items[0] : null;
            const variantId = first && first.variantId && first.variantId !== '-' ? first.variantId : productSku;
            let productDetail = null;
            let sellerVariant = null;

            if (variantId) {
                try {
                    const detail = await postJson(
                        'https://seller.ozon.ru/api/site/seller-prototype/create-bundle-by-variant-id',
                        {
                            company_id: '' + scCompanyId,
                            variant_id: '' + variantId,
                            source: 'SOURCE_UI_COPY_MERGED',
                        }
                    );
                    productDetail = detail && detail.item ? detail.item : null;
                } catch (error) {
                    productDetail = { _error: error.message || String(error) };
                }
            }

            // create-bundle no longer returns commissions[] for every category.
            // search-variant-model contains the current category's real Seller
            // Portal commission fields, so return the exact SKU item as a
            // second source instead of applying a guessed/default percentage.
            try {
                const variants = await postJson(
                    'https://seller.ozon.ru/api/v1/search-variant-model',
                    { name: String(productSku), limit: '50' }
                );
                const items = variants && Array.isArray(variants.items) ? variants.items : [];
                sellerVariant = items.find((entry) => String(entry.variant_id || '') === String(variantId))
                    || items.find((entry) => String(entry.product_id || '') === String(productSku))
                    || items[0]
                    || null;
            } catch (error) {
                sellerVariant = { _error: error.message || String(error) };
            }

            return { sku: productSku, analytics, productDetail, sellerVariant };
        },
        args: [sku, companyId, analyticsBody],
    });

    const data = results && results[0] && results[0].result;
    if (!data) throw new Error('seller.ozon.ru 页面未返回数据');

    if (data.productDetail && !data.productDetail._error) {
        try {
            data.productDetail.specifications = getProductSpecifications(data.productDetail);
        } catch (e) {}
    }

    try {
        sendToSpiderOzon({
            seller_analytics: data.analytics || null,
            serrchdata: null,
            prinfo: data.productDetail || null,
        }, sku);
    } catch (e) {}

    return data;
}

// ===== 快速核价 (extension-lite) Seller Portal API 代理 =====
async function fetchSellerPortal(path, body) {
    const tabs = await chrome.tabs.query({ url: 'https://seller.ozon.ru/*' });
    if (!tabs.length) throw new Error('请先打开 seller.ozon.ru 并登录');

    const targetTab =
        tabs.find((t) => t.active) ||
        tabs.find((t) => t.url?.includes('/app/')) ||
        tabs[0];

    const companyId = await getSellerCompanyId(targetTab);

    const doFetch = async (apiPath, reqBody, xCompanyId) => {
        const ctrl = new AbortController();
        const timer = setTimeout(() => ctrl.abort(), 25000);
        try {
            const r = await fetch('https://seller.ozon.ru/api/v1' + apiPath, {
                method: 'POST',
                signal: ctrl.signal,
                credentials: 'include',
                headers: {
                    accept: 'application/json, text/plain, */*',
                    'content-type': 'application/json',
                    'x-o3-app-name': 'seller-ui',
                    'x-o3-company-id': xCompanyId,
                    'x-o3-language': 'zh-Hans',
                    'x-o3-page-type': 'products-other',
                },
                body: JSON.stringify(reqBody),
            });
            clearTimeout(timer);
            if (r.redirected && /\/(signin|login)/.test(r.url)) {
                return { ok: false, error: 'seller.ozon.ru 登录态已过期' };
            }
            if (!r.ok) {
                const text = await r.text().catch(() => '');
                return { ok: false, error: 'HTTP ' + r.status + ': ' + text.slice(0, 160) };
            }
            return { ok: true, data: await r.json() };
        } catch (e) {
            clearTimeout(timer);
            if (e.name === 'AbortError') return { ok: false, error: 'fetch 超时' };
            return { ok: false, error: e.message || String(e) };
        }
    };

    const results = await chrome.scripting.executeScript({
        target: { tabId: targetTab.id },
        func: doFetch,
        args: [path, body, companyId],
        world: 'MAIN',
    });
    const r = results?.[0]?.result;
    if (!r) throw new Error('executeScript 无返回');
    if (!r.ok) throw new Error(r.error);
    return r.data;
}
