#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : im_chat_record_form.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 满意度
import logging
from datetime import datetime, timedelta

from django.core.cache import cache
from django.db.models import Count, F
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from django_base_ai.system.models import (
    AIDeskAppManage,
    IMChatQA,
    IMChatRecordForm,
    IMChatToGroup,
    IMChatToGroupMessage,
    IMSession,
)
from django_base_ai.utils.format_core_base_auth import get_auth_user_info
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 IMChatRecordFormSerializer(CustomModelSerializer):
    proportion = serializers.SerializerMethodField()

    def get_proportion(self, obj):
        return f"{40 / 50:.2%}"

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


class IMChatRecordFormCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = IMChatRecordForm
        fields = "__all__"


class IMChatRecordFormViewSet(CustomModelViewSet):
    """
    满意度
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = IMChatRecordForm.objects.all()
    serializer_class = IMChatRecordFormSerializer
    # extra_filter_backends = []
    filter_fields = ["im_session__ai_desk_app_manage"]

    @action(methods=["PUT"], detail=False, permission_classes=[IsAuthenticated])
    def update_record(self, request, *args, **kwargs):
        current_user = request.user
        im_session = request.data.get("im_session", 0)
        satisfaction_type = request.data.get("satisfaction_type", 0)
        satisfaction_info = request.data.get("satisfaction_info", "")
        if not im_session:
            return ErrorResponse(msg="参数不合法")
        im_session_obj = IMSession.objects.filter(session_id=im_session, creator=current_user.id).first()
        im_chat_to_group = IMChatToGroup.objects.filter(im_session__session_id=im_session_obj).first()
        if not im_session_obj:
            return ErrorResponse(msg="会话不存在或您无权操作")
        # 满意度
        IMChatRecordForm.objects.update_or_create(
            defaults={
                "im_session": im_session_obj,
                "satisfaction_type": satisfaction_type,
                "satisfaction_info": satisfaction_info,
                "creator": current_user.id,
                "modifier": current_user.id,
            },
            im_session=im_session_obj,
        )
        # 推送通知
        content = {"type": "tip", "data": "感谢评价", "id": current_user.id}
        websocket_push(f"{current_user.id}_{cache.get(current_user.id)}", message={"data": {"content": content}})
        IMChatToGroupMessage.objects.create(
            im_chat_to_group_id=im_chat_to_group.id,
            from_user_id=current_user.id,
            is_read=False,
            from_to_user_id=current_user.id,
            content=content,
        )
        return DetailResponse(msg="成功")

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def statistics(self, request, *args, **kwargs):
        """
        根据通道统计 总数 热门问题 AI 满意评价占比  一般评价占比 不满意评价占比
        """
        nid = request.GET.get("nid", 0)
        start_time = request.GET.get("start_time", "")
        end_time = request.GET.get("end_time", "")
        if not nid:
            return ErrorResponse(msg="参数错误")
        if not start_time or not end_time:
            # 统计折线图 按月统计
            start_time = datetime.now().date().strftime("%Y-%m-%d")
            end_time = (datetime.now().date() + timedelta(30)).strftime("%Y-%m-%d")
        start_time = datetime.strptime(start_time + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(end_time + " 23:59:59", "%Y-%m-%d %H:%M:%S")
        # 统计坐席人员
        seats_count = len(get_auth_user_info(AIDeskAppManage.objects.get(id=nid).seats.get("nid", [])))
        # 问答总数
        im_chat_qa_count = IMChatQA.objects.filter(
            create_datetime__range=[start_time, end_time], ai_desk_app_manage__id=nid
        ).count()
        # 热门问题/AI/未知
        im_chat_qa_result = (
            IMChatQA.objects.filter(create_datetime__range=[start_time, end_time], ai_desk_app_manage__id=nid)
            .values("q_type", name=F("ai_desk_app_manage__name"))
            .annotate(value=Count("q_type"))
            .order_by("name", "value")
        )
        # 满意 一般 不满意
        record_result = (
            IMChatRecordForm.objects.filter(
                im_session__ai_desk_app_manage__id=nid, create_datetime__range=[start_time, end_time]
            )
            .values("satisfaction_type", name=F("im_session__ai_desk_app_manage__name"))
            .annotate(value=Count("satisfaction_type"))
            .order_by("name", "value")
        )

        month_data = (
            IMChatQA.objects.filter(ai_desk_app_manage__id=nid, create_datetime__range=[start_time, end_time])
            .extra(select={"create_datetime": "DATE_FORMAT(create_datetime,'%%Y-%%m-%%d')"})
            .values("create_datetime")
            .annotate(send_num=Count("create_datetime"))
            .values("create_datetime", "send_num")
        )

        return DetailResponse(
            data={
                "im_chat_qa_count": im_chat_qa_count,
                "im_chat_qa_result": im_chat_qa_result,
                "record_result": record_result,
                "seats_count": seats_count,
                "month_data": month_data,
            }
        )

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def satisfaction_type(self, request, *args, **kwargs):
        """
        满意 一般 不满意 列表
        """
        nid = request.GET.get("nid", 0)
        start_time = request.GET.get("start_time", "")
        end_time = request.GET.get("end_time", "")
        satisfaction_type = request.GET.get("satisfaction_type", 1)
        if not nid:
            return ErrorResponse(msg="参数错误")
        if not start_time or not end_time:
            # 统计折线图 按月统计
            start_time = datetime.now().date().strftime("%Y-%m-%d")
            end_time = (datetime.now().date() + timedelta(30)).strftime("%Y-%m-%d")
        start_time = datetime.strptime(start_time + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(end_time + " 23:59:59", "%Y-%m-%d %H:%M:%S")
        # 会话总数 人工服务 不满意
        im_session_count = IMSession.objects.filter(
            create_datetime__range=[start_time, end_time], ai_desk_app_manage__id=nid
        ).count()

        record_result = (
            IMChatRecordForm.objects.filter(
                im_session__ai_desk_app_manage__id=nid,
                satisfaction_type=satisfaction_type,
                create_datetime__range=[start_time, end_time],
            )
            .values("satisfaction_info", name=F("satisfaction_info"))
            .annotate(value=Count("satisfaction_info"))
            .order_by("name", "value")
        )

        return DetailResponse(data={"im_session_count": im_session_count, "record_result": record_result})

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def satisfaction_seat(self, request, *args, **kwargs):
        """
        坐席统计
        :param
        """
        nid = request.GET.get("nid", 0)
        start_time = request.GET.get("start_time", "")
        end_time = request.GET.get("end_time", "")
        if not nid:
            return ErrorResponse(msg="参数错误")
        if not start_time or not end_time:
            # 统计折线图 按月统计
            start_time = datetime.now().date().strftime("%Y-%m-%d")
            end_time = (datetime.now().date() + timedelta(30)).strftime("%Y-%m-%d")
        start_time = datetime.strptime(start_time + " 00:00:00", "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(end_time + " 23:59:59", "%Y-%m-%d %H:%M:%S")
        result = []
        for item in range(0, 10):
            result.append(
                {
                    "username": "接待人",
                    "send_count": "100",
                    "ok_count": "900",
                    "satisfy_count": "200",
                    "generally": "300",
                    "dissatisfied": "150",
                }
            )
        return DetailResponse(data=result)
