Files
AeroTrack/lib/screens/medicine_cabinet_screen.dart
T

740 lines
27 KiB
Dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/medicine_item.dart';
import '../services/medicine_parser_service.dart';
import '../services/storage_service.dart';
import '../services/sync_service.dart';
import 'medicine_edit_dialog.dart';
import 'medicine_scan_screen.dart';
class MedicineCabinetScreen extends StatefulWidget {
final StorageService storageService;
final SyncService syncService;
const MedicineCabinetScreen({
super.key,
required this.storageService,
required this.syncService,
});
@override
State<MedicineCabinetScreen> createState() => _MedicineCabinetScreenState();
}
class _MedicineCabinetScreenState extends State<MedicineCabinetScreen> {
List<MedicineItem> _medicines = [];
String _selectedFilter = '全部';
String _searchQuery = '';
bool _isSyncing = false;
final List<String> _filters = [
'全部',
'常温药箱',
'冰箱冷藏',
'宝宝专用',
'已开封',
'⚠️ 需处理',
];
@override
void initState() {
super.initState();
_loadMedicines();
}
void _loadMedicines() {
setState(() {
_medicines = widget.storageService.getMedicines();
});
}
Future<void> _performSync() async {
if (_isSyncing) return;
setState(() => _isSyncing = true);
final res = await widget.syncService.performSync();
if (mounted) {
setState(() => _isSyncing = false);
_loadMedicines();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(res.message),
backgroundColor: res.success ? const Color(0xFF059669) : Colors.red,
duration: const Duration(seconds: 3),
),
);
}
}
Future<void> _openScan() async {
final result = await Navigator.of(context).push<ScannedMedicineInfo>(
MaterialPageRoute(builder: (_) => const MedicineScanScreen()),
);
if (result != null && mounted) {
final savedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => MedicineEditDialog(scannedInfo: result),
);
if (savedItem != null) {
await widget.storageService.saveMedicine(savedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已添加药品:${savedItem.name}')),
);
}
}
}
}
Future<void> _addNewMedicine() async {
final savedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => const MedicineEditDialog(),
);
if (savedItem != null) {
await widget.storageService.saveMedicine(savedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已添加药品:${savedItem.name}')),
);
}
}
}
Future<void> _editMedicine(MedicineItem item) async {
final updatedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => MedicineEditDialog(initialItem: item),
);
if (updatedItem != null) {
await widget.storageService.saveMedicine(updatedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已更新药品:${updatedItem.name}')),
);
}
}
}
Future<void> _deleteMedicine(MedicineItem item) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('确认下架/删除该药品?'),
content: Text('确定将【${item.name}】移出药箱吗?该操作将同步至所有设备。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('确认删除', style: TextStyle(color: Colors.white)),
),
],
),
);
if (confirmed == true) {
await widget.storageService.deleteMedicine(item.id);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已移出药品:${item.name}')),
);
}
}
}
Future<void> _openMedicineCard(MedicineItem item) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('确认开封打卡?'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('药品:${item.name}'),
const SizedBox(height: 8),
Text(
'推荐开封保质期限:${item.shelfLifeDaysAfterOpening ?? 60} 天',
style: const TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2563EB)),
),
const SizedBox(height: 8),
const Text(
'打卡后将自动开启开封保质期倒计时,全家设备实时同步。',
style: TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF2563EB)),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('确认开封', style: TextStyle(color: Colors.white)),
),
],
),
);
if (confirmed == true) {
final deviceName = await SyncService.getDeviceName();
await widget.storageService.openMedicine(item.id, deviceName: deviceName);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('【${item.name}】已成功打卡开封!')),
);
}
}
}
List<MedicineItem> get _filteredMedicines {
return _medicines.where((m) {
// 搜索关键字匹配
if (_searchQuery.isNotEmpty) {
final q = _searchQuery.toLowerCase();
final matchName = m.name.toLowerCase().contains(q);
final matchSpec = m.spec.toLowerCase().contains(q);
final matchNotes = m.notes.toLowerCase().contains(q);
if (!matchName && !matchSpec && !matchNotes) return false;
}
// 标签筛选
switch (_selectedFilter) {
case '常温药箱':
return m.storageLocation.contains('常温');
case '冰箱冷藏':
return m.storageLocation.contains('冷藏') || m.storageLocation.contains('冰箱');
case '宝宝专用':
return m.targetUser.contains('宝宝');
case '已开封':
return m.isOpened;
case '⚠️ 需处理':
return m.healthStatus == MedicineHealthStatus.expiringSoon ||
m.healthStatus == MedicineHealthStatus.overdueInUse ||
m.healthStatus == MedicineHealthStatus.expired;
case '全部':
default:
return true;
}
}).toList();
}
@override
Widget build(BuildContext context) {
// 统计指标
final totalCount = _medicines.length;
final safeCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.safe).length;
final soonCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length;
final dangerCount = _medicines.where((m) =>
m.healthStatus == MedicineHealthStatus.overdueInUse ||
m.healthStatus == MedicineHealthStatus.expired).length;
final displayList = _filteredMedicines;
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
appBar: AppBar(
title: const Text('家庭智能药箱', style: TextStyle(fontWeight: FontWeight.bold)),
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF0F172A),
elevation: 0.5,
actions: [
IconButton(
icon: _isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync, color: Color(0xFF2563EB)),
tooltip: '局域网全家同步',
onPressed: _isSyncing ? null : _performSync,
),
IconButton(
icon: const Icon(Icons.qr_code_scanner, color: Color(0xFF2563EB)),
tooltip: '扫码录药',
onPressed: _openScan,
),
],
),
body: Column(
children: [
// 1. 顶部健康看板统计卡片
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
color: Colors.white,
child: Row(
children: [
_buildStatMetric(
label: '在库药品',
count: totalCount,
color: const Color(0xFF334155),
isSelected: _selectedFilter == '全部',
onTap: () => setState(() => _selectedFilter = '全部'),
),
_buildStatMetric(
label: '安全正常',
count: safeCount,
color: const Color(0xFF10B981),
isSelected: false,
onTap: () => setState(() => _selectedFilter = '全部'),
),
_buildStatMetric(
label: '临期预警',
count: soonCount,
color: const Color(0xFFF59E0B),
isSelected: _selectedFilter == '⚠️ 需处理',
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
),
_buildStatMetric(
label: '超期/过期',
count: dangerCount,
color: const Color(0xFFEF4444),
isSelected: _selectedFilter == '⚠️ 需处理',
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
),
],
),
),
// 2. 搜索框与过滤器标签
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: Colors.white,
child: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: '搜索药品名、规格、适应症...',
prefixIcon: const Icon(Icons.search, size: 20, color: Colors.grey),
isDense: true,
filled: true,
fillColor: const Color(0xFFF1F5F9),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(vertical: 8),
),
onChanged: (val) => setState(() => _searchQuery = val.trim()),
),
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: _filters.map((f) {
final selected = _selectedFilter == f;
return Padding(
padding: const EdgeInsets.only(right: 8),
child: ChoiceChip(
label: Text(f),
selected: selected,
selectedColor: const Color(0xFF2563EB),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _selectedFilter = f);
},
),
);
}).toList(),
),
),
],
),
),
// 3. 药品列表
Expanded(
child: displayList.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.inventory_2_outlined, size: 56, color: Colors.grey.shade400),
const SizedBox(height: 12),
Text(
_searchQuery.isNotEmpty ? '没有找到符合的药品' : '药箱里还没有此类药品',
style: TextStyle(color: Colors.grey.shade600),
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _openScan,
icon: const Icon(Icons.qr_code_scanner),
label: const Text('扫描药品条码/追溯码录入'),
),
],
),
)
: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: displayList.length,
itemBuilder: (ctx, idx) {
return _buildMedicineCard(displayList[idx]);
},
),
),
],
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton.small(
heroTag: 'fab_manual',
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF2563EB),
tooltip: '手动添加药品',
onPressed: _addNewMedicine,
child: const Icon(Icons.edit_note),
),
const SizedBox(height: 10),
FloatingActionButton.extended(
heroTag: 'fab_scan',
backgroundColor: const Color(0xFF2563EB),
foregroundColor: Colors.white,
icon: const Icon(Icons.qr_code_scanner),
label: const Text('扫码录药'),
onPressed: _openScan,
),
],
),
);
}
Widget _buildStatMetric({
required String label,
required int count,
required Color color,
required bool isSelected,
required VoidCallback onTap,
}) {
return Expanded(
child: GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
color: isSelected ? color.withValues(alpha: 0.1) : Colors.transparent,
borderRadius: BorderRadius.circular(8),
),
child: Column(
children: [
Text(
count.toString(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 2),
Text(
label,
style: const TextStyle(fontSize: 11, color: Colors.black54),
),
],
),
),
),
);
}
Widget _buildMedicineCard(MedicineItem item) {
final dateFormat = DateFormat('yyyy/MM/dd');
final isDanger = item.healthStatus == MedicineHealthStatus.overdueInUse ||
item.healthStatus == MedicineHealthStatus.expired;
final isWarning = item.healthStatus == MedicineHealthStatus.expiringSoon;
Color borderColor = Colors.grey.shade200;
if (isDanger) borderColor = Colors.red.shade300;
if (isWarning) borderColor = Colors.amber.shade300;
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(color: borderColor, width: isDanger ? 1.5 : 1),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 卡片头部:图标、名称、状态 Badge 与操作菜单
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: item.category.icon == Icons.air
? const Color(0xFFEFF6FF)
: const Color(0xFFF1F5F9),
borderRadius: BorderRadius.circular(10),
),
child: Icon(item.category.icon, color: const Color(0xFF2563EB), size: 22),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFF0F172A),
),
),
if (item.spec.isNotEmpty)
Text(
'规格: ${item.spec}',
style: const TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: item.healthStatusColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: Text(
item.healthStatusLabel,
style: TextStyle(
color: item.healthStatusColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 20, color: Colors.grey),
onSelected: (val) {
if (val == 'edit') _editMedicine(item);
if (val == 'delete') _deleteMedicine(item);
},
itemBuilder: (ctx) => [
const PopupMenuItem(value: 'edit', child: Text('编辑药品')),
const PopupMenuItem(
value: 'delete',
child: Text('移出药箱', style: TextStyle(color: Colors.red)),
),
],
),
],
),
const SizedBox(height: 10),
// 存放标签与成员胶囊
Wrap(
spacing: 6,
children: [
_buildTagChip(
icon: item.storageLocation.contains('冷藏')
? Icons.ac_unit
: Icons.inventory_2_outlined,
text: item.storageLocation,
color: item.storageLocation.contains('冷藏')
? const Color(0xFF0284C7)
: const Color(0xFF64748B),
),
_buildTagChip(
icon: Icons.person_outline,
text: item.targetUser,
color: const Color(0xFFD97706),
),
if (item.barcode != null && item.barcode!.isNotEmpty)
_buildTagChip(
icon: Icons.qr_code,
text: item.barcode!.length > 13
? '追溯码 ${item.barcode!.substring(0, 6)}...'
: item.barcode!,
color: const Color(0xFF64748B),
),
],
),
const SizedBox(height: 12),
// 出厂保质期与开封情况
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(8),
),
child: Column(
children: [
Row(
children: [
const Icon(Icons.event_outlined, size: 14, color: Colors.black54),
const SizedBox(width: 4),
Text(
'出厂有效期至: ${dateFormat.format(item.expiryDate)}',
style: const TextStyle(fontSize: 12, color: Colors.black87),
),
const Spacer(),
Text(
item.daysUntilExpiry >= 0
? '剩 ${item.daysUntilExpiry} 天'
: '已过期 ${-item.daysUntilExpiry} 天',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: item.daysUntilExpiry <= 30 ? Colors.red : const Color(0xFF059669),
),
),
],
),
// 若已开封
if (item.isOpened && item.openedAt != null) ...[
const SizedBox(height: 6),
Row(
children: [
const Icon(Icons.lock_open, size: 14, color: Color(0xFF2563EB)),
const SizedBox(width: 4),
Text(
'已开封 (${dateFormat.format(item.openedAt!)})',
style: const TextStyle(fontSize: 12, color: Color(0xFF2563EB)),
),
const Spacer(),
if (item.shelfLifeDaysAfterOpening != null) ...[
Text(
(item.daysUntilInUseExpiry ?? 0) >= 0
? '开封保质剩 ${item.daysUntilInUseExpiry} 天'
: '开封超期 ${-(item.daysUntilInUseExpiry ?? 0)} 天',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: (item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.red : const Color(0xFF2563EB),
),
),
],
],
),
if (item.shelfLifeDaysAfterOpening != null) ...[
const SizedBox(height: 6),
LinearProgressIndicator(
value: (item.daysSinceOpened ?? 0) / item.shelfLifeDaysAfterOpening!,
backgroundColor: Colors.grey.shade200,
valueColor: AlwaysStoppedAnimation<Color>(
(item.daysUntilInUseExpiry ?? 0) < 0
? Colors.red
: ((item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.amber : const Color(0xFF2563EB)),
),
minHeight: 4,
borderRadius: BorderRadius.circular(2),
),
],
],
],
),
),
// 未开封一键打卡按钮
if (!item.isOpened) ...[
const SizedBox(height: 10),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF2563EB),
side: const BorderSide(color: Color(0xFF93C5FD)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
padding: const EdgeInsets.symmetric(vertical: 8),
),
onPressed: () => _openMedicineCard(item),
icon: const Icon(Icons.check_circle_outline, size: 16),
label: const Text('点击打卡开封 (开启保质倒计时)'),
),
),
],
// 危险警告提醒条 (超期或过期)
if (isDanger) ...[
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFFEF2F2),
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
const Icon(Icons.warning_amber_rounded, size: 16, color: Colors.red),
const SizedBox(width: 6),
Expanded(
child: Text(
item.healthStatus == MedicineHealthStatus.overdueInUse
? '已超出开封后推荐使用期限,易滋生细菌/失效,建议丢弃更换。'
: '已超出出厂有效期,严禁继续使用!',
style: const TextStyle(color: Colors.red, fontSize: 11, fontWeight: FontWeight.w600),
),
),
],
),
),
],
// 适应症备注
if (item.notes.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
'备忘: ${item.notes}',
style: const TextStyle(fontSize: 11, color: Colors.black54),
),
],
],
),
),
);
}
Widget _buildTagChip({
required IconData icon,
required String text,
required Color color,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 12, color: color),
const SizedBox(width: 3),
Text(
text,
style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.w500),
),
],
),
);
}
}