from datetime import datetime
from app.models.user import db, User  # 从user模块导入db，而不是从utils导入


class Log(db.Model):
    __tablename__ = 'logs'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    action = db.Column(db.String(64), nullable=False)
    target_type = db.Column(db.String(32), nullable=True)
    target_id = db.Column(db.Integer, nullable=True)
    ip_address = db.Column(db.String(45), nullable=True)
    description = db.Column(db.String(255), nullable=True)
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now)

    # 关联用户
    user = db.relationship('User', backref=db.backref('logs', lazy=True))

    def __init__(self, action, user_id=None, target_type=None, target_id=None,
                 ip_address=None, description=None):
        self.user_id = user_id
        self.action = action
        self.target_type = target_type
        self.target_id = target_id
        self.ip_address = ip_address
        self.description = description
        self.created_at = datetime.now()

    @staticmethod
    def add_log(action, user_id=None, target_type=None, target_id=None,
                ip_address=None, description=None):
        """添加一条日志记录"""
        try:
            log = Log(
                action=action,
                user_id=user_id,
                target_type=target_type,
                target_id=target_id,
                ip_address=ip_address,
                description=description
            )
            db.session.add(log)
            db.session.commit()
            return True, "日志记录成功"
        except Exception as e:
            db.session.rollback()
            return False, f"日志记录失败: {str(e)}"

    @staticmethod
    def get_logs(page=1, per_page=20, user_id=None, action=None,
                 target_type=None, start_date=None, end_date=None):
        """查询日志记录"""
        query = Log.query.order_by(Log.created_at.desc())

        if user_id:
            query = query.filter(Log.user_id == user_id)
        if action:
            query = query.filter(Log.action == action)
        if target_type:
            query = query.filter(Log.target_type == target_type)
        if start_date:
            query = query.filter(Log.created_at >= start_date)
        if end_date:
            query = query.filter(Log.created_at <= end_date)

        return query.paginate(page=page, per_page=per_page)
