const dldomain = 'https://sczfai.com';

// 常量定义
const CONSTANTS = {
    HIDDEN_TEXT: '*****',
    TILE_SELECTOR: '[class*="tile-root"]',
    PRODUCT_DETAIL_SELECTOR: "#layoutPage div[data-widget='skuShelfGoods']",
    WEB_SALE_SELECTOR: "#layoutPage div[data-widget='webSale']",
    MESSAGE_TYPE: "goseller",
    MAX_RETRY_DELAY: 0,
    DEFAULT_FXOUT: 0,
    DELAY_TIMEOUT: 500,
    COLOR: {
        POSITIVE: "#19ad85",
        NEGATIVE: "#f81155",
        PRIMARY: "#005bff"
    },
    CONTAINER_SELECTORS: {
        TYPE1: '.i5v',
        TYPE2: '.iw9_23'
    }
};

// 工具函数
function urlToBase64(imageUrl) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.src = imageUrl;
        
        img.onload = function () {
            try {
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img, 0, 0);
                resolve(canvas.toDataURL("image/jpeg", 0.75));
            } catch (error) {
                reject(error);
            }
        };
        
        img.onerror = () => reject(new Error(`无法加载图片: ${imageUrl}`));
    });
}

function normalizeWeight(weight) {
    if (!weight) return "未知";
    return weight
        .replace(/(\d+)\s*гр/g, "$1 g")
        .replace(/(\d+)\s*кг/g, "$1 kg");
}

function showTip(message, element, tipId = "goseller-copy-tips") {
    layer.tips(message, element, {
        id: tipId,
        tips: 1,
        anim: -1,
        tipsMore: false,
        isOutAnim: false,
        skin: "goseller-copy-tips"
    });
}

function showHiddenContentTip(element) {
    showTip(
        "您还没登录或者没有升级套餐，内容不可见，请前往登录或升级套餐",
        element,
        "goseller-login-tips"
    );
}

function updateSalesDynamicsColor(element, salesDynamics) {
    const sadyItem = $(element).find(".salesDynamics");
    const color = salesDynamics < 0 ? CONSTANTS.COLOR.NEGATIVE : CONSTANTS.COLOR.POSITIVE;
    sadyItem.css("color", color);
}

// API通信函数
function sendMessage(url, params = {}, type = CONSTANTS.MESSAGE_TYPE) {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({ url, params, type }, resolve);
    });
}

async function getFxoutValue(name = "fxout") {
    try {
        return await new Promise((resolve) => {
            chrome.runtime.sendMessage({
                type: "getCookie",
                url: dldomain,
                name: name
            }, (response) => resolve(response || null));
        });
    } catch (error) {
        console.error(`获取cookie失败 (${name}):`, error);
        return null;
    }
}

// 数据格式化函数
function formatdata(res, specifications) {
	console.log('ddddddddddddddd')
	console.log(specifications)
    if (!res) return createDefaultResponse();
    
    const result = createDefaultResponse();
    const { data } = result;
    
    // 基本数据
    const basicFields = {
        stock: res.stock,
        sku: res.sku,
        soldSum: res.soldSum,
        soldCount: res.soldCount,
        blockedBySeller: res.blockedBySeller,
        convToCartPdp: res.convToCartPdp,
        avgPrice: res.avgPrice,
        sessionCount: res.sessionCount,
        category1: res.category1,
        category3: res.category3,
        brand: res.brand,
        photo: res.photo,
        minSellerPrice: res.minSellerPrice,
        salesDynamics: res.salesDynamics,
        fboStock: res.fboStock,
        nullableCreateDate: res.nullableCreateDate
    };
    
    data.stock = basicFields.stock || "0";
    data.sku = basicFields.sku || "未知";
    data.gmv = basicFields.soldSum ? `${basicFields.soldSum}卢布` : "未知";
    data.sales = basicFields.soldCount || "未知";
    data.hasGollowSales = basicFields.blockedBySeller === 1 ? '否' : '是';
    data.convTocartPdp = basicFields.convToCartPdp ? `${basicFields.convToCartPdp}%` : "未知";
    data.avgPrice = basicFields.avgPrice ? `${basicFields.avgPrice}卢布` : "未知";
    data.sessionCount = basicFields.sessionCount || "0";
    data.category1 = basicFields.category1 || "未知";
    data.category3 = basicFields.category3 || "未知";
    data.brand = basicFields.brand || "没有数据";
    data.photo = basicFields.photo || "没有数据";
    data.minSellerPrice = basicFields.minSellerPrice ? `${basicFields.minSellerPrice}卢布` : "没有数据";
    data.salesDynamics = basicFields.salesDynamics || "没有数据";
    data.sellerCount = basicFields.fboStock || "-";
    
    // 日期处理
    data.pCreateDate = basicFields.nullableCreateDate ? 
        basicFields.nullableCreateDate.split('T')[0] : "未知";
    
    // 可选字段
    const optionalFields = [
        'pWeight', 'drr', 'salesSchema', 'pdpToCartConversion',
        'convToCartSearch', 'convViewToOrder', 'views',
        'nullableRedemptionRate', 'promoRevenueShare', 'avgDeliveryDays',
        'daysInPromo', 'daysWithTrafarets'
    ];
    
    optionalFields.forEach(field => {
        if (res[field] != null && res[field] !== '') {
            data[field] = res[field];
        }
    });
    
    // 佣金计算（基于卢布售价）
    const tierFromPrice = (p) => {
        if (!p || p <= 0) return null;
        if (p <= 135) return 1;
        if (p <= 437) return 2;
        return 3;
    };
    const TIER_RATE = { 1: 13, 2: 15, 3: 17 };
    const priceNum = parseFloat(basicFields.avgPrice) || 0;
    const tier = tierFromPrice(priceNum);
    const commRate = tier ? TIER_RATE[tier] : 15;
    data.commission = priceNum > 0 ? `−${(priceNum * (commRate / 100)).toFixed(2)}₽ (T${tier} ${commRate}%)` : '—';

    // 规格处理
    if (specifications) {
        data.pWeight = (specifications.weight === "0" || specifications.weight === 0) ?
            '点击获取' : specifications.weight;

        if (specifications.width && specifications.width !== "0" && specifications.width !== 0) {
            data.ptj = `${specifications.width}*${specifications.length || '0'}*${specifications.height || '0'}`;
        }

        // 长宽高（mm → cm）
        data.dimL = specifications.length ? (specifications.length / 10).toFixed(1) : '—';
        data.dimW = specifications.width  ? (specifications.width  / 10).toFixed(1) : '—';
        data.dimH = specifications.height ? (specifications.height / 10).toFixed(1) : '—';

        // 同步到 chrome.storage.local 供快速核价读取
        try {
            const storageKey = 'jz_calc_sku_specs_v1';
            const skuVal = basicFields.sku || '';
            if (skuVal && typeof chrome !== 'undefined' && chrome.storage) {
                chrome.storage.local.get([storageKey], (res) => {
                    const all = res[storageKey] || {};
                    all[skuVal] = {
                        weight: parseFloat(specifications.weight) || 0,
                        dimL: parseFloat(data.dimL) || 0,
                        dimW: parseFloat(data.dimW) || 0,
                        dimH: parseFloat(data.dimH) || 0,
                        ts: Date.now()
                    };
                    chrome.storage.local.set({ [storageKey]: all });
                });
            }
        } catch (e) { console.error('存储规格失败', e); }
    }

    return result;
}

