566 lines
19 KiB
Dart
566 lines
19 KiB
Dart
import 'dart:convert';
|
||
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';
|
||
import '../models/medicine_item.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';
|
||
static const String _keyMedicines = 'aerotrack_medicines';
|
||
|
||
final SharedPreferences _prefs;
|
||
|
||
StorageService(this._prefs);
|
||
|
||
static Future<StorageService> init() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
final service = StorageService(prefs);
|
||
await service._ensureInitialData();
|
||
await service.recalculateCanisterDoses();
|
||
return service;
|
||
}
|
||
|
||
Future<void> _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 = <DoseRecord>[];
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
// 3. 家庭药箱初始默认药品播种
|
||
if (!_prefs.containsKey(_keyMedicines)) {
|
||
final nowUtc = DateTime.now().toUtc();
|
||
final initialMedicines = [
|
||
MedicineItem(
|
||
id: 'med_flixotide_seed',
|
||
name: '辅舒酮 (丙酸氟替卡松吸入气雾剂)',
|
||
category: MedicineCategory.inhaler,
|
||
spec: '50μg/喷 × 60喷',
|
||
storageLocation: '常温药箱',
|
||
targetUser: '宝宝',
|
||
barcode: '6921147600010',
|
||
expiryDate: DateTime.now().add(const Duration(days: 365 * 2)).toUtc(),
|
||
shelfLifeDaysAfterOpening: 60,
|
||
isOpened: true,
|
||
openedAt: DateTime.now().subtract(const Duration(days: 10)).toUtc(),
|
||
notes: '拆开铝箔袋后 60 天内用完,吸入后温水漱口',
|
||
updatedAt: nowUtc,
|
||
),
|
||
MedicineItem(
|
||
id: 'med_meilin_seed',
|
||
name: '美林 (布洛芬混悬液)',
|
||
category: MedicineCategory.oralLiquid,
|
||
spec: '100ml:2g',
|
||
storageLocation: '常温药箱 (避光)',
|
||
targetUser: '宝宝',
|
||
barcode: '6925567800018',
|
||
expiryDate: DateTime.now().add(const Duration(days: 365 * 2)).toUtc(),
|
||
shelfLifeDaysAfterOpening: 60,
|
||
isOpened: false,
|
||
notes: '发热 38.5℃ 以上使用,间隔 4~6 小时',
|
||
updatedAt: nowUtc,
|
||
),
|
||
MedicineItem(
|
||
id: 'med_tobramycin_seed',
|
||
name: '托百士 (妥布霉素滴眼液)',
|
||
category: MedicineCategory.eyeDrops,
|
||
spec: '5ml:15mg',
|
||
storageLocation: '常温药箱',
|
||
targetUser: '宝宝',
|
||
barcode: '6936577800015',
|
||
expiryDate: DateTime.now().add(const Duration(days: 300)).toUtc(),
|
||
shelfLifeDaysAfterOpening: 28,
|
||
isOpened: false,
|
||
notes: '抗生素眼药水,开封后 4 周必须丢弃',
|
||
updatedAt: nowUtc,
|
||
),
|
||
];
|
||
await saveMedicines(initialMedicines);
|
||
}
|
||
}
|
||
|
||
// ========== AppSettings ==========
|
||
AppSettings getSettings() {
|
||
final raw = _prefs.getString(_keySettings);
|
||
if (raw == null) return AppSettings();
|
||
try {
|
||
return AppSettings.fromJson(raw);
|
||
} catch (_) {
|
||
return AppSettings();
|
||
}
|
||
}
|
||
|
||
Future<void> saveSettings(AppSettings settings) async {
|
||
await _prefs.setString(_keySettings, settings.toJson());
|
||
}
|
||
|
||
// ========== Bottles (物理药瓶生命周期) ==========
|
||
List<Bottle> 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<void> saveBottles(List<Bottle> 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<Bottle> 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<Canister> 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<Canister> 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<void> saveCanisters(List<Canister> 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<void> 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<void> deductSessionDoses(Map<String, int> 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<void> 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<void> resetCanisterDoses(String canisterId, int newTotal, {String deviceName = '本机'}) async {
|
||
await openNewBottle(canisterId, deviceName: deviceName);
|
||
}
|
||
|
||
/// 依据各药瓶 UUID 与真实流水账本,严格重算当前活跃药瓶的真实剩余喷数
|
||
Future<void> 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<DoseRecord> getRecords() => getAllRecords(includeDeleted: false);
|
||
|
||
/// 获取全量记录(可包含软删除墓碑,专供多端同步使用)
|
||
List<DoseRecord> 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<void> 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<void> 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();
|
||
}
|
||
}
|
||
|
||
// ========== Family Medicine Cabinet (家庭药箱) ==========
|
||
/// 获取未被软删除的有效药品列表(按有效期升序排序)
|
||
List<MedicineItem> getMedicines({bool includeDeleted = false}) {
|
||
final raw = _prefs.getStringList(_keyMedicines);
|
||
if (raw == null) return [];
|
||
try {
|
||
final list = raw
|
||
.map((item) => MedicineItem.fromJson(jsonDecode(item) as Map<String, dynamic>))
|
||
.toList();
|
||
final filtered = includeDeleted ? list : list.where((m) => !m.isDeleted).toList();
|
||
filtered.sort((a, b) => a.expiryDate.compareTo(b.expiryDate));
|
||
return filtered;
|
||
} catch (_) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/// 保存完整药品列表
|
||
Future<void> saveMedicines(List<MedicineItem> medicines) async {
|
||
final list = medicines.map((m) => jsonEncode(m.toJson())).toList();
|
||
await _prefs.setStringList(_keyMedicines, list);
|
||
}
|
||
|
||
/// 新增或更新单个药品
|
||
Future<void> saveMedicine(MedicineItem medicine) async {
|
||
final list = getMedicines(includeDeleted: true);
|
||
final index = list.indexWhere((m) => m.id == medicine.id);
|
||
if (index >= 0) {
|
||
list[index] = medicine;
|
||
} else {
|
||
list.add(medicine);
|
||
}
|
||
await saveMedicines(list);
|
||
}
|
||
|
||
/// 软删除药品(墓碑标记,支持多端同步自动下架)
|
||
Future<void> deleteMedicine(String id) async {
|
||
final list = getMedicines(includeDeleted: true);
|
||
final nowUtc = DateTime.now().toUtc();
|
||
for (int i = 0; i < list.length; i++) {
|
||
if (list[i].id == id) {
|
||
list[i] = list[i].copyWith(
|
||
isDeleted: true,
|
||
updatedAt: nowUtc,
|
||
);
|
||
break;
|
||
}
|
||
}
|
||
await saveMedicines(list);
|
||
}
|
||
|
||
/// 一键打卡开封
|
||
Future<void> openMedicine(String id, {String? deviceName}) async {
|
||
final list = getMedicines(includeDeleted: true);
|
||
final nowUtc = DateTime.now().toUtc();
|
||
for (int i = 0; i < list.length; i++) {
|
||
if (list[i].id == id) {
|
||
list[i] = list[i].copyWith(
|
||
isOpened: true,
|
||
openedAt: nowUtc,
|
||
openedByDevice: deviceName ?? '本机',
|
||
updatedAt: nowUtc,
|
||
);
|
||
break;
|
||
}
|
||
}
|
||
await saveMedicines(list);
|
||
}
|
||
}
|