# _*_ coding : UTF-8 _*_
# @Time : 2025/02/12 16:58
# @UpdateTime : 2025/02/12 16:58
# @Author : sonder
# @File : config.py
# @Software : PyCharm
# @Comment : 本程序

from typing import Optional

from fastapi import APIRouter, Depends, Path, Request, Query
from fastapi.responses import JSONResponse

from annotation.log import Log
from config.constant import BusinessType
from config.get_redis import Redis
from controller.login import LoginController
from models import Config
from schemas.common import BaseResponse
from schemas.config import AddConfigParams, DeleteConfigListParams, GetConfigInfoResponse, GetConfigListResponse
from utils.response import Response

configApi = APIRouter(
    prefix="/config",
    dependencies=[Depends(LoginController.get_current_user)],
)


@configApi.post("/add", response_class=JSONResponse, response_model=BaseResponse, summary="新增配置")
@Log(title="新增配置", business_type=BusinessType.INSERT)
async def add_config(request: Request, params: AddConfigParams):
    if await Config.get_or_none(name=params.name, key=params.key):
        return Response.error(msg="配置已存在")
    config = await Config.create(
        name=params.name,
        key=params.key,
        value=params.value,
        remark=params.remark,
        type=params.type,
    )
    if config:
        await Redis.init_system_config(request.app)
        return Response.success(msg="新增成功")
    else:
        return Response.error(msg="新增失败")


@configApi.delete("/delete/{id}", response_class=JSONResponse, response_model=BaseResponse, summary="删除配置")
@configApi.post("/delete/{id}", response_class=JSONResponse, response_model=BaseResponse, summary="删除配置")
@Log(title="删除配置", business_type=BusinessType.DELETE)
async def delete_config(request: Request, id: str = Path(description="配置ID")):
    if config := await Config.get_or_none(id=id):
        await config.delete()
        await Redis.init_system_config(request.app)
        return Response.success(msg="删除成功")
    else:
        return Response.error(msg="配置不存在")


@configApi.delete("/deleteList", response_class=JSONResponse, response_model=BaseResponse, summary="批量删除配置")
@configApi.post("/deleteList", response_class=JSONResponse, response_model=BaseResponse, summary="批量删除配置")
@Log(title="批量删除配置", business_type=BusinessType.DELETE)
async def delete_config_list(request: Request, params: DeleteConfigListParams):
    for id in set(params.ids):
        if config := await Config.get_or_none(id=id):
            await config.delete()
    await Redis.init_system_config(request.app)
    return Response.success(msg="删除成功")


@configApi.put("/update/{id}", response_class=JSONResponse, response_model=BaseResponse, summary="修改配置")
@configApi.post("/update/{id}", response_class=JSONResponse, response_model=BaseResponse, summary="修改配置")
@Log(title="修改配置", business_type=BusinessType.UPDATE)
async def update_config(request: Request, params: AddConfigParams, id: str = Path(description="配置ID")):
    if config := await Config.get_or_none(id=id):
        config.name = params.name
        config.key = params.key
        config.value = params.value
        config.remark = params.remark
        config.type = params.type
        await config.save()
        await Redis.init_system_config(request.app)
        return Response.success(msg="修改成功")
    else:
        return Response.error(msg="配置不存在")


@configApi.get("/info/{id}", response_class=JSONResponse, response_model=GetConfigInfoResponse, summary="获取配置信息")
@Log(title="获取配置信息", business_type=BusinessType.SELECT)
async def get_config_info(request: Request, id: str = Path(description="配置ID")):
    if config := await Config.get_or_none(id=id):
        data = {
            "id": config.id,
            "name": config.name,
            "key": config.key,
            "value": config.value,
            "remark": config.remark,
            "type": config.type,
            "create_time": config.create_time,
            "create_by": config.create_by,
            "update_time": config.update_time,
            "update_by": config.update_by,
        }
        return Response.success(data=data)
    else:
        return Response.error(msg="配置不存在")


@configApi.get("/list", response_class=JSONResponse, response_model=GetConfigListResponse, summary="获取配置列表")
@Log(title="获取配置列表", business_type=BusinessType.SELECT)
async def get_config_list(request: Request,
                          page: int = Query(default=1, description="当前页码"),
                          pageSize: int = Query(default=10, description="每页数量"),
                          key: Optional[str] = Query(default=None, description="配置键名"),
                          name: Optional[str] = Query(default=None, description="配置名称"),
                          type: Optional[str] = Query(default=None, description="系统内置"),
                          ):
    filterArgs = {
        f'{k}__contains': v for k, v in {
            'name': name,
            'key': key,
            'type': type,
        }.items() if v
    }
    total = await Config.filter(**filterArgs).count()
    data = await Config.filter(**filterArgs).offset((page - 1) * pageSize).limit(pageSize).values(
        id="id",
        name="name",
        key="key",
        value="value",
        remark="remark",
        type="type",
        create_time="create_time",
        create_by="create_by",
        update_time="update_time",
        update_by="update_by",
    )
    return Response.success(data={
        "total": total,
        "result": data,
        "page": page,
        "pageSize": pageSize,
    })