function createDefaultResponse() {
    return {
        msg: "操作成功",
        data: {
            stock: "0",
            sku: "未知",
            gmv: "未知",
            sales: "未知",
            hasGollowSales: "未知",
            convTocartPdp: "未知",
            avgPrice: "未知",
            sessionCount: "0",
            category1: "未知",
            category3: "未知",
            brand: "没有数据",
            photo: "没有数据",
            categoryRateList: CONSTANTS.HIDDEN_TEXT,
            logisticsList: CONSTANTS.HIDDEN_TEXT,
            currencyList: "没有数据",
            isShowVariant: false,
            minSellerPrice: "没有数据",
            salesDynamics: "没有数据",
            pCreateDate: "未知",
            sellerCount: "-",
            isCopyRight: "1",
            pWeight: "点击获取",
            plength: "未知",
            ptj: "未知",
            pwidth: "未知",
            pheight: "未知",
            drr: "-",
            salesSchema: "-",
            pdpToCartConversion: "-",
            convToCartSearch: "-",
            convViewToOrder: "-",
            views: "-",
            nullableRedemptionRate: "-",
            promoRevenueShare: "-",
            sessionCount: "-",
            avgDeliveryDays: "-",
            daysInPromo: "-",
            daysWithTrafarets: "-"
        },
        code: 200
    };
}

// 1688相关函数
async function jump1688(element, imgUrl) {
    const $element = $(element);
    $element.find("i").show();
    
    try {
        const base64 = await urlToBase64(imgUrl);
        const res = await sendMessage(
            "https://stream-upload.taobao.com/api/upload.api?appkey=1688search&folderId=0&_input_charset=utf-8&useGtrSessionFilter=false",
            base64,
            "1688"
        );
        
        $element.find("i").hide();
        
        if (res?.success && res.object?.url) {
            window.open(res.object.url, "_blank");
        } else {
            handle1688Error(res, () => jump1688(element, imgUrl));
        }
    } catch (error) {
        $element.find("i").hide();
        console.error("以图搜图失败:", error);
    }
}

function handle1688Error(res, retryCallback) {
    if (res?.url?.includes("https://login.taobao.com/member/login.jhtml")) {
        handleLoginRequired(retryCallback);
    } else if (res?.data?.url?.includes("/api/upload.api/_____tmd_____/punish?")) {
        handleVerificationRequired(res.data.url, retryCallback);
    }
}

function handleLoginRequired(retryCallback) {
    window.open("https://login.taobao.com/member/login.jhtml", "_blank");
    showConfirmationDialog(
        "以图搜图请求需先登录阿里账号，已为您打开淘宝登录页",
        retryCallback
    );
}

function handleVerificationRequired(url, retryCallback) {
    window.open(url, "_blank");
    showConfirmationDialog(
        "请求需先手动验证，已为您打开验证页面，请前往验证",
        retryCallback
    );
}

function showConfirmationDialog(message, confirmCallback) {
    layer.confirm(message, {
        title: "温馨提示",
        btn: ["我已登录", "暂不登录"],
        skin: "goseller-dialog"
    }, function (index) {
        layer.close(index);
        confirmCallback && confirmCallback();
    }, function (index) {
        layer.close(index);
    });
}

// 重量查询相关函数
async function getWaith(sku) {
    try {
        // 获取当前购物车
        const summary = await $.ajax({
            url: 'https://www.ozon.ru/api/composer-api.bx/_action/summary',
            method: 'GET',
            dataType: 'json'
        });
        
        // 清空购物车
        if (summary && summary.length > 0) {
            const cartItemIds = summary.map(item => item.id);
            await clearCart(cartItemIds);
        }
        
        // 添加商品到购物车
        await addToCart(sku);
        
        // 获取重量信息
        const cartPage = await $.ajax({
            url: 'https://www.ozon.ru/cart?tab=0',
            type: 'GET'
        });
        
        const match = cartPage.match(/"info":"[^•]+•\s*([^"]+)/);
        return match ? match[1].trim() : null;
    } catch (error) {
        console.error('获取重量失败:', error);
        throw error;
    }
}

