<template>
  <MainLayout>
    <div class="alert-rules-page">
      <el-card>
      <template #header>
        <div class="card-header">
          <h2>告警规则管理</h2>
          <div class="header-actions">
            <el-button @click="handleCheckAlerts" :loading="checking">
              <el-icon><Refresh /></el-icon>
              检查告警
            </el-button>
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              创建告警规则
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filter-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索告警规则名称..."
              clearable
              @clear="loadRules"
              @keyup.enter="loadRules"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="filterAlertType"
              placeholder="告警类型"
              clearable
              @change="loadRules"
            >
              <el-option label="全部" value="" />
              <el-option label="执行失败" value="execution_failed" />
              <el-option label="执行超时" value="execution_timeout" />
              <el-option label="错误率" value="error_rate" />
              <el-option label="资源使用" value="resource_usage" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="filterEnabled"
              placeholder="状态"
              clearable
              @change="loadRules"
            >
              <el-option label="全部" value="" />
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 告警规则列表 -->
      <el-table :data="alertRules" border stripe v-loading="loading">
        <el-table-column prop="name" label="规则名称" width="200" />
        <el-table-column prop="alert_type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeTag(row.alert_type)">
              {{ getAlertTypeLabel(row.alert_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="target_type" label="监控目标" width="120">
          <template #default="{ row }">
            {{ getTargetTypeLabel(row.target_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="notification_type" label="通知方式" width="120">
          <template #default="{ row }">
            {{ getNotificationTypeLabel(row.notification_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="trigger_count" label="触发次数" width="100" />
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.enabled"
              @change="handleToggleEnabled(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="last_triggered_at" label="最后触发" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.last_triggered_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewLogs(row)">查看日志</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadRules"
          @current-change="loadRules"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入规则描述"
          />
        </el-form-item>
        <el-form-item label="告警类型" prop="alert_type">
          <el-select v-model="form.alert_type" placeholder="请选择告警类型" @change="handleAlertTypeChange">
            <el-option label="执行失败" value="execution_failed" />
            <el-option label="执行超时" value="execution_timeout" />
            <el-option label="错误率" value="error_rate" />
            <el-option label="资源使用" value="resource_usage" />
          </el-select>
        </el-form-item>
        <el-form-item label="监控目标" prop="target_type">
          <el-select v-model="form.target_type" placeholder="请选择监控目标" @change="handleTargetTypeChange">
            <el-option label="工作流" value="workflow" />
            <el-option label="智能体" value="agent" />
            <el-option label="系统" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标ID" prop="target_id" v-if="form.target_type !== 'system'">
          <el-input v-model="form.target_id" placeholder="留空则监控所有（可选）" />
        </el-form-item>
        <el-form-item label="告警条件" prop="conditions">
          <div class="conditions-editor">
            <el-input
              v-model="conditionsJson"
              type="textarea"
              :rows="6"
              placeholder='请输入JSON格式的告警条件，例如：{"threshold": 5, "time_window": 3600, "comparison": "gt"}'
            />
            <div class="conditions-hint">
              <p>告警条件说明：</p>
              <ul>
                <li v-if="form.alert_type === 'execution_failed'">
                  执行失败：threshold（阈值）、time_window（时间窗口，秒）、comparison（比较符：gt/gte/eq）
                </li>
                <li v-if="form.alert_type === 'execution_timeout'">
                  执行超时：timeout_seconds（超时时间，秒）
                </li>
                <li v-if="form.alert_type === 'error_rate'">
                  错误率：threshold（阈值，0-1）、time_window（时间窗口，秒）
                </li>
              </ul>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="通知方式" prop="notification_type">
          <el-select v-model="form.notification_type" placeholder="请选择通知方式" @change="handleNotificationTypeChange">
            <el-option label="邮件" value="email" />
            <el-option label="Webhook" value="webhook" />
            <el-option label="站内通知" value="internal" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知配置" prop="notification_config" v-if="form.notification_type !== 'internal'">
          <div class="notification-config">
            <el-input
              v-model="notificationConfigJson"
              type="textarea"
              :rows="6"
              :placeholder="getNotificationConfigPlaceholder()"
            />
          </div>
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 告警日志对话框 -->
    <el-dialog
      v-model="logsDialogVisible"
      title="告警日志"
      width="1000px"
    >
      <el-table :data="alertLogs" border stripe v-loading="logsLoading">
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityTag(row.severity)">
              {{ row.severity }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="告警消息" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggered_at" label="触发时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.triggered_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending' || row.status === 'sent'"
              size="small"
              @click="handleAcknowledge(row)"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import api from '@/api'
import MainLayout from '@/components/MainLayout.vue'

const loading = ref(false)
const checking = ref(false)
const submitting = ref(false)
const logsLoading = ref(false)

// 列表数据
const alertRules = ref([] as any[])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 筛选条件
const searchKeyword = ref('')
const filterAlertType = ref('')
const filterEnabled = ref<boolean | ''>('')

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('创建告警规则')
const formRef = ref()
const form = ref({
  name: '',
  description: '',
  alert_type: '',
  target_type: '',
  target_id: '',
  conditions: {} as any,
  notification_type: '',
  notification_config: {} as any,
  enabled: true
})

const conditionsJson = ref('')
const notificationConfigJson = ref('')

// 告警日志
const logsDialogVisible = ref(false)
const alertLogs = ref([] as any[])
const currentRuleId = ref('')

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  alert_type: [{ required: true, message: '请选择告警类型', trigger: 'change' }],
  target_type: [{ required: true, message: '请选择监控目标', trigger: 'change' }],
  notification_type: [{ required: true, message: '请选择通知方式', trigger: 'change' }]
}

// 获取告警类型标签
const getAlertTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    'execution_failed': '执行失败',
    'execution_timeout': '执行超时',
    'error_rate': '错误率',
    'resource_usage': '资源使用'
  }
  return labels[type] || type
}

const getAlertTypeTag = (type: string) => {
  const tags: Record<string, string> = {
    'execution_failed': 'danger',
    'execution_timeout': 'warning',
    'error_rate': 'warning',
    'resource_usage': 'info'
  }
  return tags[type] || ''
}

// 获取目标类型标签
const getTargetTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    'workflow': '工作流',
    'agent': '智能体',
    'system': '系统'
  }
  return labels[type] || type
}

// 获取通知方式标签
const getNotificationTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    'email': '邮件',
    'webhook': 'Webhook',
    'internal': '站内通知'
  }
  return labels[type] || type
}

// 获取通知配置占位符
const getNotificationConfigPlaceholder = () => {
  if (form.value.notification_type === 'email') {
    return JSON.stringify({
      smtp_host: 'smtp.gmail.com',
      smtp_port: 587,
      smtp_user: 'your-email@gmail.com',
      smtp_password: 'your-password',
      to_email: 'recipient@example.com'
    }, null, 2)
  } else if (form.value.notification_type === 'webhook') {
    return JSON.stringify({
      webhook_url: 'https://example.com/webhook',
      headers: {
        'Authorization': 'Bearer token'
      }
    }, null, 2)
  }
  return ''
}

// 格式化日期时间
const formatDateTime = (dateStr: string | null) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取严重程度标签
const getSeverityTag = (severity: string) => {
  const tags: Record<string, string> = {
    'info': 'info',
    'warning': 'warning',
    'error': 'danger',
    'critical': 'danger'
  }
  return tags[severity] || ''
}

// 获取状态标签
const getStatusTag = (status: string) => {
  const tags: Record<string, string> = {
    'pending': 'info',
    'sent': 'success',
    'failed': 'danger',
    'acknowledged': 'success'
  }
  return tags[status] || ''
}

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    'pending': '待发送',
    'sent': '已发送',
    'failed': '发送失败',
    'acknowledged': '已确认'
  }
  return labels[status] || status
}

// 加载告警规则列表
const loadRules = async () => {
  loading.value = true
  try {
    const skip = (currentPage.value - 1) * pageSize.value
    const params: any = {
      skip,
      limit: pageSize.value
    }
    if (filterAlertType.value) {
      params.alert_type = filterAlertType.value
    }
    if (filterEnabled.value !== '') {
      params.enabled = filterEnabled.value
    }
    
    const response = await api.get('/api/v1/alert-rules', { params })
    alertRules.value = response.data
    total.value = response.data.length // 注意：实际应该从响应中获取总数
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载告警规则失败')
  } finally {
    loading.value = false
  }
}

// 创建告警规则
const handleCreate = () => {
  dialogTitle.value = '创建告警规则'
  form.value = {
    name: '',
    description: '',
    alert_type: '',
    target_type: '',
    target_id: '',
    conditions: {},
    notification_type: '',
    notification_config: {},
    enabled: true
  }
  conditionsJson.value = ''
  notificationConfigJson.value = ''
  dialogVisible.value = true
}

// 编辑告警规则
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑告警规则'
  form.value = { ...row }
  conditionsJson.value = JSON.stringify(row.conditions, null, 2)
  notificationConfigJson.value = row.notification_config
    ? JSON.stringify(row.notification_config, null, 2)
    : ''
  dialogVisible.value = true
}

