
class SkuPricingModal {
    constructor() {
        // DOM 相关属性
        this.modal = null; // SKU定价弹窗的DOM元素引用
        this.isInitialized = false; // 标记弹窗是否已初始化
        
        // 初始化左右数据处理模块
        this.leftData = window.skuPricingModalLeft; // 左侧SKU配置数据处理模块（物流、成本、费用等）
        this.rightData = window.skuPricingModalRight; // 右侧定价结果表格数据处理模块
        this.api = window.skuPricingApi; // SKU定价API请求模块（获取物流列表、物流数据等）

        // SKU信息对象（备用数据结构，目前主要通过leftData使用）
        this.skuInfo = {
            logisticList: [], // 物流方式列表 [{id: '', value: '', name: '', type: 'smallpack|bigpack'}]
            listCountry: [], // 国家列表 [{code: '', name: '', eName: '', data: [{min: '', max: '', deliveryFee: '', registrationFee: ''}]}]
            logisticsData: {}, // 当前选中物流的完整数据（包含countries和settlementCurrency）
            logistics: '', // 当前选中的物流方式标识 (e.g., 'eco_global', 'standard_wuyou')
            countries: [], // 当前物流运达的国家列表（冗余字段，与listCountry功能相同）
            skuAttributes: [] // SKU属性数组 [{id: '', name: '', values: ['', '']}]
        };

        // 页面滚动和操作参数
        this.x = 0; // 水平滚动距离（像素）
        this.y = 200; // 垂直滚动距离（像素），用于滚动商品SKU列表容器
        this.time = 10; // 单次滚动操作的等待时间（毫秒），控制滚动速度
    }
 

    /**
     * 初始化SKU定价弹窗
     */
    async initSkuModal() {

        //开启遮蔽罩
        window.loading.show('加载中');
        let urlParams = window.urlUtils.getUrlParam();
        console.log("urlParams",urlParams);
        let flag = urlParams['switchId'] || urlParams["productId"];
        this.rightData.resetRightData();

        if(flag){
            await window.skuUtils.scrollAndExtractData(this.x, this.y, this.time);

        }
        
        
        if (this.isInitialized) {
            console.log('SKU定价弹窗已初始化');
            this.leftData.initSkuAttributes(window.skuUtils.arrSku);
            this.renderInterface();
            // if(flag){
            window.loading.close();
            // }
            return;
        }

        // 获取弹窗元素
        this.modal = document.getElementById('skuPricingModal');
        if (!this.modal) {
            throw new Error('未找到SKU定价弹窗元素');
        }

        // 初始化数据
        await this.initData();
        console.log("this.leftData.skuAttributes", this.leftData.getSkuAttributes());
        
        // 先渲染界面
        this.renderInterface();
        
        // 再绑定事件（确保只绑定一次）
        this.bindEvents();
        
        this.isInitialized = true;
        // 关闭遮蔽罩
        // if(flag){
            window.loading.close();
        // }
        console.log('SKU定价弹窗初始化完成');
    }

    /**
     * 初始化数据
     */
    async initData() {
            await this.leftData.initLeftData();

    }



    /**
     * 将本地存储数据渲染到界面
     */
    renderStoredDataToUI() {
        if (!this.leftData || !this.leftData.getLeftData()) {
            console.warn('左侧数据模块未正确初始化，无法渲染数据');
            return;
        }

        // 获取需要渲染的数据
        const renderData = this.leftData.getLeftData().leftModalData;
        
        // 获取所有配置输入框
        const configInputs = this.modal.querySelectorAll('.sku-config-input, .sku-config-select');
        
        configInputs.forEach(input => {
            const key = input.id;
            if (key in renderData && renderData[key] !== '') {
                input.value = renderData[key];
                console.log(`渲染数据到界面: ${key} = ${renderData[key]}`);
            }
        });

        // 特殊处理利润比计算方式单选按钮
        const profitRatioRadios = this.modal.querySelectorAll('input[name="profitRatio"]');
        profitRatioRadios.forEach(radio => {
            if (Number(radio.value) === renderData.profitRatio) {
                radio.checked = true;
            }
        });

        console.log('本地存储数据渲染到界面完成');
    }