async function clearCart(cartItemIds) {
    const clearCartData = {
        name: "deleteItems",
        params: JSON.stringify({ items: cartItemIds })
    };
    
    await $.ajax({
        url: 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fcart%3Fpage_changed%3Dtrue',
        type: 'POST',
        data: JSON.stringify(clearCartData),
        contentType: 'application/json'
    });
}

async function addToCart(sku) {
    const addToCartData = [{
        id: Number(sku),
        quantity: 1
    }];
    
    await $.ajax({
        url: 'https://www.ozon.ru/api/composer-api.bx/_action/v2/addToCart',
        type: 'POST',
        data: JSON.stringify(addToCartData),
        contentType: 'application/json'
    });
}

async function handleWeightQuery($button, sku) {
    $button.html("手动查询中...").prop("disabled", true);
    
    try {
        const weight = await getWaith(sku);
        const normalizedWeight = normalizeWeight(weight);
        $button.html(`重量: ${normalizedWeight}`).prop("disabled", false);
    } catch (error) {
        console.error(`查询重量失败 (SKU: ${sku}):`, error);
        $button.html("查询失败，再试一次").prop("disabled", false);
    }
}

// 产品处理核心函数
function setupCopyFunctionality(index, sku) {
    new ClipboardJS(`.goseller-copy-${index}`, {
        text: () => {
            layer.closeAll("tips");
            showTip("复制成功", `.goseller-copy-${index}`);
            return sku;
        }
    });
}

function setupProductEventListeners(item, index, sku) {
    // 复制按钮悬停
    item.find(`.goseller-copy-${index}`).hover(
        () => showTip("复制sku", this),
        () => layer.closeAll("tips")
    );
    
    // 处理隐藏内容
    setupHiddenContentHandlers(item);
    
    // 设置重量按钮
    setupWeightButton(item, sku);
}

function setupHiddenContentHandlers(container) {
    container.find("span").each(function () {
        const $this = $(this);
        if ($this.text() !== CONSTANTS.HIDDEN_TEXT) return;
        
        $this.css({ cursor: "pointer" })
            .hover(() => showHiddenContentTip(this))
            .click(() => {
                if ($this.text() === CONSTANTS.HIDDEN_TEXT || 
                    $this.data("photo") === CONSTANTS.HIDDEN_TEXT) {
                    window.open(dldomain);
                } else if ($this.data("photo")) {
                    if ($this.find("i").is(":hidden")) {
                        jump1688($this, $this.data("photo"));
                    }
                }
            });
    });
}

function setupWeightButton(item, sku) {
    const $weightButton = item.find(`#get_weight_${sku}`);
    if ($weightButton.length === 0) return;
    
    $weightButton.off("click").on("click", async () => {
        await handleWeightQuery($weightButton, sku);
    });
}

function setupGlobalEventListeners() {
    $(".goseller-btn")
        .off("hover click")
        .hover(function() {
            if ($(this).data("photo") === CONSTANTS.HIDDEN_TEXT) {
                showHiddenContentTip(this);
            }
        })
        .click(function() {
            if ($(this).data("photo") === CONSTANTS.HIDDEN_TEXT) {
                window.open(dldomain);
            }
        });
}

// 详情页推荐产品处理
async function checkSkuShelfGoods(fxout) {
    const methodName = fxout !== 1 ? "goodHtmlnew" : "goodHtml";
    const tiles = $(CONSTANTS.TILE_SELECTOR);
    
    if ($(CONSTANTS.PRODUCT_DETAIL_SELECTOR).length === 0 || tiles.length !== 24) {
        setTimeout(() => checkSkuShelfGoods(fxout), CONSTANTS.MAX_RETRY_DELAY);
        return;
    }
    
    await processProductTiles(tiles, methodName, fxout);
    setupGlobalEventListeners();
}

async function processProductTiles(tiles, methodName, fxout) {
    const processPromises = [];
    
    for (let index = 0; index < tiles.length; index++) {
        const item = tiles.eq(index);
        if (item.data("isLoad")) continue;
        
        item.data("isLoad", true);
        processPromises.push(processSingleProduct(item, index, methodName, fxout));
    }
    
    await Promise.all(processPromises);
}

async function processSingleProduct(item, index, methodName, fxout) {
    try {
        const productLink = item.find("a")[0];
        if (!productLink) return;
        
        let res = await sendMessage("/getGoodsInfo", {
            url: productLink.href,
            fxout: fxout
        });
        
        if (fxout !== 1 && res?.items?.[0]) {
            res = formatdata(res.items[0], res.productDetail?.specifications);
        }
        
        if (!res || res.code !== 200 || !res.data) return;
        
        await renderProductData(item, res.data, index, methodName);
        setupProductEventListeners(item, index, res.data.sku);
    } catch (error) {
        console.error(`处理产品 ${index} 失败:`, error);
    }
}

async function renderProductData(item, productData, index, methodName) {
    const { sku, photo } = productData;
    if (!photo) productData.photo = item.find("img").attr("src");
    
    const html = obj[methodName](productData, index, item.children().length, false);
    item.append(html);
    
    setupCopyFunctionality(index, sku);
    updateSalesDynamicsColor(item, productData.salesDynamics);
    applyDisplayConfig(item);
}

