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

from app.controllers.index import index_controller
from app.schemas import Success, SuccessExtra
from app.schemas.index import IndexCreate, IndexUpdate, IndexResponse

router = APIRouter(tags=["指数管理"])


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


@router.get("/get", summary="查看指数详情")
async def get_index(
    id: int = Query(..., description="指数 ID"),
):
    index_obj = await index_controller.get(id=id)
    data = await index_obj.to_dict()
    return Success(data=data)


@router.post("/create", summary="创建指数")
async def create_index(
    index_in: IndexCreate,
):
    # 检查代码是否已存在
    if await index_controller.is_exist(index_in.code):
        return Success(code=400, msg="指数代码已存在")
    
    await index_controller.create(obj_in=index_in)
    return Success(msg="创建成功")


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


@router.delete("/delete", summary="删除指数")
async def delete_index(
    index_id: int = Query(..., description="指数 ID"),
):
    await index_controller.remove(id=index_id)
    return Success(msg="删除成功")