feat: 二级页面色彩刷新 + 用药/通知/设备重构 + 后端健康档案/通知管线增强 + 大量测试
## 后端 - 健康档案: 新增手术状态字段 + EF 迁移; HealthArchiveService 新增查询方法 - 健康记录: HealthRecordService 新增批量/统计方法; 契约扩展 - 用药: 新增 MedicationScheduleStatus 枚举; MedicationService 排班逻辑调整 - 通知: EfUserNotificationPipeline 重构; 新增 EfReminderCatchUpService; 通知管线支持更多场景 - 用户: UserService 账号删除逻辑; 新增 local_account_file_cleanup; EfUserRepository 扩展 - AI: medication_agent_handler 微调; prompt_manager 优化; AiConversationService 上下文处理 - Endpoint: doctor/medication/exercise/health/notification/user 等多接口调整 - BackgroundService: health_record_reminder_service 重构, 提醒补漏逻辑 - 测试: 新增 account_deletion/doctor_endpoint/medication_schedule/medication_update/prompt_manager 测试 ## 前端 - UI 系统: app_theme 大幅重构; app_colors/app_design_tokens/app_module_visuals 调整; 二级页面色彩刷新 - 主页: home_page 背景渐变 + 消息列表提取 _HomeMessages + 通知检查逻辑; chat_messages_view 全面重构 - 用药: medication_list/edit/checkin 三页重构, 新增 medication_ui_logic 抽取 - 通知: notification_prefs_page 重构, 新增 notification_prefs_logic; notification_center 优化 - 设备: device_management 重构, 新增 device_sync_ui_logic; device_scan 优化 - 趋势图: trend_page 大幅重构 - 登录: login_page 重构 - 个人资料: 新增 profile_edit_page; profile_page 优化 - 运动: 新增 exercise/ 目录 + care_plan_ui_logic - 其他: remaining_pages/report_pages/health_drawer/admin/doctor 等多页面调整 - 组件: common_widgets/app_empty_state/app_error_state/app_future_view/app_toast/ai_content 优化 - Provider: chat_provider/consultation_provider/data_providers/auth_provider 调整 - AndroidManifest: 移除多余权限 - 测试: 新增 ai_content/care_plan/home_message/login_flow/medication_checkin/medication_ui/notification_prefs/profile_device/secondary_page/swipe_delete 等大量测试 ## 文档 - 新增 ui-design-system.md 设计系统文档 - 新增 secondary-page-color-refresh 计划 + specs 目录
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||
|
||||
import '../../core/api_client.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../core/app_design_tokens.dart';
|
||||
import '../../core/app_module_visuals.dart';
|
||||
import '../../core/app_theme.dart';
|
||||
import '../../core/navigation_provider.dart';
|
||||
@@ -22,9 +25,6 @@ class MedicationCheckInPage extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
|
||||
static const _visual = AppModuleVisuals.medication;
|
||||
static const _softGreen = Color(0xFFEAF8EF);
|
||||
|
||||
Future<List<Map<String, dynamic>>>? _future;
|
||||
final Set<String> _busyDoses = {};
|
||||
|
||||
@@ -34,11 +34,9 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
|
||||
_load();
|
||||
}
|
||||
|
||||
void _load() {
|
||||
setState(() {
|
||||
_future = ref.read(medicationReminderProvider.future);
|
||||
});
|
||||
}
|
||||
void _load() => setState(() {
|
||||
_future = ref.read(medicationReminderProvider.future);
|
||||
});
|
||||
|
||||
Future<void> _refresh() async {
|
||||
ref.invalidate(medicationReminderProvider);
|
||||
@@ -48,26 +46,32 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
|
||||
|
||||
Future<void> _toggleDose(String medId, String time, bool taken) async {
|
||||
final doseKey = '$medId-$time';
|
||||
if (_busyDoses.contains(doseKey)) return;
|
||||
|
||||
if (medId.isEmpty || time.isEmpty || _busyDoses.contains(doseKey)) return;
|
||||
setState(() => _busyDoses.add(doseKey));
|
||||
try {
|
||||
final api = ref.read(apiClientProvider);
|
||||
if (taken) {
|
||||
await api.delete('/api/medications/$medId/confirm-dose/$time');
|
||||
} else {
|
||||
await api.post(
|
||||
final response = await api.post(
|
||||
'/api/medications/$medId/confirm-dose',
|
||||
data: {'scheduledTime': time, 'status': 'taken'},
|
||||
);
|
||||
final data = response.data is Map ? response.data['data'] : null;
|
||||
if (data is Map && data['success'] == false) {
|
||||
throw const ApiException('该次服药已经打卡');
|
||||
}
|
||||
}
|
||||
ref.invalidate(medicationReminderProvider);
|
||||
ref.invalidate(medicationListProvider);
|
||||
_load();
|
||||
} catch (e) {
|
||||
debugPrint('[MedCheckIn] 打卡失败: $e');
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
AppToast.show(context, '打卡失败,请稍后重试', type: AppToastType.error);
|
||||
AppToast.show(
|
||||
context,
|
||||
error is ApiException ? error.message : '打卡失败,请稍后重试',
|
||||
type: AppToastType.error,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _busyDoses.remove(doseKey));
|
||||
@@ -83,59 +87,86 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
|
||||
onPressed: () => popRoute(ref),
|
||||
),
|
||||
title: const Text('服药打卡'),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: FutureBuilder<List<Map<String, dynamic>>>(
|
||||
future: _future,
|
||||
builder: (ctx, snap) {
|
||||
if (snap.connectionState == ConnectionState.waiting &&
|
||||
!snap.hasData) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(color: AppTheme.primary),
|
||||
);
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting &&
|
||||
!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snap.hasError) {
|
||||
if (snapshot.hasError) {
|
||||
return AppErrorState(title: '用药信息加载失败', onRetry: _load);
|
||||
}
|
||||
|
||||
final reminders = _filterReminders(snap.data ?? []);
|
||||
final reminders = _filterReminders(snapshot.data ?? const []);
|
||||
if (reminders.isEmpty) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: const [
|
||||
SizedBox(height: 92),
|
||||
children: [
|
||||
const SizedBox(height: 92),
|
||||
AppEmptyState(
|
||||
icon: Icons.task_alt_outlined,
|
||||
title: '今天的用药已完成',
|
||||
subtitle: '下拉可刷新最新用药提醒',
|
||||
icon: AppModuleVisuals.medication.icon,
|
||||
title: '今天没有服药安排',
|
||||
subtitle: '今日可以安心休息,下拉可刷新最新计划',
|
||||
iconColor: AppColors.medication,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final grouped = _groupByMedication(reminders);
|
||||
final total = reminders.length;
|
||||
final taken = reminders.where(_isTaken).length;
|
||||
final pending = total - taken;
|
||||
|
||||
final sorted = [...reminders]
|
||||
..sort(
|
||||
(a, b) => _formatTime(
|
||||
a['scheduledTime']?.toString() ?? '',
|
||||
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
|
||||
);
|
||||
final taken = sorted.where(_isTaken).length;
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
padding: AppSpacing.page,
|
||||
children: [
|
||||
_CheckInSummary(total: total, taken: taken, pending: pending),
|
||||
const SizedBox(height: 14),
|
||||
...grouped.entries.map(
|
||||
(entry) => _MedicationDoseCard(
|
||||
name: entry.key,
|
||||
doses: entry.value,
|
||||
busyDoses: _busyDoses,
|
||||
onToggle: _toggleDose,
|
||||
_DoseProgressHeader(total: sorted.length, taken: taken),
|
||||
const SizedBox(height: 18),
|
||||
Container(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
child: Column(
|
||||
children: List.generate(sorted.length, (index) {
|
||||
final dose = sorted[index];
|
||||
final key =
|
||||
'${dose['id']?.toString() ?? ''}-${dose['scheduledTime']?.toString() ?? ''}';
|
||||
return _DoseTimelineRow(
|
||||
dose: dose,
|
||||
isFirst: index == 0,
|
||||
isLast: index == sorted.length - 1,
|
||||
isBusy: _busyDoses.contains(key),
|
||||
onToggle: _toggleDose,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
const Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
LucideIcons.shield,
|
||||
size: 16,
|
||||
color: AppColors.textHint,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
'请按医嘱服药,如有不适及时咨询医生',
|
||||
style: TextStyle(fontSize: 12, color: AppColors.textHint),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -148,210 +179,88 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
|
||||
List<Map<String, dynamic>> _filterReminders(
|
||||
List<Map<String, dynamic>> reminders,
|
||||
) {
|
||||
if (widget.medId == null) return reminders;
|
||||
return reminders.where((r) => r['id']?.toString() == widget.medId).toList();
|
||||
}
|
||||
|
||||
Map<String, List<Map<String, dynamic>>> _groupByMedication(
|
||||
List<Map<String, dynamic>> reminders,
|
||||
) {
|
||||
final grouped = <String, List<Map<String, dynamic>>>{};
|
||||
for (final reminder in reminders) {
|
||||
final name = reminder['name']?.toString().trim();
|
||||
grouped
|
||||
.putIfAbsent(name?.isNotEmpty == true ? name! : '未命名药品', () {
|
||||
return <Map<String, dynamic>>[];
|
||||
})
|
||||
.add(reminder);
|
||||
}
|
||||
|
||||
for (final doses in grouped.values) {
|
||||
doses.sort(
|
||||
(a, b) => _formatTime(
|
||||
a['scheduledTime']?.toString() ?? '',
|
||||
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
|
||||
);
|
||||
}
|
||||
return grouped;
|
||||
if (widget.medId == null || widget.medId!.isEmpty) return reminders;
|
||||
return reminders
|
||||
.where((item) => item['id']?.toString() == widget.medId)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
class _CheckInSummary extends StatelessWidget {
|
||||
Map<String, List<Map<String, dynamic>>> groupMedicationReminders(
|
||||
List<Map<String, dynamic>> reminders,
|
||||
) {
|
||||
final grouped = <String, List<Map<String, dynamic>>>{};
|
||||
for (var index = 0; index < reminders.length; index++) {
|
||||
final reminder = reminders[index];
|
||||
final medicationId = reminder['id']?.toString().trim();
|
||||
final key = medicationId?.isNotEmpty == true
|
||||
? medicationId!
|
||||
: 'unknown-$index';
|
||||
grouped.putIfAbsent(key, () => <Map<String, dynamic>>[]).add(reminder);
|
||||
}
|
||||
for (final doses in grouped.values) {
|
||||
doses.sort(
|
||||
(a, b) => _formatTime(
|
||||
a['scheduledTime']?.toString() ?? '',
|
||||
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
|
||||
);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
class _DoseProgressHeader extends StatelessWidget {
|
||||
final int total;
|
||||
final int taken;
|
||||
final int pending;
|
||||
|
||||
const _CheckInSummary({
|
||||
required this.total,
|
||||
required this.taken,
|
||||
required this.pending,
|
||||
});
|
||||
const _DoseProgressHeader({required this.total, required this.taken});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final now = DateTime.now();
|
||||
final progress = total == 0 ? 0.0 : taken / total;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 15),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.border, width: 1.1),
|
||||
boxShadow: [AppTheme.shadowLight],
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 42,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
gradient: _MedicationCheckInPageState._visual.gradient,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.medication_outlined,
|
||||
color: Colors.white,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
const Expanded(
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'今日服药进度',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
'${now.month}月${now.day}日 · 今日用药',
|
||||
style: AppTextStyles.sectionTitle,
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
'按提醒时间逐项确认,保持用药节奏',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
'$taken / $total 已完成',
|
||||
style: AppTextStyles.listSubtitle,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${(progress * 100).round()}%',
|
||||
style: TextStyle(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: _MedicationCheckInPageState._visual.color,
|
||||
style: AppTextStyles.summaryTitle.copyWith(
|
||||
color: AppColors.medication,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 12),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
borderRadius: AppRadius.pillBorder,
|
||||
child: LinearProgressIndicator(
|
||||
minHeight: 9,
|
||||
minHeight: 5,
|
||||
value: progress,
|
||||
backgroundColor: AppColors.cardInner,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
_MedicationCheckInPageState._visual.color,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _SummaryStat(
|
||||
label: '待完成',
|
||||
value: '$pending',
|
||||
icon: Icons.schedule_outlined,
|
||||
color: AppColors.warning,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: _SummaryStat(
|
||||
label: '已打卡',
|
||||
value: '$taken',
|
||||
icon: Icons.check_circle_outline,
|
||||
color: AppTheme.success,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: _SummaryStat(
|
||||
label: '总次数',
|
||||
value: '$total',
|
||||
icon: Icons.format_list_numbered_outlined,
|
||||
color: _MedicationCheckInPageState._visual.color,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SummaryStat extends StatelessWidget {
|
||||
final String label;
|
||||
final String value;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
|
||||
const _SummaryStat({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
constraints: const BoxConstraints(minHeight: 58),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: color.withValues(alpha: 0.14)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 17),
|
||||
const SizedBox(width: 7),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
value,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.medication),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -360,138 +269,16 @@ class _SummaryStat extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _MedicationDoseCard extends StatelessWidget {
|
||||
final String name;
|
||||
final List<Map<String, dynamic>> doses;
|
||||
final Set<String> busyDoses;
|
||||
final Future<void> Function(String medId, String time, bool taken) onToggle;
|
||||
|
||||
const _MedicationDoseCard({
|
||||
required this.name,
|
||||
required this.doses,
|
||||
required this.busyDoses,
|
||||
required this.onToggle,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dosage = doses.first['dosage']?.toString().trim() ?? '';
|
||||
final takenCount = doses.where(_isTaken).length;
|
||||
final allTaken = takenCount == doses.length;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: allTaken
|
||||
? AppTheme.success.withValues(alpha: 0.26)
|
||||
: AppColors.border,
|
||||
width: 1.1,
|
||||
),
|
||||
boxShadow: [AppTheme.shadowLight],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: allTaken
|
||||
? _MedicationCheckInPageState._softGreen
|
||||
: _MedicationCheckInPageState._visual.lightColor,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.borderLight),
|
||||
),
|
||||
child: Icon(
|
||||
allTaken ? Icons.done_all_rounded : Icons.medication_liquid,
|
||||
color: allTaken
|
||||
? AppTheme.success
|
||||
: _MedicationCheckInPageState._visual.color,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
if (dosage.isNotEmpty) ...[
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
dosage,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: allTaken
|
||||
? _MedicationCheckInPageState._softGreen
|
||||
: AppColors.cardInner,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Text(
|
||||
'$takenCount/${doses.length}',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: allTaken
|
||||
? AppTheme.success
|
||||
: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
for (var i = 0; i < doses.length; i++) ...[
|
||||
_DoseRow(
|
||||
dose: doses[i],
|
||||
isLast: i == doses.length - 1,
|
||||
isBusy: busyDoses.contains(
|
||||
'${doses[i]['id']?.toString() ?? ''}-${doses[i]['scheduledTime']?.toString() ?? ''}',
|
||||
),
|
||||
onToggle: onToggle,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DoseRow extends StatelessWidget {
|
||||
class _DoseTimelineRow extends StatelessWidget {
|
||||
final Map<String, dynamic> dose;
|
||||
final bool isFirst;
|
||||
final bool isLast;
|
||||
final bool isBusy;
|
||||
final Future<void> Function(String medId, String time, bool taken) onToggle;
|
||||
final Future<void> Function(String, String, bool) onToggle;
|
||||
|
||||
const _DoseRow({
|
||||
const _DoseTimelineRow({
|
||||
required this.dose,
|
||||
required this.isFirst,
|
||||
required this.isLast,
|
||||
required this.isBusy,
|
||||
required this.onToggle,
|
||||
@@ -499,171 +286,175 @@ class _DoseRow extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final time = dose['scheduledTime']?.toString() ?? '';
|
||||
final medId = dose['id']?.toString() ?? '';
|
||||
final isTaken = _isTaken(dose);
|
||||
final displayTime = _formatTime(time);
|
||||
final statusColor = isTaken ? AppTheme.success : AppColors.warning;
|
||||
final rawTime = dose['scheduledTime']?.toString() ?? '';
|
||||
final time = _formatTime(rawTime);
|
||||
final name = dose['name']?.toString().trim().isNotEmpty == true
|
||||
? dose['name'].toString().trim()
|
||||
: '未命名药品';
|
||||
final dosage = dose['dosage']?.toString().trim() ?? '';
|
||||
final status = dose['status']?.toString().toLowerCase() ?? 'scheduled';
|
||||
final taken = status == 'taken';
|
||||
final scheduled = status == 'scheduled';
|
||||
final color = _statusColor(status);
|
||||
|
||||
return IntrinsicHeight(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
return ConstrainedBox(
|
||||
constraints: const BoxConstraints(minHeight: 92),
|
||||
child: Stack(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 28,
|
||||
child: Column(
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 22,
|
||||
height: 22,
|
||||
decoration: BoxDecoration(
|
||||
color: isTaken ? AppTheme.success : Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: isTaken ? AppTheme.success : AppColors.border,
|
||||
width: 2,
|
||||
),
|
||||
SizedBox(
|
||||
width: 54,
|
||||
child: Text(
|
||||
time,
|
||||
style: AppTextStyles.listTitle.copyWith(fontSize: 18),
|
||||
),
|
||||
child: isTaken
|
||||
? const Icon(Icons.check, size: 14, color: Colors.white)
|
||||
: null,
|
||||
),
|
||||
if (!isLast)
|
||||
Expanded(
|
||||
child: Container(
|
||||
width: 2,
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
color: isTaken
|
||||
? AppTheme.success.withValues(alpha: 0.34)
|
||||
: AppColors.borderLight,
|
||||
),
|
||||
SizedBox(
|
||||
width: 28,
|
||||
height: 92,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
if (!isFirst)
|
||||
Positioned(
|
||||
top: 0,
|
||||
bottom: 46,
|
||||
child: Container(width: 2, color: AppColors.divider),
|
||||
),
|
||||
if (!isLast)
|
||||
Positioned(
|
||||
top: 46,
|
||||
bottom: 0,
|
||||
child: Container(width: 2, color: AppColors.divider),
|
||||
),
|
||||
Container(
|
||||
width: 20,
|
||||
height: 20,
|
||||
decoration: BoxDecoration(
|
||||
color: taken ? color : Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: color, width: 2),
|
||||
),
|
||||
child: taken
|
||||
? const Icon(
|
||||
Icons.check,
|
||||
size: 13,
|
||||
color: Colors.white,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: AppTextStyles.listTitle.copyWith(fontSize: 16),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
[
|
||||
dosage,
|
||||
_statusLabel(status),
|
||||
].where((text) => text.isNotEmpty).join(' · '),
|
||||
style: AppTextStyles.listSubtitle.copyWith(
|
||||
fontSize: 13,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
height: 36,
|
||||
child: OutlinedButton(
|
||||
onPressed: isBusy || scheduled
|
||||
? null
|
||||
: () => onToggle(medId, rawTime, taken),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 13),
|
||||
backgroundColor: taken
|
||||
? AppColors.successLight
|
||||
: Colors.white,
|
||||
foregroundColor: taken
|
||||
? AppColors.successText
|
||||
: AppColors.medication,
|
||||
disabledForegroundColor: AppColors.textHint,
|
||||
side: BorderSide(
|
||||
color: scheduled
|
||||
? AppColors.borderLight
|
||||
: (taken
|
||||
? AppColors.successText
|
||||
: AppColors.medication),
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: AppRadius.smBorder,
|
||||
),
|
||||
),
|
||||
child: isBusy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(
|
||||
scheduled ? '未到时间' : (taken ? '撤销' : '打卡'),
|
||||
style: AppTextStyles.miniButton,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(bottom: isLast ? 0 : 12),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.fromLTRB(12, 10, 10, 10),
|
||||
decoration: BoxDecoration(
|
||||
color: isTaken
|
||||
? _MedicationCheckInPageState._softGreen
|
||||
: const Color(0xFFF8FAFC),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isTaken
|
||||
? AppTheme.success.withValues(alpha: 0.18)
|
||||
: AppColors.borderLight,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.access_time, size: 18, color: statusColor),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
displayTime,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: isTaken ? AppTheme.textSub : AppTheme.text,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 1),
|
||||
Text(
|
||||
isTaken ? '已完成打卡' : '等待确认服用',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isTaken
|
||||
? AppTheme.success
|
||||
: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
height: 36,
|
||||
child: FilledButton.icon(
|
||||
onPressed: isBusy || medId.isEmpty || time.isEmpty
|
||||
? null
|
||||
: () => onToggle(medId, time, isTaken),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: isTaken
|
||||
? Colors.white
|
||||
: _MedicationCheckInPageState._visual.color,
|
||||
foregroundColor: isTaken
|
||||
? AppTheme.success
|
||||
: Colors.white,
|
||||
disabledBackgroundColor: AppColors.cardInner,
|
||||
disabledForegroundColor: AppColors.textHint,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
minimumSize: const Size(0, 36),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
side: BorderSide(
|
||||
color: isTaken
|
||||
? AppTheme.success.withValues(alpha: 0.34)
|
||||
: Colors.transparent,
|
||||
),
|
||||
),
|
||||
),
|
||||
icon: isBusy
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.textHint,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
isTaken
|
||||
? Icons.undo_rounded
|
||||
: Icons.check_rounded,
|
||||
size: 17,
|
||||
),
|
||||
label: Text(
|
||||
isTaken ? '撤销' : '打卡',
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (!isLast)
|
||||
const Positioned(
|
||||
left: 96,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Divider(
|
||||
height: 1,
|
||||
thickness: 0.7,
|
||||
color: AppColors.divider,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _isTaken(Map<String, dynamic> dose) {
|
||||
return dose['status']?.toString().toLowerCase() == 'taken';
|
||||
}
|
||||
bool _isTaken(Map<String, dynamic> dose) =>
|
||||
dose['status']?.toString().toLowerCase() == 'taken';
|
||||
|
||||
String _formatTime(String raw) {
|
||||
final value = raw.trim();
|
||||
if (value.length >= 5 && value[2] == ':') return value.substring(0, 5);
|
||||
final parsed = DateTime.tryParse(value);
|
||||
if (parsed == null) return value;
|
||||
final hour = parsed.hour.toString().padLeft(2, '0');
|
||||
final minute = parsed.minute.toString().padLeft(2, '0');
|
||||
return '$hour:$minute';
|
||||
return value.length >= 5 ? value.substring(0, 5) : value;
|
||||
}
|
||||
|
||||
String _statusLabel(String status) => switch (status) {
|
||||
'taken' => '已完成',
|
||||
'overdue' => '已超时',
|
||||
'upcoming' => '待完成',
|
||||
'skipped' => '已跳过',
|
||||
_ => '未到时间',
|
||||
};
|
||||
|
||||
Color _statusColor(String status) => switch (status) {
|
||||
'taken' => AppColors.successText,
|
||||
'overdue' => AppColors.errorText,
|
||||
'upcoming' => AppColors.blueMeasure,
|
||||
'skipped' => AppColors.textHint,
|
||||
_ => AppColors.textHint,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||
|
||||
import '../../core/api_client.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../core/app_design_tokens.dart';
|
||||
import '../../core/app_theme.dart';
|
||||
import '../../core/navigation_provider.dart';
|
||||
import '../../providers/data_providers.dart';
|
||||
import '../../widgets/app_error_state.dart';
|
||||
import '../../widgets/app_toast.dart';
|
||||
import '../../widgets/common_widgets.dart';
|
||||
import '../care_plan_ui_logic.dart';
|
||||
import 'medication_ui_logic.dart';
|
||||
|
||||
class MedicationEditPage extends ConsumerStatefulWidget {
|
||||
final String? id;
|
||||
@@ -18,117 +24,163 @@ class MedicationEditPage extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _MedicationEditPageState extends ConsumerState<MedicationEditPage> {
|
||||
final _nameCtrl = TextEditingController();
|
||||
final _dosageCtrl = TextEditingController();
|
||||
final _notesCtrl = TextEditingController();
|
||||
int _timesPerDay = 2;
|
||||
final _nameController = TextEditingController();
|
||||
final _dosageController = TextEditingController();
|
||||
final _notesController = TextEditingController();
|
||||
List<TimeOfDay> _times = [
|
||||
const TimeOfDay(hour: 8, minute: 0),
|
||||
const TimeOfDay(hour: 18, minute: 0),
|
||||
];
|
||||
DateTime _start = DateTime.now();
|
||||
DateTime? _end;
|
||||
DateTime _startDate = DateTime.now();
|
||||
DateTime? _endDate;
|
||||
bool _saving = false;
|
||||
bool _loading = false;
|
||||
String? _loadError;
|
||||
|
||||
bool get _editing => widget.id?.isNotEmpty == true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.id != null) _load();
|
||||
if (_editing) _load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameCtrl.dispose();
|
||||
_dosageCtrl.dispose();
|
||||
_notesCtrl.dispose();
|
||||
_nameController.dispose();
|
||||
_dosageController.dispose();
|
||||
_notesController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final srv = ref.read(medicationServiceProvider);
|
||||
final list = await srv.getList();
|
||||
final m = list.cast<Map<String, dynamic>?>().firstWhere(
|
||||
(x) => x?['id']?.toString() == widget.id,
|
||||
orElse: () => null,
|
||||
);
|
||||
if (m == null || !mounted) return;
|
||||
_nameCtrl.text = m['name']?.toString() ?? '';
|
||||
_dosageCtrl.text = m['dosage']?.toString() ?? '';
|
||||
_notesCtrl.text = m['notes']?.toString() ?? '';
|
||||
final tod =
|
||||
(m['timeOfDay'] as List?)?.map((t) {
|
||||
final parts = t.toString().split(':');
|
||||
return TimeOfDay(
|
||||
hour: int.tryParse(parts[0]) ?? 8,
|
||||
minute: int.tryParse(parts.length > 1 ? parts[1] : '0') ?? 0,
|
||||
);
|
||||
}).toList() ??
|
||||
[
|
||||
const TimeOfDay(hour: 8, minute: 0),
|
||||
const TimeOfDay(hour: 18, minute: 0),
|
||||
];
|
||||
_timesPerDay = tod.length;
|
||||
_times = tod;
|
||||
if (m['startDate'] != null) {
|
||||
_start = DateTime.tryParse(m['startDate'].toString()) ?? DateTime.now();
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_loadError = null;
|
||||
});
|
||||
try {
|
||||
final medications = await ref.read(medicationServiceProvider).getList();
|
||||
final medication = medications.cast<Map<String, dynamic>?>().firstWhere(
|
||||
(item) => item?['id']?.toString() == widget.id,
|
||||
orElse: () => null,
|
||||
);
|
||||
if (medication == null) throw const ApiException('该用药记录不存在');
|
||||
_nameController.text = medication['name']?.toString() ?? '';
|
||||
_dosageController.text = medication['dosage']?.toString() ?? '';
|
||||
_notesController.text = medication['notes']?.toString() ?? '';
|
||||
final loadedTimes =
|
||||
(medication['timeOfDay'] as List?)
|
||||
?.map((value) => _parseTime(value))
|
||||
.whereType<TimeOfDay>()
|
||||
.toList() ??
|
||||
[];
|
||||
if (loadedTimes.isNotEmpty) _times = loadedTimes;
|
||||
_startDate =
|
||||
DateTime.tryParse(medication['startDate']?.toString() ?? '') ??
|
||||
DateTime.now();
|
||||
_endDate = DateTime.tryParse(medication['endDate']?.toString() ?? '');
|
||||
} catch (error) {
|
||||
_loadError = error is ApiException ? error.message : '用药信息加载失败';
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
if (m['endDate'] != null) _end = DateTime.tryParse(m['endDate'].toString());
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final name = _nameCtrl.text.trim();
|
||||
if (name.isEmpty) {
|
||||
AppToast.show(context, '请输入药品名称', type: AppToastType.warning);
|
||||
final timeValues = _times.map(_timeValue).toList();
|
||||
final validation = validateMedicationForm(
|
||||
name: _nameController.text,
|
||||
dosage: _dosageController.text,
|
||||
times: timeValues,
|
||||
startDate: _startDate,
|
||||
endDate: _endDate,
|
||||
);
|
||||
if (validation != null) {
|
||||
AppToast.show(context, validation, type: AppToastType.warning);
|
||||
return;
|
||||
}
|
||||
setState(() => _loading = true);
|
||||
final data = {
|
||||
'name': name,
|
||||
'dosage': _dosageCtrl.text.trim(),
|
||||
'frequency': 'Daily',
|
||||
'notes': _notesCtrl.text.trim(),
|
||||
'timeOfDay': _times
|
||||
.map(
|
||||
(t) =>
|
||||
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}',
|
||||
)
|
||||
.toList(),
|
||||
'startDate':
|
||||
'${_start.year}-${_start.month.toString().padLeft(2, '0')}-${_start.day.toString().padLeft(2, '0')}',
|
||||
if (_end != null)
|
||||
'endDate':
|
||||
'${_end!.year}-${_end!.month.toString().padLeft(2, '0')}-${_end!.day.toString().padLeft(2, '0')}',
|
||||
setState(() => _saving = true);
|
||||
final payload = <String, dynamic>{
|
||||
'name': _nameController.text.trim(),
|
||||
'dosage': _dosageController.text.trim(),
|
||||
'frequency': _frequencyForTimes(_times.length),
|
||||
'notes': _notesController.text.trim(),
|
||||
'timeOfDay': timeValues,
|
||||
'startDate': _dateValue(_startDate),
|
||||
'endDate': _endDate == null ? null : _dateValue(_endDate!),
|
||||
'source': 'Manual',
|
||||
};
|
||||
final srv = ref.read(medicationServiceProvider);
|
||||
try {
|
||||
if (widget.id != null) {
|
||||
await srv.update(widget.id!, data);
|
||||
final service = ref.read(medicationServiceProvider);
|
||||
if (_editing) {
|
||||
await service.update(widget.id!, payload);
|
||||
} else {
|
||||
await srv.create(data);
|
||||
await service.create(payload);
|
||||
}
|
||||
ref.invalidate(medicationListProvider);
|
||||
ref.invalidate(medicationReminderProvider);
|
||||
if (mounted) popRoute(ref);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
AppToast.show(context, '保存失败', type: AppToastType.error);
|
||||
AppToast.show(
|
||||
context,
|
||||
_editing ? '用药已更新' : '用药已添加',
|
||||
type: AppToastType.success,
|
||||
);
|
||||
popRoute(ref);
|
||||
}
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
AppToast.show(
|
||||
context,
|
||||
error is ApiException ? error.message : '保存失败,请稍后重试',
|
||||
type: AppToastType.error,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
|
||||
void _updateTimes(int n) {
|
||||
setState(() {
|
||||
_timesPerDay = n;
|
||||
while (_times.length < n) {
|
||||
_times.add(const TimeOfDay(hour: 12, minute: 0));
|
||||
Future<void> _deleteMedication() async {
|
||||
if (!_editing || _saving) return;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('删除用药'),
|
||||
content: Text('确定删除“${_nameController.text.trim()}”吗?相关服药记录也将一并删除。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
setState(() => _saving = true);
|
||||
try {
|
||||
await ref.read(medicationServiceProvider).deleteMedication(widget.id!);
|
||||
ref.invalidate(medicationListProvider);
|
||||
ref.invalidate(medicationReminderProvider);
|
||||
if (mounted) {
|
||||
AppToast.show(context, '用药已删除', type: AppToastType.success);
|
||||
popRoute(ref);
|
||||
}
|
||||
while (_times.length > n) {
|
||||
_times.removeLast();
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
AppToast.show(
|
||||
context,
|
||||
error is ApiException ? error.message : '删除失败,请稍后重试',
|
||||
type: AppToastType.error,
|
||||
);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -139,282 +191,371 @@ class _MedicationEditPageState extends ConsumerState<MedicationEditPage> {
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => popRoute(ref),
|
||||
),
|
||||
title: Text(widget.id != null ? '编辑用药' : '添加用药'),
|
||||
title: Text(_editing ? '编辑用药' : '添加用药'),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: _field('药品名称', _nameCtrl, hint: '如:阿司匹林'),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: _field('剂量', _dosageCtrl, hint: '如:100mg'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_label('每日服药次数'),
|
||||
const SizedBox(height: 8),
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
final n = await showAppCountPicker(
|
||||
context,
|
||||
initialValue: _timesPerDay,
|
||||
min: 1,
|
||||
max: 4,
|
||||
label: '次',
|
||||
);
|
||||
if (n != null) _updateTimes(n);
|
||||
},
|
||||
child: _PickerBox(
|
||||
child: Text('$_timesPerDay 次/天', style: AppTextStyles.formValue),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_label('服药时间'),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: List.generate(
|
||||
_timesPerDay,
|
||||
(i) => GestureDetector(
|
||||
onTap: () async {
|
||||
final t = await showAppTimePicker(
|
||||
context,
|
||||
initialTime: _times[i],
|
||||
);
|
||||
if (t != null) setState(() => _times[i] = t);
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 10,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.mdBorder,
|
||||
border: Border.all(color: AppColors.border, width: 1),
|
||||
),
|
||||
child: Text(
|
||||
'${_times[i].hour.toString().padLeft(2, '0')}:${_times[i].minute.toString().padLeft(2, '0')}',
|
||||
style: AppTextStyles.formValue,
|
||||
),
|
||||
bottomNavigationBar: _loading || _loadError != null
|
||||
? null
|
||||
: SafeArea(
|
||||
top: false,
|
||||
child: Container(
|
||||
color: Colors.white,
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
|
||||
child: AppGradientOutlineButton(
|
||||
label: _editing ? '保存修改' : '添加用药',
|
||||
onPressed: _saving ? null : _save,
|
||||
loading: _saving,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _dateField(
|
||||
'开始日期',
|
||||
_start,
|
||||
(d) => setState(() => _start = d),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _loadError != null
|
||||
? AppErrorState(title: _loadError!, onRetry: _load)
|
||||
: ListView(
|
||||
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: [
|
||||
_FormSection(
|
||||
title: '药品信息',
|
||||
children: [
|
||||
_TextFieldRow(
|
||||
label: '药品名称',
|
||||
controller: _nameController,
|
||||
hint: '请输入药品名称',
|
||||
),
|
||||
const _SectionDivider(),
|
||||
_TextFieldRow(
|
||||
label: '剂量',
|
||||
controller: _dosageController,
|
||||
hint: '例如 100 mg',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _dateFieldOpt(
|
||||
'结束日期(可选)',
|
||||
_end,
|
||||
(d) => setState(() => _end = d),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_field('备注', _notesCtrl, hint: '如:饭后服用、睡前'),
|
||||
const SizedBox(height: 32),
|
||||
_GradientOutlineButton(
|
||||
onPressed: _loading ? null : _save,
|
||||
label: _loading ? '保存中...' : '保存',
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _label(String text) => Text(text, style: AppTextStyles.formLabel);
|
||||
|
||||
Widget _field(String label, TextEditingController ctrl, {String? hint}) =>
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_label(label),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: ctrl,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
filled: true,
|
||||
fillColor: AppTheme.surface,
|
||||
border: _inputBorder(AppColors.border),
|
||||
enabledBorder: _inputBorder(AppColors.border),
|
||||
focusedBorder: _inputBorder(AppColors.primary),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
style: AppTextStyles.formValue,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget _dateField(String label, DateTime val, ValueChanged<DateTime> cb) =>
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_label(label),
|
||||
const SizedBox(height: 6),
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
final d = await showAppDatePicker(
|
||||
context,
|
||||
initialDate: val,
|
||||
firstDate: DateTime(2024),
|
||||
lastDate: DateTime(2030),
|
||||
);
|
||||
if (d != null) cb(d);
|
||||
},
|
||||
child: _PickerBox(
|
||||
child: Text(_displayDate(val), style: AppTextStyles.formValue),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget _dateFieldOpt(
|
||||
String label,
|
||||
DateTime? val,
|
||||
ValueChanged<DateTime?> cb,
|
||||
) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_label(label),
|
||||
const SizedBox(height: 6),
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
final d = await showAppDatePicker(
|
||||
context,
|
||||
initialDate: val ?? DateTime.now(),
|
||||
firstDate: DateTime(2024),
|
||||
lastDate: DateTime(2030),
|
||||
);
|
||||
if (d != null) cb(d);
|
||||
},
|
||||
child: _PickerBox(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
val != null ? _displayDate(val) : '不设置',
|
||||
style: AppTextStyles.formValue.copyWith(
|
||||
color: val != null ? null : AppTheme.textHint,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (val != null)
|
||||
GestureDetector(
|
||||
onTap: () => cb(null),
|
||||
child: const Icon(
|
||||
Icons.close,
|
||||
size: 19,
|
||||
color: AppColors.textHint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
OutlineInputBorder _inputBorder(Color color) => OutlineInputBorder(
|
||||
borderRadius: AppRadius.mdBorder,
|
||||
borderSide: BorderSide(color: color),
|
||||
);
|
||||
}
|
||||
|
||||
class _PickerBox extends StatelessWidget {
|
||||
final Widget child;
|
||||
|
||||
const _PickerBox({required this.child});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppTheme.surface,
|
||||
borderRadius: AppRadius.mdBorder,
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GradientOutlineButton extends StatelessWidget {
|
||||
final VoidCallback? onPressed;
|
||||
final String label;
|
||||
|
||||
const _GradientOutlineButton({required this.onPressed, required this.label});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final enabled = onPressed != null;
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
gradient: enabled ? AppColors.actionOutlineGradient : null,
|
||||
color: enabled ? null : AppColors.border,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
padding: const EdgeInsets.all(1.4),
|
||||
child: Material(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
child: SizedBox(
|
||||
height: 46,
|
||||
child: Center(
|
||||
child: enabled
|
||||
? ShaderMask(
|
||||
shaderCallback: (bounds) =>
|
||||
AppColors.actionOutlineGradient.createShader(bounds),
|
||||
child: Text(
|
||||
label,
|
||||
style: AppTextStyles.button.copyWith(
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
label,
|
||||
style: AppTextStyles.button.copyWith(
|
||||
color: AppColors.textHint,
|
||||
const SizedBox(height: 16),
|
||||
_FormSection(
|
||||
title: '服用安排',
|
||||
children: [
|
||||
_PickerRow(
|
||||
label: '每日次数',
|
||||
value: '${_times.length}次',
|
||||
onTap: _pickCount,
|
||||
),
|
||||
const _SectionDivider(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 11, 12, 11),
|
||||
child: Row(
|
||||
children: [
|
||||
const Text('服药时间', style: AppTextStyles.formLabel),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.end,
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: List.generate(
|
||||
_times.length,
|
||||
(index) => _TimeButton(
|
||||
value: _timeValue(_times[index]),
|
||||
onTap: () => _pickTime(index),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_FormSection(
|
||||
title: '用药周期',
|
||||
children: [
|
||||
_PickerRow(
|
||||
label: '开始日期',
|
||||
value: _displayDate(_startDate),
|
||||
onTap: _pickStartDate,
|
||||
),
|
||||
const _SectionDivider(),
|
||||
_PickerRow(
|
||||
label: '结束日期',
|
||||
value: _endDate == null ? '长期' : _displayDate(_endDate!),
|
||||
onTap: _pickEndDate,
|
||||
onClear: _endDate == null
|
||||
? null
|
||||
: () => setState(() => _endDate = null),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_FormSection(
|
||||
title: '备注',
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: TextField(
|
||||
controller: _notesController,
|
||||
minLines: 3,
|
||||
maxLines: 5,
|
||||
maxLength: 200,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '可填写饭前、饭后或其他用药要求(选填)',
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
filled: false,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_editing) ...[
|
||||
const SizedBox(height: 16),
|
||||
Material(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: _saving ? null : _deleteMedication,
|
||||
child: const SizedBox(
|
||||
height: 54,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'删除用药',
|
||||
style: TextStyle(
|
||||
color: AppColors.errorText,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickCount() async {
|
||||
final count = await showAppCountPicker(
|
||||
context,
|
||||
initialValue: _times.length,
|
||||
min: 1,
|
||||
max: 4,
|
||||
label: '次',
|
||||
);
|
||||
if (count == null || !mounted) return;
|
||||
setState(() {
|
||||
while (_times.length < count) {
|
||||
final hour = (8 + _times.length * 5).clamp(0, 23);
|
||||
_times.add(TimeOfDay(hour: hour, minute: 0));
|
||||
}
|
||||
while (_times.length > count) {
|
||||
_times.removeLast();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pickTime(int index) async {
|
||||
final value = await showAppTimePicker(context, initialTime: _times[index]);
|
||||
if (value != null && mounted) setState(() => _times[index] = value);
|
||||
}
|
||||
|
||||
Future<void> _pickStartDate() async {
|
||||
final value = await showAppDatePicker(
|
||||
context,
|
||||
initialDate: _startDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime(2035),
|
||||
);
|
||||
if (value != null && mounted) setState(() => _startDate = value);
|
||||
}
|
||||
|
||||
Future<void> _pickEndDate() async {
|
||||
final value = await showAppDatePicker(
|
||||
context,
|
||||
initialDate: _endDate ?? _startDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime(2035),
|
||||
);
|
||||
if (value != null && mounted) setState(() => _endDate = value);
|
||||
}
|
||||
}
|
||||
|
||||
class _FormSection extends StatelessWidget {
|
||||
final String title;
|
||||
final List<Widget> children;
|
||||
|
||||
const _FormSection({required this.title, required this.children});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 2, bottom: 8),
|
||||
child: Text(
|
||||
title,
|
||||
style: AppTextStyles.sectionTitle.copyWith(fontSize: 16),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
child: Column(children: children),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TextFieldRow extends StatelessWidget {
|
||||
final String label;
|
||||
final TextEditingController controller;
|
||||
final String hint;
|
||||
|
||||
const _TextFieldRow({
|
||||
required this.label,
|
||||
required this.controller,
|
||||
required this.hint,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 82,
|
||||
child: Text(label, style: AppTextStyles.formLabel),
|
||||
),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
textAlign: TextAlign.right,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
filled: false,
|
||||
contentPadding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
style: AppTextStyles.formValue,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PickerRow extends StatelessWidget {
|
||||
final String label;
|
||||
final String value;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback? onClear;
|
||||
|
||||
const _PickerRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.onTap,
|
||||
this.onClear,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 15, 10, 15),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(label, style: AppTextStyles.formLabel)),
|
||||
Text(value, style: AppTextStyles.formValue),
|
||||
if (onClear != null)
|
||||
IconButton(
|
||||
tooltip: '清除结束日期',
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: onClear,
|
||||
icon: const Icon(Icons.close, size: 18),
|
||||
)
|
||||
else
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 6),
|
||||
child: Icon(
|
||||
LucideIcons.chevronRight,
|
||||
color: AppColors.textHint,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _displayDate(DateTime date) {
|
||||
return '${date.year}/${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')}';
|
||||
class _TimeButton extends StatelessWidget {
|
||||
final String value;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _TimeButton({required this.value, required this.onTap});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return OutlinedButton.icon(
|
||||
onPressed: onTap,
|
||||
icon: const Icon(LucideIcons.clock, size: 18),
|
||||
label: Text(value),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.primary,
|
||||
side: BorderSide(color: AppColors.primary.withValues(alpha: 0.38)),
|
||||
shape: RoundedRectangleBorder(borderRadius: AppRadius.smBorder),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionDivider extends StatelessWidget {
|
||||
const _SectionDivider();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.only(left: 16),
|
||||
child: Divider(height: 1, thickness: 0.7, color: AppColors.divider),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
TimeOfDay? _parseTime(Object value) {
|
||||
final parts = value.toString().split(':');
|
||||
if (parts.length < 2) return null;
|
||||
final hour = int.tryParse(parts[0]);
|
||||
final minute = int.tryParse(parts[1]);
|
||||
if (hour == null || minute == null) return null;
|
||||
return TimeOfDay(hour: hour, minute: minute);
|
||||
}
|
||||
|
||||
String _timeValue(TimeOfDay value) =>
|
||||
'${value.hour.toString().padLeft(2, '0')}:${value.minute.toString().padLeft(2, '0')}';
|
||||
|
||||
String _dateValue(DateTime value) =>
|
||||
'${value.year}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
|
||||
|
||||
String _displayDate(DateTime value) => formatMedicationFormDate(value);
|
||||
|
||||
String _frequencyForTimes(int count) => switch (count) {
|
||||
2 => 'TwiceDaily',
|
||||
3 => 'ThreeTimesDaily',
|
||||
_ => 'Daily',
|
||||
};
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||
|
||||
import '../../core/api_client.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../core/app_design_tokens.dart';
|
||||
import '../../core/app_module_visuals.dart';
|
||||
@@ -8,20 +11,21 @@ import '../../core/navigation_provider.dart';
|
||||
import '../../providers/data_providers.dart';
|
||||
import '../../widgets/app_empty_state.dart';
|
||||
import '../../widgets/app_future_view.dart';
|
||||
import '../../widgets/app_status_badge.dart';
|
||||
import '../../widgets/common_widgets.dart';
|
||||
import '../../widgets/enterprise_widgets.dart';
|
||||
import '../../widgets/app_toast.dart';
|
||||
import '../../widgets/common_widgets.dart';
|
||||
import '../care_plan_ui_logic.dart';
|
||||
import 'medication_ui_logic.dart';
|
||||
|
||||
class MedicationListPage extends ConsumerStatefulWidget {
|
||||
const MedicationListPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<MedicationListPage> createState() => _MedicationListPageState();
|
||||
}
|
||||
|
||||
class _MedicationListPageState extends ConsumerState<MedicationListPage> {
|
||||
static const _medVisual = AppModuleVisuals.medication;
|
||||
Future<List<Map<String, dynamic>>>? _future;
|
||||
final Set<String> _deleting = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -29,22 +33,53 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
|
||||
_load();
|
||||
}
|
||||
|
||||
void _load() {
|
||||
setState(() {
|
||||
_future = ref.read(medicationServiceProvider).getMedications('');
|
||||
});
|
||||
void _load() => setState(() {
|
||||
_future = ref.read(medicationServiceProvider).getMedications('');
|
||||
});
|
||||
|
||||
Future<void> _refresh() async {
|
||||
_load();
|
||||
await _future;
|
||||
}
|
||||
|
||||
Future<void> _delete(String id) async {
|
||||
Future<void> _confirmDelete(String id, String name) async {
|
||||
if (id.isEmpty || _deleting.contains(id)) return;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('删除用药'),
|
||||
content: Text('确定删除“$name”吗?相关服药记录也将一并删除。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
setState(() => _deleting.add(id));
|
||||
try {
|
||||
await ref.read(medicationServiceProvider).deleteMedication(id);
|
||||
ref.invalidate(medicationListProvider);
|
||||
ref.invalidate(medicationReminderProvider);
|
||||
_load();
|
||||
if (mounted) AppToast.show(context, '已删除', type: AppToastType.success);
|
||||
} catch (_) {
|
||||
if (mounted) AppToast.show(context, '用药已删除', type: AppToastType.success);
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
AppToast.show(context, '删除失败,请稍后重试', type: AppToastType.error);
|
||||
AppToast.show(
|
||||
context,
|
||||
error is ApiException ? error.message : '删除失败,请稍后重试',
|
||||
type: AppToastType.error,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _deleting.remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,83 +93,67 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
|
||||
),
|
||||
title: const Text('用药管理'),
|
||||
),
|
||||
floatingActionButton: _GradientFab(
|
||||
gradient: _medVisual.gradient,
|
||||
onTap: () => pushRoute(ref, 'medicationEdit'),
|
||||
floatingActionButton: AppCreateFab(
|
||||
tooltip: '添加用药',
|
||||
onPressed: () => pushRoute(ref, 'medicationEdit'),
|
||||
),
|
||||
body: AppFutureView<List<Map<String, dynamic>>>(
|
||||
future: _future,
|
||||
onRetry: _load,
|
||||
errorTitle: '用药信息加载失败',
|
||||
onData: (ctx, list) {
|
||||
if (list.isEmpty) {
|
||||
onData: (_, medications) {
|
||||
if (medications.isEmpty) {
|
||||
return AppEmptyState(
|
||||
icon: _medVisual.icon,
|
||||
icon: AppModuleVisuals.medication.icon,
|
||||
title: '暂无用药',
|
||||
subtitle: '点击右下角➕添加药品',
|
||||
subtitle: '点击右下角添加药品',
|
||||
iconColor: AppColors.medication,
|
||||
);
|
||||
}
|
||||
final activeCount = list.where((m) => m['isActive'] == true).length;
|
||||
final reminderCount = list.where((m) {
|
||||
final times = m['timeOfDay'] as List?;
|
||||
return times != null && times.isNotEmpty;
|
||||
}).length;
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 88),
|
||||
children: [
|
||||
EnterpriseHeader(
|
||||
title: '今日用药概览',
|
||||
subtitle: '集中管理服药计划、剂量和每日打卡状态',
|
||||
icon: _medVisual.icon,
|
||||
color: _medVisual.color,
|
||||
accent: AppColors.primary,
|
||||
showIcon: false,
|
||||
stats: [
|
||||
EnterpriseStat(
|
||||
label: '药品总数',
|
||||
value: '${list.length} 个',
|
||||
icon: Icons.inventory_2_outlined,
|
||||
),
|
||||
EnterpriseStat(
|
||||
label: '服用中',
|
||||
value: '$activeCount 个',
|
||||
icon: Icons.check_circle_outline,
|
||||
),
|
||||
EnterpriseStat(
|
||||
label: '有提醒',
|
||||
value: '$reminderCount 个',
|
||||
icon: Icons.alarm_outlined,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_MedicationListGroup(
|
||||
children: List.generate(list.length, (i) {
|
||||
final m = list[i];
|
||||
final times =
|
||||
(m['timeOfDay'] as List?)
|
||||
?.map((t) => t.toString().substring(0, 5))
|
||||
.join(' ') ??
|
||||
'';
|
||||
final isActive = m['isActive'] == true;
|
||||
final id = m['id']?.toString() ?? '';
|
||||
return SwipeDeleteTile(
|
||||
key: Key(id),
|
||||
onDelete: () => _delete(id),
|
||||
onTap: () =>
|
||||
pushRoute(ref, 'medCheckIn', params: {'id': id}),
|
||||
margin: EdgeInsets.zero,
|
||||
child: _MedicationRow(
|
||||
name: m['name']?.toString() ?? '',
|
||||
subtitle: '${m['dosage'] ?? ''} $times',
|
||||
isActive: isActive,
|
||||
showDivider: i < list.length - 1,
|
||||
visual: _medVisual,
|
||||
final groups = <CarePlanPhase, List<Map<String, dynamic>>>{
|
||||
for (final phase in CarePlanPhase.values) phase: [],
|
||||
};
|
||||
for (final medication in medications) {
|
||||
final phase = resolveCarePlanPhase(
|
||||
enabled: medication['isActive'] == true,
|
||||
startDate: medication['startDate']?.toString(),
|
||||
endDate: medication['endDate']?.toString(),
|
||||
);
|
||||
groups[phase]!.add(medication);
|
||||
}
|
||||
final active = groups[CarePlanPhase.active]!;
|
||||
final doseCount = active.fold<int>(
|
||||
0,
|
||||
(sum, item) => sum + ((item['timeOfDay'] as List?)?.length ?? 0),
|
||||
);
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: AppSpacing.pageWithFab,
|
||||
children: [
|
||||
_MedicationOverview(
|
||||
activeCount: active.length,
|
||||
doseCount: doseCount,
|
||||
nextReminder: _nextReminder(active),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
for (final phase in CarePlanPhase.values)
|
||||
if (groups[phase]!.isNotEmpty) ...[
|
||||
_MedicationPhaseGroup(
|
||||
phase: phase,
|
||||
medications: groups[phase]!,
|
||||
deleting: _deleting,
|
||||
onOpen: (id) =>
|
||||
pushRoute(ref, 'medCheckIn', params: {'id': id}),
|
||||
onEdit: (id) =>
|
||||
pushRoute(ref, 'medicationEdit', params: {'id': id}),
|
||||
onDelete: _confirmDelete,
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 18),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -142,104 +161,223 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
|
||||
}
|
||||
}
|
||||
|
||||
class _GradientFab extends StatelessWidget {
|
||||
final Gradient gradient;
|
||||
final VoidCallback onTap;
|
||||
class _MedicationOverview extends StatelessWidget {
|
||||
final int activeCount;
|
||||
final int doseCount;
|
||||
final String? nextReminder;
|
||||
|
||||
const _GradientFab({required this.gradient, required this.onTap});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
gradient: gradient,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppColors.medication.withValues(alpha: 0.22),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 8),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
child: const Icon(Icons.add, size: 28, color: Colors.white),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MedicationListGroup extends StatelessWidget {
|
||||
final List<Widget> children;
|
||||
|
||||
const _MedicationListGroup({required this.children});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.xlBorder,
|
||||
),
|
||||
child: Column(children: children),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MedicationRow extends StatelessWidget {
|
||||
final String name;
|
||||
final String subtitle;
|
||||
final bool isActive;
|
||||
final bool showDivider;
|
||||
final AppModuleVisual visual;
|
||||
|
||||
const _MedicationRow({
|
||||
required this.name,
|
||||
required this.subtitle,
|
||||
required this.isActive,
|
||||
required this.showDivider,
|
||||
required this.visual,
|
||||
const _MedicationOverview({
|
||||
required this.activeCount,
|
||||
required this.doseCount,
|
||||
required this.nextReminder,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
padding: AppSpacing.panel,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Expanded(
|
||||
child: Text('用药概览', style: AppTextStyles.sectionTitle),
|
||||
),
|
||||
Text(
|
||||
nextReminder == null ? '今日已无待服' : '下次 $nextReminder',
|
||||
style: AppTextStyles.listSubtitle.copyWith(
|
||||
color: nextReminder == null
|
||||
? AppColors.successText
|
||||
: AppColors.textSecondary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _OverviewValue(
|
||||
value: '$activeCount种',
|
||||
label: '正在服用',
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
Container(width: 1, height: 46, color: AppColors.divider),
|
||||
Expanded(
|
||||
child: _OverviewValue(
|
||||
value: '$doseCount次',
|
||||
label: '今日安排',
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OverviewValue extends StatelessWidget {
|
||||
final String value;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
const _OverviewValue({
|
||||
required this.value,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
Text(value, style: AppTextStyles.summaryTitle.copyWith(color: color)),
|
||||
const SizedBox(height: 2),
|
||||
Text(label, style: AppTextStyles.listSubtitle.copyWith(fontSize: 13)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MedicationPhaseGroup extends StatelessWidget {
|
||||
final CarePlanPhase phase;
|
||||
final List<Map<String, dynamic>> medications;
|
||||
final Set<String> deleting;
|
||||
final ValueChanged<String> onOpen;
|
||||
final ValueChanged<String> onEdit;
|
||||
final Future<void> Function(String, String) onDelete;
|
||||
|
||||
const _MedicationPhaseGroup({
|
||||
required this.phase,
|
||||
required this.medications,
|
||||
required this.deleting,
|
||||
required this.onOpen,
|
||||
required this.onEdit,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _phaseColor(phase);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 2, bottom: 9),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'${_phaseLabel(phase)}(${medications.length})',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: AppRadius.lgBorder,
|
||||
),
|
||||
child: Column(
|
||||
children: List.generate(medications.length, (index) {
|
||||
final medication = medications[index];
|
||||
final id = medication['id']?.toString() ?? '';
|
||||
final name =
|
||||
medication['name']?.toString().trim().isNotEmpty == true
|
||||
? medication['name'].toString().trim()
|
||||
: '未命名药品';
|
||||
final isDeleting = deleting.contains(id);
|
||||
return SwipeDeleteTile(
|
||||
key: ValueKey(id),
|
||||
margin: EdgeInsets.zero,
|
||||
borderRadius: BorderRadius.zero,
|
||||
enabled: !isDeleting,
|
||||
onDelete: () => onDelete(id, name),
|
||||
child: _MedicationRow(
|
||||
medication: medication,
|
||||
phase: phase,
|
||||
deleting: isDeleting,
|
||||
showDivider: index < medications.length - 1,
|
||||
onOpen: () => onOpen(id),
|
||||
onEdit: () => onEdit(id),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MedicationRow extends StatelessWidget {
|
||||
final Map<String, dynamic> medication;
|
||||
final CarePlanPhase phase;
|
||||
final bool deleting;
|
||||
final bool showDivider;
|
||||
final VoidCallback onOpen;
|
||||
final VoidCallback onEdit;
|
||||
|
||||
const _MedicationRow({
|
||||
required this.medication,
|
||||
required this.phase,
|
||||
required this.deleting,
|
||||
required this.showDivider,
|
||||
required this.onOpen,
|
||||
required this.onEdit,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final name = medication['name']?.toString() ?? '未命名药品';
|
||||
final dosage = medication['dosage']?.toString().trim() ?? '';
|
||||
final times =
|
||||
(medication['timeOfDay'] as List?)
|
||||
?.map((time) => _formatTime(time.toString()))
|
||||
.join('、') ??
|
||||
'';
|
||||
return InkWell(
|
||||
onTap: deleting ? null : onOpen,
|
||||
child: Stack(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppTheme.sLg,
|
||||
vertical: 13,
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 6, 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
gradient: isActive
|
||||
? visual.gradient
|
||||
: AppColors.surfaceGradient,
|
||||
borderRadius: AppRadius.mdBorder,
|
||||
border: Border.all(color: AppColors.borderLight),
|
||||
color: _phaseColor(phase).withValues(alpha: 0.10),
|
||||
borderRadius: AppRadius.smBorder,
|
||||
),
|
||||
child: Icon(
|
||||
visual.icon,
|
||||
size: 25,
|
||||
color: isActive ? Colors.white : AppTheme.textSub,
|
||||
AppModuleVisuals.medication.icon,
|
||||
color: _phaseColor(phase),
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppTheme.sMd),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -252,45 +390,66 @@ class _MedicationRow extends StatelessWidget {
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: AppTextStyles.listTitle.copyWith(
|
||||
color: isActive
|
||||
? AppTheme.text
|
||||
: AppTheme.textSub,
|
||||
fontSize: 17,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (!isActive) ...[
|
||||
const SizedBox(width: 6),
|
||||
AppStatusBadge(label: '已停', color: visual.color),
|
||||
if (dosage.isNotEmpty) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(dosage, style: AppTextStyles.tag),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
subtitle,
|
||||
times.isEmpty ? '未设置服药时间' : times,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: AppTextStyles.listSubtitle.copyWith(
|
||||
color: AppTheme.textSub,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_periodText(medication),
|
||||
style: AppTextStyles.listSubtitle.copyWith(
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 21,
|
||||
color: AppColors.textHint,
|
||||
),
|
||||
if (deleting)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(12),
|
||||
child: SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
tooltip: '编辑用药',
|
||||
onPressed: onEdit,
|
||||
icon: const Icon(
|
||||
LucideIcons.pencil,
|
||||
size: 21,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (showDivider)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 74),
|
||||
const Positioned(
|
||||
left: 68,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Divider(
|
||||
height: 1,
|
||||
thickness: 0.7,
|
||||
color: Color(0xFFE8ECF2),
|
||||
color: AppColors.divider,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -298,3 +457,40 @@ class _MedicationRow extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String? _nextReminder(List<Map<String, dynamic>> medications) {
|
||||
final now = TimeOfDay.now();
|
||||
final nowMinutes = now.hour * 60 + now.minute;
|
||||
final times =
|
||||
medications
|
||||
.expand((item) => (item['timeOfDay'] as List?) ?? const [])
|
||||
.map((value) => _formatTime(value.toString()))
|
||||
.where((value) => value.length == 5)
|
||||
.toList()
|
||||
..sort();
|
||||
for (final time in times) {
|
||||
final parts = time.split(':');
|
||||
final minutes =
|
||||
(int.tryParse(parts[0]) ?? 0) * 60 + (int.tryParse(parts[1]) ?? 0);
|
||||
if (minutes >= nowMinutes) return time;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _periodText(Map<String, dynamic> medication) {
|
||||
return formatMedicationPeriod(medication['startDate'], medication['endDate']);
|
||||
}
|
||||
|
||||
String _formatTime(String raw) => raw.length >= 5 ? raw.substring(0, 5) : raw;
|
||||
|
||||
String _phaseLabel(CarePlanPhase phase) => switch (phase) {
|
||||
CarePlanPhase.active => '正在服用',
|
||||
CarePlanPhase.upcoming => '即将开始',
|
||||
CarePlanPhase.ended => '已结束',
|
||||
};
|
||||
|
||||
Color _phaseColor(CarePlanPhase phase) => switch (phase) {
|
||||
CarePlanPhase.active => AppColors.successText,
|
||||
CarePlanPhase.upcoming => AppColors.blueMeasure,
|
||||
CarePlanPhase.ended => AppColors.textHint,
|
||||
};
|
||||
|
||||
33
health_app/lib/pages/medication/medication_ui_logic.dart
Normal file
33
health_app/lib/pages/medication/medication_ui_logic.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
String formatMedicationPeriod(
|
||||
Object? startValue,
|
||||
Object? endValue, {
|
||||
DateTime? now,
|
||||
}) {
|
||||
final start = DateTime.tryParse(startValue?.toString() ?? '');
|
||||
final end = DateTime.tryParse(endValue?.toString() ?? '');
|
||||
if (start == null && end == null) return '长期';
|
||||
final reference = now ?? DateTime.now();
|
||||
if (start == null) return '-- - ${_compactMedicationDate(end!, reference)}';
|
||||
final startText = _compactMedicationDate(start, reference, other: end);
|
||||
if (end == null) return '$startText - 长期';
|
||||
final endText = _compactMedicationDate(end, reference, other: start);
|
||||
return '$startText - $endText';
|
||||
}
|
||||
|
||||
String _compactMedicationDate(
|
||||
DateTime date,
|
||||
DateTime reference, {
|
||||
DateTime? other,
|
||||
}) {
|
||||
final showYear =
|
||||
date.year != reference.year || (other != null && other.year != date.year);
|
||||
final month = date.month.toString().padLeft(2, '0');
|
||||
final day = date.day.toString().padLeft(2, '0');
|
||||
return showYear ? '${date.year}.$month.$day' : '$month.$day';
|
||||
}
|
||||
|
||||
String formatMedicationFormDate(DateTime value) {
|
||||
final month = value.month.toString().padLeft(2, '0');
|
||||
final day = value.day.toString().padLeft(2, '0');
|
||||
return '${value.year}-$month-$day';
|
||||
}
|
||||
Reference in New Issue
Block a user