/**
 * SKU定价弹窗本地存储工具类
 */
window.SkuPricingStorage = {
  // 存储键名
  STORAGE_KEY: 'sku_pricing_data',
  // 物流信息存储键名
  LOGISTICS_INFO_KEY: 'logistics_info',

  // 默认SKU定价数据
  DEFAULT_DATA: {
    logistics: 'standard_wuyou',
    logisticsDiscount: 100,
    length: 0,
    width: 0,
    height: 0,
    weight: 0,
    baseCountry: 'RS',
    productCost: 0,
    discount: 0,
    platformCommission: 0,
    affiliateCommission: 0,
    transactionFee: 0,
    goldenMarketing: 0,
    activityDiscount: 0,
    lossRate: 0,
    profitRatioType: '1', // 1: 基于成本, 2: 基于售价
    profitMargin: 0,
    adRatio: 0,
    recommendPrice: 0,
    discountPrice: 0,
    maxDiscount: 0
  },

  /**
   * 获取保存的SKU定价数据
   * @returns {Promise<Object>} 合并后的定价数据
   */
  async getSkuPricingData() {
    return new Promise((resolve) => {
      chrome.storage.local.get(this.STORAGE_KEY, (result) => {
        const storedData = result[this.STORAGE_KEY] || {};
        // 合并默认数据和存储数据
        const mergedData = { ...this.DEFAULT_DATA, ...storedData };
        resolve(mergedData);
      });
    });
  },

  /**
   * 保存SKU定价数据
   * @param {Object} data - 要保存的定价数据
   * @returns {Promise<void>}
   */
  async saveSkuPricingData(data) {
    return new Promise((resolve) => {
      // 过滤掉不在默认数据中的字段，确保数据结构一致
      const validData = Object.fromEntries(
        Object.entries(data).filter(([key]) => Object.keys(this.DEFAULT_DATA).includes(key))
      );
      const saveData = {};
      saveData[this.STORAGE_KEY] = validData;
      chrome.storage.local.set(saveData, resolve);
    });
  },

  /**
   * 清除保存的SKU定价数据
   * @returns {Promise<void>}
   */
  async clearSkuPricingData() {
    return new Promise((resolve) => {
      chrome.storage.local.remove(this.STORAGE_KEY, resolve);
    });
  },

  /**
   * 保存物流信息
   * @param {Object} logisticsInfo - 物流信息对象
   * @param {string} logisticsInfo.value - 物流标识符
   * @param {string} logisticsInfo.name - 物流名称
   * @param {string} logisticsInfo.settlementCurrency - 结算货币
   * @returns {Promise<void>}
   */
  async saveLogisticsInfo(logisticsInfo) {
    return new Promise((resolve) => {
      const saveData = {};
      saveData[this.LOGISTICS_INFO_KEY] = logisticsInfo;
      chrome.storage.local.set(saveData, resolve);
    });
  },

  /**
   * 获取保存的物流信息
   * @returns {Promise<Object|null>} 物流信息对象或null
   */
  async getLogisticsInfo() {
    return new Promise((resolve) => {
      chrome.storage.local.get(this.LOGISTICS_INFO_KEY, (result) => {
        resolve(result[this.LOGISTICS_INFO_KEY] || null);
      });
    });
  }
};