<template>
  <a-modal
    v-model:visible="modalVisible"
    :title="title"
    :width="900"
    :footer="false"
    @cancel="handleClose"
  >
    <div v-if="loading" class="loading-container">
      <a-spin />
    </div>
    <div v-else-if="detail">
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="模板 ID">
          {{ detail.id }}
        </a-descriptions-item>
        <a-descriptions-item label="模板名称">
          {{ detail.name }}
        </a-descriptions-item>
        <a-descriptions-item label="模板分类">
          {{ getCategoryLabel(detail.category) }}
        </a-descriptions-item>
        <a-descriptions-item label="启用状态">
          <a-tag :color="detail.enabled ? 'green' : 'red'">
            {{ detail.enabled ? '已启用' : '已禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="标签" :span="2">
          <a-tag v-for="tag in (detail.tags || '').split(',').filter(Boolean)" :key="tag">
            {{ tag }}
          </a-tag>
          <span v-if="!detail.tags">暂无标签</span>
        </a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">
          {{ detail.description || '暂无描述' }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 规则列表 -->
      <a-divider orientation="left">规则列表</a-divider>
      <a-table
        v-if="detail.rules && detail.rules.length > 0"
        :data="detail.rules"
        :columns="ruleColumns"
        :pagination="false"
        stripe
      />
      <a-empty v-else description="暂无规则" />

      <!-- 通知渠道 -->
      <a-divider orientation="left">通知渠道</a-divider>
      <div v-if="detail.channels && detail.channels.length > 0">
        <a-tag v-for="channel in detail.channels" :key="channel.channel_id" color="arcoblue">
          {{ getChannelName(channel.channel_id) }}
        </a-tag>
      </div>
      <a-empty v-else description="暂无通知渠道" />

      <!-- 抑制规则 -->
      <a-divider orientation="left">抑制规则</a-divider>
      <div v-if="detail.suppression_rule_ids && detail.suppression_rule_ids.length > 0">
        <a-tag v-for="id in detail.suppression_rule_ids" :key="id" color="orangered">
          {{ getSuppressionName(id) }}
        </a-tag>
      </div>
      <a-empty v-else description="暂无抑制规则" />
    </div>
    <a-empty v-else description="暂无数据" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { fetchTemplateDetail, TEMPLATE_CATEGORIES, type AlertTemplate } from '@/api/ops/alertTemplate'
import type { NotificationChannel, SuppressionRule } from '@/api/ops/alertTemplate'

const props = defineProps<{
  visible: boolean
  title: string
  templateId?: number | null
  channelOptions: NotificationChannel[]
  suppressionOptions: SuppressionRule[]
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

// 计算属性处理 v-model
const modalVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

// 状态
const loading = ref(false)
const detail = ref<AlertTemplate | null>(null)

// 规则表格列
const ruleColumns = [
  { title: '规则名称', dataIndex: 'name', width: 150 },
  { title: '数据源', dataIndex: 'data_source', width: 100 },
  { title: '指标', dataIndex: 'metric_name', width: 150 },
  { title: '运算符', dataIndex: 'compare_op', width: 80 },
  { title: '阈值', dataIndex: 'threshold', width: 80 },
  { title: '持续时间', dataIndex: 'duration', width: 80 },
  { title: '告警级别', dataIndex: 'severity_code', width: 100 },
]

// 解析 JSON 字符串字段
const parseJsonField = (field: any): any[] => {
  if (!field) return []
  if (typeof field === 'string') {
    try {
      const parsed = JSON.parse(field)
      return Array.isArray(parsed) ? parsed : []
    } catch {
      return []
    }
  }
  return Array.isArray(field) ? field : []
}

// 监听visible变化，加载详情
watch(
  () => props.visible,
  async (val) => {
    if (val && props.templateId) {
      loading.value = true
      try {
        const res: any = await fetchTemplateDetail(props.templateId)
        if (res.code === 0) {
          // 解析可能为 JSON 字符串的字段
          const data = res.details
          detail.value = {
            ...data,
            rules: parseJsonField(data.rules),
            channels: parseJsonField(data.channels),
            suppression_rule_ids: parseJsonField(data.suppression_rule_ids),
          }
        }
      } catch (error) {
        console.error('获取模板详情失败:', error)
      } finally {
        loading.value = false
      }
    } else {
      detail.value = null
    }
  }
)

// 获取分类标签
const getCategoryLabel = (value: string) => {
  const item = TEMPLATE_CATEGORIES.find(c => c.value === value)
  return item?.label || value
}

// 获取渠道名称
const getChannelName = (id: number) => {
  const item = props.channelOptions.find(c => c.id === id)
  return item?.name || String(id)
}

// 获取抑制规则名称
const getSuppressionName = (id: number) => {
  const item = props.suppressionOptions.find(s => s.id === id)
  return item?.name || String(id)
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
}
</script>

<script lang="ts">
export default {
  name: 'TemplateDetailDialog',
}
</script>

<style scoped lang="less">
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style>