"""评查点分组控制器。"""

from fastapi import Body, Depends, Query
from fastapi.responses import JSONResponse

from fastapi_common.fastapi_common_security.security import verify_access_token
from fastapi_common.fastapi_common_web.controller import BaseController
from fastapi_modules.fastapi_leaudit.domian.Dto.evaluationPointGroupDto import (
    EvaluationPointGroupBatchDeleteDTO,
    EvaluationPointGroupBatchStatusDTO,
    EvaluationPointGroupBindingCreateDTO,
    EvaluationPointGroupBindingUpdateDTO,
    EvaluationPointGroupCreateDTO,
    EvaluationPointGroupRuleDraftCreateDTO,
    EvaluationPointGroupRebindDTO,
    EvaluationPointGroupUpdateDTO,
)
from fastapi_modules.fastapi_leaudit.services.evaluationPointGroupService import IEvaluationPointGroupService
from fastapi_modules.fastapi_leaudit.services.impl.evaluationPointGroupServiceImpl import EvaluationPointGroupServiceImpl
from fastapi_modules.fastapi_leaudit.services.impl.permissionServiceImpl import PermissionServiceImpl
from fastapi_modules.fastapi_leaudit.services.permissionService import IPermissionService


class EvaluationPointGroupController(BaseController):
    """评查点分组控制器。"""

    def __init__(self):
        super().__init__(prefix="/v3/evaluation-point-groups", tags=["评查点分组"])
        self.GroupService: IEvaluationPointGroupService = EvaluationPointGroupServiceImpl()
        self.PermissionService: IPermissionService = PermissionServiceImpl()

        @self.router.get("")
        async def ListEvaluationPointGroups(
            name: str | None = Query(None, description="分组名称模糊搜索"),
            code: str | None = Query(None, description="分组编码模糊搜索"),
            is_enabled: bool | None = Query(None, description="是否启用"),
            pid: int | None = Query(None, description="父分组ID，0 表示一级分组"),
            page: int = Query(1, ge=1, description="页码"),
            page_size: int = Query(20, ge=1, le=500, description="分页大小"),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有评查点分组查看权限", "data": None})
            data = await self.GroupService.ListGroups(name, code, is_enabled, pid, page, page_size)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.get("/all")
        async def ListAllEvaluationPointGroups(
            include_disabled: bool = Query(False, description="是否包含禁用分组"),
            with_rule_count: bool = Query(True, description="是否返回评查点数"),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有评查点分组查看权限", "data": None})
            data = await self.GroupService.ListAllGroups(include_disabled, with_rule_count)
            return JSONResponse(status_code=200, content=[item.model_dump() for item in data])

        @self.router.get("/by-document-types")
        async def ListEvaluationPointGroupsByDocumentTypes(
            document_type_ids: str = Query(..., description="逗号分隔的文档类型ID列表"),
            include_disabled: bool = Query(False, description="是否包含禁用分组"),
            with_rule_count: bool = Query(False, description="是否返回评查点数"),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有评查点分组查看权限", "data": None})
            document_type_id_list = [int(item.strip()) for item in document_type_ids.split(",") if item.strip().isdigit()]
            data = await self.GroupService.ListGroupsByDocumentTypes(document_type_id_list, include_disabled, with_rule_count)
            return JSONResponse(status_code=200, content=[item.model_dump() for item in data])

        @self.router.post("")
        async def CreateEvaluationPointGroup(body: EvaluationPointGroupCreateDTO, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:create:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有创建评查点分组权限", "data": None})
            data = await self.GroupService.CreateGroup(body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.patch("/batch/status")
        async def BatchUpdateEvaluationPointGroupStatus(
            body: EvaluationPointGroupBatchStatusDTO,
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:batch:write", "evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有批量更新评查点分组权限", "data": None})
            data = await self.GroupService.BatchUpdateStatus(body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.delete("/batch")
        async def BatchDeleteEvaluationPointGroups(
            body: EvaluationPointGroupBatchDeleteDTO = Body(...),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:batch:write", "evaluation_group:delete:delete"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有批量删除评查点分组权限", "data": None})
            data = await self.GroupService.BatchDelete(body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.get("/{GroupId}")
        async def GetEvaluationPointGroup(
            GroupId: int,
            with_rule_count: bool = Query(True, description="是否返回评查点数"),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有评查点分组查看权限", "data": None})
            data = await self.GroupService.GetGroup(GroupId, with_rule_count)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.put("/{GroupId}")
        async def UpdateEvaluationPointGroup(GroupId: int, body: EvaluationPointGroupUpdateDTO, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:batch:write", "evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有更新评查点分组权限", "data": None})
            data = await self.GroupService.UpdateGroup(GroupId, body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.delete("/{GroupId}")
        async def DeleteEvaluationPointGroup(GroupId: int, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:batch:write", "evaluation_group:delete:delete"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有删除评查点分组权限", "data": None})
            data = await self.GroupService.DeleteGroup(GroupId)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.get("/{GroupId}/children")
        async def GetEvaluationPointGroupChildren(
            GroupId: int,
            is_enabled: bool | None = Query(None, description="是否启用"),
            page: int = Query(1, ge=1, description="页码"),
            page_size: int = Query(20, ge=1, le=500, description="分页大小"),
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有评查点分组查看权限", "data": None})
            data = await self.GroupService.GetChildren(GroupId, is_enabled, page, page_size)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.put("/{GroupId}/rebind")
        async def RebindEvaluationPointGroup(GroupId: int, body: EvaluationPointGroupRebindDTO, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有换绑评查点分组权限", "data": None})
            data = await self.GroupService.RebindGroup(GroupId, body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.post("/{GroupId}/bindings")
        async def CreateEvaluationPointGroupBinding(GroupId: int, body: EvaluationPointGroupBindingCreateDTO, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有绑定规则集权限", "data": None})
            data = await self.GroupService.CreateBinding(GroupId, body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.put("/bindings/{BindingId}")
        async def UpdateEvaluationPointGroupBinding(BindingId: int, body: EvaluationPointGroupBindingUpdateDTO, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有更新规则集绑定权限", "data": None})
            data = await self.GroupService.UpdateBinding(BindingId, body)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.delete("/bindings/{BindingId}")
        async def DeleteEvaluationPointGroupBinding(BindingId: int, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:update:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有删除规则集绑定权限", "data": None})
            await self.GroupService.DeleteBinding(BindingId)
            return JSONResponse(status_code=200, content={"success": True})

        @self.router.get("/{GroupId}/rule-template")
        async def GetEvaluationPointGroupRuleTemplate(GroupId: int, payload: dict = Depends(verify_access_token)):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:list:read", "rules:list:read"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有查看规则模板权限", "data": None})
            data = await self.GroupService.GetRuleTemplate(GroupId)
            return JSONResponse(status_code=200, content=data.model_dump())

        @self.router.post("/{GroupId}/rule-drafts")
        async def CreateEvaluationPointGroupRuleDraft(
            GroupId: int,
            body: EvaluationPointGroupRuleDraftCreateDTO,
            payload: dict = Depends(verify_access_token),
        ):
            if not await self._check_permission(int(payload["user_id"]), ["evaluation_group:update:write", "rules:create:write"]):
                return JSONResponse(status_code=403, content={"code": 403, "msg": "当前用户没有保存规则草稿权限", "data": None})
            effective_body = body.model_copy(update={"editor_user_id": body.editor_user_id or int(payload["user_id"])})
            data = await self.GroupService.CreateRuleDraft(GroupId, effective_body)
            return JSONResponse(status_code=200, content=data.model_dump())

    async def _check_permission(self, user_id: int, permission_keys: list[str]) -> bool:
        for permission_key in permission_keys:
            if await self.PermissionService.CheckPermission(user_id, permission_key):
                return True
        return False
