#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : im_chat_to_group_message.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 群聊发送消息

import logging
from datetime import datetime

import django_filters
from django.core.cache import cache
from django_filters.rest_framework import FilterSet
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from django_base_ai.system.models import IMChatToGroup, IMChatToGroupMessage
from django_base_ai.utils.json_response import DetailResponse, ErrorResponse
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet
from django_base_ai.websocket.websocket_config import websocket_push

logger = logging.getLogger(__name__)


class IMChatToGroupMessageSerializer(CustomModelSerializer):
    class Meta:
        model = IMChatToGroupMessage
        fields = "__all__"
        read_only_fields = ["id"]


class IMChatToGroupMessageCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = IMChatToGroupMessage
        fields = "__all__"


class FilterIMChatToGroupMessage(FilterSet):
    im_session = django_filters.CharFilter(field_name="im_chat_to_group__session_id", method="filter_im_session")

    def filter_im_session(self, queryset, name, value):
        nid = self.request.GET.get("im_session")
        if IMChatToGroupMessage.objects.filter(
            from_to_user=self.request.user, im_chat_to_group__im_session__session_id=nid, is_read=True
        ).count():
            # 出于性能考虑先求总数
            IMChatToGroupMessage.objects.filter(
                from_to_user=self.request.user, im_chat_to_group__im_session__session_id=nid, is_read=True
            ).update(is_read=False)
        return queryset.filter(from_to_user=self.request.user, im_chat_to_group__im_session__session_id=nid)

    class Meta:
        model = IMChatToGroupMessage
        fields = ["im_session"]


class IMChatToGroupMessageViewSet(CustomModelViewSet):
    """
    群聊内容
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = IMChatToGroupMessage.objects.all().order_by("-id")
    serializer_class = IMChatToGroupMessageSerializer
    # extra_filter_backends = []
    filter_class = FilterIMChatToGroupMessage

    def create(self, request, *args, **kwargs):
        current_user = request.user
        copy_data = request.data
        im_session = copy_data.get("im_session", "")
        content = copy_data.get("content", {})
        # True 只发送自己
        send_self = copy_data.get("sendSelf", False)
        if im_session == "":
            return ErrorResponse(msg="参数不合法")
        # from_many_to_user__id__in=[current_user.id] 报错
        im_chat_to_group = IMChatToGroup.objects.filter(im_session__session_id=im_session).first()
        if not im_chat_to_group:
            return ErrorResponse(msg="群组不存在或您无权限访问")
        if send_self:
            from_many_to_user = [current_user.id]
        else:
            from_many_to_user = im_chat_to_group.from_many_to_user.all().values_list("id", flat=True)
            print("from_many_to_user=", from_many_to_user)
            copy_data.pop("im_session")
        im_chat_to_group_message_list = []
        for user in from_many_to_user:
            im_chat_to_group_message_list.append(
                IMChatToGroupMessage(
                    im_chat_to_group_id=im_chat_to_group.id,
                    from_user_id=current_user.id,
                    is_read=False if user == current_user.id else True,
                    from_to_user_id=user,
                    content=content,
                )
            )
            print(f"{user}_{im_chat_to_group.group_ext_info.get(str(current_user.id), 0)}发送成功")
            if int(user) != current_user.id or send_self:
                websocket_push(
                    f"{user}_{im_chat_to_group.group_ext_info.get(str(user), 0)}",
                    message={
                        "uid": current_user.id,
                        "username": current_user.username,
                        "im_session": im_session,
                        "email": current_user.email,
                        "mobile": current_user.mobile,
                        "landline": current_user.landline,
                        "avatar": current_user.avatar,
                        "name": current_user.name,
                        "update_datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        "create_datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        "data": copy_data,
                    },
                )
            # redis 记录最后一条消息
            cache.set(f"{im_session}_{user}", content, 3000)
        IMChatToGroupMessage.objects.bulk_create(im_chat_to_group_message_list)
        return DetailResponse(msg="发送成功")

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def update_read(self, request, *args, **kwargs):
        nid = self.request.GET.get("im_session")
        IMChatToGroupMessage.objects.filter(
            from_to_user=self.request.user, im_chat_to_group__im_session__session_id=nid, is_read=True
        ).update(is_read=False)
        return DetailResponse(msg="完成")
