#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : tags.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 用户自定义标签管理接口
import json
import logging

import httpx
from django.db.models import Q
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from django_base_ai.system.models import Apps, Tags
from django_base_ai.utils.json_response import DetailResponse, SuccessResponse
from django_base_ai.utils.permission import OpenApiPermission
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class TagsSerializer(CustomModelSerializer):
    user_info = serializers.SerializerMethodField(read_only=True)
    read_user_info = serializers.SerializerMethodField(read_only=True)
    edit_user_info = serializers.SerializerMethodField(read_only=True)
    dept = serializers.SerializerMethodField(read_only=True)

    def get_user_info(self, obj):
        return list(
            obj.user_info.all().values(
                "id", "username", "avatar", "name", "employee_no", "dept__short_name", "dept__name"
            )
        )

    def get_read_user_info(self, obj):
        return list(
            obj.read_user_info.all().values(
                "id", "username", "avatar", "name", "employee_no", "dept__short_name", "dept__name"
            )
        )

    def get_edit_user_info(self, obj):
        return list(
            obj.edit_user_info.all().values(
                "id", "username", "avatar", "name", "employee_no", "dept__short_name", "dept__name"
            )
        )

    def get_dept(self, obj):
        return list(obj.dept.all().values("id", "name", "short_name", "owner_user", "status"))

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


class TagsCreateSerializer(CustomModelSerializer):
    class Meta:
        model = Tags
        fields = "__all__"


class TagsUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Tags
        fields = "__all__"


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

    def validate_user_info(self, value):
        """验证并过滤不存在的用户ID"""
        if value:
            from django_base_ai.system.models import Users

            # 过滤掉不存在的用户ID
            existing_user_ids = Users.objects.filter(id__in=value).values_list("id", flat=True)
            filtered_ids = list(existing_user_ids)
            if len(filtered_ids) != len(value):
                missing_ids = set(value) - set(filtered_ids)
                logger.warning(f"Tags 初始化时发现不存在的用户ID: {missing_ids}，已自动过滤")
            return filtered_ids
        return value

    class Meta:
        model = Tags
        fields = ["name", "sort", "status", "user_info", "remark"]
        read_only_fields = ["id"]
        extra_kwargs = {}


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

    queryset = Tags.objects.all()
    serializer_class = TagsSerializer
    create_serializer_class = TagsCreateSerializer
    update_serializer_class = TagsUpdateSerializer

    # extra_filter_backends = []

    def create_or_update_tags(self, instance, action_type):
        apps_result = Apps.objects.filter(~Q(create_or_update_callback_url="")).filter(~Q(delete_callback_url="")).all()
        for item in apps_result:
            try:
                payload = json.dumps(
                    {"node_type": 3, "action_type": action_type, "info": dict(TagsSerializer(instance).data)},
                    ensure_ascii=False,
                )
                httpx.post(
                    item.create_or_update_callback_url,
                    headers={"Content-Type": "application/json; charset=utf-8"},
                    data=payload,
                )
            except Exception as e:
                print(e.args)

    def delete_tags(self, instance, action_type):
        apps_result = Apps.objects.filter(~Q(create_or_update_callback_url="")).filter(~Q(delete_callback_url="")).all()
        payload = json.dumps(
            {"node_type": 3, "action_type": action_type, "info": dict(TagsSerializer(instance).data)},
            ensure_ascii=False,
        )
        for item in apps_result:
            try:
                httpx.post(
                    item.delete_callback_url, headers={"Content-Type": "application/json; charset=utf-8"}, data=payload
                )
            except Exception as e:
                print(e.args)

    def perform_create(self, serializer):
        """
        重写 create 方法并在创建时执行回调函数
        """
        instance = serializer.save()
        self.post_create_callback(instance)

    def perform_update(self, serializer):
        """
        重写 update 方法并在更新时执行回调函数
        """
        instance = serializer.save()
        self.post_update_callback(instance)

    def destroy(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        instance = Tags.objects.filter(id=pk).first()
        self.post_delete_callback(instance)
        instance.delete()
        return DetailResponse(data=[], msg="删除成功")

    def post_create_callback(self, instance):
        """
        创建标签后的回调函数，可以执行日志记录、数据同步等操作
        """
        # 示例：可以在这里添加创建标签后要执行的操作
        print(f"标签 {instance.name} 已创建，执行回调处理。")
        self.create_or_update_tags(instance, 0)

    def post_update_callback(self, instance):
        """
        更新标签后的回调函数，可以执行日志记录、数据同步等操作
        """
        # 示例：可以在这里添加更新标签后要执行的操作
        print(f"标签 {instance.name} 已更新，执行回调处理。")
        self.create_or_update_tags(instance, 1)

    def post_delete_callback(self, instance):
        """
        删除标签后的回调函数，可以执行日志记录、数据同步等操作
        """
        # 示例：可以在这里添加删除标签后要执行的操作
        print(f"标签 {instance.name} 已删除，执行回调处理。")
        self.delete_tags(instance, 2)

    @action(methods=["GET"], detail=False, permission_classes=[OpenApiPermission], authentication_classes=[])
    def open_tags_info(self, request, *args, **kwargs):
        """
        第三方API同步部门接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            # 掩码
            serializer_data = self.set_mask_fields(serializer)
            return self.get_paginated_response(serializer_data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")

    @action(methods=["get"], detail=False, permission_classes=[IsAuthenticated])
    def other_tags(self, request, *args, **kwargs):
        """
        其它标签
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        result = []
        current_user = request.user
        queryset = (
            Tags.objects.filter(status=True)
            .filter(Q(read_user_info__in=[current_user]) | Q(edit_user_info__in=[current_user]))
            .distinct()
            .order_by("sort")
        )
        for item in queryset:
            status = False
            if item.edit_user_info.all().filter(id=current_user.id).exists():
                status = True
            user_info = item.user_info.all().values("id", "username", "avatar", "name", "employee_no")
            result.append({"id": item.id, "name": item.name, "user_info": user_info, "read_or_edit": status})
        return DetailResponse(result)
