/** * 全局配置工具类 * 用于处理应用配置,包括阿里云图片URL等 */ import { getAliyunImageUrl } from './imageUtils' import { getAliyunUrl } from '@/api/app' function getDefaultStorageConfig() { return { aliyunBaseUrl: '' } } async function fetchAndCacheStorageConfig() { const configResponse = await getAliyunUrl() // 兼容两种返回: // 1) 拦截器已解包:{ aliyunUrl: '...' } // 2) 未解包原始结构:{ code: 1, data: { aliyunUrl: '...' } } const serverConfig = configResponse && typeof configResponse === 'object' && 'aliyunUrl' in configResponse ? configResponse : configResponse?.code === 1 ? configResponse.data || {} : {} const storageConfig = { aliyunBaseUrl: (serverConfig as any).aliyunUrl || '' } uni.setStorageSync('storageConfig', storageConfig) return storageConfig } /** * 初始化应用配置 * 从服务器获取配置信息并缓存 */ export async function initAppConfig() { try { const config = await fetchAndCacheStorageConfig() console.log('应用配置初始化成功', config) } catch (error) { console.error('应用配置初始化失败:', error) uni.setStorageSync('storageConfig', getDefaultStorageConfig()) } } /** * 确保阿里云配置可用;若本地无配置则主动请求一次 */ export async function ensureStorageConfig() { const config = uni.getStorageSync('storageConfig') || {} if (config.aliyunBaseUrl) { return config } try { return await fetchAndCacheStorageConfig() } catch (error) { console.error('确保存储配置失败:', error) const defaultConfig = getDefaultStorageConfig() uni.setStorageSync('storageConfig', defaultConfig) return defaultConfig } } /** * 获取tabbar图标路径 * @param iconType 图标类型 ('home' | 'user') * @param isActive 是否为选中状态 * @returns 图标的路径 */ export function getTabBarIconPath(iconType: 'home' | 'user', isActive: boolean = false): string { // 从配置中获取阿里云基础URL const config = uni.getStorageSync('storageConfig') || {} const baseUrl = config.aliyunBaseUrl || '' // 定义本地路径映射 const localPaths = { home: { normal: 'static/images/tabbar/home.png', active: 'static/yubaoming/home_icon_active.png' }, user: { normal: 'static/images/tabbar/user.png', active: 'static/yubaoming/my_icon_active.png' } } // 如果配置了阿里云基础URL,则使用阿里云路径 if (baseUrl) { const imagePath = isActive ? localPaths[iconType].active : localPaths[iconType].normal return getAliyunImageUrl(imagePath) } // 否则返回本地路径 return isActive ? localPaths[iconType].active : localPaths[iconType].normal }