    //#region 事件绑定
    /**
     * 绑定事件
     */
    bindEvents() {
        if (!this.modal) return;

        // 选择SKU按钮事件
        const selectSkuBtn = this.modal.querySelector('#selectSkuBtn');
        if (selectSkuBtn) {
            selectSkuBtn.addEventListener('click', () => this.showSkuSelectionModal());
        }

        // SKU选择弹窗关闭事件
        const closeSkuSelectionModalBtn = document.getElementById('closeSkuSelectionModal');
        if (closeSkuSelectionModalBtn) {
            closeSkuSelectionModalBtn.addEventListener('click', () => this.hideSkuSelectionModal());
        }

        // 点击SKU选择弹窗外部关闭
        const skuSelectionModal = document.getElementById('skuSelectionModal');
        if (skuSelectionModal) {
            skuSelectionModal.addEventListener('click', (e) => {
                if (e.target === skuSelectionModal) {
                    this.hideSkuSelectionModal();
                }
            });
        }

        // 核算按钮事件（在SKU选择弹窗中）
        const calculateBtn = document.querySelector('#skuSelectionModal #calculateBtn');
        if (calculateBtn) {
            calculateBtn.addEventListener('click', () => {
                this.hideSkuSelectionModal();
                this.handleCalculate();
            });
        }

        // 已选属性展开/收缩按钮事件
        const toggleSelectedBtn = this.modal.querySelector('#toggleSelectedBtn');
        if (toggleSelectedBtn) {
            toggleSelectedBtn.addEventListener('click', () => {
                this.toggleSelectedAttributes();
            });
        }

        // 提交按钮事件
        const submitBtn = this.modal.querySelector('#submitBtn');
        if (submitBtn) {
            submitBtn.addEventListener('click', () => {
                this.handleSubmit();
            });
        }

        // 配置输入框事件
        this.bindConfigInputs();

        
        // SKU属性选择事件
        this.bindSkuAttributeEvents();

        console.log('事件绑定完成');
    }

    /**
     * 显示SKU选择弹窗
     */
    showSkuSelectionModal() {
        const modal = document.getElementById('skuSelectionModal');
        if (modal) {
            modal.style.display = 'flex';
            // 重新渲染SKU属性到新弹窗中
            this.renderSkuAttributes();
        }
    }

