import RequestManager from '@/common/request.js'
/**
 * 全局配置工具类
 * 用于项目启动时加载全局配置数据并缓存
 */

// 数据缓存对象
let configData = null;
let isLoading = false;
let loadPromise = null;
const wx_version = "104";

// 白名单页面（不需要登录即可访问）
export const whiteList = [
  "pages/shouye/index",              // 首页
  "pages/shouye/detail",             // 详情页
  "pages/shouye/huanxiang",          // 换箱页面
  "pages/mall/index",                // 商城首页
  "pages/shouye/detail_wuxian",      // 无限详情页
  "pages/sangdai/sangdai",           // 盒柜页面
  "pages/infinite/index",            // 福利首页
  "pages/user/index",                // 用户中心
  "pages/infinite/daily_check_in",   // 每日签到
  "pages/infinite/bonus_house",      // 福利屋
  "pages/other/prize_draw",          // 每日奖品抽取
  "pages/shouye/danye",              // 单页
  "pages/guize/guize",               // 规则页面
  "pages/shouye/dada_ranking",       // 达达排行榜
  "pages/shouye/yaoqing_ranking",    // 邀请排行榜
  "pages/user/login"                 // 登录页面
];

// API白名单（不需要登录即可访问的API）
export const apiWhiteList = [
  'login_record',
  'api/warehouse_index',
  'api/user',
  'api/warehouse_send_record'
];

const defaultConfig = {
  "good_type": [{ "value": 0, "sort_order": 0, "is_show": 1, "name": "全部", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 1, "sort_order": 1, "is_show": 0, "name": "一番赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 2, "sort_order": 2, "is_show": 1, "name": "无限赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 3, "sort_order": 3, "is_show": 0, "name": "擂台赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 5, "sort_order": 4, "is_show": 0, "name": "积分赏", "pay_wechat": 0, "pay_balance": 0, "pay_currency": 0, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 0 }, { "value": 6, "sort_order": 5, "is_show": 1, "name": "限时活动", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 8, "sort_order": 6, "is_show": 1, "name": "领主赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 9, "sort_order": 7, "is_show": 0, "name": "连击赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 10, "sort_order": 8, "is_show": 0, "name": "商城赏", "pay_wechat": 1, "pay_balance": 0, "pay_currency": 0, "pay_currency2": 1, "pay_coupon": 0, "is_deduction": 0 }, { "value": 11, "sort_order": 9, "is_show": 0, "name": "自制赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 15, "sort_order": 15, "is_show": 0, "name": "福利屋", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 0, "pay_currency2": 0, "pay_coupon": 0, "is_deduction": 0 }, { "value": 16, "sort_order": 16, "is_show": 1, "name": "翻倍赏", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 1, "pay_currency2": 1, "pay_coupon": 1, "is_deduction": 1 }, { "value": 17, "sort_order": 17, "is_show": 0, "name": "外卖盒子", "pay_wechat": 1, "pay_balance": 1, "pay_currency": 0, "pay_currency2": 0, "pay_coupon": 0, "is_deduction": 0 }],
  "app_setting": {
    "key": "app_setting",
    "app_name": "友达赏",
    "purchase_popup": "1",
    "exchange_times": "2",
    "balance_name": "钻石",
    "balance_icon": "https://image.zfunbox.cn/app/icons/20250412/a482b527477e74f8a18ec02ebc7f0b4e.png",
   
    "currency1_name": "UU币",
    "currency1_icon": "https://image.zfunbox.cn/app/icons/20250412/3d1741965e9439372d1ce101bd110616.png",
    "currency2_name": "达达券",
    "currency2_icon": "https://image.zfunbox.cn/app/icons/20250412/19a9f69011fd82c85ab0df3a064a309c.png",
    "win_audio": "https://image.zfunbox.cn/app/20250407/14ba53d367e1d131a344c6fd5cc0e28e.mp3",
    "applet_version": "v1.0.3",
    "sign_in_spend_limit": "1",
    "show_dadajuan_limit": "0",
    "waimai_box_id": "1049",
    "daily_free_draw_id": "1050",
    "cabinet_exchange_limit": "0",
    "daily_coupon_limit": "0",
    "update_time": 1745379501
  },
  version: wx_version
};

// 配置类
class ConfigManager {
  /**
   * 初始化并加载配置
   * 在应用启动时调用
   */
  static init() {
    return this.loadConfig();
  }

