import pyotp
from typing import List
from fastapi import Depends, APIRouter
from datetime import timedelta
from sqlalchemy.orm import Session
from app import get_db
from app.api.users import crud, schemas
from app.api.users.login_verification import authenticate_user, create_access_token, get_user, authenticate_pwd
from app.api.users.schemas import UserLoginForm, GoogleCode, GoogleLogin
from libs.google_code import get_qrcode, google_verify_result
from libs.img_code import imageCode
from libs.result_format import HttpResultResponse, HttpMessage
from libs.token_verify import auth_token, get_current_user

router = APIRouter()


@router.get("/imgCode")
def img_code():
    return HttpResultResponse(data=imageCode().getImgCode())


@router.post("/login")
def login(form_data: UserLoginForm, db: Session = Depends(get_db)):
    user_info = authenticate_user(db=db, form_data=form_data)
    if not user_info.get("result"):
        return HttpResultResponse(code=500, msg=user_info.get("msg"), data={})
    return HttpResultResponse(msg=HttpMessage.LOGIN_SUCCESS, data={"google_key": user_info.get("google_key")})


@router.post("/goodleCode")
def goodle_code(data: GoogleCode, db: Session = Depends(get_db)):
    user_data = get_user(db, data.username)
    google_key = pyotp.random_base32(64)
    google_img = get_qrcode(username=user_data.username, gtoken=google_key).decode('utf-8')
    return HttpResultResponse(data={"google_img": google_img, "google_key": google_key})


@router.post("/googleLogin")
def google_login(data: GoogleLogin, db: Session = Depends(get_db)):
    auth_info = authenticate_pwd(db=db, form_data=data)
    if not auth_info.get("result"):
        return HttpResultResponse(code=500, msg=auth_info.get("msg"))
    verify = google_verify_result(db=db, data=data)
    if verify:
        # 定义tokens过期时间
        access_token_expires = timedelta(hours=12)
        token_data = {"username": data.username, "password": data.password}
        access_token = create_access_token(data=token_data, expires_delta=access_token_expires)
        return HttpResultResponse(msg=HttpMessage.LOGIN_SUCCESS, data={"access_token": access_token, "token_type": "bearer"})
    else:
        return HttpResultResponse(code=500, msg="登录失败,谷歌动态码错误", data={})


@router.get("/tokenUser")
def token_user(token=Depends(auth_token), db: Session = Depends(get_db)):
    """通过token，获取登录用户信息"""
    user_data = get_current_user(db=db, token=token)
    return HttpResultResponse(code=200, data=user_data)


@router.post("/create")
def create_user(data: schemas.UserCreate, db: Session = Depends(get_db)):
    """添加用户"""
    db_user = crud.get_user_by_name(db, username=data.username)
    if db_user:
        return HttpResultResponse(code=400, msg=HttpMessage.USER_EXIST)
    res = crud.create_user(db=db, user=data)
    if not res:
        return HttpResultResponse(code=500, msg=res)
    return HttpResultResponse(data=res.id)


@router.post("/permission/allocation")
def read_user(data: schemas.PermissionCreate, db: Session = Depends(get_db)):
    """用户修改"""
    crud.update_user(db, data)
    return HttpResultResponse()


@router.post("/list")
def user_list(data: schemas.UserList, db: Session = Depends(get_db)):
    """用户列表"""
    result = crud.get_users(db, data)
    return HttpResultResponse(total=len(result), data=result)


@router.delete("/delete/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
    """用户删除"""
    crud.delete_user(db, user_id)
    return HttpResultResponse()
