<template>
  <PageContainer title="可观测性与告警">
    <QueryToolbar>
      <el-select v-model="metricCode" class="w-input-md" placeholder="指标">
        <el-option label="API总请求" value="API_TOTAL" />
        <el-option label="API耗时总和" value="API_DURATION_MS" />
        <el-option label="异步任务总量" value="ASYNC_JOB_TOTAL" />
        <el-option label="异步任务失败" value="ASYNC_JOB_FAILED" />
      </el-select>
      <el-input-number v-model="minutes" :min="1" :max="1440" placeholder="时间窗(分钟)" />
      <el-button v-if="canRead" @click="loadMetrics">查询指标</el-button>
      <el-button v-if="canManage" @click="handleEvaluate">立即评估告警</el-button>
      <el-button v-if="canManage" @click="handleAutoEvaluate">自动评估一次</el-button>
    </QueryToolbar>

    <el-table :data="metricRows" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="minuteSlot" label="分钟窗口" width="180" />
      <el-table-column prop="metricCode" label="指标编码" width="170" />
      <el-table-column prop="metricValue" label="指标值" />
    </el-table>
    <el-alert
      class="mt-sm"
      type="info"
      :closable="false"
      :title="`导出指标：总量 ${exportSummary.total || 0}，失败 ${exportSummary.failed || 0}`"
    />

    <el-divider />
    <SectionTitle>告警规则</SectionTitle>
    <el-form ref="ruleFormRef" :inline="true" :model="ruleForm" :rules="ruleFormRules">
      <el-form-item label="规则编码" prop="ruleCode"><el-input v-model="ruleForm.ruleCode" /></el-form-item>
      <el-form-item label="规则名称" prop="ruleName"><el-input v-model="ruleForm.ruleName" /></el-form-item>
      <el-form-item label="比较符">
        <el-select v-model="ruleForm.compareOp" class="w-input-xs">
          <el-option label=">=" value=">=" />
          <el-option label=">" value=">" />
          <el-option label="<" value="<" />
          <el-option label="<=" value="<=" />
        </el-select>
      </el-form-item>
      <el-form-item label="阈值"><el-input-number v-model="ruleForm.thresholdValue" :min="0" /></el-form-item>
      <el-form-item label="窗口"><el-input-number v-model="ruleForm.windowMinute" :min="1" /></el-form-item>
      <el-form-item label="抑制(分钟)"><el-input-number v-model="ruleForm.suppressWindowMinute" :min="0" /></el-form-item>
      <el-form-item label="状态">
        <el-select v-model="ruleForm.status" class="w-input-sm">
          <el-option label="启用" value="ENABLED" />
          <el-option label="停用" value="DISABLED" />
        </el-select>
      </el-form-item>
      <el-form-item><el-button v-if="canManage" type="primary" @click="handleCreateRule">新增规则</el-button></el-form-item>
    </el-form>

    <el-table :data="ruleRows" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="ruleCode" label="编码" width="160" />
      <el-table-column prop="ruleName" label="名称" width="180" />
      <el-table-column prop="compareOp" label="比较符" width="90" />
      <el-table-column prop="thresholdValue" label="阈值" width="100" />
      <el-table-column prop="windowMinute" label="窗口" width="90" />
      <el-table-column prop="suppressWindowMinute" label="抑制窗口" width="100" />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-divider />
    <SectionTitle>告警事件</SectionTitle>
    <el-table :data="eventRows" empty-text="暂无数据">
      <el-table-column prop="ruleCode" label="规则编码" width="160" />
      <el-table-column prop="metricCode" label="指标" width="140" />
      <el-table-column prop="currentValue" label="当前值" width="100" />
      <el-table-column prop="thresholdValue" label="阈值" width="100" />
      <el-table-column prop="alertLevel" label="级别" width="80" />
      <el-table-column prop="status" label="状态" width="90" :formatter="statusFormatter" />
      <el-table-column prop="createdAt" label="时间" />
      <el-table-column prop="recoveredAt" label="恢复时间" />
    </el-table>

    <el-dialog v-model="editVisible" title="编辑告警规则" :width="DIALOG_WIDTH.sm">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="ruleFormRules">
        <el-form-item label="规则编码" prop="ruleCode"><el-input v-model="editForm.ruleCode" /></el-form-item>
        <el-form-item label="规则名称" prop="ruleName"><el-input v-model="editForm.ruleName" /></el-form-item>
        <el-form-item label="比较符"><el-input v-model="editForm.compareOp" /></el-form-item>
        <el-form-item label="阈值"><el-input-number v-model="editForm.thresholdValue" :min="0" /></el-form-item>
        <el-form-item label="窗口"><el-input-number v-model="editForm.windowMinute" :min="1" /></el-form-item>
        <el-form-item label="抑制(分钟)"><el-input-number v-model="editForm.suppressWindowMinute" :min="0" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="启用" value="ENABLED" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRule">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import SectionTitle from "../../components/SectionTitle.vue";
import { DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  createAlertRule,
  evaluateAlertRules,
  evaluateAlertRulesAuto,
  fetchAlertEvents,
  fetchAlertRules,
  fetchObservabilityExportMetrics,
  fetchObservabilityMetrics,
  updateAlertRule,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.observability.read));
const canManage = computed(() => authStore.hasPermission(PERMS.observability.manage));

const metricCode = ref("API_TOTAL");
const minutes = ref(60);
const metricRows = ref<any[]>([]);
const exportSummary = ref<any>({ total: 0, failed: 0, points: [] });
const ruleRows = ref<any[]>([]);
const eventRows = ref<any[]>([]);

const ruleForm = ref({
  ruleCode: "API_5XX_RATE",
  ruleName: "API 5xx错误率",
  compareOp: ">=",
  thresholdValue: 5,
  windowMinute: 5,
  suppressWindowMinute: 5,
  status: "ENABLED" as "ENABLED" | "DISABLED",
});

const ruleFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();
const ruleFormRules = ref<FormRules>({
  ruleCode: [{ required: true, message: "请输入规则编码", trigger: "blur" }],
  ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
});

const editVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref<any>({});
const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const loadMetrics = async () => {
  const resp = await fetchObservabilityMetrics({ metricCode: metricCode.value, minutes: minutes.value });
  metricRows.value = resp?.data || [];
  const expResp = await fetchObservabilityExportMetrics({ minutes: minutes.value });
  exportSummary.value = expResp?.data || exportSummary.value;
};

const loadRules = async () => {
  const resp = await fetchAlertRules();
  ruleRows.value = resp?.data || [];
};

const loadEvents = async () => {
  const resp = await fetchAlertEvents();
  eventRows.value = resp?.data || [];
};

const handleCreateRule = async () => {
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await createAlertRule(ruleForm.value);
  ElMessage.success("规则创建成功");
  await loadRules();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = {
    ruleCode: row.ruleCode,
    ruleName: row.ruleName,
    compareOp: row.compareOp,
    thresholdValue: row.thresholdValue,
    windowMinute: row.windowMinute,
    suppressWindowMinute: row.suppressWindowMinute,
    status: row.status,
  };
  editVisible.value = true;
};

const handleSaveRule = async () => {
  if (!editId.value) return;

  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await updateAlertRule(editId.value, editForm.value);
  ElMessage.success("规则更新成功");
  editVisible.value = false;
  await loadRules();
};

const handleEvaluate = async () => {
  const resp = await evaluateAlertRules();
  ElMessage.success(`评估完成，触发 ${resp?.data?.triggerCount || 0} 条告警`);
  await loadEvents();
};

const handleAutoEvaluate = async () => {
  const resp = await evaluateAlertRulesAuto({ recoveryWindowMinute: 10 });
  ElMessage.success(
    `自动评估完成，触发 ${resp?.data?.triggerCount || 0} 条，恢复 ${resp?.data?.recoverCount || 0} 条`,
  );
  await loadEvents();
};

onMounted(async () => {
  if (canRead.value) {
    await Promise.all([loadMetrics(), loadRules(), loadEvents()]);
  }
});
</script>