    /**
     * 隐藏SKU选择弹窗
     */
    hideSkuSelectionModal() {
        const modal = document.getElementById('skuSelectionModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    /**
     * 绑定配置输入框事件
     */
    bindConfigInputs() {
        const configInputs = this.modal.querySelectorAll('.sku-config-input, .sku-config-select');
        
        configInputs.forEach(input => {
            if (input.id === 'baseCountryInput' || input.id === 'logisticsInput') return;
            input.addEventListener('change', async (e) => {
                const key = e.target.id;
                let value = e.target.value;
                if(e.target.type === 'number'){
                    value = Number(value);
                }

                console.log('输入框值:', value, typeof(value));
                // 1. 先同步数据
                await this.leftData.updateLeftData(key, value);
                
                // 2. 特别记录店铺折扣变化
                if (key === 'storeDiscount') {
                    console.log('店铺折扣发生改变:', value);
                }
                
                // 3. 最后执行物流相关的逻辑
            });
            
            input.addEventListener('input', (e) => {
                const key = e.target.id;
                let value = e.target.value;
                if(e.target.type === 'number'){
                    value = Number(value);
                }
                this.leftData.updateLeftData(key, value);
                
                // 特别记录店铺折扣输入
                if (key === 'storeDiscount') {
                    console.log('店铺折扣输入中:', value);
                }
            });
        });

        // 绑定利润比计算方式单选按钮事件
        const profitRatioRadios = this.modal.querySelectorAll('input[name="profitRatio"]');
        profitRatioRadios.forEach(radio => {
            radio.addEventListener('change', async (e) => {
                const profitRatio = Number(e.target.value);
                console.log('利润比计算方式切换:', profitRatio, profitRatio === 1 ? '成本' : '售价');
                
                // 1. 更新左侧数据中的profitRatio值
                await this.leftData.updateLeftData('profitRatio', profitRatio);
                
                // 2. 调用价格核算方法
                if (this.leftData.calculateRecommendPrice) {
                    this.leftData.calculateRecommendPrice();
                } else {
                    console.warn('calculateRecommendPrice方法不存在');
                }
            });
        });
    }

    /**
     * 绑定SKU属性选择事件
     */
    bindSkuAttributeEvents() {
        // 修改容器选择器，指向新弹窗中的容器
        const container = document.querySelector('#skuSelectionModal .sku-selection-body');
        if (!container) return;

        // 全选复选框
        const selectAll = container.querySelector('#selectAllAttributes');
        if (selectAll) {
            selectAll.addEventListener('change', (e) => {
                this.handleSelectAllAttributes(e.target.checked);
            });
        }

        // 属性组复选框
        const attributeCheckboxes = container.querySelectorAll('.sku-attribute-checkbox');
        attributeCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                this.handleAttributeGroupChange(e.target);
            });
        });

        // 属性值复选框
        const valueCheckboxes = container.querySelectorAll('.sku-attribute-value-checkbox');
        valueCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                this.handleAttributeValueChange(e.target);
            });
        });
    }
    /**
     * 处理提交按钮点击事件
     */
    async handleSubmit() {
        window.loading.show('处理中');
        let start = new Date().getTime();
        
        let skuData = this.rightData.getRightData().map(item => {
            return {
                skuName: Object.values(item.attributes).toString().replaceAll(',','-'),
                value: item.recommendPrice
            }
        });
        console.log('提交SKU数据:', skuData);
        await window.skuUtils.scrollAndSetInputValue(this.x, 100, 100, skuData);
        
        // 记录操作日志
        if (window.api && window.api.logOperation) {
            window.api.logOperation('SKU提交');
        }

        window.loading.close();
        console.log('SKU数据填充完成，耗时:', new Date().getTime() - start, '毫秒');
        
        // 使用自定义弹窗替代原生 alert
        if (window.AlertUtils) {
            window.AlertUtils.alert('SKU数据填充完成！', 'success', '操作成功');
        } else {
            alert('SKU数据填充完成！');
        }
        
        // window.reactUtils.setReactInputValue(input, 30);
    }

    //#endregion 事件绑定


    //#region SKU属性处理方法
    /**
     * 处理全选属性
     * @param {boolean} checked - 是否选中
     */
    handleSelectAllAttributes(checked) {
        const container = document.querySelector('#skuSelectionModal .sku-selection-body');
        if (!container) return;

        const valueCheckboxes = container.querySelectorAll('.sku-attribute-value-checkbox');
        const groupCheckboxes = container.querySelectorAll('.sku-attribute-checkbox');
        
        valueCheckboxes.forEach(checkbox => {
            checkbox.checked = checked;
        });
        
        groupCheckboxes.forEach(checkbox => {
            checkbox.checked = checked;
            // checkbox.indeterminate = false;
        });
        
        this.updateSelectedAttributes();
    }

    /**
     * 处理属性组选择
     * @param {Element} checkbox - 复选框元素
     */
    handleAttributeGroupChange(checkbox) {
        const group = checkbox.closest('.sku-attribute-group');
        const valueCheckboxes = group.querySelectorAll('.sku-attribute-value-checkbox');
        
        valueCheckboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        
        this.updateSelectedAttributes();
    }

    /**
     * 处理属性值选择
     * @param {Element} checkbox - 复选框元素
     */
    handleAttributeValueChange(checkbox) {
        this.updateSelectedAttributes();
        this.updateAttributeGroupState(checkbox);
        this.updateSelectAllState();
    }

    /**
     * 更新属性组选择状态
     * @param {Element} checkbox - 触发更新的属性值复选框
     */
    updateAttributeGroupState(checkbox) {
        const group = checkbox.closest('.sku-attribute-group');
        if (!group){
            console.warn('未找到属性组元素');
            return};

        const groupCheckbox = group.querySelector('.sku-attribute-checkbox');
        const valueCheckboxes = group.querySelectorAll('.sku-attribute-value-checkbox');
        const checkedCount = group.querySelectorAll('.sku-attribute-value-checkbox:checked').length;

        if (checkedCount === 0) {
            groupCheckbox.checked = false;
            groupCheckbox.indeterminate = false;
        } else if (checkedCount === valueCheckboxes.length) {
            groupCheckbox.checked = true;
            groupCheckbox.indeterminate = false;
        } else {
            groupCheckbox.checked = false;
            groupCheckbox.indeterminate = true;
        }
    }

    /**
     * 更新全选框状态
     */
    updateSelectAllState() {
        const container = document.querySelector('#skuSelectionModal .sku-selection-body');
        if (!container) return;

        const selectAllCheckbox = container.querySelector('#selectAllAttributes');
        if (!selectAllCheckbox) return;

        const allValueCheckboxes = container.querySelectorAll('.sku-attribute-value-checkbox');
        const checkedValueCheckboxes = container.querySelectorAll('.sku-attribute-value-checkbox:checked');
        
        // 检查是否所有属性值都被选中
        if (allValueCheckboxes.length === checkedValueCheckboxes.length) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            // 检查是否有任何属性值被选中
            const hasChecked = checkedValueCheckboxes.length > 0;
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = hasChecked;
        }
    }

    /**
     * 更新选中的属性
     */
    updateSelectedAttributes() {
        const container = document.querySelector('#skuSelectionModal .sku-selection-body');
        if (!container) return;

        const selected = [];
        const valueCheckboxes = container.querySelectorAll('.sku-attribute-value-checkbox:checked');
        
        valueCheckboxes.forEach(checkbox => {
            selected.push({
                attribute: checkbox.dataset.attribute,
                value: checkbox.value
            });
        });
        
        this.leftData.updateSelectedAttributes(selected);
        this.updateSelectedAttributesDisplay();
    }

    /**
     * 更新已选属性显示
     */
    updateSelectedAttributesDisplay() {
        const selectedList = this.modal.querySelector('#selectedAttributesList');
        const selectedCount = this.modal.querySelector('.selected-count');
        
        if (!selectedList || !selectedCount) return;
        
        const selected = this.leftData.getSelectedAttributes();
        selectedCount.textContent = selected.length;
        
        if (selected.length === 0) {
            selectedList.innerHTML = '<span class="no-selection">暂无选择</span>';
        } else {
            // 为每个已选属性创建带有颜色标签的显示
            selectedList.innerHTML = selected.map(item => {
                const colorIndex = (parseInt(item.attribute)) % 10; // 循环使用10种颜色
                return `
                    <span class="selected-attribute-item sku-color-${colorIndex}">
                        <span class="attribute-name">${this.getAttributeNameById(item.attribute)}:</span>
                        <span class="attribute-value">${item.value}</span>
                    </span>
                `;
            }).join('');
        }
    }

    /**
     * 根据属性ID获取属性名称
     * @param {string} attributeId - 属性ID
     * @returns {string} 属性名称
     */
    getAttributeNameById(attributeId) {
        const attributes = this.leftData.getSkuAttributes();
        const attribute = attributes.find(attr => attr.id.toString() === attributeId);
        return attribute ? attribute.name : `属性${attributeId}`;
    }

    /**
     * 切换已选属性显示
     */
    toggleSelectedAttributes() {
        const selectedList = this.modal.querySelector('#selectedAttributesList');
        const toggleIcon = this.modal.querySelector('.toggle-icon');
        const toggleBtn = this.modal.querySelector('#toggleSelectedBtn');
        
        if (selectedList && toggleIcon && toggleBtn) {
            const isCollapsed = selectedList.style.display === 'none';
            
            // 切换显示状态
            selectedList.style.display = isCollapsed ? 'block' : 'none';
            
            // 添加旋转动画
            if (isCollapsed) {
                // 展开时顺时针旋转180度
                toggleIcon.style.transform = 'rotate(180deg)';
                toggleBtn.setAttribute('title', '收缩已选属性');
            } else {
                // 收缩时顺时针旋转180度回到原位置
                toggleIcon.style.transform = 'rotate(0deg)';
                toggleBtn.setAttribute('title', '展开已选属性');
            }
        }
    }

        /**
     * 计算SKU组合
     * @param {Array} selectedAttributes - 选中的属性
     * @returns {Array} SKU组合数组
     */
    calculateSkuCombinations(selectedAttributes) {
        console.log("计算SKU组合时选中的属性:", selectedAttributes);
        
        // 构建树形结构数据
        const treeData = this.buildSkuAttributeTree(selectedAttributes);
        console.log("构建的树形结构数据:", treeData);
        
        // 将树形结构平铺为属性值组合
        const combinations = this.flattenTreeToCombinations(treeData);
        console.log("生成的SKU组合:", combinations);
        
        return combinations;
    }

    /**
     * 构建SKU属性树形结构
     * @param {Array} selectedAttributes - 选中的属性数组
     * @returns {Array} 树形结构数据
     */
    buildSkuAttributeTree(selectedAttributes) {
        // 属性值应该是一个树形结构,第一层属性值为根目录，第二层属性值为子目录,第三层为子目录的子目录......,
        // 结构是这样的: {name: '属性值名称1', Values: ['属性值1', '属性值2', '属性值3'], child: [{name: '属性值名称2', Values: ['属性值1', '属性值2', '属性值3'], child: []}]}
        
        // 按属性分组
        const attributeGroups = {};
        selectedAttributes.forEach(attr => {
            if (!attributeGroups[attr.attribute]) {
                attributeGroups[attr.attribute] = [];
            }
            attributeGroups[attr.attribute].push(attr.value);
        });
        
        // 构建树形结构
        const tree = [];
        let currentLevel = tree;
        
        // 遍历所有属性组，构建层级关系
        Object.keys(attributeGroups).forEach((attributeId, index) => {
            const attributeName = this.getAttributeNameById(attributeId);
            const values = attributeGroups[attributeId];
            
            const node = {
                name: attributeName,
                attributeId: attributeId,
                Values: values,
                child: []
            };
            
            // 如果是第一层，直接添加到根节点
            if (index === 0) {
                tree.push(node);
                currentLevel = node.child;
            } else {
                // 添加到当前层级的最后一个节点的子节点
                if (currentLevel.length > 0) {
                    currentLevel[currentLevel.length - 1].child.push(node);
                    currentLevel = node.child;
                } else {
                    // 如果当前层级为空，直接添加到当前层级
                    currentLevel.push(node);
                }
            }
        });
        
        return tree;
    }

    /**
     * 将树形结构平铺为属性值组合
     * @param {Array} tree - 树形结构数据
     * @returns {Array} SKU组合数组
     */
    flattenTreeToCombinations(tree) {
        const combinations = [];
        
        /**
         * 递归遍历树形结构，生成所有可能的组合
         * @param {Array} currentPath - 当前路径
         * @param {Array} remainingNodes - 剩余节点
         * @param {number} level - 当前层级
         */
        const traverse = (currentPath, remainingNodes, level = 0) => {
            if (remainingNodes.length === 0) {
                // 生成SKU组合
                if (currentPath.length > 0) {
                    const skuId = 'SKU' + (combinations.length + 1).toString().padStart(3, '0');
                    const attributes = {};
                    
                    currentPath.forEach((pathNode, index) => {
                        const attributeName = pathNode.name;
                        const attributeValue = pathNode.value;
                        attributes[attributeName] = attributeValue;
                    });
                    
                    combinations.push({
                        id: skuId,
                        attributes: attributes,
                        level: level
                    });
                }
                return;
            }
            
            const currentNode = remainingNodes[0];
            const remaining = remainingNodes.slice(1);
            
            // 遍历当前节点的所有值
            currentNode.Values.forEach(value => {
                const newPath = [...currentPath, {
                    name: currentNode.name,
                    value: value,
                    attributeId: currentNode.attributeId
                }];
                
                // 如果有子节点，先处理子节点
                if (currentNode.child && currentNode.child.length > 0) {
                    traverse(newPath, [...currentNode.child, ...remaining], level + 1);
                } else {
                    // 没有子节点，继续处理剩余节点
                    traverse(newPath, remaining, level + 1);
                }
            });
        };
        
        // 开始遍历
        traverse([], tree);
        
        return combinations;
    }


        /**
     * 计算SKU价格
     * @param {Array} combinations - SKU组合
     * @param {Object} config - 配置数据
     * @returns {Promise<Array>} 价格计算结果
    */
    async calculateSkuPrices(combinations, config) {
        const results = [];

        this.leftData.logisticList.forEach(logistic => {
            if (logistic.routeCode == config.logistics) {
                config.logisticsName = logistic.name;
            }
        });
        
        for (const combination of combinations) {
            console.log("this.leftData.logisticList.find(logistic => logistic.value == config.baseCountry)",config.baseCountry, this.leftData.leftModalData.listCountry.find(country => country.code == config.baseCountry).name);
            // 简化的价格计算逻辑
            const result = {
                id: combination.id,
                attributes: combination.attributes,
                cost: config.productCost,
                //基准国
                baseCountry: this.leftData.leftModalData.listCountry.find(country => country.code == config.baseCountry).name,// 国家
                logistics: this.leftData.logisticList.find(logistic => logistic.routeCode == config.logistics).routeName,// 物流方式
                weight: config.weight,//重量
                baseShippingFee: config.baseShippingFee,// 基准国邮费
                productCost : config.productCost,//产品成本
                recommendPrice: config.recommendPrice,//推荐售价
                profit: config.profitRatio == 1 
                ? config.profitMargin/100 * config.productCost // 利润 = 利润比例 * 产品成本
                : config.profitMargin/100 * config.recommendPrice * (1 - config.storeDiscount/100) * (1 - config.activityDiscount/100),//利润 = 利润比例 * 产品成本 * 店铺折扣 * 活动折扣
                maxDiscount: config.maxDiscount,//最大折扣
            };
            
            results.push(result);
        }
        
        return results;
    }

    //#endregion SKU属性处理方法




    /**
     * 更新静态图片资源
     */
    updateStaticImages() {
        // 更新SKU选择弹窗关闭按钮图标
        const closeBtn = document.querySelector('#closeSkuSelectionModal img');
        if (closeBtn) {
            closeBtn.src = chrome.runtime.getURL('icons/font/AliExpress_close.png');
        }
        
        // 更新主弹窗关闭按钮图标
        const mainCloseBtn = this.modal.querySelector('#closeSkuModal img');
        if (mainCloseBtn) {
            mainCloseBtn.src = chrome.runtime.getURL('icons/font/AliExpress_close.png');
        }
    }

    /**
     * 渲染界面
     */
    renderInterface() {
        // 更新静态图片资源
        this.updateStaticImages();

        // 渲染物流选择框
        this.renderLogisticsSelect();
        
        // 渲染国家选择框
        this.renderCountrySelect();
        
        // 渲染SKU属性
        this.renderSkuAttributes();
        
        // 渲染已选SKU属性
        this.renderSelectedSkuAttributes();
        
        // 更新基准国邮费显示
        this.updateBaseShippingFeeDisplay();
        
        // 渲染本地存储数据到界面
        this.renderStoredDataToUI();
        
        console.log('界面渲染完成');
    }


    //#region 数据渲染方法

    /**
     * 渲染计算结果
    */
    renderCalculationResults() {
        const rightData = this.rightData.getRightData();
        
        // 这里应该实现结果表格的渲染逻辑
        console.log('渲染计算结果:', rightData);
        
        // 右边数据渲染完之后调用右边数据操作的表格数据渲染函数
        const tableBody = this.modal.querySelector('#skuTableBody');
        if (tableBody && this.rightData.renderResultTable) {
            this.rightData.renderResultTable(rightData, tableBody);
        }
    }
    
    /**
     * 
     * 更新推荐售价输入框显示
     */
    renderRecommendPrice(){
        const recommendPriceInput = this.modal.querySelector('#recommendPrice');
        if (!recommendPriceInput) return;
        recommendPriceInput.value = this.leftData.leftModalData.recommendPrice;
    }

    /**
     * 
     * 更新折后价格输入框显示
     */
    renderDiscountPrice(){
        const discountPriceInput = this.modal.querySelector('#discountPrice');
        if (!discountPriceInput) return;
        discountPriceInput.value = this.leftData.leftModalData.discountPrice;
    }

    
    /**
     * 
     * 更新最大折扣输入框显示
     */
    renderMaxDiscount(){
        const maxDiscountInput = this.modal.querySelector('#maxDiscount');
        if (!maxDiscountInput) return;
        maxDiscountInput.value = this.leftData.leftModalData.maxDiscount;
    }
    /**
     * 更新基准国邮费输入框显示
     */
    updateBaseShippingFeeDisplay() {
        const baseShippingFeeInput = this.modal.querySelector('#baseShippingFee');
        if (!baseShippingFeeInput) return;
        
        const baseShippingFee = this.leftData.leftModalData.baseShippingFee || 0;
        baseShippingFeeInput.value = baseShippingFee;
        
        console.log('基准国邮费显示已更新:', baseShippingFee);
    }

    /**
     * 渲染物流选择框
     */
    renderLogisticsSelect() {
        const container = this.modal.querySelector('#logisticsContainer');
        if (!container) return;

        const input = container.querySelector('#logisticsInput');
        const hiddenInput = container.querySelector('#logistics');
        const dropdown = container.querySelector('#logisticsDropdown');
        
        // Update UI with current value
        const currentLogisticsCode = this.leftData.leftModalData.logistics;
        const logisticsList = this.leftData.logisticList;
        const currentLogistics = logisticsList.find(l => l.routeCode === currentLogisticsCode);
        
        if (currentLogistics) {
            input.value = currentLogistics.routeName;
            hiddenInput.value = currentLogistics.routeCode;
        } else {
             if (!currentLogisticsCode) {
                 input.value = '';
                 hiddenInput.value = '';
             }
        }

        // We only need to bind events ONCE.
        if (input.dataset.eventsBound) return;
        input.dataset.eventsBound = 'true';

        const icon = container.querySelector('#logisticsIcon');
        if (icon) {
            const iconPath = 'icons/font/AliExpress_shousuo_shang.png';
            icon.src = chrome.runtime.getURL(iconPath);
        }

        let currentRotation = 0;

        const toggleDropdown = (show) => {
            const isCurrentlyShown = dropdown.style.display === 'block';
            if (show === isCurrentlyShown) return;

            if (show) {
                dropdown.style.display = 'block';
                currentRotation += 180;
            } else {
                dropdown.style.display = 'none';
                currentRotation += 180;
            }
            if (icon) {
                icon.style.transform = `translateY(-50%) rotate(${currentRotation}deg)`;
            }
        };

        // Define renderOptions to use dynamic data
        const renderOptions = (filterText = '') => {
            // Always get the latest logistics list
            const currentLogisticsList = this.leftData.logisticList;
            const currentHiddenValue = hiddenInput.value;

            const filteredLogistics = currentLogisticsList.filter(l => 
                l.routeName.toLowerCase().includes(filterText.toLowerCase()) || 
                l.routeCode.toLowerCase().includes(filterText.toLowerCase())
            );

            if (filteredLogistics.length === 0) {
                dropdown.innerHTML = '<div class="searchable-select-option" style="color: #999; cursor: default;">无匹配物流</div>';
            } else {
                dropdown.innerHTML = filteredLogistics.map(item => 
                    `<div class="searchable-select-option ${item.routeCode === currentHiddenValue ? 'selected' : ''}" data-value="${item.routeCode}" data-name="${item.routeName}">
                        ${item.routeName}
                    </div>`
                ).join('');
            }
            
            // Bind click events for options
            dropdown.querySelectorAll('.searchable-select-option').forEach(option => {
                if (option.dataset.value) {
                    option.addEventListener('click', async () => {
                        const value = option.dataset.value;
                        const name = option.dataset.name;
                        
                        input.value = name;
                        hiddenInput.value = value;
                        toggleDropdown(false);
                        
                        // Trigger update
                        await this.leftData.updateLeftData('logistics', value);
                    });
                }
            });
        };

        input.addEventListener('focus', () => {
            // Select all text to make it easy to type new search
            input.select();
        });

        input.addEventListener('click', (e) => {
             e.stopPropagation();
             if (dropdown.style.display === 'block') {
                 toggleDropdown(false);
             } else {
                 renderOptions('');
                 toggleDropdown(true);
                 input.select();
             }
        });

        input.addEventListener('input', (e) => {
            renderOptions(e.target.value);
            if (dropdown.style.display === 'none') {
                toggleDropdown(true);
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!container.contains(e.target)) {
                toggleDropdown(false);
                // Reset input value to match hidden value if invalid
                const currentVal = hiddenInput.value;
                const currentItem = logisticsList.find(l => l.routeCode === currentVal);
                if (currentItem) {
                    input.value = currentItem.routeName;
                } else if (!currentVal) {
                    input.value = '';
                }
            }
        });
    }

    /**
     * 渲染国家选择框
     */
    renderCountrySelect() {
        const container = this.modal.querySelector('#baseCountryContainer');
        if (!container) return;

        const input = container.querySelector('#baseCountryInput');
        const hiddenInput = container.querySelector('#baseCountry');
        const dropdown = container.querySelector('#baseCountryDropdown');
        
        // Update UI with current value
        const currentCountryCode = this.leftData.leftModalData.baseCountry;
        const countries = this.leftData.leftModalData.listCountry;
        const currentCountry = countries.find(c => c.code === currentCountryCode);
        
        if (currentCountry) {
            input.value = currentCountry.name;
            hiddenInput.value = currentCountry.code;
        } else {
             if (!currentCountryCode) {
                 input.value = '';
                 hiddenInput.value = '';
             }
        }

        // We only need to bind events ONCE.
        if (input.dataset.eventsBound) return;

        const icon = container.querySelector('#baseCountryIcon');
        if (icon) {
            // Ensure the icon src is correct by using chrome.runtime.getURL
            // This fixes issues where __MSG_@@extension_id__ is not replaced in dynamically loaded HTML
            const iconPath = 'icons/font/AliExpress_shousuo_shang.png';
            icon.src = chrome.runtime.getURL(iconPath);
        }

        let currentRotation = 0;

        const toggleDropdown = (show) => {
            const isCurrentlyShown = dropdown.style.display === 'block';
            if (show === isCurrentlyShown) return;

            if (show) {
                dropdown.style.display = 'block';
                currentRotation += 180;
            } else {
                dropdown.style.display = 'none';
                currentRotation += 180;
            }
            if (icon) {
                icon.style.transform = `translateY(-50%) rotate(${currentRotation}deg)`;
            }
        };

        // Define renderOptions to use dynamic data
        const renderOptions = (filterText = '') => {
            // Always get the latest countries list
            const currentCountries = this.leftData.leftModalData.listCountry;
            const currentHiddenValue = hiddenInput.value;

            const filteredCountries = currentCountries.filter(c => 
                c.name.toLowerCase().includes(filterText.toLowerCase()) || 
                c.code.toLowerCase().includes(filterText.toLowerCase())
            );

            if (filteredCountries.length === 0) {
                dropdown.innerHTML = '<div class="searchable-select-option" style="color: #999; cursor: default;">无匹配国家</div>';
            } else {
                dropdown.innerHTML = filteredCountries.map(item => 
                    `<div class="searchable-select-option ${item.code === currentHiddenValue ? 'selected' : ''}" data-value="${item.code}" data-name="${item.name}">
                        ${item.name}
                    </div>`
                ).join('');
            }
            
            // Bind click events for options
            dropdown.querySelectorAll('.searchable-select-option').forEach(option => {
                if (option.dataset.value) {
                    option.addEventListener('click', async () => {
                        const value = option.dataset.value;
                        const name = option.dataset.name;
                        
                        input.value = name;
                        hiddenInput.value = value;
                        toggleDropdown(false);
                        
                        // Trigger update
                        await this.leftData.updateLeftData('baseCountry', value);
                    });
                }
            });
        };

        input.addEventListener('focus', () => {
            // Select all text to make it easy to type new search
            input.select();
        });

        input.addEventListener('click', (e) => {
             e.stopPropagation();
             if (dropdown.style.display === 'block') {
                 toggleDropdown(false);
             } else {
                 renderOptions('');
                 toggleDropdown(true);
                 input.select();
             }
        });

        input.addEventListener('input', (e) => {
            // Filter options on input
            renderOptions(e.target.value);
            toggleDropdown(true);
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!container.contains(e.target)) {
                if (dropdown.style.display === 'block') {
                    toggleDropdown(false);
                    
                    // Reset input to match hidden value if user typed something invalid
                    const latestCountries = this.leftData.leftModalData.listCountry;
                    const currentCode = hiddenInput.value;
                    const currentC = latestCountries.find(c => c.code === currentCode);
                    if (currentC && input.value !== currentC.name) {
                            input.value = currentC.name; 
                    }
                }
            }
        });
        
        input.dataset.eventsBound = 'true';
    }


    /**
     * 渲染多个输入框元素
     * @param {*} eles 
     */
    renderInputElements(eles) {
        eles.forEach(ele => {
            this.renderInputElement(ele.id, ele.value);
        })
    }
    /**
     * 渲染输入框元素
     * @param {*} inputId 
     * @param {*} value 
     */
    renderInputElement(inputId, value) {
        const input = this.modal.querySelector(`#${inputId}`);
        if (input) {
            input.value = value;
        }
    }

    /**
     * 渲染已选SKU属性
     */
    renderSelectedSkuAttributes() {
        // 动态设置已选属性区域的图标路径
        const toggleIcon = this.modal.querySelector('.toggle-icon');
        if (toggleIcon) {
            toggleIcon.src = chrome.runtime.getURL(`icons/font/AliExpress_shousuo_shang.png`);
            console.log('已选SKU属性区域图标路径已动态设置');
        }
        
        // 更新已选属性显示
        this.updateSelectedAttributes();
    }

    /**
     * 渲染SKU属性
     */
    renderSkuAttributes() {
        // 修改容器选择器，指向新弹窗中的容器
        const container = document.querySelector('#skuSelectionModal .sku-selection-body');
        if (!container) return;
        
        const attributes = this.leftData.getSkuAttributes();
        
        // 保留全选复选框，只动态生成属性组
        container.innerHTML = `
            <div class="sku-select-all">
                <label><input type="checkbox" id="selectAllAttributes"> 全选</label>
            </div>
            ${attributes.map((attr, index) => {
                const colorIndex = index % 10; // 循环使用10种颜色
                return `
                    <div class="sku-attribute-group sku-color-${colorIndex}">
                        <div class="sku-attribute-header">
                            <label><input type="checkbox" class="sku-attribute-checkbox" checked> ${attr.name}</label>
                        </div>
                        <div class="sku-attribute-values">
                            ${attr.values.map(value => 
                                `<label><input type="checkbox" class="sku-attribute-value-checkbox" data-attribute="${attr.id}" value="${value}" checked> ${value}</label>`
                            ).join('')}
                        </div>
                    </div>
                `;
            }).join('')}
        `;
        
        // 重新绑定事件
        this.bindSkuAttributeEvents();
    }

    //#endregion 数据渲染方法



    /**
     * 处理核算按钮点击
     */
    async handleCalculate() {
        try {
            console.log('开始核算...');
            
            // 验证数据
            const validation = this.leftData.validateLeftData();
            if (!validation.isValid) {
                if (window.AlertUtils) {
                    window.AlertUtils.alert(`数据验证失败: ${validation.errors.join(', ')}`, 'error');
                } else {
                    alert(`数据验证失败: ${validation.errors.join(', ')}`);
                }
                return;
            }
            
            // 获取左侧数据
            const leftData = this.leftData.getLeftData();
            
            // 计算SKU组合
            const skuCombinations = this.calculateSkuCombinations(leftData.selectedAttributes);
            
            // 计算每个SKU的价格
            const calculationResults = await this.calculateSkuPrices(skuCombinations, leftData.leftModalData);
            
            // 更新右侧数据
            this.rightData.addCalculationResults(calculationResults);
            // this.rightData.calculateSummaryData(calculationResults);
            
            // 渲染结果
            this.renderCalculationResults();
            
            console.log('核算完成');
            
        } catch (error) {
            console.error('核算失败:', error);
            if (window.AlertUtils) {
                window.AlertUtils.alert('核算失败，请检查数据后重试', 'error');
            } else {
                alert('核算失败，请检查数据后重试');
            }
        }
    }
    /**
     * 重置弹窗
     */
    resetModal() {
        this.leftData.resetLeftData();
        this.rightData.resetRightData();
        this.renderInterface();
        console.log('弹窗已重置');
    }
}

// 创建全局实例
window.skuPricingModal = new SkuPricingModal();

// 导出初始化函数供工厂模式调用
window.initSkuModal = function() {
    return window.skuPricingModal.initSkuModal();
};