from sqlalchemy import String, Column, Integer, create_engine, DateTime, Boolean, ForeignKey, Float
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime

Base = declarative_base()

# 增加 to_dict() 方法到 Base 类中
def to_dict(self):
    return {c.name: getattr(self, c.name, None)
            for c in self.__table__.columns}
# 将对象可以转化为 dict 类型
Base.to_dict = to_dict

class UserAuthority(Base):
    __tablename__ = 'authority'

    id = Column(Integer, primary_key=True, autoincrement=True)
    authority = Column(String(20), index=True, comment="权限名称")
    role = Column(Integer, ForeignKey(
        "role.id", ondelete="SET NULL"), index=True, comment="角色id")
    create_time = Column(DateTime, default=datetime.now(), comment="创建时间")

    # 反向查询外键，可在 UserRole 实例对象中调用 UserAuthority 的属性，如 UserRole.UserAuthority
    user = relationship('UserRole', backref="UserAuthority")

    def __repr__(self):
        return "<user (id='%s', role='%s')>" % (self.id, self.role)

class UserRole(Base):
    __tablename__ = 'role'

    id = Column(Integer, primary_key=True, autoincrement=True)
    role = Column(String(20), index=True, unique=True, comment="角色名")
    create_time = Column(DateTime, default=datetime.now(), comment="创建时间")

    # 反向查询外键，可在 User 实例对象中调用 UserRole 的属性，如 User.UserRole
    user = relationship('User', backref="UserRole")

    def __repr__(self):
        return "<user (id='%s', role='%s')>" % (self.id, self.role)

class User(Base):
    # 表名
    __tablename__ = 'user'

    # 表结构
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(20), index=True, unique=True, comment="用户名")
    password = Column(String(128), comment="密码")
    role = Column(Integer, ForeignKey(
        "role.id", ondelete="SET NULL"), index=True, comment="角色id")
    is_delete = Column(Boolean, default=True, index=True,
                       comment="删除标记, 为True时表示可用")
    create_time = Column(DateTime, default=datetime.now(), comment="创建时间")
    last_login = Column(DateTime, default=datetime.now(),
                        nullable=False, comment="最后登陆时间")
    update_time = Column(DateTime, default=datetime.now(),
                         nullable=False, comment="更新时间")

    def __repr__(self):
        return "<user (id='%s', name='%s')>" % (self.id, self.name)

# 定义 Player 对象:
class Player(Base):
    # 表的名字:
    __tablename__ = 'player'

    # 表的结构:
    player_id = Column(Integer, primary_key=True, autoincrement=True)
    team_id = Column(Integer)
    player_name = Column(String(255))
    height = Column(Float(3,2))

    def __repr__(self):
        return "<player (player_id='%s', player_name='%s')>" % (self.player_id, self.player_name)


