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

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

from app.common.response import SuccessResponse, StreamResponse
from app.core.dependencies import AuthPermission, redis_getter
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 BizMecService
from .schema import BizMecCreateSchema, BizMecUpdateSchema, BizMecQueryParam

BizMecRouter = APIRouter(prefix='/mec', tags=["机构信息模块"]) 

@BizMecRouter.get("/detail/{id}", summary="获取机构信息详情", description="获取机构信息详情")
async def get_mec_detail_controller(
    id: int = Path(..., description="ID"),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:query"]))
) -> JSONResponse:
    """获取机构信息详情接口"""
    result_dict = await BizMecService.detail_mec_service(auth=auth, id=id)
    log.info(f"获取机构信息详情成功 {id}")
    return SuccessResponse(data=result_dict, msg="获取机构信息详情成功")

@BizMecRouter.get("/detailForNo/{mec_no}", summary="获取机构信息详情", description="获取机构信息详情")
async def get_mec_detail_controller(
    mec_no: str = Path(..., description="MecNo"),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:query"]))
) -> JSONResponse:
    """获取机构信息详情接口"""
    result_dict = await BizMecService.detail_mec_service_for_no(auth=auth, mec_no=mec_no)
    log.info(f"获取机构信息详情成功 {id}")
    return SuccessResponse(data=result_dict, msg="获取机构信息详情成功")

@BizMecRouter.get("/list", summary="查询机构信息列表", description="查询机构信息列表")
async def get_mec_list_controller(
    page: PaginationQueryParam = Depends(),
    search: BizMecQueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:query"]))
) -> JSONResponse:
    """查询机构信息列表接口（数据库分页）"""
    result_dict = await BizMecService.page_mec_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="查询机构信息列表成功")

@BizMecRouter.post("/create", summary="创建机构信息", description="创建机构信息")
async def create_mec_controller(
    data: BizMecCreateSchema,
    redis: Redis = Depends(redis_getter),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:create"]))
) -> JSONResponse:
    """创建机构信息接口"""
    result_dict = await BizMecService.create_mec_service(auth=auth, data=data,redis=redis)
    log.info("创建机构信息成功")
    return SuccessResponse(data=result_dict, msg="创建机构信息成功")

@BizMecRouter.put("/update/{id}", summary="修改机构信息", description="修改机构信息")
async def update_mec_controller(
    data: BizMecUpdateSchema,
    id: int = Path(..., description="ID"),
    redis: Redis = Depends(redis_getter),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:update"]))
) -> JSONResponse:
    """修改机构信息接口"""
    result_dict = await BizMecService.update_mec_service(auth=auth, id=id, data=data,redis=redis)
    log.info("修改机构信息成功")
    return SuccessResponse(data=result_dict, msg="修改机构信息成功")

@BizMecRouter.delete("/delete", summary="删除机构信息", description="删除机构信息")
async def delete_mec_controller(
    ids: list[int] = Body(..., description="ID列表"),
    redis: Redis = Depends(redis_getter),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:delete"]))
) -> JSONResponse:
    """删除机构信息接口"""
    await BizMecService.delete_mec_service(auth=auth, ids=ids,redis=redis)
    log.info(f"删除机构信息成功: {ids}")
    return SuccessResponse(msg="删除机构信息成功")

@BizMecRouter.patch("/available/setting", summary="批量修改机构信息状态", description="批量修改机构信息状态")
async def batch_set_available_mec_controller(
    data: BatchSetAvailable,
    redis: Redis = Depends(redis_getter),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:patch"]))
) -> JSONResponse:
    """批量修改机构信息状态接口"""
    await BizMecService.set_available_mec_service(auth=auth, data=data,redis=redis)
    log.info(f"批量修改机构信息状态成功: {data.ids}")
    return SuccessResponse(msg="批量修改机构信息状态成功")

@BizMecRouter.post('/export', summary="导出机构信息", description="导出机构信息")
async def export_mec_list_controller(
    search: BizMecQueryParam = Depends(),
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:export"]))
) -> StreamingResponse:
    """导出机构信息接口"""
    result_dict_list = await BizMecService.list_mec_service(search=search, auth=auth)
    export_result = await BizMecService.batch_export_mec_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_mec.xlsx'
        }
    )

@BizMecRouter.post('/import', summary="导入机构信息", description="导入机构信息")
async def import_mec_list_controller(
    file: UploadFile,
    auth: AuthSchema = Depends(AuthPermission(["module_business:mec:import"]))
) -> JSONResponse:
    """导入机构信息接口"""
    batch_import_result = await BizMecService.batch_import_mec_service(file=file, auth=auth, update_support=True)
    log.info("导入机构信息成功")
    
    return SuccessResponse(data=batch_import_result, msg="导入机构信息成功")

@BizMecRouter.post('/download/template', summary="获取机构信息导入模板", description="获取机构信息导入模板", dependencies=[Depends(AuthPermission(["module_business:mec:download"]))])
async def export_mec_template_controller() -> StreamingResponse:
    """获取机构信息导入模板接口"""
    import_template_result = await BizMecService.import_template_download_mec_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_mec_template.xlsx'}
    )