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, add_google_key
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

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")
async 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")
async def goodleCode(data: GoogleCode, db: Session = Depends(get_db)):
    user_data = get_user(db, data.username)
    update_info = add_google_key(db=db, user_id=user_data.id)
    if not update_info.get("result"):
        return HttpResultResponse(code=500, msg="谷歌二维码生成失败")
    return get_qrcode(username=user_data.username, gtoken=update_info.get("google_key"))


@router.post("/googleLogin")
async def googleLogin(data: GoogleLogin, db: Session = Depends(get_db)):
    user_data = get_user(db, data.username)
    verify = google_verify_result(secret_key=user_data.google_key, google_code=data.google_code)
    if verify:
        # 定义tokens过期时间
        access_token_expires = timedelta(hours=12)
        token_data = {
            "username": user_data.username,
            "google_key": user_data.google_key
        }
        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)
