import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/network/api_exception.dart'; import '../../providers/bill_edit_provider.dart'; import '../../providers/category_provider.dart'; import '../../utils/amount_input_formatter.dart'; import '../../utils/date_util.dart'; import '../../utils/toast.dart'; import '../../widgets/category_picker_grid.dart'; import '../../widgets/state_views.dart'; import '../../widgets/cute_icon.dart'; /// 账单编辑页(复刻 uniApp pages/bill/detail.vue 的编辑能力,并补上删除) class BillEditPage extends ConsumerStatefulWidget { const BillEditPage({super.key, required this.billId}); final int billId; @override ConsumerState createState() => _BillEditPageState(); } class _BillEditPageState extends ConsumerState { final _amountController = TextEditingController(); final _descriptionController = TextEditingController(); @override void dispose() { _amountController.dispose(); _descriptionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final state = ref.watch(billEditProvider(widget.billId)); final notifier = ref.read(billEditProvider(widget.billId).notifier); // 服务端数据回填时同步非受控输入框(与记账页同一套 revision 机制) ref.listen( billEditProvider(widget.billId).select((s) => s.revision), (prev, next) { if (prev == next) return; final s = ref.read(billEditProvider(widget.billId)); _amountController.text = s.amount?.toStringAsFixed(2) ?? ''; _descriptionController.text = s.description; }, ); return Scaffold( appBar: AppBar(title: const Text('编辑账单')), body: Container( width: double.infinity, height: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Color(0xFFFFE5CC), Color(0xFFFFD4A8), Color(0xFFFFC08A)], ), ), child: _body(state, notifier), ), ); } Widget _body(BillEditState state, BillEditNotifier notifier) { if (state.loading) { return const Center(child: LoadingView(tip: '账单加载中...')); } if (state.loadError != null) { return Center( child: Padding( padding: const EdgeInsets.all(24), child: ErrorView(message: state.loadError!, onRetry: notifier.reload), ), ); } return ListView( padding: const EdgeInsets.all(16), children: [ _sectionLabel('账单类型'), _typeSelector(state, notifier), const SizedBox(height: 16), _sectionLabel('分类'), _categorySection(state, notifier), const SizedBox(height: 16), _sectionLabel('金额'), _amountField(state, notifier), const SizedBox(height: 16), _sectionLabel('日期'), _dateField(state, notifier), const SizedBox(height: 16), _sectionLabel('备注'), _descriptionField(notifier), const SizedBox(height: 28), _footer(state, notifier), const SizedBox(height: 40), ], ); } Widget _sectionLabel(String text) => Padding( padding: const EdgeInsets.only(bottom: 8, left: 4), child: Text( text, style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF5D4037), ), ), ); // ---- 类型 ---- Widget _typeSelector(BillEditState state, BillEditNotifier notifier) { return Row( children: [ _typeCard('expense', '支出', 1, state, notifier), const SizedBox(width: 10), _typeCard('income', '收入', 2, state, notifier), ], ); } Widget _typeCard( String icon, String label, int type, BillEditState state, BillEditNotifier notifier, ) { final active = state.type == type; return Expanded( child: GestureDetector( onTap: () => notifier.setType(type), child: AnimatedContainer( duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(vertical: 12), decoration: BoxDecoration( color: active ? Colors.white : Colors.white.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(14), border: Border.all( color: active ? const Color(0xFFC8956E) : Colors.transparent, width: 2, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CuteIcon(icon, size: 22), const SizedBox(width: 8), Text( label, style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold, color: active ? const Color(0xFF5D4037) : const Color(0xFF8D6E63), ), ), ], ), ), ), ); } // ---- 分类 ---- Widget _categorySection(BillEditState state, BillEditNotifier notifier) { return Consumer( builder: (context, ref, _) { final categoriesAsync = ref.watch(categoriesProvider(state.type)); return categoriesAsync.when( loading: () => const LoadingView(padding: EdgeInsets.all(20)), error: (e, _) => ErrorView(message: asApiException(e).message), data: (categories) => CategoryPickerGrid( categories: categories, selectedId: state.categoryId, onSelect: notifier.setCategory, crossAxisCount: 4, ), ); }, ); } // ---- 金额 ---- Widget _amountField(BillEditState state, BillEditNotifier notifier) { return TextField( controller: _amountController, keyboardType: const TextInputType.numberWithOptions(decimal: true), inputFormatters: [AmountInputFormatter()], style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF5D4037)), decoration: InputDecoration( hintText: '请输入金额', prefixText: '¥ ', prefixStyle: const TextStyle( fontSize: 18, color: Color(0xFFC8956E), fontWeight: FontWeight.bold, ), filled: true, fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none, ), ), onChanged: (v) => notifier.setAmount(double.tryParse(v)), ); } // ---- 日期 ---- Widget _dateField(BillEditState state, BillEditNotifier notifier) { return GestureDetector( onTap: () async { final initial = DateTime.tryParse(state.billDate) ?? DateTime.now(); final picked = await showDatePicker( context: context, initialDate: initial, firstDate: DateTime(2000), lastDate: DateTime(2100), ); if (picked != null) notifier.setDate(formatDate(picked)); }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(14), ), child: Row( children: [ Text(state.billDate, style: const TextStyle(fontSize: 15, color: Color(0xFF5D4037))), const Spacer(), const Icon(Icons.chevron_right, color: Color(0xFF8D6E63)), ], ), ), ); } // ---- 备注 ---- Widget _descriptionField(BillEditNotifier notifier) { return TextField( controller: _descriptionController, maxLines: 3, maxLength: 200, style: const TextStyle(fontSize: 15, color: Color(0xFF5D4037)), decoration: InputDecoration( hintText: '请输入备注(可选)', filled: true, fillColor: Colors.white, border: OutlineInputBorder( borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none, ), ), onChanged: notifier.setDescription, ); } // ---- 底部:删除 + 保存 ---- Widget _footer(BillEditState state, BillEditNotifier notifier) { final busy = state.submitting; return Row( children: [ Expanded( child: SizedBox( height: 48, child: OutlinedButton( style: OutlinedButton.styleFrom( backgroundColor: Colors.white, foregroundColor: const Color(0xFFD32F2F), side: const BorderSide(color: Color(0xFFE0C9A6)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), ), onPressed: busy ? null : () => _confirmDelete(notifier), child: const Text('删除', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)), ), ), ), const SizedBox(width: 12), Expanded( flex: 2, child: SizedBox( height: 48, child: FilledButton( style: FilledButton.styleFrom( backgroundColor: const Color(0xFFC8956E), foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), ), onPressed: busy ? null : () => _save(notifier), child: busy ? const SizedBox( width: 22, height: 22, child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white), ) : const Text( '保 存', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 3), ), ), ), ), ], ); } Future _save(BillEditNotifier notifier) async { try { await notifier.save(); if (!mounted) return; showToast(context, '已保存', icon: 'check'); Navigator.of(context).pop(); } on ApiException catch (e) { if (mounted) showToast(context, e.message, error: true); } catch (_) { if (mounted) showToast(context, '保存失败,请重试', error: true); } } Future _confirmDelete(BillEditNotifier notifier) async { final confirmed = await showDialog( context: context, builder: (dialogContext) => AlertDialog( title: const Text('确认删除'), content: const Text('确定要删除这笔账单吗?删除后无法恢复'), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext, false), child: const Text('取消', style: TextStyle(color: Color(0xFF8D6E63))), ), TextButton( onPressed: () => Navigator.pop(dialogContext, true), child: const Text('删除', style: TextStyle(color: Color(0xFFD32F2F))), ), ], ), ); if (confirmed != true) return; try { await notifier.remove(); if (!mounted) return; showToast(context, '已删除'); Navigator.of(context).pop(); } on ApiException catch (e) { if (mounted) showToast(context, e.message, error: true); } catch (_) { if (mounted) showToast(context, '删除失败,请重试', error: true); } } }