Files
AeroTrack/lib/services/active_session_service.dart

338 lines
9.9 KiB
Dart

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<Canister> _activeMedications = [];
final List<SessionStep> _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<Canister> get activeMedications => _activeMedications;
List<SessionStep> 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<Canister> medications,
required AppSettings settings,
}) {
// 强制临床顺序:万托林 (支气管舒张剂,非激素) 严格排在第一位,辅舒酮 (激素) 排在第二位
final sortedMeds = List<Canister>.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<void> confirmAndSave(StorageService storageService) async {
final Map<String, int> 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 activeFlix = storageService.getActiveFlixotideBottle();
final activeVent = storageService.getActiveVentolinBottle();
final record = DoseRecord(
id: const Uuid().v4(),
startTime: (_sessionStartTime ?? DateTime.now()).toUtc(),
endTime: (_sessionEndTime ?? DateTime.now()).toUtc(),
flixotidePuffs: totalFlixotide,
ventolinPuffs: totalVentolin,
flixotideBottleId: totalFlixotide > 0 ? activeFlix?.id : null,
ventolinBottleId: totalVentolin > 0 ? activeVent?.id : null,
rinsedMouth: _rinsedMouth,
washedFace: _washedFace,
updatedAt: DateTime.now().toUtc(),
);
await storageService.addRecord(record);
await storageService.deductSessionDoses(deductions);
cancelSession();
}
}