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


class Notification(db.Model):
    __tablename__ = 'notifications'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    title = db.Column(db.String(128), nullable=False)
    content = db.Column(db.Text, nullable=False)
    type = db.Column(db.String(32), nullable=False)  # 通知类型：system, borrow, return, overdue, etc.
    status = db.Column(db.Integer, default=0)  # 0-未读, 1-已读
    sender_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now)
    read_at = db.Column(db.DateTime)

    # 关联关系
    user = db.relationship('User', foreign_keys=[user_id], backref='notifications')
    sender = db.relationship('User', foreign_keys=[sender_id], backref='sent_notifications')

    def to_dict(self):
        """将通知转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'title': self.title,
            'content': self.content,
            'type': self.type,
            'status': self.status,
            'sender_id': self.sender_id,
            'sender_name': self.sender.username if self.sender else 'System',
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'read_at': self.read_at.strftime('%Y-%m-%d %H:%M:%S') if self.read_at else None
        }

    @staticmethod
    def get_user_notifications(user_id, page=1, per_page=10, unread_only=False):
        """获取用户通知"""
        query = Notification.query.filter_by(user_id=user_id)

        if unread_only:
            query = query.filter_by(status=0)

        return query.order_by(Notification.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )

    @staticmethod
    def get_unread_count(user_id):
        """获取用户未读通知数量"""
        return Notification.query.filter_by(user_id=user_id, status=0).count()

    @staticmethod
    def mark_as_read(notification_id, user_id=None):
        """将通知标记为已读"""
        notification = Notification.query.get(notification_id)

        if not notification:
            return False, "通知不存在"

        # 验证用户权限
        if user_id and notification.user_id != user_id:
            return False, "无权操作此通知"

        notification.status = 1
        notification.read_at = datetime.now()

        try:
            db.session.commit()
            return True, "已标记为已读"
        except Exception as e:
            db.session.rollback()
            return False, str(e)

    @staticmethod
    def create_notification(user_id, title, content, notification_type, sender_id=None):
        """创建新通知"""
        notification = Notification(
            user_id=user_id,
            title=title,
            content=content,
            type=notification_type,
            sender_id=sender_id
        )

        try:
            db.session.add(notification)
            db.session.commit()
            return True, notification
        except Exception as e:
            db.session.rollback()
            return False, str(e)

    @staticmethod
    def create_system_notification(user_ids, title, content, notification_type, sender_id=None):
        """创建系统通知，发送给多个用户"""
        success_count = 0
        fail_count = 0

        for user_id in user_ids:
            success, _ = Notification.create_notification(
                user_id=user_id,
                title=title,
                content=content,
                notification_type=notification_type,
                sender_id=sender_id
            )

            if success:
                success_count += 1
            else:
                fail_count += 1

        return success_count, fail_count
