#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : im_chat_to_user.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : IM 单聊消息发送与记录。

import logging

from django.core.cache import cache

from django_base_ai.system.models import IMChatToUser, IMSession
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
from django_base_ai.websocket.websocket_config import websocket_push

logger = logging.getLogger(__name__)


class IMChatToUserSerializer(CustomModelSerializer):
    class Meta:
        model = IMChatToUser
        fields = "__all__"
        read_only_fields = ["id"]


class IMChatToUserCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = IMChatToUser
        fields = "__all__"


class IMChatToUserViewSet(CustomModelViewSet):
    """
    会话管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = IMChatToUser.objects.all()
    serializer_class = IMChatToUserSerializer
    # extra_filter_backends = []

    def create(self, request, *args, **kwargs):
        copy_data = request.data
        current_user = request.user
        from_to_user = copy_data.get("from_to_user")
        # 点对点聊天 A To B
        im_session = None
        im_chat_to_user_obj = IMChatToUser.objects.filter(creator=current_user.id, from_to_user=from_to_user).first()
        if im_chat_to_user_obj is None:
            im_session = IMSession.objects.create(im_session_type=0, creator=current_user.id, modifier=current_user.id)
        else:
            im_session = im_chat_to_user_obj.im_session
        copy_data.update({"im_session": im_session.id})
        serializer = self.get_serializer(data=copy_data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        content = serializer.data.get("content", {})
        websocket_push(f"{from_to_user}", message={"nid": serializer.data.get("id", 0), "content": content})
        cache.set(f"{im_session}_{current_user.id}", content, 3000)
        return DetailResponse(data=serializer.data, msg="新增成功")
