import utils
from datetime import datetime
from typing import List, Optional, Tuple
from models.log_data import LogModel
from stores.log_store import LogStore

class LogService:
    def __init__(self):
        self._log_store = LogStore()
        self._logger = utils.get_logger()

    def add_operation_log(self, username: str, operation_type: str, operation_desc: str,
                         operation_result: Optional[int] = None,
                         operation_module: Optional[str] = None,
                         operation_data: Optional[str] = None,
                         operation_ip: Optional[str] = None,
                         data_changes: Optional[str] = None) -> None:
        """
        添加操作日志
        :param username: 用户名
        :param operation_type: 操作类型
        :param operation_desc: 操作描述
        :param operation_result: 操作结果(0:失败, 1:成功)
        :param operation_module: 操作模块
        :param operation_data: 操作数据
        :param operation_ip: 操作IP
        :param data_changes: 数据变更记录
        """
        try:
            log = LogModel(
                username=username,
                operation_type=operation_type,
                operation_desc=operation_desc,
                operation_result=operation_result,
                operation_module=operation_module,
                operation_data=operation_data,
                operation_ip=operation_ip,
                data_changes=data_changes,
                created_at=datetime.now()
            )
            self._log_store.insert_log(log)
        except Exception as e:
            self._logger.error(f"----添加操作日志失败-----: {e}")



    def get_logs_paginated(self, page: int, per_page: int, username: str = None, operation_type: str =None, operation_module: str =None,
                          start_date: datetime = None, end_date: datetime = None) -> Tuple[List[LogModel], int]:
        """
        分页获取日志列表
        :param page: 页码
        :param per_page: 每页数量
        :param username: 用户名筛选
        :param start_date: 开始时间
        :param end_date: 结束时间
        :return: 日志列表和总数
        """
        return self._log_store.query_logs_paginated(page, per_page, username, operation_type,operation_module,start_date, end_date)