from app.models.database import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from flask_login import UserMixin
from app.models.permission import RolePermission, Permission

#db = SQLAlchemy()


class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(128), unique=True, nullable=True)
    phone = db.Column(db.String(20), unique=True, nullable=True)
    nickname = db.Column(db.String(64), nullable=True)
    status = db.Column(db.Integer, default=1)  # 1: active, 0: disabled
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'), default=2)  # 2: 普通用户, 1: 管理员
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    def __init__(self, username, password, email=None, phone=None, nickname=None, role_id=2, status=1):
        self.username = username
        self.set_password(password)
        self.email = email
        self.phone = phone
        self.nickname = nickname
        self.role_id = role_id
        self.status = status  # 新增

    @property
    def is_active(self):
        return self.status == 1

    def set_password(self, password):
        """设置密码，使用哈希加密"""
        self.password = generate_password_hash(password)

    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password, password)

    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'phone': self.phone,
            'nickname': self.nickname,
            'status': self.status,
            'role_id': self.role_id,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

    @classmethod
    def create_user(cls, username, password, email=None, phone=None, nickname=None, role_id=2):
        """创建新用户"""
        user = User(
            username=username,
            password=password,
            email=email,
            phone=phone,
            nickname=nickname,
            role_id=role_id
        )
        db.session.add(user)
        db.session.commit()
        return user


class Role(db.Model):
    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    role_name = db.Column(db.String(32), unique=True, nullable=False)
    description = db.Column(db.String(128))

    permissions = db.relationship(
        'Permission',
        secondary='role_permissions',
        backref=db.backref('roles', lazy='dynamic'),
        lazy='dynamic'
    )

    users = db.relationship('User', backref='role')
