# -*- coding: utf-8 -*-
"""
@Time : 2025/8/15 19:29
@Auth : 九月的海
@File : views.py
@IDE : PyCharm
@Motto : Catch as catch can....
"""
from chuangliangBaidu.migrations.BaidutaskQuery import AsyncTaskDataQuery
from chuangliangProject.magic_cat.task_client_magic import MagicTaskQuery
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from django.shortcuts import render
import json
import logging
from django.views.decorators.csrf import csrf_exempt
from chuangliangProject.magic_cat.rule_task import RuleTaskQuery

logger = logging.getLogger('chuangliang')


def get_task_details(request):
    """获取任务详情的API接口（优化版）"""
    # 获取任务ID参数
    task_id = request.GET.get('task_id')
    current_time = timezone.now().strftime("%Y-%m-%d %H:%M:%S")

    # 处理浏览器请求的Accept头
    is_browser_request = 'text/html' in request.META.get('HTTP_ACCEPT', '')

    # 参数验证
    if not task_id:
        error_data = {
            "code": 400,
            "message": "缺少参数: task_id",
            "time": current_time,
            "endpoint": request.path,
            "method": request.method
        }
        if is_browser_request:
            logger.error(error_data)
            return render(request, 'json_formatter3.html', {
                "json_data": json.dumps(error_data, ensure_ascii=False),
                "status": 400
            })
        logger.error(error_data)
        return JsonResponse(error_data, status=400, json_dumps_params={'ensure_ascii': False})

    try:
        # 转换为整数
        task_id = int(task_id)
    except ValueError:
        error_data = {
            "code": 400,
            "message": "task_id 必须是整数",
            "time": current_time,
            "provided_value": task_id
        }
        if is_browser_request:
            logger.error(error_data)
            return render(request, 'json_formatter3.html', {
                "json_data": json.dumps(error_data, ensure_ascii=False),
                "status": 400
            })
        logger.error(error_data)
        return JsonResponse(error_data, status=400, json_dumps_params={'ensure_ascii': False})

    # 创建查询实例并获取数据
    try:
        logger.info(f'查询的任务ID: {task_id}')
        task_query = AsyncTaskDataQuery(task_id)
        result = task_query.get_task_details()
        # 处理任务日志并解码中文
        task_logs = result.get("task_logs", [])
        for log in task_logs:
            # 处理 task_param
            if isinstance(log.get('task_param'), str):
                try:
                    log['task_param'] = json.loads(log['task_param'])
                except json.JSONDecodeError:
                    pass
            # 处理 result_data
            if isinstance(log.get('result_data'), str):
                try:
                    log['result_data'] = json.loads(log['result_data'])
                except json.JSONDecodeError:
                    pass

        # 准备响应数据
        response_data = {
            "code": 200,
            "message": "查询成功",
            "check_time": current_time,
            "task_id": task_id,
            "batch_id": result.get("batch_id", ""),
            "total_logs": len(task_logs),
            "task_logs": task_logs,
            "create_status": result.get("create_status", "")
        }

        # 如果是浏览器请求，返回HTML视图
        if is_browser_request:
            logger.info(json.dumps(response_data))
            return render(request, 'json_formatter3.html', {
                # "json_data": response_data,
                "json_data": json.dumps(response_data, ensure_ascii=False, indent=2),
                "status": 200,
                "task_id": task_id
            })

        logger.info(response_data)
        return JsonResponse(
            response_data,
            json_dumps_params={'ensure_ascii': False}
        )

    except Exception as e:
        error_data = {
            "code": 500,
            "message": "服务器内部错误",
            "error": str(e),
            "time": current_time,
            "task_id": task_id
        }
        if is_browser_request:
            logger.error(error_data)
            return render(request, 'json_formatter3.html', {
                "json_data": json.dumps(error_data, ensure_ascii=False),
                "status": 500
            })
        logger.error(error_data)
        return JsonResponse(error_data, status=500, json_dumps_params={'ensure_ascii': False})


# @csrf_exempt  # 如果不需要CSRF保护，可以添加此装饰器
@require_http_methods(["GET"])  # 限制只允许GET请求
def get_magic_task_info(request):
    """
    获取魔剪任务信息的GET接口
    接收参数：task - 任务ID
    """
    task_id = request.GET.get('taskid')
    # 验证参数
    if not task_id:
        return JsonResponse({
            'status': 'error',
            'message': '缺少必要参数: task'
        }, status=400, json_dumps_params={'ensure_ascii': False})

    try:
        # 将参数转换为整数
        task_id = int(task_id)
    except ValueError:
        return JsonResponse({
            'status': 'error',
            'message': '参数格式错误: task必须是整数'
        }, status=400, json_dumps_params={'ensure_ascii': False})

    try:
        # 创建查询实例并获取任务信息
        task_query = MagicTaskQuery(task_id)
        result = task_query.get_task_info()

        # 返回成功响应
        return JsonResponse(result, status=200, json_dumps_params={'ensure_ascii': False})

    except Exception as e:
        # 记录错误日志（实际项目中应该使用日志模块）
        print(f"查询魔剪任务信息失败: {str(e)}")

        # 返回错误响应
        return JsonResponse({
            'status': 'error',
            'message': f'查询失败: {str(e)}'
        }, status=500, json_dumps_params={'ensure_ascii': False})


@csrf_exempt  # 如果不需要CSRF保护，可以加上这个装饰器
@require_GET  # 确保只接受GET请求
def get_task_data_by_rule_name(request):
    """
    通过rule_name参数查询任务数据的接口
    """
    # 获取请求参数
    rule_name = request.GET.get('rule_name')

    # 检查参数是否提供
    if not rule_name:
        return JsonResponse({
            'success': False,
            'message': '缺少必要参数: rule_name',
            'data': []
        }, status=400, json_dumps_params={'ensure_ascii': False})

    try:
        # 创建查询对象并获取数据
        rule_query = RuleTaskQuery(rule_name)
        result = rule_query.get_comprehensive_data()
        # 返回成功响应
        return JsonResponse(result, status=200, json_dumps_params={'ensure_ascii': False})

    except Exception as e:
        # 处理异常情况
        return JsonResponse({
            'success': False,
            'message': f'查询过程中发生错误: {str(e)}',
            'data': []
        }, status=500, json_dumps_params={'ensure_ascii': False})