from fastapi import APIRouter, Query
from tortoise.expressions import Q

from app.controllers.esg import esg_controller
from app.schemas import Success, SuccessExtra
from app.schemas.esg import ESGCreate, ESGUpdate, ESGResponse

router = APIRouter(tags=["ESG管理"])


@router.get("/list", summary="查看ESG列表")
async def list_esg(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    code: str = Query(None, description="ESG代码"),
    name: str = Query(None, description="ESG名称"),
    level: str = Query(None, description="ESG级别"),
):
    q = Q()
    if code:
        q &= Q(code__contains=code)
    if name:
        q &= Q(name__contains=name)
    if level:
        q &= Q(level__contains=level)
    total, esg_objs = await esg_controller.list(page=page, page_size=page_size, search=q, order=["id"])
    data = [await obj.to_dict() for obj in esg_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@router.get("/get", summary="查看ESG详情")
async def get_esg(
    id: int = Query(..., description="ESG ID"),
):
    esg_obj = await esg_controller.get(id=id)
    data = await esg_obj.to_dict()
    return Success(data=data)


@router.post("/create", summary="创建ESG")
async def create_esg(
    esg_in: ESGCreate,
):
    # 检查代码是否已存在
    if await esg_controller.is_exist(esg_in.code):
        return Success(code=400, msg="ESG代码已存在")
    
    await esg_controller.create(obj_in=esg_in)
    return Success(msg="创建成功")


@router.post("/update", summary="更新ESG")
async def update_esg(
    esg_in: ESGUpdate,
):
    # 检查代码是否已存在（排除当前记录）
    if esg_in.code:
        existing_obj = await esg_controller.model.filter(code=esg_in.code).exclude(id=esg_in.id).first()
        if existing_obj:
            return Success(code=400, msg="ESG代码已存在")
    
    await esg_controller.update(id=esg_in.id, obj_in=esg_in)
    return Success(msg="更新成功")


@router.delete("/delete", summary="删除ESG")
async def delete_esg(
    esg_id: int = Query(..., description="ESG ID"),
):
    await esg_controller.remove(id=esg_id)
    return Success(msg="删除成功")