#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : dictionary.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 数据字典 CRUD 与树形结构、初始化。
import logging

from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView

from django_base_ai import dispatch
from django_base_ai.system.models import Dictionary
from django_base_ai.utils.json_response import DetailResponse, SuccessResponse
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class DictionarySerializer(CustomModelSerializer):
    """
    字典-序列化器
    """

    dictionary_tree = serializers.SerializerMethodField()

    def get_dictionary_tree(self, obj: Dictionary):
        if obj.type != 9:
            return None
        return dispatch.get_all_list(None, obj.value)

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


class DictionaryInitSerializer(CustomModelSerializer):
    """
    初始化获取数信息(用于生成初始化json文件)
    """

    children = serializers.SerializerMethodField()

    def get_children(self, obj: Dictionary):
        data = []
        instance = Dictionary.objects.filter(parent_id=obj.id)
        if instance:
            serializer = DictionaryInitSerializer(instance=instance, many=True)
            data = serializer.data
        return data

    def save(self, **kwargs):
        instance = super().save(**kwargs)
        children = self.initial_data.get("children")
        if children:
            for data in children:
                data["parent"] = instance.id
                filter_data = {"value": data["value"], "parent": data["parent"]}
                instance_obj = Dictionary.objects.filter(**filter_data).first()
                if instance_obj and not self.initial_data.get("reset"):
                    continue
                serializer = DictionaryInitSerializer(instance_obj, data=data, request=self.request)
                serializer.is_valid(raise_exception=True)
                serializer.save()
        return instance

    class Meta:
        model = Dictionary
        fields = [
            "label",
            "value",
            "parent",
            "type",
            "color",
            "icon",
            "is_value",
            "status",
            "sort",
            "remark",
            "creator",
            "dept_belong_id",
            "children",
        ]
        read_only_fields = ["id"]
        extra_kwargs = {"creator": {"write_only": True}, "dept_belong_id": {"write_only": True}}


class DictionaryCreateUpdateSerializer(CustomModelSerializer):
    """
    字典管理 创建/更新时的列化器
    """

    class Meta:
        model = Dictionary
        fields = "__all__"


class DictionaryViewSet(CustomModelViewSet):
    """
    字典管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Dictionary.objects.all()
    serializer_class = DictionarySerializer
    # extra_filter_backends = []
    search_fields = ["label", "value"]

    @action(methods=["get"], detail=False, permission_classes=[AllowAny], authentication_classes=[])
    def dictionary_tree(self, request, *args, **kwargs):
        """
        返回指定节点递归树
        """
        key_value = request.GET.get("value", None)
        result = dispatch.get_all_list(None, key_value)
        return DetailResponse(result)


class InitDictionaryViewSet(APIView):
    """
    获取初始化配置
    """

    authentication_classes = []
    permission_classes = []
    queryset = Dictionary.objects.all()

    def get(self, request):
        dictionary_key = self.request.query_params.get("dictionary_key")
        if dictionary_key:
            if dictionary_key == "all":
                data = [ele for ele in dispatch.get_dictionary_config().values()]
                if not data:
                    dispatch.refresh_dictionary()
                    data = [ele for ele in dispatch.get_dictionary_config().values()]
            else:
                data = self.queryset.filter(parent__value=dictionary_key, status=True).values(
                    "id", "label", "value", "type", "color", "icon", "remark"
                )
            return SuccessResponse(data=data, msg="获取成功")
        return SuccessResponse(data=[], msg="获取成功")
