From 394bb727c7991685d4e308641e5169c4dadd8047 Mon Sep 17 00:00:00 2001 From: shen <> Date: Tue, 27 Oct 2026 06:36:48 -0700 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=A5=E6=A0=BC=E7=A1=AE=E4=BF=9D?= =?UTF-8?q?=E4=B8=87=E6=89=98=E6=9E=97=E5=85=88=E8=A1=8C=E5=90=B8=E5=85=A5?= =?UTF-8?q?=EF=BC=8C=E9=80=80=E5=87=BA=E4=BC=9A=E8=AF=9D=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E4=B8=8D=E4=B8=AD=E6=96=AD=E8=AE=A1=E6=97=B6=EF=BC=88=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=90=8E=E5=8F=B0=E6=8C=81=E7=BB=AD=E5=80=92=E8=AE=A1?= =?UTF-8?q?=E6=97=B6=E4=B8=8E=E4=B8=BB=E9=A1=B5=E6=82=AC=E6=B5=AE=E5=8D=A1?= =?UTF-8?q?=E7=89=87=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/screens/home_screen.dart | 163 ++++- lib/screens/session_screen.dart | 855 +++++++++-------------- lib/services/active_session_service.dart | 331 +++++++++ lib/services/storage_service.dart | 15 +- test/widget_test.dart | 32 + 5 files changed, 883 insertions(+), 513 deletions(-) create mode 100644 lib/services/active_session_service.dart diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 3245491..520ae2a 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -11,6 +11,7 @@ import 'settings_screen.dart'; import 'plan_config_screen.dart'; import 'lan_sync_screen.dart'; import '../services/sync_service.dart'; +import '../services/active_session_service.dart'; class HomeScreen extends StatefulWidget { final StorageService storageService; @@ -27,10 +28,12 @@ class _HomeScreenState extends State { late List _activeCanisters; late AppSettings _settings; DoseRecord? _lastRecord; + final ActiveSessionService _sessionService = ActiveSessionService(); @override void initState() { super.initState(); + _sessionService.addListener(_onSessionUpdate); _loadData(); // 局域网静默尝试同步拉取最新状态 SyncService(widget.storageService).syncSilently().then((_) { @@ -38,6 +41,16 @@ class _HomeScreenState extends State { }); } + @override + void dispose() { + _sessionService.removeListener(_onSessionUpdate); + super.dispose(); + } + + void _onSessionUpdate() { + if (mounted) setState(() {}); + } + void _loadData() { setState(() { _flixotide = widget.storageService.getPrimaryFlixotide()!; @@ -60,8 +73,14 @@ class _HomeScreenState extends State { } } + String _formatTime(int totalSeconds) { + final m = (totalSeconds ~/ 60).toString().padLeft(2, '0'); + final s = (totalSeconds % 60).toString().padLeft(2, '0'); + return '$m:$s'; + } + Future _startSession() async { - if (_activeCanisters.isEmpty) { + if (_activeCanisters.isEmpty && !_sessionService.isActive) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('请先在方案配置中至少勾选一种使用的药物!')), ); @@ -88,6 +107,8 @@ class _HomeScreenState extends State { ), ); } + } else { + _loadData(); } } @@ -291,6 +312,12 @@ class _HomeScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + // 模块 0:若有后台进行中的雾化,展示醒目实时卡片 (返回主页不中断计时) + if (_sessionService.isActive) ...[ + _buildActiveSessionBanner(), + const SizedBox(height: 16), + ], + // 模块 1:定时提醒状态条 _buildReminderBar(), @@ -314,6 +341,124 @@ class _HomeScreenState extends State { ); } + // 0. 进行中雾化实时悬浮卡片 (返回主页不中断计时) + Widget _buildActiveSessionBanner() { + final step = _sessionService.currentStep; + final isWaiting = _sessionService.isWaitingForNextMed; + final isFinished = _sessionService.isFinished; + + Color bg; + Color border; + IconData icon; + String title; + String subtitle; + String actionLabel; + + if (isFinished) { + bg = const Color(0xFFECFDF5); + border = const Color(0xFF6EE7B7); + icon = Icons.check_circle; + title = '雾化吸入已全部完成!'; + subtitle = '请点击进入确认打卡并完成漱口洗脸'; + actionLabel = '确认打卡 ↗'; + } else if (isWaiting) { + bg = const Color(0xFFFFFBEB); + border = const Color(0xFFFCD34D); + icon = Icons.alarm_on; + final nextName = _sessionService.nextStep?.canister?.name.split(" ")[0] ?? '第二组药物'; + title = '两药间隔等待已结束!'; + subtitle = '气道已充分舒张,点击手动开始吸入【$nextName】'; + actionLabel = '开始第二组 ↗'; + } else { + bg = const Color(0xFF0F172A); + border = const Color(0xFF334155); + icon = Icons.hourglass_top_rounded; + title = '雾化计时进行中 • ${step?.title ?? ""}'; + subtitle = '剩余 ${_formatTime(_sessionService.remainingSeconds)} • 后台持续计时中'; + actionLabel = '全屏界面 ↗'; + } + + final isDark = !isFinished && !isWaiting; + + return InkWell( + onTap: _startSession, + borderRadius: BorderRadius.circular(16), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: border, width: 1.5), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 3), + ), + ], + ), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: isDark ? Colors.white10 : Colors.white, + shape: BoxShape.circle, + ), + child: Icon( + icon, + color: isFinished + ? const Color(0xFF059669) + : (isWaiting ? const Color(0xFFD97706) : const Color(0xFF38BDF8)), + size: 22, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: isDark ? Colors.white : (isFinished ? const Color(0xFF065F46) : const Color(0xFF92400E)), + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: TextStyle( + fontSize: 12, + color: isDark ? const Color(0xFF94A3B8) : (isFinished ? const Color(0xFF047857) : const Color(0xFFB45309)), + ), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF2563EB) : (isFinished ? const Color(0xFF10B981) : const Color(0xFFF59E0B)), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + actionLabel, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 11, + ), + ), + ), + ], + ), + ), + ); + } + // 1. 到点提醒状态条 Widget _buildReminderBar() { final mTime = '${_settings.morningReminderHour.toString().padLeft(2, '0')}:${_settings.morningReminderMinute.toString().padLeft(2, '0')}'; @@ -418,11 +563,11 @@ class _HomeScreenState extends State { const SizedBox(height: 20), - // 主行动按钮:开始雾化 + // 主行动按钮:开始雾化 / 继续后台雾化 ElevatedButton( onPressed: _startSession, style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFF2563EB), + backgroundColor: _sessionService.isActive ? const Color(0xFF10B981) : const Color(0xFF2563EB), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), @@ -431,10 +576,18 @@ class _HomeScreenState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon(Icons.play_circle_fill, size: 22), + Icon(_sessionService.isActive ? Icons.play_arrow_rounded : Icons.play_circle_fill, size: 22), const SizedBox(width: 8), Text( - _activeCanisters.length > 1 ? '按方案开始雾化 (带$crossMinutes分钟间隔)' : '开始吸入 ${_activeCanisters.first.name.split(" ")[0]}', + _sessionService.isActive + ? (_sessionService.isWaitingForNextMed + ? '两药间隔已结束:点击开始第二组' + : (_sessionService.isFinished + ? '雾化已完成:点击确认打卡' + : '继续进行中雾化 (${_formatTime(_sessionService.remainingSeconds)})')) + : (_activeCanisters.length > 1 + ? '按方案开始雾化 (万托林先行 • 带$crossMinutes分钟间隔)' + : '开始吸入 ${_activeCanisters.first.name.split(" ")[0]}'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold), ), ], diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dart index 62581c5..f851624 100644 --- a/lib/screens/session_screen.dart +++ b/lib/screens/session_screen.dart @@ -1,41 +1,7 @@ -import 'dart:async'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:uuid/uuid.dart'; import '../models/canister.dart'; -import '../models/app_settings.dart'; -import '../models/dose_record.dart'; import '../services/storage_service.dart'; -import '../services/tts_service.dart'; -import '../services/sync_service.dart'; -import '../services/audio_service.dart'; - -enum StepType { - inhale, // 正在吸入某药某喷 - intraPuffWait, // 同药两喷之间等待 (30s) - crossDrugWait, // 两药之间等待 (默认 5min,可调) - finished, // 全部完成 -} - -class SessionStep { - final StepType type; - final Canister? canister; - final int puffIndex; // 第几喷 (1-based) - final int totalPuffs; // 该药共几喷 - int durationSeconds; // 倒计时时长 (秒) - final String title; - final String subtitle; - - SessionStep({ - required this.type, - this.canister, - this.puffIndex = 1, - this.totalPuffs = 1, - required this.durationSeconds, - required this.title, - required this.subtitle, - }); -} +import '../services/active_session_service.dart'; class SessionScreen extends StatefulWidget { final StorageService storageService; @@ -52,234 +18,67 @@ class SessionScreen extends StatefulWidget { } class _SessionScreenState extends State { - late AppSettings _settings; - late DateTime _sessionStartTime; - DateTime? _sessionEndTime; - - final List _steps = []; - int _currentStepIndex = 0; - - Timer? _timer; - int _remainingSeconds = 0; - int _totalStageSeconds = 0; - - bool _rinsedMouth = true; - bool _washedFace = true; - bool _isWaitingForNextMed = false; + final ActiveSessionService _sessionService = ActiveSessionService(); @override void initState() { super.initState(); - _settings = widget.storageService.getSettings(); - _sessionStartTime = DateTime.now(); + _sessionService.addListener(_onSessionUpdate); - _buildStepsPipeline(); - - WidgetsBinding.instance.addPostFrameCallback((_) { - if (_steps.isNotEmpty) { - _startStep(0); - } - }); - } - - void _buildStepsPipeline() { - _steps.clear(); - - for (int i = 0; i < widget.activeMedications.length; i++) { - final med = widget.activeMedications[i]; - - for (int p = 1; p <= med.puffsPerSession; p++) { - // 吸入步骤 - _steps.add( - SessionStep( - type: StepType.inhale, - canister: med, - puffIndex: p, - totalPuffs: med.puffsPerSession, - durationSeconds: med.inhalationSeconds, - title: '吸入 ${med.name}', - subtitle: '第 $p / ${med.puffsPerSession} 喷 • 面罩紧贴口鼻,平稳深呼吸', - ), - ); - - // 如果同药还有下一喷,插入 30 秒同药间隔 - if (p < med.puffsPerSession) { - _steps.add( - SessionStep( - type: StepType.intraPuffWait, - canister: med, - puffIndex: p, - totalPuffs: med.puffsPerSession, - durationSeconds: _settings.intraPuffIntervalSeconds, - title: '${med.name} 连喷间隔', - subtitle: '请间隔 30 秒使药雾沉降并重新摇匀,切勿连喷', - ), - ); - } - } - - // 如果后面还有其他药物,插入多药跨药间隔 (默认 5 分钟) - if (i < widget.activeMedications.length - 1) { - final nextMed = widget.activeMedications[i + 1]; - _steps.add( - SessionStep( - type: StepType.crossDrugWait, - canister: med, - durationSeconds: _settings.crossDrugIntervalSeconds, - title: '两药间隔等待 (建议 5 分钟)', - subtitle: '${med.name} 舒张气道中,到点后将提示吸入 ${nextMed.name}', - ), - ); - } + // 若当前未在执行雾化,则开启新的会话 + if (!_sessionService.isActive && widget.activeMedications.isNotEmpty) { + final settings = widget.storageService.getSettings(); + _sessionService.startNewSession( + medications: widget.activeMedications, + settings: settings, + ); } } @override void dispose() { - _timer?.cancel(); - TtsService().stop(); + _sessionService.removeListener(_onSessionUpdate); + // 注意:退出界面绝不销毁计时器!ActiveSessionService 在后台继续计时与语音提醒 super.dispose(); } - void _triggerFeedback({bool isFinished = false}) { - if (_settings.enableVibration) { - HapticFeedback.heavyImpact(); - } - if (_settings.enableSound) { - if (isFinished) { - AudioService().playSessionComplete(); - } else { - AudioService().playStepComplete(); + void _onSessionUpdate() { + if (mounted) setState(() {}); + } + + Future _confirmAbortSession() async { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('放弃本次雾化?'), + content: const Text('放弃后将重置当前的雾化与倒计时进度,不会扣除药瓶剩余喷数。'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('继续雾化'), + ), + ElevatedButton( + onPressed: () => Navigator.pop(ctx, true), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.redAccent, + foregroundColor: Colors.white, + ), + child: const Text('确认放弃'), + ), + ], + ), + ); + + if (confirmed == true) { + _sessionService.cancelSession(); + if (mounted) { + Navigator.of(context).pop(false); } } } - void _speakStep(SessionStep step) { - if (!_settings.enableVoicePrompt) return; - if (step.type == StepType.inhale) { - final medName = step.canister?.name.split(" ")[0] ?? '药物'; - TtsService().speak('请吸入$medName第${step.puffIndex}喷,口鼻密闭,慢而深地吸气。'); - } else if (step.type == StepType.intraPuffWait) { - TtsService().speak('第${step.puffIndex}喷吸入完成,请等待三十秒后吸入下一喷。'); - } else if (step.type == StepType.crossDrugWait) { - final minutes = step.durationSeconds ~/ 60; - TtsService().speak('两药间隔开始,请等待$minutes分钟,待气道充分扩张。'); - } - } - - void _startStep(int index) { - if (index >= _steps.length) { - _finishSession(); - return; - } - - final step = _steps[index]; - _timer?.cancel(); - - setState(() { - _currentStepIndex = index; - _remainingSeconds = step.durationSeconds; - _totalStageSeconds = step.durationSeconds; - }); - - _speakStep(step); - - _timer = Timer.periodic(const Duration(seconds: 1), (timer) { - if (_remainingSeconds > 1) { - setState(() { - _remainingSeconds--; - }); - } else { - timer.cancel(); - _onStepCompleted(); - } - }); - } - - void _onStepCompleted() { - _triggerFeedback(); - - if (_currentStepIndex < _steps.length) { - final currentStep = _steps[_currentStepIndex]; - // 如果当前是两药间隔等待,到点后提醒用户,并等待手动点击确认后再开始第二种药物 - if (currentStep.type == StepType.crossDrugWait && _currentStepIndex + 1 < _steps.length) { - _timer?.cancel(); - if (_settings.enableSound) { - AudioService().playSessionComplete(); - } - final nextMed = _steps[_currentStepIndex + 1].canister; - final nextName = nextMed?.name.split(' ')[0] ?? '第二组药物'; - if (_settings.enableVoicePrompt) { - TtsService().speak('两药间隔等待已结束!气道已充分舒张。请换上$nextName,戴好面罩后点击屏幕开始吸入。'); - } - setState(() { - _isWaitingForNextMed = true; - }); - return; - } - } - - if (_currentStepIndex + 1 < _steps.length) { - _startStep(_currentStepIndex + 1); - } else { - _finishSession(); - } - } - - void _finishSession() { - _timer?.cancel(); - _sessionEndTime = DateTime.now(); - _triggerFeedback(isFinished: true); - if (_settings.enableVoicePrompt) { - Future.delayed(const Duration(milliseconds: 1000), () { - if (mounted) { - TtsService().speak('本次雾化吸入已全部完成,请及时用清水漱口并洗脸!'); - } - }); - } - setState(() { - _currentStepIndex = _steps.length; // 进入完成态 - }); - } - - void _adjustCurrentTime(int deltaSeconds) { - setState(() { - final newRemaining = (_remainingSeconds + deltaSeconds).clamp(1, 1800); - _remainingSeconds = newRemaining; - if (_currentStepIndex < _steps.length) { - _steps[_currentStepIndex].durationSeconds = newRemaining; - } - }); - } - Future _saveAndExit() async { - final Map deductions = {}; - int totalFlixotide = 0; - int totalVentolin = 0; - - for (var med in widget.activeMedications) { - deductions[med.id] = med.puffsPerSession; - if (med.isSteroid) { - totalFlixotide += med.puffsPerSession; - } else { - totalVentolin += med.puffsPerSession; - } - } - - final record = DoseRecord( - id: const Uuid().v4(), - startTime: _sessionStartTime, - endTime: _sessionEndTime ?? DateTime.now(), - flixotidePuffs: totalFlixotide, - ventolinPuffs: totalVentolin, - rinsedMouth: _rinsedMouth, - washedFace: _washedFace, - ); - - await widget.storageService.deductSessionDoses(deductions); - await widget.storageService.addRecord(record); - SyncService(widget.storageService).syncSilently(); - + await _sessionService.confirmAndSave(widget.storageService); if (mounted) { Navigator.of(context).pop(true); } @@ -293,90 +92,129 @@ class _SessionScreenState extends State { @override Widget build(BuildContext context) { - if (_currentStepIndex >= _steps.length) { + if (!_sessionService.isActive) { + return Scaffold( + backgroundColor: const Color(0xFF0F172A), + body: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('当前无进行中的雾化会话', style: TextStyle(color: Colors.white)), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('返回首页'), + ), + ], + ), + ), + ); + } + + if (_sessionService.isFinished) { return _buildFinishedView(); } - if (_isWaitingForNextMed && _currentStepIndex + 1 < _steps.length) { - return _buildWaitingForNextMedView(_steps[_currentStepIndex + 1]); + if (_sessionService.isWaitingForNextMed && _sessionService.nextStep != null) { + return _buildWaitingForNextMedView(_sessionService.nextStep!); + } + + final step = _sessionService.currentStep; + if (step == null) { + return _buildFinishedView(); } - final step = _steps[_currentStepIndex]; final isCross = step.type == StepType.crossDrugWait; - return Scaffold( - backgroundColor: const Color(0xFF0F172A), - appBar: AppBar( - backgroundColor: Colors.transparent, - elevation: 0, - foregroundColor: Colors.white, - title: Text( - '雾化中 (${_currentStepIndex + 1}/${_steps.length})', - style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold), - ), - actions: [ - TextButton( + return PopScope( + canPop: true, // 允许返回主页,后台继续计时 + child: Scaffold( + backgroundColor: const Color(0xFF0F172A), + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + foregroundColor: Colors.white, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + tooltip: '返回主页 (后台继续计时)', onPressed: () => Navigator.of(context).pop(), - child: const Text('退出', style: TextStyle(color: Colors.white70)), ), - ], - ), - body: SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), - child: Column( - children: [ - // 顶部步骤徽章 - _buildStepBadge(step), + title: Text( + '雾化中 (${_sessionService.currentStepIndex + 1}/${_sessionService.steps.length})', + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold), + ), + actions: [ + TextButton( + onPressed: _confirmAbortSession, + child: const Text('放弃本次', style: TextStyle(color: Colors.redAccent, fontSize: 13)), + ), + ], + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + child: Column( + children: [ + // 顶部步骤徽章 + _buildStepBadge(step), - const SizedBox(height: 24), + const SizedBox(height: 20), - Text( - step.title, - textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), - ), - const SizedBox(height: 8), - Text( - step.subtitle, - textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white60, fontSize: 13), - ), + Text( + step.title, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + step.subtitle, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white60, fontSize: 13), + ), - const Spacer(), + const Spacer(), - // 倒计时核心大表盘 - _buildTimerDial(isCross), + // 倒计时核心大表盘 + _buildTimerDial(isCross), - const SizedBox(height: 16), + const SizedBox(height: 16), - // 动态调节时间微调器 - _buildTimeAdjustControls(isCross), + // 动态调节时间微调器 + _buildTimeAdjustControls(isCross), - const Spacer(), + const Spacer(), - // 下一步按钮 - Row( - children: [ - Expanded( - child: ElevatedButton( - onPressed: _onStepCompleted, - style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFF2563EB), - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 16), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - elevation: 0, - ), - child: Text( - _currentStepIndex + 1 < _steps.length ? '下一步 / 提前进入下一阶段' : '完成雾化', - style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold), + // 提示文字 + Text( + isCross ? '💡 返回主页计时不会中断,到点将自动响铃与语音提醒' : '💡 返回主页后台持续计时,再次点击即可返回全屏', + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white38, fontSize: 11), + ), + const SizedBox(height: 10), + + // 下一步按钮 + Row( + children: [ + Expanded( + child: ElevatedButton( + onPressed: () => _sessionService.completeCurrentStep(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF2563EB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + elevation: 0, + ), + child: Text( + _sessionService.currentStepIndex + 1 < _sessionService.steps.length ? '下一步 / 提前进入下一阶段' : '完成雾化', + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold), + ), ), ), - ), - ], - ), - ], + ], + ), + ], + ), ), ), ), @@ -399,7 +237,7 @@ class _SessionScreenState extends State { label = '万托林 (舒张气道)'; } } else if (step.type == StepType.intraPuffWait) { - label = '同药两喷间隔'; + label = '同药两喷间隔 (30秒)'; } else if (step.type == StepType.crossDrugWait) { bg = Colors.amber.withValues(alpha: 0.2); fg = Colors.amberAccent; @@ -421,8 +259,8 @@ class _SessionScreenState extends State { } Widget _buildTimerDial(bool isCross) { - final progress = _totalStageSeconds > 0 - ? (_remainingSeconds / _totalStageSeconds).clamp(0.0, 1.0) + final progress = _sessionService.totalStageSeconds > 0 + ? (_sessionService.remainingSeconds / _sessionService.totalStageSeconds).clamp(0.0, 1.0) : 0.0; return Center( @@ -448,7 +286,7 @@ class _SessionScreenState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - _formatTime(_remainingSeconds), + _formatTime(_sessionService.remainingSeconds), style: const TextStyle( fontSize: 48, fontWeight: FontWeight.w900, @@ -477,7 +315,7 @@ class _SessionScreenState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ OutlinedButton.icon( - onPressed: () => _adjustCurrentTime(-delta), + onPressed: () => _sessionService.adjustCurrentTime(-delta), style: OutlinedButton.styleFrom( foregroundColor: Colors.white70, side: const BorderSide(color: Colors.white24), @@ -488,7 +326,7 @@ class _SessionScreenState extends State { ), const SizedBox(width: 16), OutlinedButton.icon( - onPressed: () => _adjustCurrentTime(delta), + onPressed: () => _sessionService.adjustCurrentTime(delta), style: OutlinedButton.styleFrom( foregroundColor: Colors.white70, side: const BorderSide(color: Colors.white24), @@ -501,11 +339,198 @@ class _SessionScreenState extends State { ); } + Widget _buildWaitingForNextMedView(SessionStep nextStep) { + final nextMed = nextStep.canister; + final nextName = nextMed?.name ?? '第二种药物'; + final shortName = nextName.split(' ')[0]; + final isSteroid = nextMed?.isSteroid ?? false; + + return PopScope( + canPop: true, + child: Scaffold( + backgroundColor: const Color(0xFF0F172A), + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + foregroundColor: Colors.white, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + tooltip: '返回主页', + onPressed: () => Navigator.of(context).pop(), + ), + title: const Text( + '两药间隔等待结束', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + actions: [ + TextButton( + onPressed: _confirmAbortSession, + child: const Text('放弃本次', style: TextStyle(color: Colors.redAccent, fontSize: 13)), + ), + ], + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + child: Column( + children: [ + // 状态标志 + Container( + width: 64, + height: 64, + decoration: BoxDecoration( + color: const Color(0xFF10B981).withValues(alpha: 0.15), + shape: BoxShape.circle, + border: Border.all(color: const Color(0xFF10B981), width: 2), + ), + child: const Icon(Icons.check, color: Color(0xFF10B981), size: 36), + ), + const SizedBox(height: 16), + const Text( + '两药间隔倒计时已结束', + style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 6), + const Text( + '气道已充分舒张吸收,已暂停等待手动开始', + style: TextStyle(color: Color(0xFF94A3B8), fontSize: 13), + ), + + const SizedBox(height: 24), + + // 第二组药物卡片 + Container( + width: double.infinity, + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF1E293B), + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: isSteroid ? const Color(0xFF059669) : const Color(0xFF2563EB), + width: 1.5, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: isSteroid + ? const Color(0xFF10B981).withValues(alpha: 0.2) + : const Color(0xFF2563EB).withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(10), + ), + child: Center( + child: Text( + isSteroid ? '辅' : '万', + style: TextStyle( + color: isSteroid ? const Color(0xFF34D399) : const Color(0xFF60A5FA), + fontWeight: FontWeight.bold, + fontSize: 18, + ), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '准备开始第二组用药', + style: TextStyle( + fontSize: 12, + color: isSteroid ? const Color(0xFF34D399) : const Color(0xFF60A5FA), + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 2), + Text( + nextName, + style: const TextStyle( + fontSize: 16, + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 14), + const Divider(color: Colors.white12, height: 1), + const SizedBox(height: 14), + Text( + '计划用药:${nextMed?.puffsPerSession ?? 1} 喷 • 单喷吸气时长 ${nextMed?.inhalationSeconds ?? 15} 秒', + style: const TextStyle(fontSize: 13, color: Color(0xFFCBD5E1), fontWeight: FontWeight.w600), + ), + const SizedBox(height: 12), + _buildCheckTip('1. 请取下前序药物,换上【$shortName】并充分摇匀'), + _buildCheckTip('2. 将储雾罐面罩紧贴口鼻,保持自然平静呼吸'), + _buildCheckTip('3. 一切就绪后,按压药瓶并点击下方按钮开始吸入'), + ], + ), + ), + + const Spacer(), + + // 手动开始第二组大按钮 + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: () => _sessionService.startNextMedication(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF2563EB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 18), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + elevation: 4, + ), + icon: const Icon(Icons.play_arrow_rounded, size: 26), + label: Text( + '开始吸入【$shortName】第 1 喷', + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _buildCheckTip(String text) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('• ', style: TextStyle(color: Color(0xFF38BDF8), fontSize: 13, fontWeight: FontWeight.bold)), + Expanded( + child: Text( + text, + style: const TextStyle(color: Color(0xFF94A3B8), fontSize: 12, height: 1.4), + ), + ), + ], + ), + ); + } + Widget _buildFinishedView() { - final duration = (_sessionEndTime ?? DateTime.now()).difference(_sessionStartTime); + final startTime = _sessionService.sessionStartTime ?? DateTime.now(); + final endTime = _sessionService.sessionEndTime ?? DateTime.now(); + final duration = endTime.difference(startTime); final minutes = duration.inMinutes; final seconds = duration.inSeconds % 60; - final hasSteroid = widget.activeMedications.any((m) => m.isSteroid); + final hasSteroid = _sessionService.activeMedications.any((m) => m.isSteroid); return Scaffold( backgroundColor: Colors.white, @@ -543,7 +568,7 @@ class _SessionScreenState extends State { const SizedBox(height: 24), - // 漱口洗脸 Checklist (当吸入了含激素药物如辅舒酮时显示) + // 漱口洗脸 Checklist if (hasSteroid) ...[ Container( padding: const EdgeInsets.all(16), @@ -568,17 +593,17 @@ class _SessionScreenState extends State { const SizedBox(height: 10), CheckboxListTile( contentPadding: EdgeInsets.zero, - value: _rinsedMouth, + value: _sessionService.rinsedMouth, activeColor: const Color(0xFF10B981), title: const Text('清水彻底漱口并吐出 (防鹅口疮/声音嘶哑)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)), - onChanged: (val) => setState(() => _rinsedMouth = val ?? true), + onChanged: (val) => _sessionService.rinsedMouth = val ?? true, ), CheckboxListTile( contentPadding: EdgeInsets.zero, - value: _washedFace, + value: _sessionService.washedFace, activeColor: const Color(0xFF10B981), title: const Text('温水擦洗面部口鼻区域 (防皮炎)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)), - onChanged: (val) => setState(() => _washedFace = val ?? true), + onChanged: (val) => _sessionService.washedFace = val ?? true, ), ], ), @@ -595,7 +620,7 @@ class _SessionScreenState extends State { border: Border.all(color: const Color(0xFFE2E8F0)), ), child: Column( - children: widget.activeMedications.map((m) { + children: _sessionService.activeMedications.map((m) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( @@ -631,186 +656,4 @@ class _SessionScreenState extends State { ), ); } - - Widget _buildWaitingForNextMedView(SessionStep nextStep) { - final nextMed = nextStep.canister; - final nextName = nextMed?.name ?? '第二种药物'; - final shortName = nextName.split(' ')[0]; - final isSteroid = nextMed?.isSteroid ?? false; - - return Scaffold( - backgroundColor: const Color(0xFF0F172A), - appBar: AppBar( - backgroundColor: Colors.transparent, - elevation: 0, - foregroundColor: Colors.white, - title: const Text( - '两药间隔等待结束', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('退出', style: TextStyle(color: Colors.white70)), - ), - ], - ), - body: SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), - child: Column( - children: [ - // 状态标志 - Container( - width: 64, - height: 64, - decoration: BoxDecoration( - color: const Color(0xFF10B981).withValues(alpha: 0.15), - shape: BoxShape.circle, - border: Border.all(color: const Color(0xFF10B981), width: 2), - ), - child: const Icon(Icons.check, color: Color(0xFF10B981), size: 36), - ), - const SizedBox(height: 16), - const Text( - '两药间隔倒计时已结束', - style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), - ), - const SizedBox(height: 6), - const Text( - '气道已充分舒张吸收,已暂停等待手动开始', - style: TextStyle(color: Color(0xFF94A3B8), fontSize: 13), - ), - - const SizedBox(height: 24), - - // 第二组药物卡片 - Container( - width: double.infinity, - padding: const EdgeInsets.all(18), - decoration: BoxDecoration( - color: const Color(0xFF1E293B), - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: isSteroid ? const Color(0xFF059669) : const Color(0xFF2563EB), - width: 1.5, - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: isSteroid - ? const Color(0xFF10B981).withValues(alpha: 0.2) - : const Color(0xFF2563EB).withValues(alpha: 0.2), - borderRadius: BorderRadius.circular(10), - ), - child: Center( - child: Text( - isSteroid ? '辅' : '万', - style: TextStyle( - color: isSteroid ? const Color(0xFF34D399) : const Color(0xFF60A5FA), - fontWeight: FontWeight.bold, - fontSize: 18, - ), - ), - ), - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '准备开始第二组用药', - style: TextStyle( - fontSize: 12, - color: isSteroid ? const Color(0xFF34D399) : const Color(0xFF60A5FA), - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 2), - Text( - nextName, - style: const TextStyle( - fontSize: 16, - color: Colors.white, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - ), - ], - ), - const SizedBox(height: 14), - const Divider(color: Colors.white12, height: 1), - const SizedBox(height: 14), - Text( - '计划用药:${nextMed?.puffsPerSession ?? 1} 喷 • 单喷吸气时长 ${nextMed?.inhalationSeconds ?? 15} 秒', - style: const TextStyle(fontSize: 13, color: Color(0xFFCBD5E1), fontWeight: FontWeight.w600), - ), - const SizedBox(height: 12), - _buildCheckTip('1. 请取下前序药物,换上【$shortName】并充分摇匀'), - _buildCheckTip('2. 将储雾罐面罩紧贴口鼻,保持自然平静呼吸'), - _buildCheckTip('3. 一切就绪后,按压药瓶并点击下方按钮开始吸入'), - ], - ), - ), - - const Spacer(), - - // 手动开始第二组大按钮 - SizedBox( - width: double.infinity, - child: ElevatedButton.icon( - onPressed: () { - setState(() { - _isWaitingForNextMed = false; - }); - _startStep(_currentStepIndex + 1); - }, - style: ElevatedButton.styleFrom( - backgroundColor: const Color(0xFF2563EB), - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 18), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - elevation: 4, - ), - icon: const Icon(Icons.play_arrow_rounded, size: 26), - label: Text( - '开始吸入【$shortName】第 1 喷', - style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - ), - ), - ), - ], - ), - ), - ), - ); - } - - Widget _buildCheckTip(String text) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 3), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text('• ', style: TextStyle(color: Color(0xFF38BDF8), fontSize: 13, fontWeight: FontWeight.bold)), - Expanded( - child: Text( - text, - style: const TextStyle(color: Color(0xFF94A3B8), fontSize: 12, height: 1.4), - ), - ), - ], - ), - ); - } } diff --git a/lib/services/active_session_service.dart b/lib/services/active_session_service.dart new file mode 100644 index 0000000..5ff30a8 --- /dev/null +++ b/lib/services/active_session_service.dart @@ -0,0 +1,331 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:uuid/uuid.dart'; +import '../models/canister.dart'; +import '../models/app_settings.dart'; +import '../models/dose_record.dart'; +import 'storage_service.dart'; +import 'tts_service.dart'; +import 'audio_service.dart'; + +enum StepType { + inhale, // 正在吸入某药某喷 + intraPuffWait, // 同药两喷之间等待 (30s) + crossDrugWait, // 两药之间等待 (默认 5min,可调) +} + +class SessionStep { + final StepType type; + final Canister? canister; + final int puffIndex; + final int totalPuffs; + int durationSeconds; + final String title; + final String subtitle; + + SessionStep({ + required this.type, + this.canister, + this.puffIndex = 1, + this.totalPuffs = 1, + required this.durationSeconds, + required this.title, + required this.subtitle, + }); +} + +class ActiveSessionService extends ChangeNotifier { + static final ActiveSessionService _instance = ActiveSessionService._internal(); + factory ActiveSessionService() => _instance; + ActiveSessionService._internal(); + + bool _isActive = false; + bool _isFinished = false; + bool _isWaitingForNextMed = false; + + List _activeMedications = []; + final List _steps = []; + int _currentStepIndex = 0; + + DateTime? _sessionStartTime; + DateTime? _sessionEndTime; + + Timer? _timer; + int _remainingSeconds = 0; + int _totalStageSeconds = 0; + + bool _rinsedMouth = true; + bool _washedFace = true; + + AppSettings? _settings; + + // Getters + bool get isActive => _isActive; + bool get isFinished => _isFinished; + bool get isWaitingForNextMed => _isWaitingForNextMed; + List get activeMedications => _activeMedications; + List get steps => _steps; + int get currentStepIndex => _currentStepIndex; + DateTime? get sessionStartTime => _sessionStartTime; + DateTime? get sessionEndTime => _sessionEndTime; + int get remainingSeconds => _remainingSeconds; + int get totalStageSeconds => _totalStageSeconds; + bool get rinsedMouth => _rinsedMouth; + bool get washedFace => _washedFace; + + set rinsedMouth(bool val) { + _rinsedMouth = val; + notifyListeners(); + } + + set washedFace(bool val) { + _washedFace = val; + notifyListeners(); + } + + SessionStep? get currentStep => + (_currentStepIndex >= 0 && _currentStepIndex < _steps.length) ? _steps[_currentStepIndex] : null; + + SessionStep? get nextStep => + (_currentStepIndex + 1 < _steps.length) ? _steps[_currentStepIndex + 1] : null; + + void startNewSession({ + required List medications, + required AppSettings settings, + }) { + // 强制临床顺序:万托林 (支气管舒张剂,非激素) 严格排在第一位,辅舒酮 (激素) 排在第二位 + final sortedMeds = List.from(medications); + sortedMeds.sort((a, b) { + if (!a.isSteroid && b.isSteroid) return -1; + if (a.isSteroid && !b.isSteroid) return 1; + return a.sortOrder.compareTo(b.sortOrder); + }); + + _activeMedications = sortedMeds; + _settings = settings; + _sessionStartTime = DateTime.now(); + _sessionEndTime = null; + _isFinished = false; + _isWaitingForNextMed = false; + _rinsedMouth = true; + _washedFace = true; + + _buildStepsPipeline(); + + _isActive = true; + if (_steps.isNotEmpty) { + _startStep(0); + } + notifyListeners(); + } + + void _buildStepsPipeline() { + _steps.clear(); + final settings = _settings ?? AppSettings(); + + for (int i = 0; i < _activeMedications.length; i++) { + final med = _activeMedications[i]; + + for (int p = 1; p <= med.puffsPerSession; p++) { + _steps.add( + SessionStep( + type: StepType.inhale, + canister: med, + puffIndex: p, + totalPuffs: med.puffsPerSession, + durationSeconds: med.inhalationSeconds, + title: '吸入 ${med.name}', + subtitle: '第 $p / ${med.puffsPerSession} 喷 • 面罩紧贴口鼻,平稳深呼吸', + ), + ); + + if (p < med.puffsPerSession) { + _steps.add( + SessionStep( + type: StepType.intraPuffWait, + canister: med, + puffIndex: p, + totalPuffs: med.puffsPerSession, + durationSeconds: settings.intraPuffIntervalSeconds, + title: '${med.name} 连喷间隔', + subtitle: '请间隔 30 秒使药雾沉降并重新摇匀,切勿连喷', + ), + ); + } + } + + if (i < _activeMedications.length - 1) { + final nextMed = _activeMedications[i + 1]; + _steps.add( + SessionStep( + type: StepType.crossDrugWait, + canister: med, + durationSeconds: settings.crossDrugIntervalSeconds, + title: '两药间隔等待 (建议 5 分钟)', + subtitle: '${med.name} 舒张气道中,到点后将提示吸入 ${nextMed.name}', + ), + ); + } + } + } + + void _startStep(int index) { + if (index >= _steps.length) { + _finishSession(); + return; + } + + final step = _steps[index]; + _timer?.cancel(); + + _currentStepIndex = index; + _remainingSeconds = step.durationSeconds; + _totalStageSeconds = step.durationSeconds; + _isWaitingForNextMed = false; + + _speakStep(step); + notifyListeners(); + + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (_remainingSeconds > 1) { + _remainingSeconds--; + notifyListeners(); + } else { + timer.cancel(); + _onStepCompleted(); + } + }); + } + + void completeCurrentStep() { + _onStepCompleted(); + } + + void startNextMedication() { + _isWaitingForNextMed = false; + _startStep(_currentStepIndex + 1); + } + + void adjustCurrentTime(int deltaSeconds) { + _remainingSeconds = (_remainingSeconds + deltaSeconds).clamp(1, 1800); + if (_currentStepIndex < _steps.length) { + _steps[_currentStepIndex].durationSeconds = _remainingSeconds; + } + notifyListeners(); + } + + void _onStepCompleted() { + _triggerFeedback(); + + if (_currentStepIndex < _steps.length) { + final currentStep = _steps[_currentStepIndex]; + // 如果当前是两药间隔等待,到点后提醒用户,并等待手动点击确认后再开始第二种药物 + if (currentStep.type == StepType.crossDrugWait && _currentStepIndex + 1 < _steps.length) { + _timer?.cancel(); + if (_settings?.enableSound ?? true) { + AudioService().playSessionComplete(); + } + final nextMed = _steps[_currentStepIndex + 1].canister; + final nextName = nextMed?.name.split(' ')[0] ?? '第二组药物'; + if (_settings?.enableVoicePrompt ?? true) { + TtsService().speak('两药间隔等待已结束!气道已充分舒张。请换上$nextName,戴好面罩后点击屏幕开始吸入。'); + } + _isWaitingForNextMed = true; + notifyListeners(); + return; + } + } + + if (_currentStepIndex + 1 < _steps.length) { + _startStep(_currentStepIndex + 1); + } else { + _finishSession(); + } + } + + void _finishSession() { + _timer?.cancel(); + _sessionEndTime = DateTime.now(); + _isFinished = true; + _currentStepIndex = _steps.length; + + _triggerFeedback(isFinished: true); + if (_settings?.enableVoicePrompt ?? true) { + Future.delayed(const Duration(milliseconds: 1000), () { + TtsService().speak('本次雾化吸入已全部完成,请及时用清水漱口并洗脸!'); + }); + } + notifyListeners(); + } + + void _triggerFeedback({bool isFinished = false}) { + final settings = _settings ?? AppSettings(); + if (settings.enableVibration) { + HapticFeedback.heavyImpact(); + } + if (settings.enableSound) { + if (isFinished) { + AudioService().playSessionComplete(); + } else { + AudioService().playStepComplete(); + } + } + } + + void _speakStep(SessionStep step) { + if (!(_settings?.enableVoicePrompt ?? true)) return; + if (step.type == StepType.inhale) { + final medName = step.canister?.name.split(" ")[0] ?? '药物'; + TtsService().speak('请吸入$medName第${step.puffIndex}喷,口鼻密闭,慢而深地吸气。'); + } else if (step.type == StepType.intraPuffWait) { + TtsService().speak('第${step.puffIndex}喷吸入完成,请等待三十秒后吸入下一喷。'); + } else if (step.type == StepType.crossDrugWait) { + final minutes = step.durationSeconds ~/ 60; + TtsService().speak('两药间隔开始,请等待$minutes分钟,待气道充分扩张。'); + } + } + + // 完全放弃/取消本次雾化 + void cancelSession() { + _timer?.cancel(); + _isActive = false; + _isFinished = false; + _isWaitingForNextMed = false; + _steps.clear(); + _currentStepIndex = 0; + TtsService().stop(); + notifyListeners(); + } + + // 结算并保存记录 + Future confirmAndSave(StorageService storageService) async { + final Map deductions = {}; + int totalFlixotide = 0; + int totalVentolin = 0; + + for (var med in _activeMedications) { + deductions[med.id] = med.puffsPerSession; + if (med.isSteroid) { + totalFlixotide += med.puffsPerSession; + } else { + totalVentolin += med.puffsPerSession; + } + } + + final record = DoseRecord( + id: const Uuid().v4(), + startTime: _sessionStartTime ?? DateTime.now(), + endTime: _sessionEndTime ?? DateTime.now(), + flixotidePuffs: totalFlixotide, + ventolinPuffs: totalVentolin, + rinsedMouth: _rinsedMouth, + washedFace: _washedFace, + ); + + await storageService.addRecord(record); + await storageService.deductSessionDoses(deductions); + + cancelSession(); + } +} diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 750b6ff..8dd3922 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -74,12 +74,23 @@ class StorageService { final raw = _prefs.getStringList(_keyCanisters); if (raw == null) return []; final list = raw.map((item) => Canister.fromJson(item)).toList(); - list.sort((a, b) => a.sortOrder.compareTo(b.sortOrder)); + // 严格遵循临床联合雾化顺序:万托林 (支气管舒张剂,非激素) 必须优先于辅舒酮 (糖皮质激素) + 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() { - return getCanisters().where((c) => c.isEnabled).toList(); + 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 { diff --git a/test/widget_test.dart b/test/widget_test.dart index e4082f2..2fb50e6 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -43,4 +43,36 @@ void main() { expect(find.text('42'), findsOneWidget); expect(find.text('/ 60 喷剩余'), findsOneWidget); }); + + test('Clinical ordering: Ventolin must always precede Flixotide', () { + final flixotide = Canister( + id: 'flixotide', + name: '辅舒酮', + totalDoses: 60, + remainingDoses: 60, + openedAt: DateTime.now(), + isSteroid: true, + sortOrder: 2, + ); + final ventolin = Canister( + id: 'ventolin', + name: '万托林', + totalDoses: 200, + remainingDoses: 200, + openedAt: DateTime.now(), + isSteroid: false, + sortOrder: 1, + ); + + // Even if inserted in reverse order [Flixotide, Ventolin] + final list = [flixotide, ventolin]; + list.sort((a, b) { + if (!a.isSteroid && b.isSteroid) return -1; + if (a.isSteroid && !b.isSteroid) return 1; + return a.sortOrder.compareTo(b.sortOrder); + }); + + expect(list.first.name, '万托林'); + expect(list.last.name, '辅舒酮'); + }); }