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'; 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, }); } class SessionScreen extends StatefulWidget { final StorageService storageService; final List activeMedications; const SessionScreen({ super.key, required this.storageService, required this.activeMedications, }); @override State createState() => _SessionScreenState(); } 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; @override void initState() { super.initState(); _settings = widget.storageService.getSettings(); _sessionStartTime = DateTime.now(); _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}', ), ); } } } @override void dispose() { _timer?.cancel(); TtsService().stop(); super.dispose(); } void _triggerFeedback() { if (_settings.enableVibration) { HapticFeedback.heavyImpact(); } if (_settings.enableSound) { SystemSound.play(SystemSoundType.alert); } } 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; }); _timer = Timer.periodic(const Duration(seconds: 1), (timer) { if (_remainingSeconds > 1) { setState(() { _remainingSeconds--; }); } else { timer.cancel(); _onStepCompleted(); } }); } void _onStepCompleted() { _triggerFeedback(); if (_currentStepIndex + 1 < _steps.length) { final nextStep = _steps[_currentStepIndex + 1]; if (_settings.enableVoicePrompt) { if (nextStep.type == StepType.crossDrugWait) { TtsService().speak('两药间隔开始,请等待五分钟'); } else if (nextStep.type == StepType.inhale) { final medName = nextStep.canister?.name.split(" ")[0] ?? '药物'; TtsService().speak('请吸入$medName第${nextStep.puffIndex}喷'); } else if (nextStep.type == StepType.intraPuffWait) { TtsService().speak('请等待三十秒后喷第二喷'); } } _startStep(_currentStepIndex + 1); } else { _finishSession(); } } void _finishSession() { _timer?.cancel(); _sessionEndTime = DateTime.now(); _triggerFeedback(); if (_settings.enableVoicePrompt) { 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(); if (mounted) { Navigator.of(context).pop(true); } } String _formatTime(int totalSeconds) { final m = (totalSeconds ~/ 60).toString().padLeft(2, '0'); final s = (totalSeconds % 60).toString().padLeft(2, '0'); return '$m:$s'; } @override Widget build(BuildContext context) { if (_currentStepIndex >= _steps.length) { 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( 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), const SizedBox(height: 24), 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(), // 倒计时核心大表盘 _buildTimerDial(isCross), const SizedBox(height: 16), // 动态调节时间微调器 _buildTimeAdjustControls(isCross), 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), ), ), ), ], ), ], ), ), ), ); } Widget _buildStepBadge(SessionStep step) { Color bg = Colors.blue.withValues(alpha: 0.2); Color fg = Colors.blueAccent; String label = ''; if (step.type == StepType.inhale) { if (step.canister?.isSteroid ?? false) { bg = const Color(0xFF10B981).withValues(alpha: 0.2); fg = const Color(0xFF34D399); label = '辅舒酮 (激素吸入)'; } else { bg = Colors.cyan.withValues(alpha: 0.2); fg = Colors.cyanAccent; label = '万托林 (舒张气道)'; } } else if (step.type == StepType.intraPuffWait) { label = '同药两喷间隔'; } else if (step.type == StepType.crossDrugWait) { bg = Colors.amber.withValues(alpha: 0.2); fg = Colors.amberAccent; label = '⭐ 多药物间隔中 (后台提醒已就绪)'; } return Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), decoration: BoxDecoration( color: bg, borderRadius: BorderRadius.circular(20), border: Border.all(color: fg.withValues(alpha: 0.3)), ), child: Text( label, style: TextStyle(color: fg, fontSize: 12, fontWeight: FontWeight.bold), ), ); } Widget _buildTimerDial(bool isCross) { final progress = _totalStageSeconds > 0 ? (_remainingSeconds / _totalStageSeconds).clamp(0.0, 1.0) : 0.0; return Center( child: SizedBox( width: 220, height: 220, child: Stack( alignment: Alignment.center, children: [ SizedBox( width: 220, height: 220, child: CircularProgressIndicator( value: progress, strokeWidth: 8, backgroundColor: Colors.white10, valueColor: AlwaysStoppedAnimation( isCross ? Colors.amberAccent : const Color(0xFF38BDF8), ), ), ), Column( mainAxisSize: MainAxisSize.min, children: [ Text( _formatTime(_remainingSeconds), style: const TextStyle( fontSize: 48, fontWeight: FontWeight.w900, fontFamily: 'monospace', color: Colors.white, letterSpacing: -1, ), ), Text( isCross ? '两药间隔到点提示' : '吸入倒计时', style: const TextStyle(color: Colors.white38, fontSize: 12), ), ], ), ], ), ), ); } Widget _buildTimeAdjustControls(bool isCross) { final delta = isCross ? 60 : 5; final unitText = isCross ? '1分钟' : '5秒'; return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ OutlinedButton.icon( onPressed: () => _adjustCurrentTime(-delta), style: OutlinedButton.styleFrom( foregroundColor: Colors.white70, side: const BorderSide(color: Colors.white24), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), icon: const Icon(Icons.remove, size: 16), label: Text('-$unitText'), ), const SizedBox(width: 16), OutlinedButton.icon( onPressed: () => _adjustCurrentTime(delta), style: OutlinedButton.styleFrom( foregroundColor: Colors.white70, side: const BorderSide(color: Colors.white24), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), icon: const Icon(Icons.add, size: 16), label: Text('+$unitText'), ), ], ); } Widget _buildFinishedView() { final duration = (_sessionEndTime ?? DateTime.now()).difference(_sessionStartTime); final minutes = duration.inMinutes; final seconds = duration.inSeconds % 60; final hasSteroid = widget.activeMedications.any((m) => m.isSteroid); return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: const Text('用药完成提醒', style: TextStyle(fontWeight: FontWeight.bold)), automaticallyImplyLeading: false, backgroundColor: Colors.white, elevation: 0, ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 10), Container( width: 72, height: 72, decoration: const BoxDecoration( color: Color(0xFFD1FAE5), shape: BoxShape.circle, ), child: const Icon(Icons.check, color: Color(0xFF059669), size: 40), ), const SizedBox(height: 16), const Text( '本次用药方案已完成!', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), const SizedBox(height: 4), Text( '总耗时 $minutes 分 $seconds 秒', style: const TextStyle(color: Colors.grey, fontSize: 13), ), const SizedBox(height: 24), // 漱口洗脸 Checklist (当吸入了含激素药物如辅舒酮时显示) if (hasSteroid) ...[ Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: const Color(0xFFFFF1F2), borderRadius: BorderRadius.circular(16), border: Border.all(color: const Color(0xFFFECDD3)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Row( children: [ Icon(Icons.warning_amber_rounded, color: Color(0xFFE11D48), size: 18), SizedBox(width: 6), Text( '必须完成的收尾工作 (防激素副作用)', style: TextStyle(color: Color(0xFFBE123C), fontWeight: FontWeight.bold, fontSize: 13), ), ], ), const SizedBox(height: 10), CheckboxListTile( contentPadding: EdgeInsets.zero, value: _rinsedMouth, activeColor: const Color(0xFF10B981), title: const Text('清水彻底漱口并吐出 (防鹅口疮/声音嘶哑)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)), onChanged: (val) => setState(() => _rinsedMouth = val ?? true), ), CheckboxListTile( contentPadding: EdgeInsets.zero, value: _washedFace, activeColor: const Color(0xFF10B981), title: const Text('温水擦洗面部口鼻区域 (防皮炎)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)), onChanged: (val) => setState(() => _washedFace = val ?? true), ), ], ), ), const SizedBox(height: 16), ], // 扣减清单 Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( color: const Color(0xFFF8FAFC), borderRadius: BorderRadius.circular(14), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: Column( children: widget.activeMedications.map((m) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(m.name, style: const TextStyle(fontSize: 13, color: Color(0xFF334155))), Text('扣除 ${m.puffsPerSession} 喷', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Color(0xFF0F172A))), ], ), ); }).toList(), ), ), const Spacer(), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: _saveAndExit, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF0F172A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), ), child: const Text('确认并保存记录', style: TextStyle(fontWeight: FontWeight.bold)), ), ), ], ), ), ), ); } }