# -*- 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 GatewayService
from .schema import GatewayCreateSchema, GatewayUpdateSchema, GatewayQueryParam

GatewayRouter = APIRouter(prefix='/gateway', tags=["网关信息模块"]) 

@GatewayRouter.get("/detail/{id}", summary="获取网关信息详情", description="获取网关信息详情")
async def get_gateway_detail_controller(
    id: int = Path(..., description="ID"),
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:query"]))
) -> JSONResponse:
    """获取网关信息详情接口"""
    result_dict = await GatewayService.detail_gateway_service(auth=auth, id=id)
    log.info(f"获取网关信息详情成功 {id}")
    return SuccessResponse(data=result_dict, msg="获取网关信息详情成功")

@GatewayRouter.get("/list", summary="查询网关信息列表", description="查询网关信息列表")
async def get_gateway_list_controller(
    page: PaginationQueryParam = Depends(),
    search: GatewayQueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:query"]))
) -> JSONResponse:
    """查询网关信息列表接口（数据库分页）"""
    result_dict = await GatewayService.page_gateway_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("查询网关信息列表成功")
    return SuccessResponse(data=result_dict, msg="查询网关信息列表成功")

@GatewayRouter.post("/create", summary="创建网关信息", description="创建网关信息")
async def create_gateway_controller(
    data: GatewayCreateSchema,
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:create"]))
) -> JSONResponse:
    """创建网关信息接口"""
    result_dict = await GatewayService.create_gateway_service(auth=auth, data=data)
    log.info("创建网关信息成功")
    return SuccessResponse(data=result_dict, msg="创建网关信息成功")

@GatewayRouter.put("/update/{id}", summary="修改网关信息", description="修改网关信息")
async def update_gateway_controller(
    data: GatewayUpdateSchema,
    id: int = Path(..., description="ID"),
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:update"]))
) -> JSONResponse:
    """修改网关信息接口"""
    result_dict = await GatewayService.update_gateway_service(auth=auth, id=id, data=data)
    log.info("修改网关信息成功")
    return SuccessResponse(data=result_dict, msg="修改网关信息成功")

@GatewayRouter.delete("/delete", summary="删除网关信息", description="删除网关信息")
async def delete_gateway_controller(
    ids: list[int] = Body(..., description="ID列表"),
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:delete"]))
) -> JSONResponse:
    """删除网关信息接口"""
    await GatewayService.delete_gateway_service(auth=auth, ids=ids)
    log.info(f"删除网关信息成功: {ids}")
    return SuccessResponse(msg="删除网关信息成功")

@GatewayRouter.patch("/available/setting", summary="批量修改网关信息状态", description="批量修改网关信息状态")
async def batch_set_available_gateway_controller(
    data: BatchSetAvailable,
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:patch"]))
) -> JSONResponse:
    """批量修改网关信息状态接口"""
    await GatewayService.set_available_gateway_service(auth=auth, data=data)
    log.info(f"批量修改网关信息状态成功: {data.ids}")
    return SuccessResponse(msg="批量修改网关信息状态成功")

@GatewayRouter.post('/export', summary="导出网关信息", description="导出网关信息")
async def export_gateway_list_controller(
    search: GatewayQueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:export"]))
) -> StreamingResponse:
    """导出网关信息接口"""
    result_dict_list = await GatewayService.list_gateway_service(search=search, auth=auth)
    export_result = await GatewayService.batch_export_gateway_service(obj_list=result_dict_list)
    log.info('导出网关信息成功')

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

@GatewayRouter.post('/import', summary="导入网关信息", description="导入网关信息")
async def import_gateway_list_controller(
    file: UploadFile,
    auth: AuthSchema = Depends(AuthPermission(["module_business:gateway:import"]))
) -> JSONResponse:
    """导入网关信息接口"""
    batch_import_result = await GatewayService.batch_import_gateway_service(file=file, auth=auth, update_support=True)
    log.info("导入网关信息成功")
    
    return SuccessResponse(data=batch_import_result, msg="导入网关信息成功")

@GatewayRouter.post('/download/template', summary="获取网关信息导入模板", description="获取网关信息导入模板", dependencies=[Depends(AuthPermission(["module_business:gateway:download"]))])
async def export_gateway_template_controller() -> StreamingResponse:
    """获取网关信息导入模板接口"""
    import_template_result = await GatewayService.import_template_download_gateway_service()
    log.info('获取网关信息导入模板成功')

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