from typing import Dict, Any, Optional from core.db import db from models.history import History, GameTypeEnum class HistoryManager: """历史记录管理器,负责记录和查询历史记录""" def __init__(self): """初始化历史记录管理器""" pass @staticmethod def record_question(result: Dict[str, Any]) -> int: """记录问题生成历史 Args: result: 生成的问题结果 Returns: 历史记录ID """ # 只有生成题目时记录日志 try: # 确保question_type是有效的题目类型(A-E) game_type = GameTypeEnum(result.get('type')) # 创建HistoryDTO对象 history_dto = History( game_type=game_type, question=result.get('question', ''), numbers=','.join(map(str, result.get('numbers', []))), answers= str(result.get('answers', '')) ) # 添加历史记录 return db.add_history(history_dto) except (ValueError, KeyError) as e: # 记录错误但不中断流程 print(f"记录历史失败: {e}") return -1 @staticmethod def get_history(game_type: Optional[str] = None, start_date: Optional[str] = None, end_date: Optional[str] = None, page: int = 1, page_size: int = 10, only_favorite: bool = False, include_deleted: bool = False) : """获取历史记录,支持分页查询 Args: game_type: 类型 start_date: 开始日期,格式为 YYYY-MM-DD end_date: 结束日期,格式为 YYYY-MM-DD page: 页码,从1开始 page_size: 每页记录数 only_favorite: 是否只查询收藏的记录 include_deleted: 是否包含已删除的记录 Returns: Tuple[List[Dict[str, Any]], int]: 历史记录DTO列表和总记录数 """ # 从数据库获取历史记录,使用分页 db_records, total_count = db.get_history(game_type, start_date, end_date, page, page_size, only_favorite, include_deleted) # 转换为DTO对象 history_records = [] for record in db_records: try: # 尝试将记录转换为DTO history_dto = History.from_db_record(record) history_records.append(history_dto.dict()) except Exception as e: print(f"转换历史记录失败: {e}") # 添加原始记录,确保不丢失数据 history_records.append(record) return history_records, total_count @staticmethod def toggle_favorite(history_id: int) -> bool: """切换历史记录的收藏状态 Args: history_id: 历史记录ID Returns: bool: 操作是否成功 """ return db.toggle_favorite(history_id) @staticmethod def toggle_delete(history_id: int) -> bool: """切换历史记录的删除状态 Args: history_id: 历史记录ID Returns: bool: 操作是否成功 """ return db.toggle_delete(history_id) @staticmethod def soft_delete(history_id: int) -> bool: """软删除历史记录 Args: history_id: 历史记录ID Returns: bool: 操作是否成功 """ return db.soft_delete(history_id)