#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : menu_button.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 菜单按钮（权限点）CRUD。
import logging

from django.db.models import CharField, Value
from django.db.models.functions import Concat
from rest_framework.decorators import action

from django_base_ai.system.models import Menu, MenuButton
from django_base_ai.utils.json_response import DetailResponse
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class MenuButtonSerializer(CustomModelSerializer):
    """
    菜单按钮-序列化器
    """

    class Meta:
        model = MenuButton
        fields = ["id", "name", "value", "api", "method", "menu"]
        read_only_fields = ["id"]


class MenuButtonInitSerializer(CustomModelSerializer):
    """
    初始化菜单按钮-序列化器
    """

    class Meta:
        model = MenuButton
        fields = ["id", "name", "value", "api", "method", "menu"]
        read_only_fields = ["id"]


class MenuButtonCreateUpdateSerializer(CustomModelSerializer):
    """
    初始化菜单按钮-序列化器
    """

    class Meta:
        model = MenuButton
        fields = "__all__"
        read_only_fields = ["id"]


class MenuButtonViewSet(CustomModelViewSet):
    """
    菜单按钮接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = MenuButton.objects.all()
    serializer_class = MenuButtonSerializer
    create_serializer_class = MenuButtonCreateUpdateSerializer
    update_serializer_class = MenuButtonCreateUpdateSerializer
    # extra_filter_backends = []

    @action(methods=["GET"], detail=False, permission_classes=[])
    def get_btn_permission(self, request):
        """
        获取当前用户的按钮权限
        """
        user = request.user
        if not user.is_superuser:
            menu_ids = user.role.values_list("menu__id", flat=True)
        else:
            menu_ids = Menu.objects.filter(status=1)
        queryset = (
            MenuButton.objects.filter(menu__in=menu_ids)
            .annotate(permission=Concat("menu__web_path", Value(":"), "value", output_field=CharField()))
            .values_list("permission", flat=True)
        )
        return DetailResponse(data=queryset)