// 删除告警规则
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除告警规则 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/api/v1/alert-rules/${row.id}`)
    ElMessage.success('删除成功')
    loadRules()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '删除失败')
    }
  }
}

// 切换启用状态
const handleToggleEnabled = async (row: any) => {
  try {
    await api.put(`/api/v1/alert-rules/${row.id}`, {
      enabled: row.enabled
    })
    ElMessage.success(row.enabled ? '已启用' : '已禁用')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '更新失败')
    row.enabled = !row.enabled // 恢复原状态
  }
}

// 查看告警日志
const handleViewLogs = async (row: any) => {
  currentRuleId.value = row.id
  logsDialogVisible.value = true
  logsLoading.value = true
  try {
    const response = await api.get(`/api/v1/alert-rules/${row.id}/logs`)
    alertLogs.value = response.data
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载告警日志失败')
  } finally {
    logsLoading.value = false
  }
}

// 确认告警
const handleAcknowledge = async (log: any) => {
  try {
    await api.post(`/api/v1/alert-rules/${currentRuleId.value}/acknowledge/${log.id}`)
    ElMessage.success('告警已确认')
    handleViewLogs({ id: currentRuleId.value })
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '确认失败')
  }
}

// 告警类型改变
const handleAlertTypeChange = () => {
  // 重置条件
  conditionsJson.value = ''
}

// 目标类型改变
const handleTargetTypeChange = () => {
  if (form.value.target_type === 'system') {
    form.value.target_id = ''
  }
}

// 通知方式改变
const handleNotificationTypeChange = () => {
  notificationConfigJson.value = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitting.value = true
      try {
        // 解析JSON
        try {
          form.value.conditions = JSON.parse(conditionsJson.value)
        } catch (e) {
          ElMessage.error('告警条件JSON格式错误')
          return
        }
        
        if (notificationConfigJson.value) {
          try {
            form.value.notification_config = JSON.parse(notificationConfigJson.value)
          } catch (e) {
            ElMessage.error('通知配置JSON格式错误')
            return
          }
        }
        
        if (dialogTitle.value === '创建告警规则') {
          await api.post('/api/v1/alert-rules', form.value)
          ElMessage.success('创建成功')
        } else {
          await api.put(`/api/v1/alert-rules/${form.value.id}`, form.value)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        loadRules()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.detail || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 检查告警
const handleCheckAlerts = async () => {
  checking.value = true
  try {
    const response = await api.post('/api/v1/alert-rules/check')
    ElMessage.success(response.data.message)
    loadRules()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '检查告警失败')
  } finally {
    checking.value = false
  }
}

// 组件挂载
onMounted(() => {
  loadRules()
})
</script>

<style scoped>
.alert-rules-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.conditions-editor {
  width: 100%;
}

.conditions-hint {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.conditions-hint ul {
  margin: 5px 0;
  padding-left: 20px;
}

.notification-config {
  width: 100%;
}
</style>
