from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.db_session import get_db
from app.model.schemas.sys_user_schemas import SysUserLogin
from app.common import reponse_code as rc
from app.model.crud import sys_user_crud as us
from app.common.bcrypt_pw import verify_password
from app.common.jwt_check import generate_token
from app.common.redis_cli import redis_conn
"""
用户登录统一接口
"""

login = APIRouter()


@login.post("")
def login_check(user: SysUserLogin, session: Session = Depends(get_db)):
    """
    登录验证，并返回token
    :param session:
    :param user: 登录参数信息
    :return: response
    """
    query_user = us.get_user_by_username(username=user.username, session=session)
    if query_user is None:
        return rc.response_error('您输入的用户名不正确')
    if not verify_password(user.password, query_user.password):
        return rc.response_error("您输入的密码不正确")
    if not query_user.user_status == '0':
        return rc.response_error(msg="登录失败，账号已被禁用，请联系管理员")
    token = generate_token(query_user.id, query_user.username)
    redis_conn.set(query_user.id, token)
    return rc.response_success(msg="登录成功", data=token)