298 lines
10 KiB
Dart
298 lines
10 KiB
Dart
import 'dart:convert';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:http/http.dart' as http;
|
||
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/medicine_item.dart';
|
||
import 'storage_service.dart';
|
||
|
||
class SyncResult {
|
||
final bool success;
|
||
final String message;
|
||
final int? latencyMs;
|
||
final int newRecordsCount;
|
||
|
||
SyncResult({
|
||
required this.success,
|
||
required this.message,
|
||
this.latencyMs,
|
||
this.newRecordsCount = 0,
|
||
});
|
||
}
|
||
|
||
class SyncService {
|
||
static const String _keyServerUrl = 'aerotrack_lan_server_url';
|
||
static const String _keyDeviceName = 'aerotrack_device_name';
|
||
static const String _keyDeviceId = 'aerotrack_device_id';
|
||
static const String _keyLastSync = 'aerotrack_last_sync_time';
|
||
static const String _keyAutoSync = 'aerotrack_auto_sync';
|
||
|
||
// 默认局域网地址推荐(契合私有服务器 192.168.21.200)
|
||
static const String defaultServerUrl = 'http://192.168.21.200:8090';
|
||
|
||
final StorageService storageService;
|
||
|
||
SyncService(this.storageService);
|
||
|
||
static Future<String> getDeviceId() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
String? id = prefs.getString(_keyDeviceId);
|
||
if (id == null) {
|
||
id = const Uuid().v4();
|
||
await prefs.setString(_keyDeviceId, id);
|
||
}
|
||
return id;
|
||
}
|
||
|
||
static Future<String> getServerUrl() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
return prefs.getString(_keyServerUrl) ?? defaultServerUrl;
|
||
}
|
||
|
||
static Future<void> setServerUrl(String url) async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.setString(_keyServerUrl, url.trim());
|
||
}
|
||
|
||
static Future<String> getDeviceName() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
return prefs.getString(_keyDeviceName) ?? '家人手机';
|
||
}
|
||
|
||
static Future<void> setDeviceName(String name) async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.setString(_keyDeviceName, name.trim());
|
||
}
|
||
|
||
static Future<bool> getAutoSyncEnabled() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
return prefs.getBool(_keyAutoSync) ?? true;
|
||
}
|
||
|
||
static Future<void> setAutoSyncEnabled(bool enabled) async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.setBool(_keyAutoSync, enabled);
|
||
}
|
||
|
||
static Future<DateTime?> getLastSyncTime() async {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
final str = prefs.getString(_keyLastSync);
|
||
return str != null ? DateTime.tryParse(str) : null;
|
||
}
|
||
|
||
/// 测试与局域网服务器连通性
|
||
static Future<int?> pingServer(String serverUrl) async {
|
||
try {
|
||
final cleanUrl = serverUrl.trim().replaceAll(RegExp(r'/+$'), '');
|
||
final uri = Uri.parse('$cleanUrl/api/v1/ping');
|
||
final stopwatch = Stopwatch()..start();
|
||
|
||
final res = await http.get(uri).timeout(const Duration(seconds: 3));
|
||
stopwatch.stop();
|
||
|
||
if (res.statusCode == 200) {
|
||
return stopwatch.elapsedMilliseconds;
|
||
}
|
||
} catch (e) {
|
||
debugPrint('Ping server error: $e');
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// 执行完整双向增量同步
|
||
Future<SyncResult> performSync({String? customUrl}) async {
|
||
final baseUrl = (customUrl ?? await getServerUrl()).replaceAll(RegExp(r'/+$'), '');
|
||
final deviceName = await getDeviceName();
|
||
final deviceId = await getDeviceId();
|
||
|
||
final pingMs = await pingServer(baseUrl);
|
||
if (pingMs == null) {
|
||
return SyncResult(
|
||
success: false,
|
||
message: '无法连接局域网服务器 ($baseUrl),请检查 Wi-Fi 或 IP 地址',
|
||
);
|
||
}
|
||
|
||
try {
|
||
await storageService.recalculateCanisterDoses();
|
||
final localRecords = storageService.getAllRecords(includeDeleted: true);
|
||
final localBottles = storageService.getBottles();
|
||
final localCanisters = storageService.getCanisters();
|
||
final localMedicines = storageService.getMedicines(includeDeleted: true);
|
||
final lastSync = await getLastSyncTime();
|
||
|
||
final body = json.encode({
|
||
'device_name': deviceName,
|
||
'device_id': deviceId,
|
||
'last_sync_time': lastSync?.toUtc().toIso8601String(),
|
||
'records': localRecords.map((r) => r.toMap()).toList(),
|
||
'bottles': localBottles.map((b) => b.toMap()).toList(),
|
||
'canisters': localCanisters.map((c) => c.toMap()).toList(),
|
||
'medicines': localMedicines.map((m) => m.toJson()).toList(),
|
||
});
|
||
|
||
final syncUri = Uri.parse('$baseUrl/api/v1/sync');
|
||
final res = await http.post(
|
||
syncUri,
|
||
headers: {'Content-Type': 'application/json; charset=utf-8'},
|
||
body: body,
|
||
).timeout(const Duration(seconds: 6));
|
||
|
||
if (res.statusCode == 200) {
|
||
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||
|
||
// 1. 合并远端药瓶生命周期实体 Bottles
|
||
final remoteBottlesRaw = data['bottles'] as List<dynamic>? ?? [];
|
||
final remoteBottles = remoteBottlesRaw
|
||
.map((item) => Bottle.fromMap(item as Map<String, dynamic>))
|
||
.toList();
|
||
|
||
if (remoteBottles.isNotEmpty) {
|
||
final bottles = storageService.getBottles();
|
||
final bottleMap = {for (var b in bottles) b.id: b};
|
||
|
||
for (var rb in remoteBottles) {
|
||
final lb = bottleMap[rb.id];
|
||
if (lb == null) {
|
||
bottles.add(rb);
|
||
} else {
|
||
// LWW 依据 updatedAt 解决冲突
|
||
if (rb.updatedAt.isAfter(lb.updatedAt) || (rb.isActive != lb.isActive && !rb.isActive)) {
|
||
final idx = bottles.indexWhere((b) => b.id == rb.id);
|
||
if (idx != -1) {
|
||
bottles[idx] = rb;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
await storageService.saveBottles(bottles);
|
||
}
|
||
|
||
// 2. 双向合并全量流水记录 (含软删除墓碑同步)
|
||
final remoteRecordsRaw = data['records'] as List<dynamic>? ?? [];
|
||
final remoteRecords = remoteRecordsRaw
|
||
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
|
||
.toList();
|
||
|
||
final allLocalRecords = storageService.getAllRecords(includeDeleted: true);
|
||
final localRecordMap = {for (var r in allLocalRecords) r.id: r};
|
||
int newCount = 0;
|
||
bool recordListChanged = false;
|
||
|
||
for (var rr in remoteRecords) {
|
||
final lr = localRecordMap[rr.id];
|
||
if (lr == null) {
|
||
allLocalRecords.add(rr);
|
||
if (!rr.isDeleted) newCount++;
|
||
recordListChanged = true;
|
||
} else {
|
||
// 远端记录有状态变更(例如标记软删除或补充了 bottleId)
|
||
if (rr.updatedAt.isAfter(lr.updatedAt) || (rr.isDeleted && !lr.isDeleted)) {
|
||
final idx = allLocalRecords.indexWhere((r) => r.id == rr.id);
|
||
if (idx != -1) {
|
||
allLocalRecords[idx] = rr;
|
||
recordListChanged = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if (recordListChanged) {
|
||
allLocalRecords.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||
final rawList = allLocalRecords.map((r) => r.toJson()).toList();
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.setStringList('aerotrack_records', rawList);
|
||
}
|
||
|
||
// 3. 合并远端药瓶方案基础配置
|
||
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
|
||
final remoteCanisters = remoteCanistersRaw
|
||
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
|
||
.toList();
|
||
|
||
if (remoteCanisters.isNotEmpty) {
|
||
final currentCanisters = storageService.getCanisters();
|
||
final localMap = {for (var c in currentCanisters) c.id: c};
|
||
|
||
for (var rc in remoteCanisters) {
|
||
final lc = localMap[rc.id];
|
||
if (lc != null) {
|
||
lc.name = rc.name;
|
||
lc.isEnabled = rc.isEnabled;
|
||
lc.puffsPerSession = rc.puffsPerSession;
|
||
lc.inhalationSeconds = rc.inhalationSeconds;
|
||
lc.sortOrder = rc.sortOrder;
|
||
lc.note = rc.note;
|
||
} else {
|
||
currentCanisters.add(rc);
|
||
}
|
||
}
|
||
await storageService.saveCanisters(currentCanisters);
|
||
}
|
||
|
||
// 3.5. 合并远端家庭药箱药品数据 (Medicines)
|
||
final remoteMedicinesRaw = data['medicines'] as List<dynamic>? ?? [];
|
||
if (remoteMedicinesRaw.isNotEmpty) {
|
||
final remoteMedicines = remoteMedicinesRaw
|
||
.map((item) => MedicineItem.fromJson(item as Map<String, dynamic>))
|
||
.toList();
|
||
|
||
final localMedicines = storageService.getMedicines(includeDeleted: true);
|
||
final localMedMap = {for (var m in localMedicines) m.id: m};
|
||
|
||
for (var rm in remoteMedicines) {
|
||
final lm = localMedMap[rm.id];
|
||
if (lm == null) {
|
||
localMedicines.add(rm);
|
||
} else {
|
||
if (rm.updatedAt.isAfter(lm.updatedAt) || (rm.isDeleted && !lm.isDeleted)) {
|
||
final idx = localMedicines.indexWhere((m) => m.id == rm.id);
|
||
if (idx != -1) {
|
||
localMedicines[idx] = rm;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
await storageService.saveMedicines(localMedicines);
|
||
}
|
||
|
||
// 4. 核心终极核算:严格由 active 药瓶 UUID 与全量流水确定性重算各药瓶喷数与开封时间
|
||
await storageService.recalculateCanisterDoses();
|
||
|
||
// 5. 更新同步时间戳
|
||
final prefs = await SharedPreferences.getInstance();
|
||
await prefs.setString(_keyLastSync, DateTime.now().toUtc().toIso8601String());
|
||
|
||
return SyncResult(
|
||
success: true,
|
||
message: '同步成功!拉取到 $newCount 条新记录',
|
||
latencyMs: pingMs,
|
||
newRecordsCount: newCount,
|
||
);
|
||
} else {
|
||
return SyncResult(
|
||
success: false,
|
||
message: '服务器返回错误 HTTP ${res.statusCode}',
|
||
);
|
||
}
|
||
} catch (e) {
|
||
return SyncResult(
|
||
success: false,
|
||
message: '同步中断: $e',
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 默默在后台尝试同步(失败不弹窗干扰用户)
|
||
Future<void> syncSilently() async {
|
||
final enabled = await getAutoSyncEnabled();
|
||
if (!enabled) return;
|
||
try {
|
||
await performSync();
|
||
} catch (_) {}
|
||
}
|
||
}
|