from fastapi import APIRouter, Depends
from app.model.schemas.sys_user_schemas import SysUserOut, SysUserIn, SysUserPager
from app.common import reponse_code as rc
from app.model.crud import sys_user_crud as us
from app.model.sys_model import SysUser
from app.common.redis_cli import redis_conn

from sqlalchemy.orm import Session
from app.db.db_session import get_db
"""
用户管理模块
"""
user = APIRouter()


@user.post("/pager")
def user_pager(user: SysUserPager, session: Session = Depends(get_db)):
    pager = us.user_pager(user, session)
    return rc.response_success_pager(pager)


@user.post("/add")
def add_user(user: SysUserIn, session: Session = Depends(get_db)):
    """
    新增用户
    :param session:
    :param user: 用户信息
    :return:
    """
    if us.check_username(user.username, session):
        return rc.response_error(msg="该用户名已存在！")
    else:
        user_in = SysUser(**user.dict())
        user_in.user_status = '0'
        if us.add_user(user_in, session):
            return rc.response_success(msg="保存成功")
        else:
            return rc.response_error(msg="保存失败")


@user.get("/{id}")
def get_user(id: int, session: Session = Depends(get_db)):
    """
    根据用户id获取用户信息
    :param session:
    :param id: 用户id
    :return: 用户信息
    """
    user = us.get_user_by_id(id, session)
    if user is None:
        return rc.response_success(data=None)
    user_out = SysUserOut.from_orm(user)
    return rc.response_success(data=user_out.dict())


@user.post("/stop/{id}")
def stop_user(id: int, session: Session = Depends(get_db)):
    """
    停用用户。修改用户状态，并删除保存过的登录redis
    :param session:
    :param id:
    :return:
    """
    user = us.get_user_by_id(id, session)
    if user is None:
        return rc.response_error("用户查询错误，请稍后再试")
    us.stop_user(user)
    redis_conn.delete(id)
    return rc.response_success("停用用户成功")


@user.post("/start/{id}")
def start_user(id: int, session: Session = Depends(get_db)):
    """
    启用用户。修改用户状态
    :param session:
    :param id:
    :return:
    """
    user = us.get_user_by_id(id, session)
    if user is None:
        return rc.response_error("用户查询错误，请稍后再试")
    us.start_user(user)
    return rc.response_success("启用用户成功")
