import constant from './constant' // 存储变量名 let storageKey = 'storage_data' // 存储节点变量名 let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions] const storage = { set: function(key, value) { if (storageNodeKeys.indexOf(key) != -1) { let tmp = uni.getStorageSync(storageKey) tmp = tmp ? tmp : {} tmp[key] = value uni.setStorageSync(storageKey, tmp) } }, get: function(key) { let storageData = uni.getStorageSync(storageKey) || {} return storageData[key] || "" }, remove: function(key) { let storageData = uni.getStorageSync(storageKey) || {} delete storageData[key] uni.setStorageSync(storageKey, storageData) }, clean: function() { uni.removeStorageSync(storageKey) }, // 新增:获取存储信息 getStorageInfo: function() { try { const info = uni.getStorageInfoSync() console.log('💾 存储信息:', { keys: info.keys, currentSize: info.currentSize, limitSize: info.limitSize, usage: ((info.currentSize / info.limitSize) * 100).toFixed(2) + '%' }) return info } catch (e) { console.error('获取存储信息失败:', e) return null } }, // 新增:清理所有存储(慎用) clearAll: function() { try { uni.clearStorageSync() console.log('✅ 清理所有存储成功') } catch (e) { console.error('清理存储失败:', e) } }, // 新增:检查并清理过期数据 checkAndClean: function() { try { const info = uni.getStorageInfoSync() const usagePercent = (info.currentSize / info.limitSize) * 100 // 如果使用超过 80%,提示用户 if (usagePercent > 80) { console.warn('⚠️ 存储空间使用超过 80%:', usagePercent.toFixed(2) + '%') // 自动清理非必要的缓存 const keysToKeep = [storageKey, 'token', 'uni-id-pages-userInfo'] info.keys.forEach(key => { if (!keysToKeep.includes(key)) { try { uni.removeStorageSync(key) console.log('🗑️ 清理缓存:', key) } catch (e) { console.error('清理失败:', key, e) } } }) } } catch (e) { console.error('检查存储失败:', e) } } } export default storage