#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : message_center_target_user.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 IsAuthenticated

from django_base_ai.system.models import MessageCenterTargetUser
from django_base_ai.utils.json_response import DetailResponse, ErrorResponse, 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 MessageCenterTargetUserSerializer(CustomModelSerializer):
    u_id = serializers.IntegerField(read_only=True, source="users.id")
    name = serializers.StringRelatedField(read_only=True, source="users.name")
    username = serializers.StringRelatedField(read_only=True, source="users.username")
    title = serializers.StringRelatedField(read_only=True, source="messagecenter.title")
    short_content = serializers.StringRelatedField(read_only=True, source="messagecenter.short_content")
    thumbnail = serializers.StringRelatedField(read_only=True, source="messagecenter.thumbnail")
    message_type = serializers.IntegerField(read_only=True, source="messagecenter.message_type")
    content = serializers.StringRelatedField(read_only=True, source="messagecenter.content")
    url = serializers.StringRelatedField(read_only=True, source="messagecenter.url")
    target_type = serializers.IntegerField(read_only=True, source="messagecenter.target_type")
    is_withdraw = serializers.BooleanField(read_only=True, source="messagecenter.is_withdraw")
    ext_kwargs = serializers.JSONField(read_only=True, source="messagecenter.ext_kwargs")
    description = serializers.JSONField(read_only=True, source="messagecenter.description")

    class Meta:
        model = MessageCenterTargetUser
        fields = "__all__"
        read_only_fields = ["id"]
        # depth = 1


class ExportUserProfileSerializer(CustomModelSerializer):
    """
    用户导出 序列化器
    """

    is_read = serializers.SerializerMethodField(read_only=True)

    def get_is_read(self, instance):
        return "已读" if instance.is_read else "未读"

    class Meta:
        model = MessageCenterTargetUser
        fields = ("users__username", "is_read", "create_datetime", "update_datetime")


class MessageCenterTargetUserViewSet(CustomModelViewSet):
    """
    消息中心用户列表接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = MessageCenterTargetUser.objects.order_by("-id")
    serializer_class = MessageCenterTargetUserSerializer
    filter_fields = ["messagecenter", "$users__name"]
    search_fields = ["messagecenter__title", "messagecenter__short_content"]
    # 导出
    export_field_label = {
        "users__username": "用户账号",
        "is_read": "是否已读",
        "create_datetime": "创建时间",
        "update_datetime": "修改时间",
    }
    export_serializer_class = ExportUserProfileSerializer

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def get_first_msg(self, request):
        """
        获取最新的一条消息
        """
        self_user_id = self.request.user.id
        instance = (
            MessageCenterTargetUser.objects.filter(users__id=self_user_id, is_read=False)
            .order_by("-create_datetime")
            .first()
        )
        if not instance:
            return DetailResponse(msg="没有未读消息")
        serializer = self.get_serializer(instance)
        return DetailResponse(msg="已读", data=serializer.data)

    @action(methods=["GET"], detail=False, permission_classes=[OpenApiPermission], authentication_classes=[])
    def open_api_message_user_list(self, request):
        nid = request.GET.get("nid", None)
        if not nid:
            return ErrorResponse("消息nid参数错误")
        queryset = MessageCenterTargetUser.objects.filter(messagecenter__id=nid).all()
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def my_message(self, request, *args, **kwargs):
        """
        获取我的消息
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = MessageCenterTargetUser.objects.filter(users__id=self.request.user.id).order_by("-create_datetime")
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            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 click_one_read(self, request, *args, **kwargs):
        mid = request.GET.get("mid", None)
        if not mid:
            return ErrorResponse("消息ID参数错误")
        instance = MessageCenterTargetUser.objects.filter(id=mid, users__id=request.user.id).first()
        instance.is_read = True
        instance.save(update_fields=["is_read"])
        serializer = self.get_serializer(instance)
        return DetailResponse(msg="已读", data=serializer.data)
