# app/models/system.py
from app.extensions import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

class SysUser(db.Model):
    __tablename__ = 'sys_user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False)
    # 注意：如果允许邮箱为空，建议去掉 unique=True 或者在数据库层面处理空字符串
    email = db.Column(db.String(100), unique=True)
    department = db.Column(db.String(100))
    role = db.Column(db.String(50))
    status = db.Column(db.String(20), default='active')
    password_hash = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.now) # 新增创建时间

    def set_password(self, password):
        """生成加密密码"""
        self.password_hash = generate_password_hash(password)

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

    def to_dict(self):
        """序列化为字典，供接口返回使用"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'department': self.department,
            'role': self.role,
            'status': self.status,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else ''
        }

class SysLog(db.Model):
    """
    系统操作日志表
    对应数据库表: sys_log
    """
    __tablename__ = 'sys_log'

    id = db.Column(db.Integer, primary_key=True)
    op_time = db.Column(db.DateTime, default=datetime.now)
    op_user_name = db.Column(db.String(100))
    op_user_id = db.Column(db.String(50))
    module_name = db.Column(db.String(100))
    action_type = db.Column(db.String(50))
    target_table = db.Column(db.String(100))
    target_id = db.Column(db.Integer)
    description = db.Column(db.Text)
    ip_address = db.Column(db.String(50))

    def to_dict(self):
        return {
            'id': self.id,
            'op_time': self.op_time.isoformat() if self.op_time else None,
            'op_user_name': self.op_user_name,
            'module_name': self.module_name,
            'action_type': self.action_type,
            'description': self.description
        }