function applyDisplayConfig(item) {
    chrome.storage.local.get(['analysis_display_config'], (res) => {
        const config = res.analysis_display_config || {};
        if (Object.keys(config).length === 0) return;

        const fieldMap = {
            '商品编码': 'sku',
            '一级类目': 'category1',
            '三级类目': 'category3',
            '月销量': 'sales',
            '月销售额': 'gmv',
            '月销售变化': 'salesDynamics',
            '平均价格': 'avgPrice',
            '最低售价': 'minSellerPrice',
            '加购率': 'convTocartPdp',
            '浏览量': 'sessionCount',
            '是否允许复制': 'hasGollowSales',
            '库存': 'stock',
            '品牌': 'brand',
            '首次上架时间': 'pCreateDate',
            '出售时间': 'pCreateDate',
            '重量': 'pWeight',
            '佣金': 'commission',
            '曝光量': 'views',
            '曝光转化率': 'convViewToOrder',
            '搜索转换率': 'convToCartSearch',
            '结单率': 'nullableRedemptionRate',
            '推广费用占比': 'drr',
            '开模板活动天数': 'daysWithTrafarets',
            '开启模板活动天数': 'daysWithTrafarets',
            '开促销天数': 'daysInPromo',
            '开启促销天数': 'daysInPromo',
            '促销收入占比': 'promoRevenueShare',
            '平均运输时间': 'avgDeliveryDays',
            '配送方式': 'salesSchema',
            '销售该商品卖家数量': 'sellerCount',
            '体积': 'ptj',
            '平均售价': 'avgPrice',
            '30天销量': 'sales',
            '30天销售额': 'gmv',
            '30天销售变化': 'salesDynamics',
            '曝光次数': 'views',
            '详情页访问量': 'sessionCount',
        };

        // .hq_main .itemR
        item.find('.hq_datamain .itemR').each(function() {
            const label = $(this).find('p').first().text().trim();
            const key = fieldMap[label];
            if (key && config[key] === false) {
                $(this).hide();
            }
        });

        // 更新 itemR 底边框：最后一行不显示底边框
        item.find('.hq_datamain .itemR-grid').each(function() {
            const $grid = $(this);
            const visibleItems = $grid.find('.itemR:visible');
            const totalVisible = visibleItems.length;
            if (totalVisible > 0) {
                const lastRowStart = Math.floor((totalVisible - 1) / 3) * 3;
                visibleItems.each(function(index) {
                    $(this).css('border-bottom', index >= lastRowStart ? 'none' : '1px solid #e9ebef');
                });
            }
        });

        // .hq_main li.model1
        item.find('.hq_datamain li.model1').each(function() {
            const raw = $(this).text().trim();
            const label = raw.split(/[：:]/)[0].trim();
            const key = fieldMap[label];
            if (key && config[key] === false) {
                $(this).hide();
            }
        });

        // .goseller-card .layui-form-item
        item.find('.goseller-card-body .layui-form-item').each(function() {
            const text = $(this).text().trim();
            const label = text.split(/[：:]/)[0].trim();
            const key = fieldMap[label];
            if (key && config[key] === false) {
                $(this).hide();
            }
        });
    });
}

// 列表页处理
async function queryGoods(fxout = CONSTANTS.DEFAULT_FXOUT) {
    const methodName = fxout !== 1 ? "goodHtmlnew" : "goodHtml";
    const tiles = $(CONSTANTS.TILE_SELECTOR);
    
    await processTilesWithDelay(tiles, methodName, fxout);
    setupGlobalEventListeners();
}

async function processTilesWithDelay(tiles, methodName, fxout) {
    for (let index = 0; index < tiles.length; index++) {
        const item = tiles.eq(index);
        if (item.data("isLoad")) continue;
        
        item.data("isLoad", true);
        await processTileWithTimeout(item, index, methodName, fxout);
    }
}

async function processTileWithTimeout(item, index, methodName, fxout) {
    return new Promise(resolve => {
        setTimeout(async () => {
            try {
                await processSingleTile(item, index, methodName, fxout);
            } finally {
                resolve();
            }
        }, CONSTANTS.DELAY_TIMEOUT);
    });
}

async function processSingleTile(item, index, methodName, fxout) {
    const productLink = item.find("a")[0];
    if (!productLink) return;
    
    let res = await sendMessage("/getGoodsInfo", {
        url: productLink.href,
        fxout: fxout
    });
    
    if (fxout !== 1 && res?.items?.[0]) {
        res = formatdata(res.items[0], res.productDetail?.specifications);
    }
    
    if (!res || res.code !== 200 || !res.data) return;
    
    const container = getProductContainer(item);
    const { sku } = res.data;
    
    container.append(obj[methodName](res.data, index, item.children().length))
        .css("flex-wrap", "wrap");
    
    container.removeAttr('style');
    setupProductInteraction(container, index, sku, res.data);
    applyDisplayConfig(container);
}

function getProductContainer(item) {
    const type2Container = item.find(CONSTANTS.CONTAINER_SELECTORS.TYPE2);
    if (type2Container.length > 0) return type2Container.eq(0);
    
    const type1Container = item.find(CONSTANTS.CONTAINER_SELECTORS.TYPE1)
        .filter((_, el) => $(el).attr("class"));
    if (type1Container.length > 0) return type1Container.eq(0);
    
    return item;
}

function setupProductInteraction(container, index, sku, productData) {
    // 复制按钮悬停
    container.find(`.goseller-copy-${index}`).hover(
        () => showTip("复制商品id", this),
        () => layer.closeAll("tips")
    );
    
    // 隐藏内容处理
    setupHiddenContentHandlers(container);
    
    // 销售动态颜色
    updateSalesDynamicsColor(container, productData.salesDynamics);
    
    // 重量按钮
    setupWeightButton(container, sku);
    
    // 图片搜索
    setupImageSearch(container);
}

