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 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 getServerUrl() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(_keyServerUrl) ?? defaultServerUrl; } static Future setServerUrl(String url) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_keyServerUrl, url.trim()); } static Future getDeviceName() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(_keyDeviceName) ?? '家人手机'; } static Future setDeviceName(String name) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_keyDeviceName, name.trim()); } static Future getAutoSyncEnabled() async { final prefs = await SharedPreferences.getInstance(); return prefs.getBool(_keyAutoSync) ?? true; } static Future setAutoSyncEnabled(bool enabled) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_keyAutoSync, enabled); } static Future getLastSyncTime() async { final prefs = await SharedPreferences.getInstance(); final str = prefs.getString(_keyLastSync); return str != null ? DateTime.tryParse(str) : null; } /// 测试与局域网服务器连通性 static Future 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 performSync({String? customUrl}) async { final baseUrl = (customUrl ?? await getServerUrl()).replaceAll(RegExp(r'/+$'), ''); final deviceName = await getDeviceName(); final deviceId = await getDeviceId(); try { final stopwatch = Stopwatch()..start(); final ping = await http .get(Uri.parse('$baseUrl/api/v1/ping')) .timeout(const Duration(seconds: 3)); final pingMs = stopwatch.elapsedMilliseconds; if (ping.statusCode != 200) { return SyncResult(success: false, message: '服务器连接检查失败'); } final capabilities = jsonDecode(utf8.decode(ping.bodyBytes)); final syncVersion = capabilities is Map ? capabilities['sync_version'] : null; if (syncVersion is! int || syncVersion < 2) { return SyncResult(success: false, message: '同步服务器需要更新,才能恢复药瓶和完整用药记录'); } 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; // 1. 合并远端药瓶生命周期实体 Bottles final remoteBottles = (data['bottles'] as List) .map((item) => Bottle.fromMap(item as Map)) .toList(); final remoteRecords = (data['records'] as List) .map((item) => DoseRecord.fromMap(item as Map)) .toList(); final sentBottles = {for (final bottle in localBottles) bottle.id: bottle.toJson()}; final bottles = {for (final bottle in storageService.getBottles()) bottle.id: bottle}; for (final remote in remoteBottles) { final local = bottles[remote.id]; // 服务器已合并这次提交。只保留请求发出后才发生的本地换瓶。 if (local == null || local.toJson() == sentBottles[remote.id]) { bottles[remote.id] = remote; } } await storageService.saveBottles(bottles.values.toList()); // 2. 双向合并全量流水记录 (含软删除墓碑同步) 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? ?? []; final remoteCanisters = remoteCanistersRaw .map((item) => Canister.fromMap(item as Map)) .toList(); if (remoteCanisters.isNotEmpty) { final canisters = { for (final local in storageService.getCanisters()) local.id: local, for (final remote in remoteCanisters) remote.id: remote, }; await storageService.saveCanisters(canisters.values.toList()); } // 3.5. 合并远端家庭药箱药品数据 (Medicines) final remoteMedicinesRaw = data['medicines'] as List? ?? []; if (remoteMedicinesRaw.isNotEmpty) { final remoteMedicines = remoteMedicinesRaw .map((item) => MedicineItem.fromJson(item as Map)) .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 syncSilently() async { final enabled = await getAutoSyncEnabled(); if (!enabled) return; try { await performSync(); } catch (_) {} } }