import 'dart:convert'; /// 离线缓存服务 /// 基于 Hive 提供本地数据存储能力 class CacheService { static CacheService? _instance; final Map _memoryCache = {}; bool _isInitialized = false; CacheService._internal(); factory CacheService() { _instance ??= CacheService._internal(); return _instance!; } /// 初始化缓存(打开 Hive Box) Future initialize() async { if (_isInitialized) return; try { // TODO: 初始化 Hive // await Hive.initFlutter(); // await Hive.openBox(AppConstants.cacheBoxName); // await Hive.openBox(AppConstants.userBoxName); _isInitialized = true; print('[CacheService] 缓存服务已初始化(模拟)'); } catch (e) { print('[CacheService] 初始化失败: $e'); } } /// 写入缓存 Future put(String key, dynamic value, {String box = 'default'}) async { try { // TODO: 使用 Hive 持久化 // final cacheBox = Hive.box(AppConstants.cacheBoxName); // await cacheBox.put(key, value); _memoryCache['$box:$key'] = value; } catch (e) { print('[CacheService] 写入缓存失败: $e'); } } /// 读取缓存 Future get(String key, {String box = 'default'}) async { try { // TODO: 使用 Hive 读取 // final cacheBox = Hive.box(AppConstants.cacheBoxName); // return cacheBox.get(key) as T?; return _memoryCache['$box:$key'] as T?; } catch (e) { print('[CacheService] 读取缓存失败: $e'); return null; } } /// 删除缓存 Future delete(String key, {String box = 'default'}) async { try { _memoryCache.remove('$box:$key'); } catch (e) { print('[CacheService] 删除缓存失败: $e'); } } /// 清空指定 Box 的所有缓存 Future clearBox({String box = 'default'}) async { try { _memoryCache.removeWhere((key, _) => key.startsWith('$box:')); } catch (e) { print('[CacheService] 清空缓存失败: $e'); } } /// 清空所有缓存 Future clearAll() async { try { _memoryCache.clear(); } catch (e) { print('[CacheService] 清空所有缓存失败: $e'); } } /// 缓存 JSON 对象 Future cacheJson(String key, Map data, {String box = 'default'}) async { await put(key, json.encode(data), box: box); } /// 读取缓存的 JSON 对象 Future?> getCachedJson(String key, {String box = 'default'}) async { final data = await get(key, box: box); if (data == null) return null; try { return json.decode(data) as Map; } catch (e) { return null; } } /// 缓存列表数据 Future cacheList(String key, List> items, {String box = 'default'}) async { await put(key, json.encode(items), box: box); } /// 读取缓存的列表数据 Future>?> getCachedList(String key, {String box = 'default'}) async { final data = await get(key, box: box); if (data == null) return null; try { final decoded = json.decode(data) as List; return decoded.cast>(); } catch (e) { return null; } } /// 检查是否有缓存 Future has(String key, {String box = 'default'}) async { return _memoryCache.containsKey('$box:$key'); } }