#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : task_run_history.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 任务运行历史查询接口
import logging

from rest_framework.decorators import action

from django_base_ai.system.models import TaskRunHistory
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

logger = logging.getLogger(__name__)


class TaskRunHistorySerializer(CustomModelSerializer):
    class Meta:
        model = TaskRunHistory
        fields = ["id", "url_name", "start_time", "end_time", "status_code", "request_config"]
        read_only_fields = ["id"]


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

    queryset = TaskRunHistory.objects.order_by("-create_datetime")
    serializer_class = TaskRunHistorySerializer
    # extra_filter_backends = []
    filter_fields = ["base_task", "periodic_task", "$url_name"]

    # 查询request的结果
    @action(methods=["GET"], detail=False)
    def get_request_result(self, request):
        nid = self.request.query_params.get("id", 0)
        if not nid:
            return ErrorResponse(msg="参数不合法")
        run_result = TaskRunHistory.objects.get(id=nid).run_result
        return DetailResponse(data={"run_result": run_result}, msg="获取成功")

    # 根据时间查询
    def get_queryset(self):
        queryset = super().get_queryset()
        # 获取查询参数
        base_task = self.request.GET.get("base_task", 0)
        periodic_task = self.request.GET.get("periodic_task", 0)
        start_date = self.request.GET.get("start_date", "")
        end_date = self.request.GET.get("end_date", "")
        if periodic_task:
            # 定时器的查询
            queryset = queryset.filter(base_task=base_task, periodic_task=periodic_task)
        else:
            # 手动执行的查询
            queryset = queryset.filter(base_task=base_task, periodic_task__isnull=True)
        # 时间过滤
        if start_date and end_date:
            queryset = queryset.filter(end_time__range=(start_date, end_date))
        elif start_date:
            queryset = queryset.filter(end_time__gte=start_date)
        elif end_date:
            queryset = queryset.filter(end_time__lte=end_date)
        return queryset