function setupImageSearch(container) {
    container.find("[data-photo]").on("click", function () {
        const $this = $(this);
        if ($this.data("photo") && $this.find("i").is(":hidden")) {
            jump1688($this, $this.data("photo"));
        }
    });
}

// 详情页处理
async function queryGood(fxout) {
    checkSkuShelfGoods(fxout);
    
    try {
        let res = await sendMessage("/getGoodsInfo", {
            url: window.location.href,
            fxout: fxout
        });
        console.log(res);
        const methodName = fxout !== 1 ? "goodHtmlnew" : "goodHtml";
        if (fxout !== 1 && res?.items?.[0]) {
            res = formatdata(res.items[0], res.productDetail.specifications);
        }
        
        if (res?.code === 200 && res.data) {
            setTimeout(() => {
                renderProductDetail(res.data, methodName);
            }, 700);
        }
    } catch (error) {
        console.error("查询商品详情失败:", error);
    }
}

async function renderProductDetail(productData, methodName) {
    const { sku } = productData;
    const container = $(CONSTANTS.WEB_SALE_SELECTOR).eq(0);
    
    if (container.length === 0) return;
    
    container.append(obj[methodName](productData, 'product', 4, true))
        .css("flex-wrap", "wrap");
    
    container.removeAttr('style');
    updateSalesDynamicsColor(container, productData.salesDynamics);
    setupDetailCopyFunctionality(sku);
    await autoFetchWeight(sku);
    applyDisplayConfig(container);
}

function setupDetailCopyFunctionality(sku) {
    new ClipboardJS('.goseller-copy-product', {
        text: () => {
            layer.closeAll("tips");
            showTip("复制成功", '.goseller-copy-product');
            return sku;
        }
    });
}

async function autoFetchWeight(sku) {
    const $weightButton = $(`#get_weight_${sku}`);
    if ($weightButton.length === 0 || !$weightButton.html().includes('点击获取')) return;
    
    $weightButton.html("获取重量中...").prop("disabled", true);
    
    try {
        const weight = await getWaith(sku);
        const normalizedWeight = normalizeWeight(weight);
        $weightButton.html(`重量: ${normalizedWeight || "未知"}`)
            .prop("disabled", false);
    } catch (error) {
        console.error(`自动获取重量失败 (SKU: ${sku}):`, error);
        setupManualWeightRetry($weightButton, sku);
    }
}

function setupManualWeightRetry($button, sku) {
    $button.html("自动获取失败，点击重试").prop("disabled", false);
    
    $button.off("click").on("click", async () => {
        await handleWeightQuery($button, sku);
    });
}

// 页面观察器
function setCJ(fxout) {
    const isProductPage = window.location.href.includes("/product/") || 
                         window.location.href.includes("/context/detail/");
    
    if (isProductPage) {
        queryGood(fxout);
    } else {
        setupPageObserver(fxout);
    }
}

function setupPageObserver(fxout) {
    const targetElement = document.getElementById("__ozon") || 
                         document.getElementById("paginatorContent");
    
    if (!targetElement) return;
    
    let recordHeight = 0;
    const observer = new MutationObserver(() => {
        const height = window.getComputedStyle(targetElement).getPropertyValue("height");
        if (height === recordHeight) return;
        
        recordHeight = height;
        queryGoods(fxout);
    });
    
    observer.observe(targetElement, {
        childList: true,
        attributes: true,
        characterData: true,
        subtree: true
    });
}

