import 'package:shared_preferences/shared_preferences.dart'; import 'package:uuid/uuid.dart'; import '../models/bottle.dart'; import '../models/canister.dart'; import '../models/dose_record.dart'; import '../models/app_settings.dart'; class StorageService { static const String _keySettings = 'aerotrack_settings'; static const String _keyCanisters = 'aerotrack_canisters'; static const String _keyRecords = 'aerotrack_records'; static const String _keyBottles = 'aerotrack_bottles'; final SharedPreferences _prefs; StorageService(this._prefs); static Future init() async { final prefs = await SharedPreferences.getInstance(); final service = StorageService(prefs); await service._ensureInitialData(); await service.recalculateCanisterDoses(); return service; } Future _ensureInitialData() async { // 1. 首次启动初始化默认药品方案配置 if (!_prefs.containsKey(_keyCanisters)) { final defaultCanisters = [ Canister( id: 'ventolin_primary', name: '万托林 (硫酸沙丁胺醇)', totalDoses: 200, remainingDoses: 200, openedAt: DateTime(2020, 1, 1).toUtc(), isEnabled: true, puffsPerSession: 2, inhalationSeconds: 15, isSteroid: false, sortOrder: 1, // 先舒张支气管 note: '支气管舒张剂,通常先吸入', ), Canister( id: 'flixotide_primary', name: '辅舒酮 (丙酸氟替卡松)', totalDoses: 60, remainingDoses: 60, openedAt: DateTime(2020, 1, 1).toUtc(), isEnabled: true, puffsPerSession: 2, inhalationSeconds: 15, isSteroid: true, sortOrder: 2, // 后抗炎消肿 note: '糖皮质激素,每瓶60喷', ), ]; await saveCanisters(defaultCanisters); } // 2. 物理药瓶生命周期实体初始化与历史流水平滑迁移 final existingBottles = getBottles(); if (existingBottles.isEmpty) { final initialFlixBottle = Bottle( id: 'flix_b1_initial', canisterId: 'flixotide_primary', name: '辅舒酮 (丙酸氟替卡松)', sequenceNumber: 1, totalDoses: 60, openedAt: DateTime(2020, 1, 1).toUtc(), isActive: true, openedByDevice: '系统初始化', updatedAt: DateTime.now().toUtc(), ); final initialVentBottle = Bottle( id: 'vent_b1_initial', canisterId: 'ventolin_primary', name: '万托林 (硫酸沙丁胺醇)', sequenceNumber: 1, totalDoses: 200, openedAt: DateTime(2020, 1, 1).toUtc(), isActive: true, openedByDevice: '系统初始化', updatedAt: DateTime.now().toUtc(), ); await saveBottles([initialFlixBottle, initialVentBottle]); // 历史平滑过渡:若存在未绑定 bottle_id 的历史用药记录,全部归属到第 1 瓶 final allRawRecords = getAllRecords(includeDeleted: true); bool recordsUpdated = false; final migratedRecords = []; for (var r in allRawRecords) { String? fId = r.flixotideBottleId; String? vId = r.ventolinBottleId; if (r.flixotidePuffs > 0 && fId == null) { fId = initialFlixBottle.id; recordsUpdated = true; } if (r.ventolinPuffs > 0 && vId == null) { vId = initialVentBottle.id; recordsUpdated = true; } if (fId != r.flixotideBottleId || vId != r.ventolinBottleId) { migratedRecords.add(DoseRecord( id: r.id, startTime: r.startTime, endTime: r.endTime, flixotidePuffs: r.flixotidePuffs, ventolinPuffs: r.ventolinPuffs, flixotideBottleId: fId, ventolinBottleId: vId, rinsedMouth: r.rinsedMouth, washedFace: r.washedFace, isPrime: r.isPrime, isDeleted: r.isDeleted, note: r.note, updatedAt: r.updatedAt, )); } else { migratedRecords.add(r); } } if (recordsUpdated) { final list = migratedRecords.map((r) => r.toJson()).toList(); await _prefs.setStringList(_keyRecords, list); } } } // ========== AppSettings ========== AppSettings getSettings() { final raw = _prefs.getString(_keySettings); if (raw == null) return AppSettings(); try { return AppSettings.fromJson(raw); } catch (_) { return AppSettings(); } } Future saveSettings(AppSettings settings) async { await _prefs.setString(_keySettings, settings.toJson()); } // ========== Bottles (物理药瓶生命周期) ========== List getBottles() { final raw = _prefs.getStringList(_keyBottles); if (raw == null) return []; try { final list = raw.map((item) => Bottle.fromJson(item)).toList(); list.sort((a, b) => a.sequenceNumber.compareTo(b.sequenceNumber)); return list; } catch (_) { return []; } } Future saveBottles(List bottles) async { final list = bottles.map((b) => b.toJson()).toList(); await _prefs.setStringList(_keyBottles, list); } Bottle? getActiveBottle(String canisterId) { final bottles = getBottles(); try { return bottles.firstWhere((b) => b.canisterId == canisterId && b.isActive); } catch (_) { final matched = bottles.where((b) => b.canisterId == canisterId).toList(); return matched.isNotEmpty ? matched.last : null; } } Bottle? getActiveFlixotideBottle() => getActiveBottle('flixotide_primary'); Bottle? getActiveVentolinBottle() => getActiveBottle('ventolin_primary'); /// 开启新药瓶:归档旧瓶,激活带有全新 UUID 的新瓶实体 Future openNewBottle(String canisterId, {required String deviceName}) async { final bottles = getBottles(); final nowUtc = DateTime.now().toUtc(); int nextSeq = 1; for (var b in bottles) { if (b.canisterId == canisterId && b.isActive) { b.isActive = false; b.finishedAt = nowUtc; b.updatedAt = nowUtc; } if (b.canisterId == canisterId && b.sequenceNumber >= nextSeq) { nextSeq = b.sequenceNumber + 1; } } final canisters = getCanisters(); final config = canisters.firstWhere( (c) => c.id == canisterId, orElse: () => Canister( id: canisterId, name: canisterId.contains('flix') ? '辅舒酮 (丙酸氟替卡松)' : '万托林 (硫酸沙丁胺醇)', totalDoses: canisterId.contains('flix') ? 60 : 200, remainingDoses: canisterId.contains('flix') ? 60 : 200, openedAt: nowUtc, ), ); final prefix = canisterId.contains('flix') ? 'flix' : 'vent'; final randomSuffix = const Uuid().v4().substring(0, 8); final newBottle = Bottle( id: '${prefix}_b${nextSeq}_$randomSuffix', canisterId: canisterId, name: config.name, sequenceNumber: nextSeq, totalDoses: config.totalDoses, openedAt: nowUtc, isActive: true, openedByDevice: deviceName, updatedAt: nowUtc, ); bottles.add(newBottle); await saveBottles(bottles); // 同步更新方案配置中的开瓶时间与初始满喷 for (var c in canisters) { if (c.id == canisterId) { c.openedAt = nowUtc; c.remainingDoses = c.totalDoses; } } await saveCanisters(canisters); await recalculateCanisterDoses(); return newBottle; } // ========== Canisters ========== List getCanisters() { final raw = _prefs.getStringList(_keyCanisters); if (raw == null) return []; final list = raw.map((item) => Canister.fromJson(item)).toList(); // 严格遵循临床联合雾化顺序:万托林 (支气管舒张剂,非激素) 必须优先于辅舒酮 (糖皮质激素) list.sort((a, b) { if (!a.isSteroid && b.isSteroid) return -1; if (a.isSteroid && !b.isSteroid) return 1; return a.sortOrder.compareTo(b.sortOrder); }); return list; } List getActiveCanisters() { final list = getCanisters().where((c) => c.isEnabled).toList(); list.sort((a, b) { if (!a.isSteroid && b.isSteroid) return -1; if (a.isSteroid && !b.isSteroid) return 1; return a.sortOrder.compareTo(b.sortOrder); }); return list; } Future saveCanisters(List canisters) async { final list = canisters.map((c) => c.toJson()).toList(); await _prefs.setStringList(_keyCanisters, list); } Canister? getPrimaryFlixotide() { final canisters = getCanisters(); return canisters.firstWhere( (c) => c.isSteroid, orElse: () => canisters.first, ); } Canister? getPrimaryVentolin() { final canisters = getCanisters(); return canisters.firstWhere( (c) => !c.isSteroid, orElse: () => canisters.last, ); } Future updateCanister(Canister updated) async { final canisters = getCanisters(); final index = canisters.indexWhere((c) => c.id == updated.id); if (index != -1) { canisters[index] = updated; } else { canisters.add(updated); } await saveCanisters(canisters); } Future deductSessionDoses(Map deductions) async { final canisters = getCanisters(); for (var c in canisters) { if (deductions.containsKey(c.id)) { final used = deductions[c.id]!; c.remainingDoses = (c.remainingDoses - used).clamp(0, c.totalDoses); } } await saveCanisters(canisters); } Future deductDoses({int flixotideDoses = 0, int ventolinDoses = 0}) async { final canisters = getCanisters(); for (var c in canisters) { if (c.isSteroid && flixotideDoses > 0) { c.remainingDoses = (c.remainingDoses - flixotideDoses).clamp(0, c.totalDoses); } else if (!c.isSteroid && ventolinDoses > 0) { c.remainingDoses = (c.remainingDoses - ventolinDoses).clamp(0, c.totalDoses); } } await saveCanisters(canisters); } Future resetCanisterDoses(String canisterId, int newTotal, {String deviceName = '本机'}) async { await openNewBottle(canisterId, deviceName: deviceName); } /// 依据各药瓶 UUID 与真实流水账本,严格重算当前活跃药瓶的真实剩余喷数 Future recalculateCanisterDoses() async { final canisters = getCanisters(); if (canisters.isEmpty) return; final records = getAllRecords(includeDeleted: false); bool changed = false; for (var c in canisters) { final activeBottle = getActiveBottle(c.id); int consumedPuffs = 0; if (activeBottle != null) { for (var r in records) { if (c.isSteroid) { // 优先依据明确绑定的 bottleId 核算 if (r.flixotideBottleId == activeBottle.id) { consumedPuffs += r.flixotidePuffs; } else if (r.flixotideBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) { // 兼容早期未绑定 bottleId 的旧数据 consumedPuffs += r.flixotidePuffs; } } else { if (r.ventolinBottleId == activeBottle.id) { consumedPuffs += r.ventolinPuffs; } else if (r.ventolinBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) { consumedPuffs += r.ventolinPuffs; } } } final correctRemaining = (activeBottle.totalDoses - consumedPuffs).clamp(0, activeBottle.totalDoses); if (c.remainingDoses != correctRemaining || c.openedAt != activeBottle.openedAt) { c.remainingDoses = correctRemaining; c.openedAt = activeBottle.openedAt; changed = true; } } else { // 无 activeBottle 时的保护逻辑 for (var r in records) { if (c.isSteroid) { consumedPuffs += r.flixotidePuffs; } else { consumedPuffs += r.ventolinPuffs; } } final correctRemaining = (c.totalDoses - consumedPuffs).clamp(0, c.totalDoses); if (c.remainingDoses != correctRemaining) { c.remainingDoses = correctRemaining; changed = true; } } } if (changed) { await saveCanisters(canisters); } } // ========== DoseRecords ========== /// 获取对用户可见的有效流水记录(默认过滤掉软删除墓碑记录) List getRecords() => getAllRecords(includeDeleted: false); /// 获取全量记录(可包含软删除墓碑,专供多端同步使用) List getAllRecords({bool includeDeleted = false}) { final raw = _prefs.getStringList(_keyRecords); if (raw == null) return []; try { final list = raw.map((item) => DoseRecord.fromJson(item)).toList(); final filtered = includeDeleted ? list : list.where((r) => !r.isDeleted).toList(); filtered.sort((a, b) => b.startTime.compareTo(a.startTime)); return filtered; } catch (_) { return []; } } Future addRecord(DoseRecord record) async { final records = getAllRecords(includeDeleted: true); records.insert(0, record); final list = records.map((r) => r.toJson()).toList(); await _prefs.setStringList(_keyRecords, list); await recalculateCanisterDoses(); } /// 软删除记录(墓碑机制):全网标记废弃,喷数自动准确恢复 Future deleteRecord(String id) async { final records = getAllRecords(includeDeleted: true); final nowUtc = DateTime.now().toUtc(); bool updated = false; for (int i = 0; i < records.length; i++) { if (records[i].id == id) { final old = records[i]; records[i] = DoseRecord( id: old.id, startTime: old.startTime, endTime: old.endTime, flixotidePuffs: old.flixotidePuffs, ventolinPuffs: old.ventolinPuffs, flixotideBottleId: old.flixotideBottleId, ventolinBottleId: old.ventolinBottleId, rinsedMouth: old.rinsedMouth, washedFace: old.washedFace, isPrime: old.isPrime, isDeleted: true, note: old.note, updatedAt: nowUtc, ); updated = true; break; } } if (updated) { final list = records.map((r) => r.toJson()).toList(); await _prefs.setStringList(_keyRecords, list); await recalculateCanisterDoses(); } } }