# -*- coding: utf-8 -*-

from fastapi import APIRouter, Depends, UploadFile, Body, Path, Query
from fastapi.responses import StreamingResponse, JSONResponse

from app.common.response import SuccessResponse, StreamResponse
from app.core.dependencies import AuthPermission
from app.api.v1.module_system.auth.schema import AuthSchema
from app.core.base_params import PaginationQueryParam
from app.utils.common_util import bytes2file_response
from app.core.logger import log
from app.core.base_schema import BatchSetAvailable

from .service import {{ class_name }}Service
from .schema import {{ class_name }}CreateSchema, {{ class_name }}UpdateSchema, {{ class_name }}QueryParam

{{ class_name }}Router = APIRouter(prefix='/{{ business_name }}', tags=["{{ function_name }}模块"]) 

@{{ class_name }}Router.get("/detail/{id}", summary="获取{{ function_name }}详情", description="获取{{ function_name }}详情")
async def get_{{ business_name }}_detail_controller(
    id: int = Path(..., description="ID"),
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:query"]))
) -> JSONResponse:
    """获取{{ function_name }}详情接口"""
    result_dict = await {{ class_name }}Service.detail_{{ business_name }}_service(auth=auth, id=id)
    log.info(f"获取{{ function_name }}详情成功 {id}")
    return SuccessResponse(data=result_dict, msg="获取{{ function_name }}详情成功")

@{{ class_name }}Router.get("/list", summary="查询{{ function_name }}列表", description="查询{{ function_name }}列表")
async def get_{{ business_name }}_list_controller(
    page: PaginationQueryParam = Depends(),
    search: {{ class_name }}QueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:query"]))
) -> JSONResponse:
    """查询{{ function_name }}列表接口（数据库分页）"""
    result_dict = await {{ class_name }}Service.page_{{ business_name }}_service(
        auth=auth,
        page_no=page.page_no if page.page_no is not None else 1,
        page_size=page.page_size if page.page_size is not None else 10,
        search=search,
        order_by=page.order_by
    )
    log.info("查询{{ function_name }}列表成功")
    return SuccessResponse(data=result_dict, msg="查询{{ function_name }}列表成功")

@{{ class_name }}Router.post("/create", summary="创建{{ function_name }}", description="创建{{ function_name }}")
async def create_{{ business_name }}_controller(
    data: {{ class_name }}CreateSchema,
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:create"]))
) -> JSONResponse:
    """创建{{ function_name }}接口"""
    result_dict = await {{ class_name }}Service.create_{{ business_name }}_service(auth=auth, data=data)
    log.info("创建{{ function_name }}成功")
    return SuccessResponse(data=result_dict, msg="创建{{ function_name }}成功")

@{{ class_name }}Router.put("/update/{id}", summary="修改{{ function_name }}", description="修改{{ function_name }}")
async def update_{{ business_name }}_controller(
    data: {{ class_name }}UpdateSchema,
    id: int = Path(..., description="ID"),
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:update"]))
) -> JSONResponse:
    """修改{{ function_name }}接口"""
    result_dict = await {{ class_name }}Service.update_{{ business_name }}_service(auth=auth, id=id, data=data)
    log.info("修改{{ function_name }}成功")
    return SuccessResponse(data=result_dict, msg="修改{{ function_name }}成功")

@{{ class_name }}Router.delete("/delete", summary="删除{{ function_name }}", description="删除{{ function_name }}")
async def delete_{{ business_name }}_controller(
    ids: list[int] = Body(..., description="ID列表"),
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:delete"]))
) -> JSONResponse:
    """删除{{ function_name }}接口"""
    await {{ class_name }}Service.delete_{{ business_name }}_service(auth=auth, ids=ids)
    log.info(f"删除{{ function_name }}成功: {ids}")
    return SuccessResponse(msg="删除{{ function_name }}成功")

@{{ class_name }}Router.patch("/available/setting", summary="批量修改{{ function_name }}状态", description="批量修改{{ function_name }}状态")
async def batch_set_available_{{ business_name }}_controller(
    data: BatchSetAvailable,
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:patch"]))
) -> JSONResponse:
    """批量修改{{ function_name }}状态接口"""
    await {{ class_name }}Service.set_available_{{ business_name }}_service(auth=auth, data=data)
    log.info(f"批量修改{{ function_name }}状态成功: {data.ids}")
    return SuccessResponse(msg="批量修改{{ function_name }}状态成功")

@{{ class_name }}Router.post('/export', summary="导出{{ function_name }}", description="导出{{ function_name }}")
async def export_{{ business_name }}_list_controller(
    search: {{ class_name }}QueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:export"]))
) -> StreamingResponse:
    """导出{{ function_name }}接口"""
    result_dict_list = await {{ class_name }}Service.list_{{ business_name }}_service(search=search, auth=auth)
    export_result = await {{ class_name }}Service.batch_export_{{ business_name }}_service(obj_list=result_dict_list)
    log.info('导出{{ function_name }}成功')

    return StreamResponse(
        data=bytes2file_response(export_result),
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers={
            'Content-Disposition': 'attachment; filename={{ table_name }}.xlsx'
        }
    )

@{{ class_name }}Router.post('/import', summary="导入{{ function_name }}", description="导入{{ function_name }}")
async def import_{{ business_name }}_list_controller(
    file: UploadFile,
    auth: AuthSchema = Depends(AuthPermission(["{{ permission_prefix }}:import"]))
) -> JSONResponse:
    """导入{{ function_name }}接口"""
    batch_import_result = await {{ class_name }}Service.batch_import_{{ business_name }}_service(file=file, auth=auth, update_support=True)
    log.info("导入{{ function_name }}成功")
    
    return SuccessResponse(data=batch_import_result, msg="导入{{ function_name }}成功")

@{{ class_name }}Router.post('/download/template', summary="获取{{ function_name }}导入模板", description="获取{{ function_name }}导入模板", dependencies=[Depends(AuthPermission(["{{ permission_prefix }}:download"]))])
async def export_{{ business_name }}_template_controller() -> StreamingResponse:
    """获取{{ function_name }}导入模板接口"""
    import_template_result = await {{ class_name }}Service.import_template_download_{{ business_name }}_service()
    log.info('获取{{ function_name }}导入模板成功')

    return StreamResponse(
        data=bytes2file_response(import_template_result),
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers={'Content-Disposition': 'attachment; filename={{ table_name }}_template.xlsx'}
    )