import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:uuid/uuid.dart'; import '../models/canister.dart'; import '../models/dose_record.dart'; import '../models/app_settings.dart'; import '../services/storage_service.dart'; import '../models/medicine_item.dart'; import 'session_screen.dart'; import 'history_screen.dart'; import 'settings_screen.dart'; import 'plan_config_screen.dart'; import 'lan_sync_screen.dart'; import 'medicine_cabinet_screen.dart'; import '../services/sync_service.dart'; import '../services/active_session_service.dart'; class HomeScreen extends StatefulWidget { final StorageService storageService; final VoidCallback? onNavigateToCabinet; const HomeScreen({ super.key, required this.storageService, this.onNavigateToCabinet, }); @override State createState() => _HomeScreenState(); } class _HomeScreenState extends State { late Canister _flixotide; late Canister _ventolin; late List _activeCanisters; late AppSettings _settings; DoseRecord? _lastRecord; List _todayRecords = []; final ActiveSessionService _sessionService = ActiveSessionService(); @override void initState() { super.initState(); _sessionService.addListener(_onSessionUpdate); _loadData(); // 局域网静默尝试同步拉取最新状态 SyncService(widget.storageService).syncSilently().then((_) { if (mounted) _loadData(); }); } @override void dispose() { _sessionService.removeListener(_onSessionUpdate); super.dispose(); } void _onSessionUpdate() { if (mounted) setState(() {}); } void _loadData() { setState(() { _flixotide = widget.storageService.getPrimaryFlixotide()!; _ventolin = widget.storageService.getPrimaryVentolin()!; _activeCanisters = widget.storageService.getActiveCanisters(); _settings = widget.storageService.getSettings(); // 排除试喷扣除记录,只统计真实雾化 final records = widget.storageService.getRecords().where((r) => !r.isPrime).toList(); _lastRecord = records.isNotEmpty ? records.first : null; final now = DateTime.now(); _todayRecords = records.where((r) { final t = r.startTime.toLocal(); return t.year == now.year && t.month == now.month && t.day == now.day; }).toList() ..sort((a, b) => a.startTime.compareTo(b.startTime)); }); } /// 早/晚时段分界点(当天分钟数):取早间与晚间提醒时间的中点 int get _sessionSplitMinute { final m = _settings.morningReminderHour * 60 + _settings.morningReminderMinute; final e = _settings.eveningReminderHour * 60 + _settings.eveningReminderMinute; return e > m ? (m + e) ~/ 2 : 12 * 60; } bool _isMorningRecord(DoseRecord r) { final t = r.startTime.toLocal(); return t.hour * 60 + t.minute < _sessionSplitMinute; } String _recordDetail(DoseRecord r) { final parts = [ if (r.ventolinPuffs > 0) '万托林 ${r.ventolinPuffs}喷', if (r.flixotidePuffs > 0) '辅舒酮 ${r.flixotidePuffs}喷', ]; return parts.isEmpty ? '无喷数' : parts.join(' + '); } void _showTodayRecordsSheet() { showModalBottomSheet( context: context, backgroundColor: Colors.white, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))), builder: (ctx) => SafeArea( child: Padding( padding: const EdgeInsets.fromLTRB(20, 16, 20, 20), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '今日雾化明细(共 ${_todayRecords.length} 次)', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF0F172A)), ), const SizedBox(height: 12), if (_todayRecords.isEmpty) const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Text('今天还没有雾化记录', style: TextStyle(color: Colors.grey, fontSize: 13)), ) else ..._todayRecords.map((r) => Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: Row( children: [ const Icon(Icons.check_circle, color: Color(0xFF10B981), size: 18), const SizedBox(width: 10), Text( DateFormat('HH:mm').format(r.startTime.toLocal()), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Color(0xFF0F172A)), ), const SizedBox(width: 8), Text( _isMorningRecord(r) ? '早间' : '晚间', style: const TextStyle(fontSize: 12, color: Color(0xFF64748B)), ), const SizedBox(width: 12), Expanded( child: Text( _recordDetail(r), style: const TextStyle(fontSize: 13, color: Color(0xFF334155)), overflow: TextOverflow.ellipsis, ), ), ], ), )), ], ), ), ), ); } Future _openPlanConfig() async { final result = await Navigator.of(context).push( MaterialPageRoute( builder: (_) => PlanConfigScreen(storageService: widget.storageService), ), ); if (result == true) { _loadData(); } } 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 && !_sessionService.isActive) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('请先在方案配置中至少勾选一种使用的药物!')), ); _openPlanConfig(); return; } final result = await Navigator.of(context).push( MaterialPageRoute( builder: (_) => SessionScreen( storageService: widget.storageService, activeMedications: _activeCanisters, ), ), ); if (result == true) { _loadData(); SyncService(widget.storageService).syncSilently(); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('已成功记录本次吸入时间并扣减对应喷数!'), backgroundColor: Color(0xFF10B981), ), ); } } else { _loadData(); } } Future _quickDeduct() async { final confirmed = await showDialog( context: context, builder: (ctx) => AlertDialog( title: const Text('极速打卡'), content: Text( _activeCanisters.isEmpty ? '当前未启用任何药物,请先配置方案' : '确认直接按照当前方案打卡扣除相应喷数吗?\n${_activeCanisters.map((c) => "${c.name}: ${c.puffsPerSession}喷").join("\n")}', ), actions: [ TextButton( onPressed: () => Navigator.pop(ctx, false), child: const Text('取消'), ), ElevatedButton( onPressed: () => Navigator.pop(ctx, true), child: const Text('确认打卡'), ), ], ), ); if (confirmed == true && _activeCanisters.isNotEmpty) { final Map deductions = {}; int flixotideDoses = 0; int ventolinDoses = 0; for (var c in _activeCanisters) { deductions[c.id] = c.puffsPerSession; if (c.isSteroid) { flixotideDoses += c.puffsPerSession; } else { ventolinDoses += c.puffsPerSession; } } final nowUtc = DateTime.now().toUtc(); final activeFlix = widget.storageService.getActiveFlixotideBottle(); final activeVent = widget.storageService.getActiveVentolinBottle(); final record = DoseRecord( id: const Uuid().v4(), startTime: nowUtc, endTime: nowUtc, flixotidePuffs: flixotideDoses, ventolinPuffs: ventolinDoses, flixotideBottleId: flixotideDoses > 0 ? activeFlix?.id : null, ventolinBottleId: ventolinDoses > 0 ? activeVent?.id : null, updatedAt: nowUtc, ); await widget.storageService.deductSessionDoses(deductions); await widget.storageService.addRecord(record); _loadData(); SyncService(widget.storageService).syncSilently(); } } Future _logPrimePuff(Canister canister) async { final confirmed = await showDialog( context: context, builder: (ctx) => AlertDialog( title: Text('扣除试喷 (Prime) - ${canister.name.split(" ")[0]}'), content: Text('新开封药瓶或久置后向空中试喷,扣除【${canister.name}】1 喷?'), actions: [ TextButton( onPressed: () => Navigator.pop(ctx, false), child: const Text('取消'), ), ElevatedButton( onPressed: () => Navigator.pop(ctx, true), child: const Text('扣减 1 喷'), ), ], ), ); if (confirmed == true) { final nowUtc = DateTime.now().toUtc(); final activeBottle = widget.storageService.getActiveBottle(canister.id); final record = DoseRecord( id: const Uuid().v4(), startTime: nowUtc, endTime: nowUtc, flixotidePuffs: canister.isSteroid ? 1 : 0, ventolinPuffs: canister.isSteroid ? 0 : 1, flixotideBottleId: canister.isSteroid ? activeBottle?.id : null, ventolinBottleId: !canister.isSteroid ? activeBottle?.id : null, isPrime: true, note: '${canister.name.split(" ")[0]}试喷', updatedAt: nowUtc, ); await widget.storageService.deductSessionDoses({canister.id: 1}); await widget.storageService.addRecord(record); _loadData(); SyncService(widget.storageService).syncSilently(); } } Future _resetCanister(Canister canister) async { final activeBottle = widget.storageService.getActiveBottle(canister.id); final currentSeq = activeBottle?.sequenceNumber ?? 1; final nextSeq = currentSeq + 1; final confirmed = await showDialog( context: context, builder: (ctx) => AlertDialog( title: Text('换新药瓶 - ${canister.name.split(" ")[0]}'), content: Text('当前正在使用第 $currentSeq 瓶。\n确认拆封启用【第 $nextSeq 瓶】,并将剩余次数重置为满瓶 (${canister.totalDoses} 喷) 吗?'), actions: [ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), ElevatedButton( onPressed: () => Navigator.pop(ctx, true), child: Text('确认启用第 $nextSeq 瓶'), ), ], ), ); if (confirmed == true) { final deviceName = await SyncService.getDeviceName(); final newBottle = await widget.storageService.openNewBottle(canister.id, deviceName: deviceName); _loadData(); SyncService(widget.storageService).syncSilently(); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('已成功启用第 ${newBottle.sequenceNumber} 瓶【${canister.name.split(" ")[0]}】,剩余次数已更新为满瓶!'), backgroundColor: const Color(0xFF10B981), ), ); } } } String _formatLastTime(DateTime dt) { final now = DateTime.now(); final isToday = now.year == dt.year && now.month == dt.month && now.day == dt.day; final timeStr = DateFormat('HH:mm').format(dt); if (isToday) { return '今天 $timeStr'; } return DateFormat('MM-dd HH:mm').format(dt); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF8FAFC), appBar: AppBar( backgroundColor: Colors.white, elevation: 0, centerTitle: false, titleSpacing: 16, title: const Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.air, color: Color(0xFF2563EB), size: 24), SizedBox(width: 8), Text( '舒雾记', style: TextStyle( color: Color(0xFF0F172A), fontWeight: FontWeight.bold, fontSize: 18, ), ), ], ), actions: [ IconButton( icon: const Icon(Icons.sync, color: Color(0xFF2563EB)), tooltip: '局域网同步', visualDensity: VisualDensity.compact, onPressed: () async { await Navigator.of(context).push( MaterialPageRoute( builder: (_) => LanSyncScreen(storageService: widget.storageService), ), ); _loadData(); }, ), IconButton( icon: const Icon(Icons.history, color: Color(0xFF475569)), tooltip: '历史记录', visualDensity: VisualDensity.compact, onPressed: () async { await Navigator.of(context).push( MaterialPageRoute( builder: (_) => HistoryScreen(storageService: widget.storageService), ), ); _loadData(); }, ), IconButton( icon: const Icon(Icons.settings_outlined, color: Color(0xFF475569)), tooltip: '系统设置', visualDensity: VisualDensity.compact, onPressed: () async { await Navigator.of(context).push( MaterialPageRoute( builder: (_) => SettingsScreen(storageService: widget.storageService), ), ); _loadData(); }, ), const SizedBox(width: 8), ], ), body: SingleChildScrollView( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // 模块 0:若有后台进行中的雾化,展示醒目实时卡片 (返回主页不中断计时) if (_sessionService.isActive) ...[ _buildActiveSessionBanner(), const SizedBox(height: 16), ], // 模块 1:定时提醒状态条 _buildReminderBar(), const SizedBox(height: 16), // 模块 2:核心行动区 —— 今日用药方案执行卡 (消除只吸辅舒酮的误解) _buildActionPlanHeroCard(), const SizedBox(height: 24), // 模块 3:药品余量与剩余次数监控区 (重点展示辅舒酮剩余 60 喷) _buildMedicationDosesSection(), const SizedBox(height: 20), // 模块 3.5:家庭智能药箱看板入口 _buildFamilyMedicineCabinetCard(), const SizedBox(height: 20), // 模块 4:最近吸入记录底栏 _buildLastRecordFooter(), ], ), ), ); } // 3.5 家庭智能药箱入口卡片 Widget _buildFamilyMedicineCabinetCard() { final medicines = widget.storageService.getMedicines(); final dangerCount = medicines.where((m) => m.healthStatus == MedicineHealthStatus.overdueInUse || m.healthStatus == MedicineHealthStatus.expired).length; final soonCount = medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length; Color badgeBg = const Color(0xFFEFF6FF); Color badgeColor = const Color(0xFF2563EB); String badgeText = '${medicines.length} 种在库'; if (dangerCount > 0) { badgeBg = const Color(0xFFFEF2F2); badgeColor = const Color(0xFFEF4444); badgeText = '⚠️ $dangerCount 种已超期/过期'; } else if (soonCount > 0) { badgeBg = const Color(0xFFFEF3C7); badgeColor = const Color(0xFFD97706); badgeText = '🟡 $soonCount 种即将到期'; } return Card( elevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide(color: dangerCount > 0 ? Colors.red.shade300 : const Color(0xFFE2E8F0)), ), child: InkWell( onTap: () async { if (widget.onNavigateToCabinet != null) { widget.onNavigateToCabinet!(); return; } await Navigator.of(context).push( MaterialPageRoute( builder: (_) => MedicineCabinetScreen( storageService: widget.storageService, syncService: SyncService(widget.storageService), ), ), ); _loadData(); }, borderRadius: BorderRadius.circular(16), child: Padding( padding: const EdgeInsets.all(16), child: Row( children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: const Color(0xFFECFDF5), borderRadius: BorderRadius.circular(12), ), child: const Icon( Icons.medical_services_outlined, color: Color(0xFF059669), size: 24, ), ), const SizedBox(width: 14), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ const Text( '家庭智能药箱', style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold, color: Color(0xFF0F172A), ), ), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: badgeBg, borderRadius: BorderRadius.circular(6), ), child: Text( badgeText, style: TextStyle( color: badgeColor, fontSize: 11, fontWeight: FontWeight.bold, ), ), ), ], ), const SizedBox(height: 3), const Text( '出厂有效期与开封保质期智能监控 · 扫码即识', style: TextStyle(fontSize: 12, color: Colors.black54), ), ], ), ), const Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey), ], ), ), ), ); } // 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')}'; final eTime = '${_settings.eveningReminderHour.toString().padLeft(2, '0')}:${_settings.eveningReminderMinute.toString().padLeft(2, '0')}'; final morningDone = _todayRecords.where(_isMorningRecord).toList(); final eveningDone = _todayRecords.where((r) => !_isMorningRecord(r)).toList(); final now = DateTime.now(); final nowMinute = now.hour * 60 + now.minute; final morningDue = _settings.morningReminderHour * 60 + _settings.morningReminderMinute; final eveningDue = _settings.eveningReminderHour * 60 + _settings.eveningReminderMinute; final morningOverdue = morningDone.isEmpty && nowMinute >= morningDue; final eveningOverdue = eveningDone.isEmpty && nowMinute >= eveningDue; final allDone = morningDone.isNotEmpty && eveningDone.isNotEmpty; // 配色:全部完成=绿;已过提醒时间未做=橙;其余=原黄色 final Color bg, border, accent, textColor; if (allDone) { bg = const Color(0xFFD1FAE5); border = const Color(0xFFA7F3D0); accent = const Color(0xFF059669); textColor = const Color(0xFF065F46); } else if (morningOverdue || eveningOverdue) { bg = const Color(0xFFFFEDD5); border = const Color(0xFFFDBA74); accent = const Color(0xFFEA580C); textColor = const Color(0xFF9A3412); } else { bg = const Color(0xFFFEF3C7); border = const Color(0xFFFDE68A); accent = const Color(0xFFD97706); textColor = const Color(0xFF92400E); } Widget slotRow(String label, String dueTime, List done, bool overdue) { final String status; if (done.isNotEmpty) { final times = done.map((r) => DateFormat('HH:mm').format(r.startTime.toLocal())).join('、'); status = done.length > 1 ? '已完成 ${done.length} 次 ($times)' : '已完成 $times'; } else { status = overdue ? '未完成(已过时间)' : '待完成'; } return Row( children: [ Icon( done.isNotEmpty ? Icons.check_circle : Icons.radio_button_unchecked, size: 16, color: done.isNotEmpty ? const Color(0xFF10B981) : (overdue ? const Color(0xFFEA580C) : accent), ), const SizedBox(width: 6), Text('$label $dueTime', style: TextStyle(fontSize: 12, color: textColor)), const SizedBox(width: 8), Expanded( child: Text( status, style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: textColor), overflow: TextOverflow.ellipsis, ), ), ], ); } return Material( color: Colors.transparent, child: InkWell( onTap: _showTodayRecordsSheet, borderRadius: BorderRadius.circular(12), child: Ink( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), decoration: BoxDecoration( color: bg, borderRadius: BorderRadius.circular(12), border: Border.all(color: border), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Icon(Icons.access_time_filled, color: accent, size: 18), const SizedBox(width: 8), Expanded( child: Text( '今日已雾化 ${_todayRecords.length} 次', style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: textColor), ), ), Text( _activeCanisters.length > 1 ? '当前为双药方案' : '当前为单药方案', style: TextStyle(fontSize: 11, color: accent), ), Icon(Icons.chevron_right, color: accent, size: 16), ], ), const SizedBox(height: 6), slotRow('早间', mTime, morningDone, morningOverdue), const SizedBox(height: 4), slotRow('晚间', eTime, eveningDone, eveningOverdue), ], ), ), ), ); } // 2. 核心行动区:清晰列出本次雾化包含的具体药物和步骤流程 Widget _buildActionPlanHeroCard() { final crossMinutes = _settings.crossDrugIntervalSeconds ~/ 60; return Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: const Color(0xFFDBEAFE)), boxShadow: [ BoxShadow( color: const Color(0xFF2563EB).withValues(alpha: 0.06), blurRadius: 16, offset: const Offset(0, 4), ), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 头部:方案名称与修改入口 Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( padding: const EdgeInsets.all(6), decoration: BoxDecoration( color: const Color(0xFFEFF6FF), borderRadius: BorderRadius.circular(8), ), child: const Icon(Icons.medication, color: Color(0xFF2563EB), size: 18), ), const SizedBox(width: 8), const Text( '当前执行方案', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: Color(0xFF0F172A)), ), ], ), InkWell( onTap: _openPlanConfig, borderRadius: BorderRadius.circular(8), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Row( children: [ Text('配置方案', style: TextStyle(color: Color(0xFF2563EB), fontSize: 12, fontWeight: FontWeight.bold)), Icon(Icons.chevron_right, color: Color(0xFF2563EB), size: 16), ], ), ), ), ], ), const SizedBox(height: 16), // 步骤流程横向清晰展示 if (_activeCanisters.isEmpty) ...[ Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: Colors.grey.shade50, borderRadius: BorderRadius.circular(12)), child: const Text('未勾选任何药物,请点击右上角配置方案', style: TextStyle(color: Colors.grey, fontSize: 12)), ), ] else ...[ _buildPlanFlowDiagram(crossMinutes), ], const SizedBox(height: 20), // 主行动按钮:开始雾化 / 继续后台雾化 (加大宽度,文本居中显示) SizedBox( width: double.infinity, child: ElevatedButton( onPressed: _startSession, style: ElevatedButton.styleFrom( backgroundColor: _sessionService.isActive ? const Color(0xFF10B981) : const Color(0xFF2563EB), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), elevation: 2, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Icon(_sessionService.isActive ? Icons.play_arrow_rounded : Icons.play_circle_fill, size: 22), const SizedBox(width: 8), Flexible( child: Text( _sessionService.isActive ? (_sessionService.isWaitingForNextMed ? '两药间隔已结束:开始第二组' : (_sessionService.isFinished ? '雾化已完成:确认打卡' : '继续雾化 (${_formatTime(_sessionService.remainingSeconds)})')) : (_activeCanisters.length > 1 ? '开始联合雾化 (万托林先行)' : '开始吸入 ${_activeCanisters.first.name.split(" ")[0]}'), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold), textAlign: TextAlign.center, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), ), const SizedBox(height: 10), // 次级打卡按钮 Center( child: TextButton.icon( onPressed: _quickDeduct, icon: const Icon(Icons.flash_on, size: 16, color: Color(0xFF64748B)), label: const Text('极速打卡 (已做完免计时)', style: TextStyle(fontSize: 12, color: Color(0xFF64748B), fontWeight: FontWeight.w600)), ), ), ], ), ); } // 步骤条小部件 Widget _buildPlanFlowDiagram(int crossMinutes) { return Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: const Color(0xFFF8FAFC), borderRadius: BorderRadius.circular(14), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: Column( children: [ for (int i = 0; i < _activeCanisters.length; i++) ...[ Row( children: [ Container( width: 22, height: 22, decoration: BoxDecoration( color: _activeCanisters[i].isSteroid ? const Color(0xFF10B981) : const Color(0xFF2563EB), shape: BoxShape.circle, ), child: Center( child: Text( '${i + 1}', style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.bold), ), ), ), const SizedBox(width: 10), Expanded( child: Text( _activeCanisters[i].name, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Color(0xFF1E293B)), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), border: Border.all(color: const Color(0xFFCBD5E1)), ), child: Text( '${_activeCanisters[i].puffsPerSession} 喷 (${_activeCanisters[i].inhalationSeconds}s/喷)', style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Color(0xFF475569)), ), ), ], ), if (i < _activeCanisters.length - 1) Padding( padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 9), child: Row( children: [ Container(width: 2, height: 18, color: const Color(0xFFF59E0B)), const SizedBox(width: 19), Flexible( child: Text( '⏳ 间隔等待 $crossMinutes 分钟 (万托林舒张气道,到点提醒)', style: const TextStyle(fontSize: 11, color: Color(0xFFB45309), fontWeight: FontWeight.w600), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), ], ], ), ); } // 3. 药品余量与剩余次数监控区 (仅显示当前方案参与启用的药物) Widget _buildMedicationDosesSection() { final flixDaily = _flixotide.puffsPerSession * 2; final flixDays = flixDaily > 0 ? (_flixotide.remainingDoses / flixDaily).floor() : 0; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( '当前方案药瓶余量 (防止空喷)', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Color(0xFF475569)), ), Text( '已启用 ${_activeCanisters.length} 种药物', style: const TextStyle(fontSize: 11, color: Colors.grey), ), ], ), const SizedBox(height: 12), if (_activeCanisters.isEmpty) Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: const Center( child: Text( '当前未启用任何药物,请点击上方【配置方案】勾选要使用的药物', style: TextStyle(color: Colors.grey, fontSize: 13), ), ), ), // 仅在辅舒酮参与方案时显示 if (_flixotide.isEnabled) _buildFlixotideDoseCard(flixDays), if (_flixotide.isEnabled && _ventolin.isEnabled) const SizedBox(height: 12), // 仅在万托林参与方案时显示 if (_ventolin.isEnabled) _buildVentolinDoseCard(), ], ); } // 辅舒酮剩余次数卡片 Widget _buildFlixotideDoseCard(int remainingDays) { final percent = (_flixotide.remainingDoses / _flixotide.totalDoses).clamp(0.0, 1.0); final isLow = _flixotide.isLowDose; final statusColor = isLow ? const Color(0xFFEF4444) : (percent <= 0.35 ? const Color(0xFFF59E0B) : const Color(0xFF10B981)); return Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all( color: isLow ? const Color(0xFFFCA5A5) : const Color(0xFFE2E8F0), width: isLow ? 1.5 : 1, ), boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.02), blurRadius: 8, offset: const Offset(0, 2)), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 标题与报警 Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( width: 32, height: 32, decoration: BoxDecoration( color: const Color(0xFFECFDF5), borderRadius: BorderRadius.circular(8), ), child: const Center( child: Text('辅', style: TextStyle(color: Color(0xFF059669), fontWeight: FontWeight.bold, fontSize: 15)), ), ), const SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _flixotide.name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Color(0xFF0F172A)), ), const Text('吸入糖皮质激素 • 严密防空喷', style: TextStyle(fontSize: 11, color: Colors.grey)), ], ), ], ), if (isLow) Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( color: const Color(0xFFFEE2E2), borderRadius: BorderRadius.circular(6), ), child: const Text('⚠️ 快用完请备药', style: TextStyle(color: Color(0xFFDC2626), fontSize: 11, fontWeight: FontWeight.bold)), ) else Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( color: const Color(0xFFF1F5F9), borderRadius: BorderRadius.circular(6), ), child: Text('预计可用 $remainingDays 天', style: const TextStyle(color: Color(0xFF475569), fontSize: 11, fontWeight: FontWeight.w600)), ), ], ), const SizedBox(height: 16), // 核心数字与进度条 Row( crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text('辅舒酮剩余 ', style: TextStyle(fontSize: 13, color: Color(0xFF64748B), fontWeight: FontWeight.w500)), Text( '${_flixotide.remainingDoses}', style: TextStyle( fontSize: 32, fontWeight: FontWeight.w900, color: statusColor, height: 1.0, ), ), Text( ' / ${_flixotide.totalDoses} 喷', style: const TextStyle(fontSize: 13, color: Color(0xFF94A3B8), fontWeight: FontWeight.bold), ), ], ), Text( '已消耗 ${_flixotide.totalDoses - _flixotide.remainingDoses} 喷', style: const TextStyle(fontSize: 11, color: Color(0xFF94A3B8)), ), ], ), const SizedBox(height: 8), // 进度条 ClipRRect( borderRadius: BorderRadius.circular(6), child: LinearProgressIndicator( value: percent, minHeight: 10, backgroundColor: const Color(0xFFF1F5F9), valueColor: AlwaysStoppedAnimation(statusColor), ), ), const SizedBox(height: 12), // 底部快捷按钮:试喷扣减 与 换新药重置 Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton.icon( onPressed: () => _logPrimePuff(_flixotide), style: OutlinedButton.styleFrom( visualDensity: VisualDensity.compact, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), side: const BorderSide(color: Color(0xFFCBD5E1)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), icon: const Icon(Icons.air, size: 14, color: Color(0xFF2563EB)), label: const Text('试喷扣减 1 喷', style: TextStyle(fontSize: 11, color: Color(0xFF2563EB))), ), const SizedBox(width: 8), OutlinedButton.icon( onPressed: () => _resetCanister(_flixotide), style: OutlinedButton.styleFrom( visualDensity: VisualDensity.compact, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), side: const BorderSide(color: Color(0xFFCBD5E1)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), icon: const Icon(Icons.refresh, size: 14, color: Color(0xFF475569)), label: const Text('开新瓶(重置60喷)', style: TextStyle(fontSize: 11, color: Color(0xFF475569))), ), ], ), ], ), ); } // 万托林剩余次数卡片 Widget _buildVentolinDoseCard() { final percent = (_ventolin.remainingDoses / _ventolin.totalDoses).clamp(0.0, 1.0); return Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(18), border: Border.all(color: const Color(0xFFE2E8F0)), boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.02), blurRadius: 8, offset: const Offset(0, 2)), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( width: 32, height: 32, decoration: BoxDecoration( color: const Color(0xFFEFF6FF), borderRadius: BorderRadius.circular(8), ), child: const Center( child: Text('万', style: TextStyle(color: Color(0xFF2563EB), fontWeight: FontWeight.bold, fontSize: 15)), ), ), const SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _ventolin.name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Color(0xFF0F172A)), ), const Text('支气管舒张急救药 • 标称 200 喷', style: TextStyle(fontSize: 11, color: Colors.grey)), ], ), ], ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: _ventolin.isEnabled ? const Color(0xFFEFF6FF) : const Color(0xFFF1F5F9), borderRadius: BorderRadius.circular(6), ), child: Text( _ventolin.isEnabled ? '参与本次方案' : '未参与方案', style: TextStyle( color: _ventolin.isEnabled ? const Color(0xFF2563EB) : Colors.grey, fontSize: 11, fontWeight: FontWeight.w600, ), ), ), ], ), const SizedBox(height: 12), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text('万托林剩余 ', style: TextStyle(fontSize: 13, color: Color(0xFF64748B), fontWeight: FontWeight.w500)), Text( '${_ventolin.remainingDoses}', style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w900, color: Color(0xFF2563EB)), ), Text(' / ${_ventolin.totalDoses} 喷', style: const TextStyle(fontSize: 13, color: Color(0xFF94A3B8), fontWeight: FontWeight.bold)), ], ), Text( '已消耗 ${_ventolin.totalDoses - _ventolin.remainingDoses} 喷', style: const TextStyle(fontSize: 11, color: Color(0xFF94A3B8)), ), ], ), const SizedBox(height: 8), ClipRRect( borderRadius: BorderRadius.circular(6), child: LinearProgressIndicator( value: percent, minHeight: 8, backgroundColor: const Color(0xFFF1F5F9), valueColor: const AlwaysStoppedAnimation(Color(0xFF2563EB)), ), ), const SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton.icon( onPressed: () => _logPrimePuff(_ventolin), style: OutlinedButton.styleFrom( visualDensity: VisualDensity.compact, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), side: const BorderSide(color: Color(0xFFCBD5E1)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), icon: const Icon(Icons.air, size: 14, color: Color(0xFF2563EB)), label: const Text('试喷扣减 1 喷', style: TextStyle(fontSize: 11, color: Color(0xFF2563EB))), ), const SizedBox(width: 8), OutlinedButton.icon( onPressed: () => _resetCanister(_ventolin), style: OutlinedButton.styleFrom( visualDensity: VisualDensity.compact, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), side: const BorderSide(color: Color(0xFFCBD5E1)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), icon: const Icon(Icons.refresh, size: 14, color: Color(0xFF475569)), label: const Text('开新瓶(重置200喷)', style: TextStyle(fontSize: 11, color: Color(0xFF475569))), ), ], ), ], ), ); } // 4. 最近吸入时间记录底栏 Widget _buildLastRecordFooter() { if (_lastRecord == null) { return Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)), child: const Center( child: Text('暂无历史吸入记录,点击上方按钮开始', style: TextStyle(color: Colors.grey, fontSize: 12)), ), ); } final timeStr = _formatLastTime(_lastRecord!.startTime); final detailStr = _lastRecord!.ventolinPuffs > 0 ? '万托林 ${_lastRecord!.ventolinPuffs}喷 + 辅舒酮 ${_lastRecord!.flixotidePuffs}喷' : '辅舒酮 ${_lastRecord!.flixotidePuffs}喷'; return Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ const Icon(Icons.check_circle, color: Color(0xFF10B981), size: 16), const SizedBox(width: 8), Text('上次完成:$timeStr ($detailStr)', style: const TextStyle(fontSize: 12, color: Color(0xFF334155))), ], ), const Icon(Icons.chevron_right, color: Colors.grey, size: 18), ], ), ); } }