# coding:utf-8

from fastapi import APIRouter, Depends, UploadFile, File
from app.api import Response, get_current_user
from app.models.base_model import get_db
from app.models.role_model import RoleData, RoleModel
from app.models.system import SystemData, SystemLicense
from app.models.user_model import UserModel
from app.service.system import services_get_system_data, services_update_system_data, service_upload_logo_image, \
    services_update_system_license

system_router = APIRouter()


@system_router.get("/info", response_model=Response)
async def api_get_system_data(db=Depends(get_db)):

    data = await services_get_system_data(db)
    return Response(code=200, msg="successfully", data=data)


@system_router.put("/info", response_model=Response)
async def api_update_system_data(system: SystemData, u: UserModel = Depends(get_current_user), db=Depends(get_db)):

    data = await services_update_system_data(db, system.title, system.desc, system.logo)
    if not data:
        return Response(code=500, msg="failed", data=data)
    return Response(code=200, msg="successfully", data=data)


@system_router.post("/upload", response_model=Response)
async def api_upload_logo_image(file: UploadFile = File(...)):
    file_name = await service_upload_logo_image(file)
    if not file_name:
        return Response(code=500, msg="failed", data={"logo": ""})
    return Response(code=200, msg="successfully", data={"logo": file_name})


@system_router.put("/license", response_model=Response)
async def api_update_system_license(system: SystemLicense, db=Depends(get_db)):

    msg = await services_update_system_license(db, system.licenseCode)
    if msg:
        return Response(code=400, msg=msg, data={})
    return Response(code=200, msg="successfully", data={})

