<template>
  <a-modal
    :visible="visible"
    title="通知渠道详情"
    width="800px"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :footer="false"
  >
    <a-descriptions
      v-if="channelDetail"
      :column="2"
      bordered
      size="large"
    >
      <a-descriptions-item label="渠道名称">
        {{ channelDetail.name || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="渠道类型">
        <a-tag :color="getChannelTypeColor(channelDetail.type)">
          {{ getChannelTypeName(channelDetail.type) }}
        </a-tag>
      </a-descriptions-item>

      <a-descriptions-item label="状态" :span="2">
        <a-tag :color="channelDetail.enabled ? 'green' : 'red'">
          {{ channelDetail.enabled ? '开启' : '关闭' }}
        </a-tag>
      </a-descriptions-item>

      <a-descriptions-item label="消息模板" :span="2">
        <div class="template-content">
          {{ channelDetail.message_template || '-' }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="限流次数">
        {{ channelDetail.rate_limit === 0 ? '不限制' : channelDetail.rate_limit || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="限流窗口（秒）">
        {{ channelDetail.rate_limit_window || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="告警级别过滤" :span="2">
        <a-space wrap>
          <a-tag
            v-for="(level, index) in getSeverityLevels(channelDetail.severity_filter)"
            :key="index"
          >
            {{ level }}
          </a-tag>
          <span v-if="!channelDetail.severity_filter">-</span>
        </a-space>
      </a-descriptions-item>

      <a-descriptions-item label="静默时间段" :span="2">
        <div v-if="getQuietHoursDisplay()">
          <a-tag color="blue">已启用</a-tag>
          <span style="margin-left: 8px">
            {{ getQuietHoursDisplay() }}
          </span>
        </div>
        <a-tag v-else color="gray">未启用</a-tag>
      </a-descriptions-item>

      <a-descriptions-item label="重试次数">
        {{ channelDetail.retry_times || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="重试间隔（秒）">
        {{ channelDetail.retry_interval || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="描述" :span="2">
        <div class="description-content">
          {{ channelDetail.description || '-' }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="创建时间">
        {{ formatTime(channelDetail.created_at) || '-' }}
      </a-descriptions-item>

      <a-descriptions-item label="更新时间">
        {{ formatTime(channelDetail.updated_at) || '-' }}
      </a-descriptions-item>
    </a-descriptions>

    <a-spin v-else :loading="loading" style="display: block; padding: 60px 0;">
      <a-empty description="加载中..." />
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchNoticeChannelDetail } from '@/api/ops/noticeChannel'

interface NoticeChannel {
  id?: number
  name?: string
  type?: string
  config?: string
  message_template?: string
  rate_limit?: number
  rate_limit_window?: number
  severity_filter?: string
  quiet_hours?: string
  retry_times?: number
  retry_interval?: number
  enabled?: boolean
  description?: string
  created_at?: string
  updated_at?: string
}

interface Props {
  visible: boolean
  channelId: number | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const channelDetail = ref<NoticeChannel | null>(null)
const loading = ref(false)

// 渠道类型映射
const channelTypeMap: Record<string, { name: string; color: string }> = {
  email: { name: '邮件', color: 'blue' },
  sms: { name: '短信', color: 'cyan' },
  webhook: { name: 'Webhook', color: 'purple' },
  dingtalk: { name: '钉钉', color: 'red' },
  wechat: { name: '企业微信', color: 'green' },
  feishu: { name: '飞书', color: 'orange' },
  slack: { name: 'Slack', color: 'arcoblue' },
}

// 获取渠道类型名称
const getChannelTypeName = (type?: string) => {
  return channelTypeMap[type || '']?.name || type || '-'
}

// 获取渠道类型颜色
const getChannelTypeColor = (type?: string) => {
  return channelTypeMap[type || '']?.color || 'gray'
}

// 获取告警级别列表
const getSeverityLevels = (filter?: string) => {
  if (!filter) return []
  return filter.split(',').filter((v) => v.trim())
}

// 获取静默时间段显示
const getQuietHoursDisplay = () => {
  if (!channelDetail.value?.quiet_hours) return ''
  try {
    const quietHoursData = JSON.parse(channelDetail.value.quiet_hours)
    if (quietHoursData.enabled) {
      return `${quietHoursData.start || '--:--'} 至 ${quietHoursData.end || '--:--'} (${quietHoursData.timezone || 'Asia/Shanghai'})`
    }
  } catch (error) {
    console.error('解析静默时间段失败:', error)
  }
  return ''
}

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    })
  } catch (error) {
    return time
  }
}

// 获取渠道详情
const fetchDetail = async () => {
  if (!props.channelId) {
    channelDetail.value = null
    return
  }

  loading.value = true
  try {
    const res = await fetchNoticeChannelDetail(props.channelId)
    if (res.code === 0) {
      channelDetail.value = res.details || res.data
    } else {
      Message.error(res.message || '获取详情失败')
      channelDetail.value = null
    }
  } catch (error) {
    Message.error('获取详情失败')
    console.error(error)
    channelDetail.value = null
  } finally {
    loading.value = false
  }
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.channelId) {
      fetchDetail()
    } else {
      channelDetail.value = null
    }
  }
)

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}
</script>

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

<style scoped lang="less">
.template-content,
.description-content {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 200px;
  overflow-y: auto;
}
</style>
