from django.contrib import auth
from rest_framework.views import APIView
from django.core.exceptions import ValidationError

from api.utils import *
from api.models import Alert
import requests

import json

class AlertAPI(APIView):
    # 获取告警列表
    def get(self, request):
        if not request.user.identity == 'admin':
            return failed(message="仅允许管理员访问")
        alerts = []
        for alert in Alert.objects.all():
            alerts.append({
                'name': alert.name,
                'level': alert.level,
                'metric': alert.metric,
                'threshold': alert.threshold,
                'handle': alert.handle,
            })
        return success(data=alerts)
    
    def post(self, request):
        if not request.user.identity == 'admin':
            return failed(message="仅允许管理员访问")
        operation = request.data.get('operation')
        # 新建告警
        if operation == 'create':
            data = request.data
            try:
                alert = Alert.objects.create(
                    name=data.get('name'),
                    level=data.get('level'),
                    metric=data.get('metric'),
                    threshold=float(data.get('threshold')),
                    handle=data.get('handle'),
                    state='enable'  # 目前创建的告警都将持续生效
                )
                # 创建成功返回新建告警的ID
                return success(message="告警规则创建成功", data={'id': alert.id})
            except ValidationError as error:
                return failed(message=f"参数验证失败: {error}")
                
            except Exception as error:
                # 处理其他异常（如 threshold 转换失败）
                return failed(message=f"创建失败: {str(error)}")
        
        # 删除告警
        if operation == 'delete':
            name = request.data.get('name')
            if not name:
                return failed(message="删除告警时未传递ID信息")
            try:
                alert = Alert.objects.get(name=str(name))
            except Alert.DoesNotExist:
                return failed(message=f"未找到名称为{name}的告警")
            alert.delete()
            return success(message="告警规则删除成功", data={'id': alert.id})
        
        # 开关告警
        if operation == 'switch':
            id = request.data.get('id')
            state = request.data.get('state')
            if not state in ['enable', 'disable']:
                return failed(message=f"传递状态值:{state}不被允许")
            if not id:
                return failed(message="开关告警时未传递ID信息")
            try:
                alert = Alert.objects.get(id=int(id))
            except Alert.DoesNotExist:
                return failed(message=f"未找到ID为{id}的告警")
            alert.state = state
            alert.save()
            return success(message="告警规则切换开关成功", data={'id': alert.id})


class AlertCheck(APIView):
    # 检查是否有触发的告警
    def get(self, request):
        if not request.user.identity == 'admin':
            return failed(message="仅允许管理员访问")
        triggeredAlerts = [alert.id for alert in Alert.objects.checkAlert()]
        # 返回的仅为触发告警的ID
        return success(data=triggeredAlerts)
    
            