import 'package:flutter/material.dart'; import 'package:drag_and_drop_lists/drag_and_drop_lists.dart'; import 'package:go_router/go_router.dart'; import 'package:lucide_icons/lucide_icons.dart'; import '../../../../core/di/injection.dart'; import '../../../../core/router/app_routes.dart'; import '../../../../core/theme/design_tokens.dart'; import '../../../home/ui/navigation/home_return_policy.dart'; import '../../../../shared/widgets/app_pull_refresh_feedback.dart'; import '../../../../shared/widgets/app_pressable.dart'; import '../../../../shared/widgets/back_title_page_header.dart'; import '../../../../shared/widgets/error_retry_surface.dart'; import '../../../../shared/widgets/full_screen_loading.dart'; import '../../../../shared/widgets/toast/toast.dart'; import '../../../../shared/widgets/toast/toast_type.dart'; import '../../../calendar/ui/calendar_state_manager.dart'; import '../../../calendar/ui/widgets/bottom_dock.dart'; import '../../data/todo_api.dart'; import '../../data/todo_repository.dart'; class TodoQuadrantsScreen extends StatefulWidget { const TodoQuadrantsScreen({super.key}); @override State createState() => _TodoQuadrantsScreenState(); } class _TodoQuadrantsScreenState extends State { final TodoApi _todoApi = sl(); final TodoRepository _todoRepository = sl(); List _todos = []; bool _isLoading = true; bool _isPullRefreshing = false; bool _loadingTodosRequest = false; bool _isReordering = false; String? _error; Future _onItemReorder( int oldItemIndex, int oldListIndex, int newItemIndex, int newListIndex, ) async { if (_isReordering) { return; } final sourceQuadrant = _quadrantByListIndex(oldListIndex); final targetQuadrant = _quadrantByListIndex(newListIndex); final sourceItems = _sortedQuadrantTodos(sourceQuadrant); if (oldItemIndex < 0 || oldItemIndex >= sourceItems.length) { return; } final todoId = sourceItems[oldItemIndex].id; final previousTodos = List.from(_todos); try { setState(() { _isReordering = true; }); final reordered = _reorderTodos( todoId: todoId, sourceQuadrant: sourceQuadrant, targetQuadrant: targetQuadrant, insertIndex: newItemIndex, ); if (reordered == null) { return; } setState(() => _todos = reordered.todos); await _todoApi.reorderTodos( reordered.changedTodos .map( (updated) => TodoReorderItemPayload( id: updated.id, priority: updated.priority, order: updated.order, ), ) .toList(growable: false), ); } catch (e) { if (!mounted) return; setState(() { _todos = previousTodos; }); Toast.show(context, '移动失败', type: ToastType.error); } finally { if (mounted) { setState(() { _isReordering = false; }); } } } int _quadrantByListIndex(int listIndex) { switch (listIndex) { case 0: return 1; case 1: return 3; case 2: return 2; default: return 1; } } _ReorderResult? _reorderTodos({ required String todoId, required int sourceQuadrant, required int targetQuadrant, required int insertIndex, }) { final byId = {for (final todo in _todos) todo.id: todo}; final moving = byId[todoId]; if (moving == null) { return null; } final sourceList = _sortedQuadrantTodos(sourceQuadrant); final targetList = sourceQuadrant == targetQuadrant ? sourceList : _sortedQuadrantTodos(targetQuadrant); final sourceIndex = sourceList.indexWhere((todo) => todo.id == todoId); if (sourceIndex == -1) { return null; } final mutableSource = List.from(sourceList); final extracted = mutableSource.removeAt(sourceIndex); int targetIndex = insertIndex; if (sourceQuadrant == targetQuadrant && sourceIndex < targetIndex) { targetIndex -= 1; } if (targetIndex < 0) { targetIndex = 0; } final mutableTarget = sourceQuadrant == targetQuadrant ? mutableSource : List.from(targetList); if (targetIndex > mutableTarget.length) { targetIndex = mutableTarget.length; } final moved = extracted.copyWith(priority: targetQuadrant); mutableTarget.insert(targetIndex, moved); final updatedById = {}; void reindex(List list, int priority) { for (var index = 0; index < list.length; index += 1) { final current = list[index]; final updated = current.copyWith(priority: priority, order: index); list[index] = updated; if (current.priority != updated.priority || current.order != updated.order) { updatedById[updated.id] = updated; } } } if (sourceQuadrant == targetQuadrant) { reindex(mutableTarget, targetQuadrant); } else { reindex(mutableSource, sourceQuadrant); reindex(mutableTarget, targetQuadrant); } if (updatedById.isEmpty) { return null; } final updatedTodos = _todos .map((todo) => updatedById[todo.id] ?? todo) .toList(growable: false); return _ReorderResult( todos: updatedTodos, changedTodos: updatedById.values.toList(growable: false), ); } @override void initState() { super.initState(); _loadTodos(); } Future _loadTodos({bool showPageLoader = true}) async { if (_loadingTodosRequest || _isPullRefreshing) { return; } _loadingTodosRequest = true; setState(() { if (showPageLoader) { _isLoading = true; _error = null; } else { _isPullRefreshing = true; } }); try { final todos = await _todoRepository.getPendingTodos( forceRefresh: !showPageLoader, ); if (!mounted) { return; } setState(() { _todos = todos; _isLoading = false; _isPullRefreshing = false; _error = null; }); } catch (e) { if (!mounted) { return; } if (showPageLoader) { setState(() { _error = e.toString(); _isLoading = false; _isPullRefreshing = false; }); } else { setState(() => _isPullRefreshing = false); Toast.show(context, '刷新失败,请稍后重试', type: ToastType.error); } } finally { _loadingTodosRequest = false; } } Future _onPullRefresh() async { await _loadTodos(showPageLoader: false); } List get _importantUrgent => _sortedQuadrantTodos(1); List get _urgentNotImportant => _sortedQuadrantTodos(3); List get _importantNotUrgent => _sortedQuadrantTodos(2); List _sortedQuadrantTodos(int quadrantValue) { final list = _todos.where((t) => t.priority == quadrantValue).toList(); list.sort((a, b) { final byOrder = a.order.compareTo(b.order); if (byOrder != 0) { return byOrder; } return a.createdAt.compareTo(b.createdAt); }); return list; } Future _completeTodo(TodoResponse todo) async { try { await _todoRepository.completeTodo(todo.id); if (mounted) { Toast.show(context, '已完成', type: ToastType.success); } try { await _loadTodos(); } catch (_) { // ignore reload error } } catch (e) { if (mounted) { Toast.show(context, '完成失败: $e', type: ToastType.error); } } } void _navigateToDetail(TodoResponse todo) { context.push(AppRoutes.todoDetail(todo.id)); } Future _addTodo() async { final created = await context.push(AppRoutes.todoCreate); if (created == true) { await _loadTodos(); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.todoBg, body: PopScope( canPop: false, onPopInvokedWithResult: (didPop, result) { if (!didPop) { returnToHomePreserveState(context, forceGoHome: true); } }, child: SafeArea( child: Column( children: [ _buildHeader(), Expanded(child: _buildContent(withScroll: true)), _buildBottomDock(), ], ), ), ), ); } Widget _buildHeader() { return BackTitlePageHeader( title: '待办事项', showBackButton: false, trailing: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ AppPressable( borderRadius: BorderRadius.circular(AppRadius.full), onTap: _loadTodos, child: Container( width: 36, height: 36, decoration: BoxDecoration( color: AppColors.messageBtnWrap, borderRadius: BorderRadius.circular(AppRadius.full), border: Border.all(color: AppColors.messageBtnBorder), ), child: const Icon( LucideIcons.refreshCcw, size: 18, color: AppColors.slate600, ), ), ), const SizedBox(width: AppSpacing.sm), AppPressable( borderRadius: BorderRadius.circular(AppRadius.full), onTap: _addTodo, child: Container( width: 36, height: 36, decoration: BoxDecoration( color: AppColors.blue600, borderRadius: BorderRadius.circular(AppRadius.full), boxShadow: [ BoxShadow( color: AppColors.blue300.withValues(alpha: 0.28), blurRadius: AppRadius.lg, offset: const Offset(0, AppSpacing.xs), ), ], ), child: const Icon( LucideIcons.plus, size: 18, color: AppColors.white, ), ), ), ], ), ); } Widget _buildContent({bool withScroll = false}) { if (_isLoading) { return const FullScreenLoading(); } if (_error != null) { return ErrorRetrySurface(message: '加载失败: $_error', onRetry: _loadTodos); } final content = _buildDragBoard(); if (withScroll) { return Stack( children: [ RefreshIndicator.noSpinner(onRefresh: _onPullRefresh, child: content), Align( alignment: Alignment.topCenter, child: AppPullRefreshFeedback(visible: _isPullRefreshing), ), ], ); } return content; } Widget _buildDragBoard() { final quadrants = [ _QuadrantMeta( value: 1, title: '重要紧急', textColor: AppColors.g1Text, dividerColor: AppColors.g1Divider, borderColor: AppColors.g1Border, items: _importantUrgent, ), _QuadrantMeta( value: 3, title: '紧急不重要', textColor: AppColors.g2Text, dividerColor: AppColors.g2Divider, borderColor: AppColors.g2Border, items: _urgentNotImportant, ), _QuadrantMeta( value: 2, title: '重要不紧急', textColor: AppColors.g3Text, dividerColor: AppColors.g3Divider, borderColor: AppColors.g3Border, items: _importantNotUrgent, ), ]; final lists = quadrants .map( (meta) => DragAndDropList( canDrag: false, header: _buildQuadrantHeader(meta), contentsWhenEmpty: _buildEmptyQuadrant(), lastTarget: const SizedBox(height: AppSpacing.lg), decoration: BoxDecoration( color: AppColors.todoCardBg, borderRadius: BorderRadius.circular(14), border: Border.all(color: meta.borderColor), ), children: meta.items .map( (item) => DragAndDropItem( child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.sm, ), child: _TodoItemWidget( item: item, onComplete: () => _completeTodo(item), onTap: () => _navigateToDetail(item), ), ), ), ) .toList(growable: false), ), ) .toList(growable: false); return SingleChildScrollView( padding: const EdgeInsets.fromLTRB( AppSpacing.lg, AppSpacing.xs, AppSpacing.lg, 96, ), child: DragAndDropLists( children: lists, onItemReorder: _onItemReorder, onListReorder: (oldListIndex, newListIndex) {}, listDivider: const SizedBox(height: AppSpacing.md), itemDivider: Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md), child: Container(height: 1, color: AppColors.slate100), ), listPadding: EdgeInsets.zero, itemDecorationWhileDragging: BoxDecoration( color: AppColors.todoCardBg, borderRadius: BorderRadius.circular(AppRadius.md), border: Border.all(color: AppColors.borderSecondary), boxShadow: [ BoxShadow( color: AppColors.slate200.withValues(alpha: 0.6), blurRadius: AppRadius.md, offset: const Offset(0, AppSpacing.xs), ), ], ), itemGhost: const SizedBox(height: 42), itemDragOnLongPress: true, lastItemTargetHeight: AppSpacing.xl, disableScrolling: true, ), ); } Widget _buildQuadrantHeader(_QuadrantMeta meta) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( meta.title, style: TextStyle( fontFamily: 'Inter', fontSize: 15, fontWeight: FontWeight.w700, color: meta.textColor, ), ), Text( '${meta.items.length}项', style: TextStyle( fontFamily: 'Inter', fontSize: 12, fontWeight: FontWeight.w700, color: meta.textColor, ), ), ], ), ), Container(height: 1, color: meta.dividerColor), const SizedBox(height: AppSpacing.sm), ], ); } Widget _buildEmptyQuadrant() { return SizedBox( height: 60, child: Center( child: Text( '暂无待办', style: TextStyle( fontFamily: 'Inter', fontSize: 13, color: AppColors.slate400, ), ), ), ); } Widget _buildBottomDock() { return BottomDock( activeTab: DockTab.todo, onTodoTap: () {}, onCalendarTap: () { final manager = sl(); final viewType = manager.viewType; final date = manager.selectedDate; final dateStr = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}'; if (viewType == CalendarViewType.month) { context.push(AppRoutes.calendarMonth); } else { context.push('${AppRoutes.calendarDayWeek}?date=$dateStr'); } }, onHomeTap: () => returnToHomePreserveState(context, forceGoHome: true), ); } } class _ReorderResult { final List todos; final List changedTodos; const _ReorderResult({required this.todos, required this.changedTodos}); } class _QuadrantMeta { final int value; final String title; final Color textColor; final Color dividerColor; final Color borderColor; final List items; const _QuadrantMeta({ required this.value, required this.title, required this.textColor, required this.dividerColor, required this.borderColor, required this.items, }); } class _TodoItemWidget extends StatefulWidget { final TodoResponse item; final VoidCallback onComplete; final VoidCallback onTap; const _TodoItemWidget({ required this.item, required this.onComplete, required this.onTap, }); @override State<_TodoItemWidget> createState() => _TodoItemWidgetState(); } class _TodoItemWidgetState extends State<_TodoItemWidget> with SingleTickerProviderStateMixin { bool _isChecked = false; late AnimationController _controller; late Animation _scaleAnimation; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 200), vsync: this, ); _scaleAnimation = Tween( begin: 0.0, end: 1.0, ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOutBack)); } @override void dispose() { _controller.dispose(); super.dispose(); } void _handleCheckTap() async { if (_isChecked) return; setState(() { _isChecked = true; }); _controller.forward().then((_) { widget.onComplete(); }); } @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.onTap, child: SizedBox( height: 42, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( widget.item.title, style: const TextStyle( fontFamily: 'Inter', fontSize: 13, fontWeight: FontWeight.w600, color: AppColors.slate700, ), ), ), GestureDetector( onTap: _handleCheckTap, child: AnimatedBuilder( animation: _controller, builder: (context, child) { return Container( width: 20, height: 20, decoration: BoxDecoration( color: _isChecked ? AppColors.blue600 : Colors.white, border: Border.all( color: _isChecked ? AppColors.blue600 : AppColors.slate300, width: 1.5, ), borderRadius: BorderRadius.circular(4), ), child: _isChecked ? Transform.scale( scale: _scaleAnimation.value, child: const Icon( Icons.check, size: 14, color: Colors.white, ), ) : null, ); }, ), ), ], ), ), ); } }