from fastapi import APIRouter, Depends
from app.api import Response, pwd_context, get_current_user, ResponseList
from app.config.const import USER_STATSU_DELETE
from app.models.base_model import get_db
from app.models.user import PageParameter, UserStatus, UserInfo, LoginData, UserPassword, UserDept
from app.models.user_model import UserModel
from app.service.auth import is_valid_password, verify_password, password_rsa
from app.service.user import get_user_list, edit_user_status, delete_user_data, create_user, edit_user_data, \
    edit_user_pwd, get_user_info, get_user_routers, get_user_menus, get_user_permission, get_user_dept, change_user_pwd, \
    user_data_service, edit_user_dept

user_router = APIRouter()


@user_router.get("/list", response_model=Response)
async def user_list(current:int, pageSize:int, keyword="", current_user: UserModel = Depends(get_current_user),
                    db=Depends(get_db)):
    return Response(code=200, msg="", data=await get_user_list(db, current, pageSize, keyword,
                                                               current_user.permission, current_user.id))


@user_router.post("/add_user", response_model=Response)
async def add_user(user: UserInfo, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    if not user.userName:
        return Response(code=400, msg="The userName cannot be empty!")
    if "@" in user.userName:
        return Response(code=400, msg="Username cannot contain @")
    if user.pwd:
        if not is_valid_password(user.pwd):
            return Response(code=400, msg="The password must be at least 8 and contain both numbers and letters")
    db_user = db.query(UserModel).filter(UserModel.username == user.userName, UserModel.status != USER_STATSU_DELETE).first()
    if db_user:
        return Response(code=400, msg="user already created")
    pwd = user.pwd
    if not pwd:
        pwd = "basic123456"
    user_flag = await create_user(db, user.userName, user.email, user.phone, user.loginName, pwd, user.roles,
                                  user.groups, current_user.id)
    # if not is_create:
    #     return Response(code=500, msg="user create failure", data={})
    return Response(code=200, msg="user create successfully", data={"userFlag": user_flag})


@user_router.put("/edit_user", response_model=Response)
async def edit_user(user: UserInfo, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    user_info = db.query(UserModel).filter(UserModel.id == user.userId).first()
    if not user_info:
        return Response(code=200, msg="user does not exist")
    is_edit = await edit_user_data(db, user.userId, user.email, user.phone, user.loginName, user.roles, user.groups)
    if not is_edit:
        return Response(code=500, msg="user edit failure", data={})
    return Response(code=200, msg="user edit successfully", data={})


@user_router.put("/change_status", response_model=Response)
async def change_user_status(user: UserStatus, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    if user.status not in ["0", "1"]:
        return Response(code=400, msg="The status cannot be {}!".format(user.status))
    db_user = db.query(UserModel).filter(UserModel.id == user.userId).first()
    if not db_user:
        return Response(code=200, msg="user does not exist")
    is_edit = await edit_user_status(db, user.status, user.userId)
    if not is_edit:
        return Response(code=500, msg="user status edit failure", data={})
    return Response(code=200, msg="user status edit successfully", data={})


@user_router.delete("/delete_user/{user_id}", response_model=Response)
async def delete_user(user_id, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if not db_user:
        return Response(code=200, msg="user does not exist")
    is_edit = await delete_user_data(db, user_id)
    if not is_edit:
        return Response(code=500, msg="user delete failure", data={})
    return Response(code=200, msg="user delete successfully", data={})


@user_router.put("/reset_pwd", response_model=Response)
async def reset_user_pwd(user: UserStatus,  current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    is_edit = await edit_user_pwd(db, user.userId, current_user.id)
    if not is_edit:
        return Response(code=500, msg="user pwd reset failure", data={})
    return Response(code=200, msg="user pwd reset successfully", data={})


@user_router.put("/change_password", response_model=Response)
async def change_user_password(user: UserPassword,  current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    user_info = db.query(UserModel).filter(UserModel.id==current_user.id).first()
    if not user_info:
        return Response(code=401, msg="Incorrect change password !")
    old_password = await password_rsa(user.oldPassword)
    new_password = await password_rsa(user.newPassword)
    if not verify_password(old_password, user_info.hashed_password):
        return Response(code=400, msg="Incorrect password !")
    if not is_valid_password(new_password):
        return Response(code=400, msg="The password must be at least 8 and contain both numbers and letters")
    is_edit = await change_user_pwd(db, user_info.id, new_password)
    if not is_edit:
        return Response(code=500, msg="user pwd change failure", data={})
    return Response(code=200, msg="user pwd change success", data={})


@user_router.get("/user_info", response_model=Response)
async def user_info(current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    user_info = await get_user_info(db,  current_user.id)
    if not user_info:
        return Response(code=500, msg="user get failure", data={})
    return Response(code=200, msg="successfully", data=user_info)


@user_router.get("/user_routers", response_model=Response)
async def user_routers(current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    routers = await get_user_routers(db,  current_user.id)
    if not routers:
        return Response(code=500, msg="user get failure", data={})
    return Response(code=200, msg="successfully", data=routers)


@user_router.get("/menus", response_model=ResponseList)
async def user_menus(keyword="", current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    menus = await get_user_menus(db,  current_user.id)
    # return Response(code=200, msg="successfully", data=menus)
    # result = [item.to_dict() for item in agents]
    return ResponseList(code=200, msg="successfully", data=menus)


@user_router.get("/permission", response_model=Response)
async def user_permission(userId:int, current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    menus = await get_user_permission(db,  userId)
    return Response(code=200, msg="successfully", data=menus)


@user_router.get("/dept", response_model=Response)
async def user_dept_api(userId:int, current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    menus = await get_user_dept(db, userId)
    return Response(code=200, msg="successfully", data=menus)


@user_router.get("/user_data", response_model=Response)
async def user_data_api(userId, current_user: UserModel = Depends(get_current_user),db=Depends(get_db)):
    user_info = await user_data_service(db, userId)
    if not user_info:
        return Response(code=500, msg="user get failure", data={})
    return Response(code=200, msg="successfully", data=user_info)



@user_router.put("/dept", response_model=Response)
async def edit_user(user: UserDept, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    user_info = db.query(UserModel).filter(UserModel.id == user.userId).first()
    if not user_info:
        return Response(code=400, msg="user does not exist")
    is_edit = await edit_user_dept(db, user.userId, user.depts)
    if not is_edit:
        return Response(code=500, msg="user edit failure", data={})
    return Response(code=200, msg="user edit successfully", data={})


@user_router.get("/ping", response_model=Response)
async def user_ping(current_user: UserModel = Depends(get_current_user)):
    return Response(code=200, msg="", data={})