import RequestManager from '@/common/request.js' /** * 全局配置工具类 * 用于项目启动时加载全局配置数据并缓存 */ // 数据缓存对象 let configData = null; let isLoading = false; let loadPromise = null; // 配置类 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('全局配置数据加载成功'); 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, defaultValue = null) { if (!configData) { console.warn('配置数据尚未加载,获取本地缓存中。。。'); configData = uni.getStorageSync("configData"); if (configData != null) { return configData; } return defaultValue; } return key in configData ? configData[key] : defaultValue; } /** * 盒子类型 * @returns {Object} 商品类型对象 */ static getGoodType() { let goodType = this.get('good_type'); if (goodType != null) { return goodType.map(item => { return { id: item.value, title: item.name } }); } return []; } /** * 刷新配置数据 * @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; } } export default ConfigManager;