Files
AeroTrack/lib/screens/medicine_edit_dialog.dart
T

590 lines
24 KiB
Dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import '../models/medicine_item.dart';
import '../services/medicine_parser_service.dart';
class MedicineEditDialog extends StatefulWidget {
final MedicineItem? initialItem;
final ScannedMedicineInfo? scannedInfo;
const MedicineEditDialog({
super.key,
this.initialItem,
this.scannedInfo,
});
@override
State<MedicineEditDialog> createState() => _MedicineEditDialogState();
}
class _MedicineEditDialogState extends State<MedicineEditDialog> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _nameController;
late TextEditingController _specController;
late TextEditingController _barcodeController;
late TextEditingController _batchNumberController;
late TextEditingController _shelfLifeDaysController;
late TextEditingController _notesController;
late MedicineCategory _category;
late String _storageLocation;
late String _targetUser;
late DateTime _expiryDate;
DateTime? _productionDate;
late bool _isOpened;
DateTime? _openedAt;
final List<String> _commonLocations = [
'常温药箱',
'冰箱冷藏 (2-8℃)',
'随身急救包',
'卧室床头',
];
final List<String> _commonUsers = [
'宝宝',
'全家',
'爸爸',
'妈妈',
'老人',
];
@override
void initState() {
super.initState();
final init = widget.initialItem;
final scan = widget.scannedInfo;
final now = DateTime.now();
_nameController = TextEditingController(
text: init?.name ?? scan?.name ?? '',
);
_specController = TextEditingController(
text: init?.spec ?? scan?.spec ?? '',
);
_barcodeController = TextEditingController(
text: init?.barcode ?? scan?.barcode ?? '',
);
_batchNumberController = TextEditingController(
text: init?.batchNumber ?? scan?.batchNumber ?? '',
);
_category = init?.category ?? scan?.category ?? MedicineCategory.oralLiquid;
_storageLocation = init?.storageLocation ?? scan?.storageLocation ?? '常温药箱';
_targetUser = init?.targetUser ?? scan?.targetUser ?? '宝宝';
_expiryDate = init?.expiryDate ??
scan?.expiryDate ??
DateTime(now.year + 2, now.month, now.day);
_productionDate = init?.productionDate ?? scan?.productionDate;
final defaultShelfLife = _category.defaultShelfLifeDaysAfterOpening;
final initShelfLife = init?.shelfLifeDaysAfterOpening ??
scan?.shelfLifeDaysAfterOpening ??
defaultShelfLife;
_shelfLifeDaysController = TextEditingController(
text: initShelfLife != null ? initShelfLife.toString() : '',
);
_isOpened = init?.isOpened ?? false;
_openedAt = init?.openedAt ?? (_isOpened ? now : null);
_notesController = TextEditingController(
text: init?.notes ?? scan?.notes ?? '',
);
}
@override
void dispose() {
_nameController.dispose();
_specController.dispose();
_barcodeController.dispose();
_batchNumberController.dispose();
_shelfLifeDaysController.dispose();
_notesController.dispose();
super.dispose();
}
void _onCategoryChanged(MedicineCategory newCat) {
setState(() {
_category = newCat;
final defaultDays = newCat.defaultShelfLifeDaysAfterOpening;
if (defaultDays != null && _shelfLifeDaysController.text.isEmpty) {
_shelfLifeDaysController.text = defaultDays.toString();
}
});
}
Future<void> _pickExpiryDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _expiryDate,
firstDate: DateTime(2020),
lastDate: DateTime(2035),
helpText: '选择药品出厂有效期至',
);
if (picked != null) {
setState(() => _expiryDate = picked);
}
}
Future<void> _pickProductionDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _productionDate ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now(),
helpText: '选择药品生产日期 (选填)',
);
if (picked != null) {
setState(() => _productionDate = picked);
}
}
Future<void> _pickOpenedDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _openedAt ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now(),
helpText: '选择开封日期',
);
if (picked != null) {
setState(() => _openedAt = picked);
}
}
void _save() {
if (!_formKey.currentState!.validate()) return;
final nowUtc = DateTime.now().toUtc();
final shelfLife = int.tryParse(_shelfLifeDaysController.text.trim());
final item = MedicineItem(
id: widget.initialItem?.id ?? const Uuid().v4(),
name: _nameController.text.trim(),
category: _category,
spec: _specController.text.trim(),
storageLocation: _storageLocation,
targetUser: _targetUser,
barcode: _barcodeController.text.trim().isNotEmpty ? _barcodeController.text.trim() : null,
batchNumber: _batchNumberController.text.trim().isNotEmpty ? _batchNumberController.text.trim() : null,
productionDate: _productionDate,
expiryDate: _expiryDate,
shelfLifeDaysAfterOpening: shelfLife,
isOpened: _isOpened,
openedAt: _isOpened ? (_openedAt ?? DateTime.now()) : null,
openedByDevice: widget.initialItem?.openedByDevice,
notes: _notesController.text.trim(),
isDeleted: false,
updatedAt: nowUtc,
);
Navigator.of(context).pop(item);
}
@override
Widget build(BuildContext context) {
final isEditing = widget.initialItem != null;
final dateFormat = DateFormat('yyyy年MM月dd日');
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
child: Container(
constraints: const BoxConstraints(maxWidth: 520, maxHeight: 720),
child: Column(
children: [
// 标题栏
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
decoration: const BoxDecoration(
color: Color(0xFF2563EB),
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Row(
children: [
Icon(
isEditing ? Icons.edit_note : Icons.add_circle_outline,
color: Colors.white,
),
const SizedBox(width: 10),
Text(
isEditing ? '编辑家庭药品' : '录入新药品',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white70),
onPressed: () => Navigator.pop(context),
),
],
),
),
// 表单内容
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 1. 药品名称
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: '药品名称 *',
hintText: '如 美林 (布洛芬混悬液)',
prefixIcon: Icon(Icons.medication),
border: OutlineInputBorder(),
),
validator: (v) => (v == null || v.trim().isEmpty) ? '请输入药品名称' : null,
),
const SizedBox(height: 16),
// 2. 剂型类别
const Text(
'剂型类别 (自动联动开封保质天数):',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 6,
children: MedicineCategory.values.map((cat) {
final selected = _category == cat;
return ChoiceChip(
label: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(cat.icon, size: 16, color: selected ? Colors.white : Colors.black87),
const SizedBox(width: 4),
Text(cat.label),
],
),
selected: selected,
selectedColor: const Color(0xFF2563EB),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) _onCategoryChanged(cat);
},
);
}).toList(),
),
const SizedBox(height: 16),
// 3. 规格与条码
Row(
children: [
Expanded(
child: TextFormField(
controller: _specController,
decoration: const InputDecoration(
labelText: '规格/容量',
hintText: '如 100ml / 60喷',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
controller: _barcodeController,
decoration: const InputDecoration(
labelText: '条码/追溯码',
hintText: '69码或20位码',
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 16),
// 4. 存放位置
const Text(
'存放位置:',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _commonLocations.map((loc) {
final selected = _storageLocation == loc;
return ChoiceChip(
label: Text(loc),
selected: selected,
selectedColor: const Color(0xFF059669),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _storageLocation = loc);
},
);
}).toList(),
),
const SizedBox(height: 16),
// 5. 适用成员
const Text(
'适用成员:',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _commonUsers.map((user) {
final selected = _targetUser == user;
return ChoiceChip(
label: Text(user),
selected: selected,
selectedColor: const Color(0xFFD97706),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _targetUser = user);
},
);
}).toList(),
),
const SizedBox(height: 20),
const Divider(),
const SizedBox(height: 10),
// 6. 出厂有效期至 (核心)
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'出厂有效期至 *',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
const SizedBox(height: 4),
InkWell(
onTap: _pickExpiryDate,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.event, color: Color(0xFF2563EB), size: 18),
const SizedBox(width: 8),
Text(
dateFormat.format(_expiryDate),
style: const TextStyle(fontWeight: FontWeight.w600),
),
],
),
),
),
],
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'生产日期 (选填)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
const SizedBox(height: 4),
InkWell(
onTap: _pickProductionDate,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.calendar_today_outlined, size: 16, color: Colors.grey),
const SizedBox(width: 8),
Text(
_productionDate != null
? dateFormat.format(_productionDate!)
: '点击选填',
style: TextStyle(
color: _productionDate != null ? Colors.black87 : Colors.grey,
),
),
],
),
),
),
],
),
),
],
),
const SizedBox(height: 16),
// 7. 生产批号与开封后保质期
Row(
children: [
Expanded(
child: TextFormField(
controller: _batchNumberController,
decoration: const InputDecoration(
labelText: '生产批号 (选填)',
hintText: '如 LOT A123',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
controller: _shelfLifeDaysController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '开封后可用天数',
hintText: '如 28 或 60',
suffixText: '天',
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 16),
// 8. 是否已开封打卡
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _isOpened ? const Color(0xFFEFF6FF) : const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: _isOpened ? const Color(0xFF93C5FD) : Colors.grey.shade300,
),
),
child: Column(
children: [
Row(
children: [
Icon(
_isOpened ? Icons.lock_open : Icons.lock_outline,
color: _isOpened ? const Color(0xFF2563EB) : Colors.grey,
),
const SizedBox(width: 8),
const Text(
'当前是否已开封使用:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const Spacer(),
Switch(
value: _isOpened,
activeTrackColor: const Color(0xFF2563EB),
onChanged: (val) {
setState(() {
_isOpened = val;
if (val && _openedAt == null) {
_openedAt = DateTime.now();
}
});
},
),
],
),
if (_isOpened) ...[
const Divider(),
Row(
children: [
const Text('开封日期:', style: TextStyle(fontSize: 13)),
const Spacer(),
TextButton.icon(
onPressed: _pickOpenedDate,
icon: const Icon(Icons.edit_calendar, size: 16),
label: Text(
_openedAt != null ? dateFormat.format(_openedAt!) : '今天',
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
],
],
),
),
const SizedBox(height: 16),
// 9. 用药备注
TextFormField(
controller: _notesController,
maxLines: 2,
decoration: const InputDecoration(
labelText: '适应症/用药备忘',
hintText: '如:38.5℃以上发热使用,间隔4~6小时',
border: OutlineInputBorder(),
),
),
],
),
),
),
),
// 底部操作按钮
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration(
color: Colors.grey.shade50,
border: Border(top: BorderSide(color: Colors.grey.shade200)),
borderRadius: const BorderRadius.vertical(bottom: Radius.circular(20)),
),
child: Row(
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Colors.grey)),
),
const Spacer(),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2563EB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
onPressed: _save,
icon: const Icon(Icons.check),
label: Text(isEditing ? '保存修改' : '确认录入'),
),
],
),
),
],
),
),
);
}
}