#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : im_session.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 会话表
import logging

from django.core.cache import cache
from rest_framework import serializers

from django_base_ai.system.models import IMChatToGroupMessage, IMChatToUser, IMSession
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class IMSessionSerializer(CustomModelSerializer):
    userinfo = serializers.SerializerMethodField()
    seats = serializers.SerializerMethodField()
    session_id = serializers.SerializerMethodField()
    un_read_count = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()
    update_datetime = serializers.SerializerMethodField()
    create_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    def get_userinfo(self, obj):
        from_user = obj.parent.from_user if obj.parent else obj.from_user
        return {
            "uid": from_user.id,
            "username": from_user.username,
            "email": from_user.email,
            "mobile": from_user.mobile,
            "landline": from_user.landline,
            "avatar": from_user.avatar,
            "name": from_user.name,
            "alias": from_user.alias,
            "main_department": from_user.main_department,
            "dept": from_user.dept.name if from_user.dept else "",
        }

    def get_un_read_count(self, obj):
        session_id = obj.parent if obj.parent else obj
        if obj.session_type:
            return IMChatToGroupMessage.objects.filter(
                im_chat_to_group__im_session=session_id, from_to_user=self.request.user, is_read=True
            ).count()
        return IMChatToUser.objects.filter(im_session=session_id, from_to_user=self.request.user, is_read=True).count()

    def get_last_message(self, obj):
        return cache.get(f"{obj.parent.session_id if obj.parent else obj.session_id}_{self.request.user.id}", {})

    def get_update_datetime(self, obj):
        return obj.update_datetime.strftime("%H:%M")

    def get_session_id(self, obj):
        return obj.parent.session_id if obj.parent else obj.session_id

    def get_seats(self, obj):
        if not obj.ai_desk_app_manage:
            return None
        return obj.ai_desk_app_manage.seats

    class Meta:
        model = IMSession
        fields = [
            "id",
            "session_id",
            "userinfo",
            "is_it_pinned",
            "is_claim",
            "is_colse",
            "un_read_count",
            "last_message",
            "ai_desk_app_manage",
            "seats",
            "create_datetime",
            "update_datetime",
        ]
        read_only_fields = ["id"]


class IMSessionCreateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        kwargs.update({"from_user": self.request.user})
        data = super().save(**kwargs)
        data.save()
        return data

    class Meta:
        model = IMSession
        fields = "__all__"


class IMSessionUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = IMSession
        fields = "__all__"


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

    queryset = IMSession.objects.all().filter(is_colse=False).order_by("-create_datetime")
    serializer_class = IMSessionSerializer
    filter_fields = ["session_id", "is_it_pinned", "is_claim", "is_colse", "ai_desk_app_manage"]
    create_serializer_class = IMSessionCreateSerializer
    update_serializer_class = IMSessionUpdateSerializer
    # extra_filter_backends = []
