| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- """
- 核心Todo类,负责待办事项的业务逻辑
- """
- from datetime import datetime
- from typing import List, Optional, Dict
- class TodoItem:
- """待办事项数据模型"""
-
- def __init__(self, id: int, title: str, completed: bool = False,
- created_at: Optional[str] = None):
- self.id = id
- self.title = title
- self.completed = completed
- self.created_at = created_at or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
- def to_dict(self) -> Dict:
- """转换为字典格式"""
- return {
- "id": self.id,
- "title": self.title,
- "completed": self.completed,
- "created_at": self.created_at
- }
-
- @classmethod
- def from_dict(cls, data: Dict) -> 'TodoItem':
- """从字典创建TodoItem对象"""
- return cls(
- id=data["id"],
- title=data["title"],
- completed=data.get("completed", False),
- created_at=data.get("created_at")
- )
-
- def __repr__(self) -> str:
- status = "✓" if self.completed else " "
- return f"[{status}] {self.id}. {self.title}"
- class Todo:
- """待办事项管理类"""
-
- def __init__(self):
- self.items: List[TodoItem] = []
- self.next_id: int = 1
-
- def add(self, title: str) -> TodoItem:
- """添加待办事项"""
- if not title or not title.strip():
- raise ValueError("待办事项标题不能为空")
-
- item = TodoItem(id=self.next_id, title=title.strip())
- self.items.append(item)
- self.next_id += 1
- return item
-
- def delete(self, item_id: int) -> bool:
- """删除待办事项"""
- for i, item in enumerate(self.items):
- if item.id == item_id:
- self.items.pop(i)
- return True
- return False
-
- def complete(self, item_id: int) -> bool:
- """标记待办事项为完成"""
- item = self.get_by_id(item_id)
- if item:
- item.completed = True
- return True
- return False
-
- def uncomplete(self, item_id: int) -> bool:
- """标记待办事项为未完成"""
- item = self.get_by_id(item_id)
- if item:
- item.completed = False
- return True
- return False
-
- def get_by_id(self, item_id: int) -> Optional[TodoItem]:
- """根据ID获取待办事项"""
- for item in self.items:
- if item.id == item_id:
- return item
- return None
-
- def get_all(self) -> List[TodoItem]:
- """获取所有待办事项"""
- return self.items.copy()
-
- def get_pending(self) -> List[TodoItem]:
- """获取未完成的待办事项"""
- return [item for item in self.items if not item.completed]
-
- def get_completed(self) -> List[TodoItem]:
- """获取已完成的待办事项"""
- return [item for item in self.items if item.completed]
-
- def clear_completed(self) -> int:
- """清除所有已完成的待办事项,返回清除的数量"""
- completed_count = len(self.get_completed())
- self.items = [item for item in self.items if not item.completed]
- return completed_count
-
- def to_dict(self) -> Dict:
- """转换为字典格式用于存储"""
- return {
- "todos": [item.to_dict() for item in self.items],
- "next_id": self.next_id
- }
-
- def from_dict(self, data: Dict):
- """从字典加载数据"""
- self.items = [TodoItem.from_dict(item_data) for item_data in data.get("todos", [])]
- self.next_id = data.get("next_id", 1)
|