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

from app.controllers.industry import industry_controller
from app.schemas import Success, SuccessExtra
from app.schemas.industry import IndustryCreate, IndustryUpdate, IndustryResponse

router = APIRouter(tags=["行业管理"])


@router.get("/list", summary="查看行业列表")
async def list_industry(
    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, industry_objs = await industry_controller.list(page=page, page_size=page_size, search=q, order=["id"])
    data = [await obj.to_dict() for obj in industry_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@router.get("/get", summary="查看行业详情")
async def get_industry(
    id: int = Query(..., description="行业 ID"),
):
    industry_obj = await industry_controller.get(id=id)
    data = await industry_obj.to_dict()
    return Success(data=data)


@router.post("/create", summary="创建行业")
async def create_industry(
    industry_in: IndustryCreate,
):
    # 检查代码是否已存在
    if await industry_controller.is_exist(industry_in.code):
        return Success(code=400, msg="行业代码已存在")
    
    await industry_controller.create(obj_in=industry_in)
    return Success(msg="创建成功")


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


@router.delete("/delete", summary="删除行业")
async def delete_industry(
    industry_id: int = Query(..., description="行业 ID"),
):
    await industry_controller.remove(id=industry_id)
    return Success(msg="删除成功")