"""
  @author: LinTao
  @time: 2022/9/11 15:04
  @desc:
"""
import random
import time

from flask import session
from sqlalchemy import Table

from common.database import dbconnect

dbsession, md, DBase = dbconnect()


class Users(DBase):
    __table__ = Table('users', md, autoload=True)

    def find_by_username(self, username):
        """查询用户名，用于注册时判断用户名是否已经注册过，也可用于登录校验"""
        result = dbsession.query(Users).filter_by(username=username).all()
        return result


    def find_by_userid(self, userid):
        """查询用户ID"""
        result = dbsession.query(Users).filter_by(userid=userid).one()
        return result


    def do_register(self, username, password):
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        nickname = username.split('@')[0]  # 默认邮箱账号前缀
        avatar = str(random.randint(1, 15))  # 从15张头像图片中随机选择一张
        user = Users(username=username, password=password, role='user', credit=50,
                     nickname=nickname, avatar=avatar + '.png', createtime=now, updatetime=now)
        dbsession.add(user)
        dbsession.commit()
        return user


    def update_credit(self, credit):
        """修改用户剩余积分；正数表示增加积分，负数表示减少积分"""
        user = dbsession.query(Users).filter_by(userid=session.get('userid')).one()
        user.credit = int(user.credit) + credit
        dbsession.commit()