  /**
   * 加载配置数据
   * @returns {Promise} 返回加载完成的Promise
   */
  static loadConfig() {
    // 避免重复加载
    if (isLoading) {
      return loadPromise;
    }

    isLoading = true;
    loadPromise = new Promise((resolve, reject) => {
      RequestManager.get('config')
        .then(res => {
          if (res.status === 1 && res.data) {
            configData = res.data;
            console.log('全局配置数据加载成功');
            let _configData = uni.getStorageSync("configData");
            uni.setStorageSync('configData', configData);
            if (_configData != null && _configData != '') {
              if (_configData.app_setting.applet_version != configData.app_setting.applet_version) {
                console.log('版本号不一致，需要更新');
                const updateManager = uni.getUpdateManager();
                uni.showModal({
                  title: "更新提示",
                  content: "新版本已经准备好，是否重启应用？",
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      console.log('开始重启');
                      wx.restartMiniProgram({ path: "/pages/shouye/index" });
                      // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      //updateManager.applyUpdate();

                      //#ifdef MP-WEIXIN

                      //#endif
                    }
                  },
                });
              }
            }
            resolve(configData);
          } else {
            console.error('加载配置数据失败:', res.msg || '未知错误');
            reject(new Error(res.msg || '加载配置失败'));
          }
        })
        .catch(err => {
          console.error('请求配置数据失败:', err);
          isLoading = false;
          reject(err);
        });
    });

    return loadPromise;
  }

  /**
   * 获取所有配置数据
   * @returns {Object} 配置数据对象
   */
  static getAll() {
    if (configData) {
      return configData;
    } else {
      console.warn('配置数据尚未加载，获取本地缓存中。。。');
      configData = uni.getStorageSync("configData");
      if (configData != null) {
        return configData;
      }
      this.loadConfig();
      return {};
    }
  }

  /**
   * 获取指定键的配置值
   * @param {String} key 配置键
   * @param {any} defaultValue 默认值，当键不存在时返回
   * @returns {any} 配置值
   */
  static get(key) {
    if (!configData) {
      console.warn('配置数据尚未加载，获取本地缓存中。。。');
      configData = uni.getStorageSync("configData");
      if (configData != null && configData != "") {
        // 不直接返回configData，继续执行下面的代码
      } else {
        configData = defaultConfig;
      }

    }
    return key in configData ? configData[key] : defaultConfig[key];
  }

  /**
   * 盒子类型
   * @returns {Object} 商品类型对象
   */
  static getGoodType() {
    let goodType = this.get('good_type');
    if (goodType != null) {
      if (this.GetVersion()) {
        return goodType.filter(item => item.is_show === 1 && (item.value === 2||item.value === 0)).map(item => {
          return {
            id: item.value,
            title: item.name
          }
        });
      }
      return goodType.filter(item => item.is_show === 1).map(item => {
        console.log(item);

        return {
          id: item.value,
          title: item.name
        }
      });
    }
    return [];
  }

  /**
   * 获取指定盒子类型
   * @param {Number} type 盒子类型
   * @returns {Object} 盒子类型对象
   */
  static getGoodTypeFind(type) {
    let goodType = this.get('good_type');
    if (goodType != null) {
      return goodType.find(item => item.value == type);
    }
  }

  /**
   * 刷新配置数据
   * @returns {Promise} 返回刷新完成的Promise
   */
  static refresh() {
    isLoading = false;
    return this.loadConfig();
  }

  /**
   * 检查配置是否已加载
   * @returns {Boolean} 是否已加载
   */
  static isLoaded() {
    return configData !== null;
  }

  /**
   * 获取应用设置
   * @param {String} key 设置键
   * @returns {Object|String|null} 设置值
   */
  static getAppSetting(key = null) {
    let appSetting = this.get('app_setting');
    if (key == null) {
      return appSetting;
    }
    return key in appSetting ? appSetting[key] : null;
  }

  /**
   * 获取指定键的配置值
   * @param {String} key 配置键
   * @param {any} defaultValue 默认值，当键不存在时返回
   * @returns {any} 配置值
   */
  static async getAsync(key, defaultValue = null) {
    if (!configData) {
      // console.warn('配置数据尚未加载，正在加载中...');
      await this.loadConfig();
      if (configData) {
        return key in configData ? configData[key] : defaultValue;;
      }
      return defaultValue;
    }

    return key in configData ? configData[key] : defaultValue;
  }

  /**
   * 获取应用设置
   * @param {String} key 设置键
   * @returns {Object|String|null} 设置值
   */
  static async getAppSettingAsync(key = null) {
    let appSetting = await this.getAsync('app_setting');
    if (key == null) {
      return appSetting;
    }
    return key in appSetting ? appSetting[key] : null;
  }

  /**
   * 获取版本号
   * @returns {Boolean} 是否为微信版本
   */
  static GetVersion() {
    let version = this.get('version');
    if (version == wx_version) {
      return true;
    }
    return false;
  }
}

export default ConfigManager; 