// 模板对象（保持不变）
const obj = {
    goodHtml: function({
        sku,
        brand,
        category1,
        stock,
        category3,
        sales,
        convTocartPdp,
        gmv,
        sessionCount,
        avgPrice,
        hasGollowSales,
        photo,
        minSellerPrice,
        salesDynamics,
        pCreateDate,
        sellerCount,
        pWeight,
        ptj,
        commission,
        dimL,
        dimW,
        dimH,
    }, index, childLength, isGood = false) {
        if (isGood) {
            return `
            <div class="hq_main">
                <div class="hq_title"><img src="chrome-extension://${chrome.runtime.id}/img/logo.png" style="height: auto; object-fit: contain; width: 160px;"></div>
                <div class="hq_datamain">
                <li class="model1">商品编码：<span>${sku}</span><button type="button" class="copy goseller-copy-${index}">
                    <svg t="1690864067709" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2319" width="24" height="24">
                        <path d="M638.596211 191.936191q30.628116 0 54.62014 13.272183t41.347956 32.66999 26.544367 41.858425 9.188435 39.81655l0 576.829511q0 29.607178-11.740778 53.088734t-30.628116 39.81655-42.368893 25.52343-46.963111 9.188435l-503.322034 0q-19.397807 0-42.368893-11.230309t-42.879362-29.607178-33.180459-42.368893-13.272183-48.494516l0-568.662014q0-21.439681 10.209372-44.410768t26.544367-42.368893 37.774676-32.159521 44.921236-12.761715l515.57328 0zM578.360917 830.021934q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM578.360917 574.787637q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM759.0668 0q43.900299 0 80.654038 26.033898t63.808574 64.319043 42.368893 82.695912 15.314058 81.164506l0 542.117647q0 21.439681-12.761715 39.306082t-31.138584 30.628116-39.81655 20.418744-39.81655 7.657029l-4.083749 0 0-609.499501q-8.167498-70.444666-43.900299-108.219342t-94.947159-49.004985l-498.217348 0q1.020937-2.041874 1.020937-7.14656 0-20.418744 12.251246-41.858425t32.159521-38.795613 44.410768-28.586241 49.004985-11.230309l423.688933 0z" p-id="2320" fill="#005bff"></path>
                    </svg>
                </button></li>
                <li class="model1">一级类目：<span>【${category1}】</span></li>
                <li class="model1">三级类目：<span>【${category3}】</span></li>
                <div class="itemR-grid">
                    <div class="itemR"><p>月销量</p><span>${sales}</span></div>
                    <div class="itemR"><p>月销售额</p><span>${gmv}</span></div>
                    <div class="itemR"><p>月销售变化</p><span class="salesDynamics" data-dy="${salesDynamics}" style="color:#005bff">${salesDynamics ? salesDynamics > 0 ? salesDynamics + '%↑' : salesDynamics + "%↓" : '-'}</span></div>
                    <div class="itemR"><p>平均价格</p><span>${avgPrice}</span></div>
                    <div class="itemR"><p>最低售价</p><span>${minSellerPrice}</span></div>
                    <div class="itemR"><p>加购率</p><span>${convTocartPdp}</span></div>
                    <div class="itemR"><p>浏览量</p><span>${sessionCount}</span></div>
                    <div class="itemR"><p>加购率</p><span>${convTocartPdp}</span></div>
                    <div class="itemR"><p>是否允许复制</p><span>${hasGollowSales}</span></div>
                    <div class="itemR"><p>库存</p><span>${stock}</span></div>
                    <div class="itemR"><p>佣金</p><span>${commission || '—'}</span></div>
                    <div class="itemR"><p>重量</p><span id="get_weight_${sku}" data-sku="${sku}">${pWeight}克</span></div>
                </div>
                <li class="model1">品牌：<span>【${brand}】</span></li>
                <li class="model1">首次上架时间：<span>【${pCreateDate}】</span></li>
                </div>
            </div>`;
        } else {
            return `
            <div style="text-align: center" class="goseller-card ${isGood ? "goseller-card-good" : ""}">
            <div class="goseller-card-box">
				<div class="goseller-card-header">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <h4>商品ID：<span>${sku}</span>
                            <button type="button" class="copy goseller-copy-${index}">
                                <svg t="1690864067709" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2319" width="256" height="256">
                                    <path d="M638.596211 191.936191q30.628116 0 54.62014 13.272183t41.347956 32.66999 26.544367 41.858425 9.188435 39.81655l0 576.829511q0 29.607178-11.740778 53.088734t-30.628116 39.81655-42.368893 25.52343-46.963111 9.188435l-503.322034 0q-19.397807 0-42.368893-11.230309t-42.879362-29.607178-33.180459-42.368893-13.272183-48.494516l0-568.662014q0-21.439681 10.209372-44.410768t26.544367-42.368893 37.774676-32.159521 44.921236-12.761715l515.57328 0zM578.360917 830.021934q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM578.360917 574.787637q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM759.0668 0q43.900299 0 80.654038 26.033898t63.808574 64.319043 42.368893 82.695912 15.314058 81.164506l0 542.117647q0 21.439681-12.761715 39.306082t-31.138584 30.628116-39.81655 20.418744-39.81655 7.657029l-4.083749 0 0-609.499501q-8.167498-70.444666-43.900299-108.219342t-94.947159-49.004985l-498.217348 0q1.020937-2.041874 1.020937-7.14656 0-20.418744 12.251246-41.858425t32.159521-38.795613 44.410768-28.586241 49.004985-11.230309l423.688933 0z" p-id="2320" fill="#005bff"></path>
                                </svg>
                            </button>
                            </h4>
                        </div>
                    </form>
                    <p class="h-tilte" style="text-align: center">数据一览</p>
                </div>
                <div class="goseller-card-body">
                    <form class="layui-form">
                        <div class="layui-form-item">品牌：<span class="brand">${brand}</span></div>
                        <div class="layui-form-item">出售时间：<span style="color:#005bff">${pCreateDate}</span></div>
                        <div class="layui-form-item">一级类目：<span>${category1}</span></div>
                        <div class="layui-form-item">三级类目：<span>${category3}</span></div>
                        <div class="layui-form-item">30天销量：<span style="color:#005bff">${sales}</span></div>
                        <div class="layui-form-item">30天销售额：<span style="color:#005bff">${gmv}</span></div>
                        <div class="layui-form-item">30天销售变化：<span class="salesDynamics" data-dy="${salesDynamics}" style="color:#005bff">${salesDynamics ? salesDynamics > 0 ? salesDynamics + '%↑' : salesDynamics + "%↓" : '-'}</span></div>
                        <div class="layui-form-item">平均售价：<span>${avgPrice}</span></div>
                        <div class="layui-form-item">最低售价：<span>${minSellerPrice}</span></div>
                        <div class="layui-form-item">加购率：<span style="color:#005bff">${convTocartPdp}</span></div>
                        <div class="layui-form-item">浏览量：<span>${sessionCount}</span></div>
                        <div class="layui-form-item">佣金：<span class="brand">${commission || '—'}</span></div>
                        <div class="layui-form-item">重量：<span>${pWeight}g</span></div>
                        <div class="layui-form-item">销售该商品卖家数量：<span style="color:#005bff">${sellerCount}</span></div>
                        <div class="layui-form-item">是否允许复制：<span>${hasGollowSales}</span></div>
                    </form>
                </div>
            </div></div>`;
        }
    },

    goodHtmlnew: function({
        sku,
        brand,
        category1,
        stock,
        category3,
        sales,
        convTocartPdp,
        gmv,
        sessionCount,
        avgPrice,
        hasGollowSales,
        photo,
        minSellerPrice,
        salesDynamics,
        pCreateDate,
        sellerCount,
        pWeight,
        ptj,
        commission,
        dimL,
        dimW,
        dimH,
        drr,
        salesSchema,
        pdpToCartConversion,
        convToCartSearch,
        convViewToOrder,
        views,
        nullableRedemptionRate,
        promoRevenueShare,
        avgDeliveryDays,
        daysInPromo,
        daysWithTrafarets
    }, index, childLength, isGood = false) {
        if (isGood) {
            return `
            <div class="hq_main">
                <div class="hq_title"><img src="chrome-extension://${chrome.runtime.id}/img/logo.png" style="height: auto; object-fit: contain; width: 160px;"></div>
                <div class="hq_datamain">
                <li class="model1">商品编码：<span>${sku}</span><button type="button" class="copy goseller-copy-${index}">
                    <svg t="1690864067709" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2319" width="24" height="24">
                        <path d="M638.596211 191.936191q30.628116 0 54.62014 13.272183t41.347956 32.66999 26.544367 41.858425 9.188435 39.81655l0 576.829511q0 29.607178-11.740778 53.088734t-30.628116 39.81655-42.368893 25.52343-46.963111 9.188435l-503.322034 0q-19.397807 0-42.368893-11.230309t-42.879362-29.607178-33.180459-42.368893-13.272183-48.494516l0-568.662014q0-21.439681 10.209372-44.410768t26.544367-42.368893 37.774676-32.159521 44.921236-12.761715l515.57328 0zM578.360917 830.021934q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM578.360917 574.787637q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM759.0668 0q43.900299 0 80.654038 26.033898t63.808574 64.319043 42.368893 82.695912 15.314058 81.164506l0 542.117647q0 21.439681-12.761715 39.306082t-31.138584 30.628116-39.81655 20.418744-39.81655 7.657029l-4.083749 0 0-609.499501q-8.167498-70.444666-43.900299-108.219342t-94.947159-49.004985l-498.217348 0q1.020937-2.041874 1.020937-7.14656 0-20.418744 12.251246-41.858425t32.159521-38.795613 44.410768-28.586241 49.004985-11.230309l423.688933 0z" p-id="2320" fill="#005bff"></path>
                    </svg>
                </button></li>
                <li class="model1">一级类目：<span>【${category1}】</span></li>
                <li class="model1">三级类目：<span>【${category3}】</span></li>
                <div class="itemR-grid">
                    <div class="itemR"><p>月销量</p><span>${sales}</span></div>
                    <div class="itemR"><p>月销售额</p><span>${gmv}</span></div>
                    <div class="itemR"><p>月销售变化</p><span class="salesDynamics" data-dy="${salesDynamics}" style="color:#005bff">${salesDynamics ? salesDynamics > 0 ? salesDynamics + '%↑' : salesDynamics + "%↓" : '-'}</span></div>
                    <div class="itemR" data-field="avgPrice"><p>平均价格</p><span>${avgPrice}</span></div>
                    <div class="itemR" data-field="minSellerPrice"><p>最低售价</p><span>${minSellerPrice}</span></div>
                    <div class="itemR" data-field="brand"><p>品牌</p><span>${brand}</span></div>
                    <div class="itemR" data-field="views"><p>曝光量</p><span>${views}</span></div>
                    <div class="itemR" data-field="convViewToOrder"><p>曝光转化率</p><span>${convViewToOrder}%</span></div>
                    <div class="itemR" data-field="convToCartSearch"><p>搜索转换率</p><span>${convToCartSearch}</span></div>
                    <div class="itemR" data-field="convTocartPdp"><p>加购率</p><span>${convTocartPdp}</span></div>
                    <div class="itemR" data-field="nullableRedemptionRate"><p>结单率</p><span>${nullableRedemptionRate}%</span></div>
                    <div class="itemR" data-field="drr"><p>推广费用占比</p><span>${drr}%</span></div>
                    <div class="itemR" data-field="daysWithTrafarets"><p>开模板活动天数</p><span>${daysWithTrafarets}</span></div>
                    <div class="itemR" data-field="daysInPromo"><p>开促销天数</p><span>${daysInPromo}</span></div>
                    <div class="itemR" data-field="promoRevenueShare"><p>促销收入占比</p><span>${promoRevenueShare}%</span></div>
                    <div class="itemR" data-field="avgDeliveryDays"><p>平均运输时间</p><span>${avgDeliveryDays}天</span></div>
                    <div class="itemR" data-field="salesSchema"><p>配送方式</p><span>${salesSchema}</span></div>
                    <div class="itemR" data-field="sellerCount"><p>销售该商品卖家数量</p><span>${sellerCount}</span></div>
                    <div class="itemR" data-field="hasGollowSales"><p>是否允许复制</p><span>${hasGollowSales}</span></div>
                    <div class="itemR" data-field="pCreateDate"><p>出售时间</p><span>${pCreateDate}</span></div>
                    <div class="itemR" data-field="stock"><p>库存</p><span>${stock}</span></div>
                    <div class="itemR" data-field="commission"><p>佣金</p><span>${commission || '—'}</span></div>
                    <div class="itemR" data-field="ptj"><p>体积</p><span>${ptj}</span></div>
                    <div class="itemR" data-field="pWeight"><p>重量</p><span class="get_weight" id="get_weight_${sku}" data-sku="${sku}">📦${pWeight}g</span></div>
                </div>
                </div>
            </div>`;
        } else {
            return `
            <div style="text-align: center" class="goseller-card ${isGood ? "goseller-card-good" : ""}">
            <div class="goseller-card-box">
				<div class="goseller-card-header">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <h4>商品ID：<span>${sku}</span>
                            <button type="button" class="copy goseller-copy-${index}">
                                <svg t="1690864067709" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2319" width="256" height="256">
                                    <path d="M638.596211 191.936191q30.628116 0 54.62014 13.272183t41.347956 32.66999 26.544367 41.858425 9.188435 39.81655l0 576.829511q0 29.607178-11.740778 53.088734t-30.628116 39.81655-42.368893 25.52343-46.963111 9.188435l-503.322034 0q-19.397807 0-42.368893-11.230309t-42.879362-29.607178-33.180459-42.368893-13.272183-48.494516l0-568.662014q0-21.439681 10.209372-44.410768t26.544367-42.368893 37.774676-32.159521 44.921236-12.761715l515.57328 0zM578.360917 830.021934q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM578.360917 574.787637q26.544367 0 45.431705-18.376869t18.887338-44.921236-18.887338-45.431705-45.431705-18.887338l-382.851446 0q-26.544367 0-45.431705 18.887338t-18.887338 45.431705 18.887338 44.921236 45.431705 18.376869l382.851446 0zM759.0668 0q43.900299 0 80.654038 26.033898t63.808574 64.319043 42.368893 82.695912 15.314058 81.164506l0 542.117647q0 21.439681-12.761715 39.306082t-31.138584 30.628116-39.81655 20.418744-39.81655 7.657029l-4.083749 0 0-609.499501q-8.167498-70.444666-43.900299-108.219342t-94.947159-49.004985l-498.217348 0q1.020937-2.041874 1.020937-7.14656 0-20.418744 12.251246-41.858425t32.159521-38.795613 44.410768-28.586241 49.004985-11.230309l423.688933 0z" p-id="2320" fill="#005bff"></path>
                                </svg>
                            </button>
                            </h4>
                        </div>
                    </form>
                    <p class="h-tilte" style="text-align: center">数据一览</p>
                </div>
                <div class="goseller-card-body">
                    <form class="layui-form">
                        <div class="layui-form-item">品牌：<span class="brand">${brand}</span></div>
                        <div class="layui-form-item">出售时间：<span style="color:#005bff">${pCreateDate}</span></div>
                        <div class="layui-form-item">一级类目：<span>${category1}</span></div>
                        <div class="layui-form-item">三级类目：<span>${category3}</span></div>
                        <div class="layui-form-item">30天销量：<span style="color:#005bff">${sales}</span></div>
                        <div class="layui-form-item">30天销售额：<span style="color:#005bff">${gmv}</span></div>
                        <div class="layui-form-item">30天销售变化：<span class="salesDynamics" data-dy="${salesDynamics}" style="color:#005bff">${salesDynamics ? salesDynamics > 0 ? salesDynamics + '%↑' : salesDynamics + "%↓" : '-'}</span></div>
                        <div class="layui-form-item">平均售价：<span>${avgPrice}</span></div>
                        <div class="layui-form-item">最低售价：<span>${minSellerPrice}</span></div>
                        <div class="layui-form-item">加购率：<span style="color:#005bff">${convTocartPdp}</span></div>
                        <div class="layui-form-item">浏览量：<span>${sessionCount}</span></div>
                        <div class="layui-form-item">推广费用占比：<span class="brand">${drr}%</span></div>
                        <div class="layui-form-item">开启模板活动天数：<span class="brand">${daysWithTrafarets}</span></div>
                        <div class="layui-form-item">搜索转换率：<span class="brand">${convToCartSearch}</span></div>
                        <div class="layui-form-item">曝光转化率：<span class="brand">${convViewToOrder}%</span></div>
                        <div class="layui-form-item">曝光次数：<span class="brand">${views}</span></div>
                        <div class="layui-form-item">开启促销天数：<span class="brand">${daysInPromo}</span></div>
                        <div class="layui-form-item">详情页访问量：<span class="brand">${sessionCount}</span></div>
                        <div class="layui-form-item">平均运输时间：<span class="brand">${avgDeliveryDays}天</span></div>
                        <div class="layui-form-item">结单率：<span class="brand">${nullableRedemptionRate}%</span></div>
                        <div class="layui-form-item">促销收入占比：<span class="brand">${promoRevenueShare}%</span></div>
                        <div class="layui-form-item">配送方式：<span class="brand">${salesSchema}</span></div>
                        <div class="layui-form-item">佣金：<span class="brand">${commission || '—'}</span></div>
                        <div class="layui-form-item"><span class="get_weight_${sku}" data-sku="${sku}" id="get_weighta_${sku}">体积:${ptj}</span></div>
                        <div class="layui-form-item"><span class="get_weight_${sku}" data-sku="${sku}" id="get_weight_${sku}">重量:${pWeight}g</span></div>
                        <div class="layui-form-item">销售该商品卖家数量：<span style="color:#005bff">${sellerCount}</span></div>
                        <div class="layui-form-item">是否允许复制：<span>${hasGollowSales}</span></div>
                    </form>
                </div>
            </div></div>`;
        }
    }
};

// 主入口函数
$(document).ready(async function () {
    try {
        const fenxiValue = await getFxoutValue('opfenxi');
        const fenxi = fenxiValue ? JSON.parse(fenxiValue) : null;
        
        if (fenxi !== 1) return;
        
        const fxoutValue = await getFxoutValue();
        const fxout = fxoutValue ? JSON.parse(fxoutValue) : CONSTANTS.DEFAULT_FXOUT;
        
        if (fenxi === 1) {
            setCJ(fxout);
        }
    } catch (error) {
        console.error("初始化失败:", error);
    }
});