import time
from typing import List

import pyotp
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 oauth2_scheme, auth_token, get_current_user

router = APIRouter()


@router.get("/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return users


@router.get("/imgCode")
def imgCode():
    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.HFDU, data={"google_key": user_info.get("google_key")})


@router.post("/goodleCode")
def goodleCode(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 googleLogin(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.HFDU, data={"access_token": access_token, "token_type": "bearer"})
    else:
        return HttpResultResponse(code=500, msg="登录失败,谷歌动态码错误", 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)
    return HttpResultResponse(data=res.id)


# @router.get("/{user_id}")
# def read_user(user_id: int, db: Session = Depends(get_db)):
#     """查询单个用户信息"""
#     db_user = crud.get_user(db, user_id=user_id)
#     if db_user is None:
#         return HttpResultResponse(code=400, msg=HttpMessage.USER_NOT_EXIST)
#     return HttpResultResponse(data=db_user)


@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)