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


class Announcement(db.Model):
    __tablename__ = 'announcements'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128), nullable=False)
    content = db.Column(db.Text, nullable=False)
    publisher_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    is_top = db.Column(db.Boolean, default=False)
    status = db.Column(db.Integer, default=1)  # 1-正常, 0-已下架
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now)
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now)

    # 关联关系
    publisher = db.relationship('User', backref='announcements')

    def to_dict(self):
        """将公告转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'content': self.content,
            'publisher_id': self.publisher_id,
            'publisher_name': self.publisher.username if self.publisher else '',
            'is_top': self.is_top,
            'status': self.status,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

    @staticmethod
    def get_active_announcements(limit=None):
        """获取活跃的公告"""
        query = Announcement.query.filter_by(status=1).order_by(
            Announcement.is_top.desc(),
            Announcement.created_at.desc()
        )

        if limit:
            query = query.limit(limit)

        return query.all()

    @staticmethod
    def get_announcement_by_id(announcement_id):
        """根据ID获取公告"""
        return Announcement.query.get(announcement_id)

    @staticmethod
    def create_announcement(title, content, publisher_id, is_top=False):
        """创建新公告"""
        announcement = Announcement(
            title=title,
            content=content,
            publisher_id=publisher_id,
            is_top=is_top
        )

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

    @staticmethod
    def update_announcement(announcement_id, title, content, is_top=None):
        """更新公告内容"""
        announcement = Announcement.query.get(announcement_id)

        if not announcement:
            return False, "公告不存在"

        announcement.title = title
        announcement.content = content

        if is_top is not None:
            announcement.is_top = is_top

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

    @staticmethod
    def change_status(announcement_id, status):
        """更改公告状态"""
        announcement = Announcement.query.get(announcement_id)

        if not announcement:
            return False, "公告不存在"

        announcement.status = status

        try:
            db.session.commit()
            return True, "状态已更新"
        except Exception as e:
            db.session.rollback()
            return False, str(e)

    @staticmethod
    def change_top_status(announcement_id, is_top):
        """更改置顶状态"""
        announcement = Announcement.query.get(announcement_id)

        if not announcement:
            return False, "公告不存在"

        announcement.is_top = is_top

        try:
            db.session.commit()
            return True, "置顶状态已更新"
        except Exception as e:
            db.session.rollback()
            return False, str(e)
