<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑通知渠道' : '新建通知渠道'"
    width="800px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-form-item
        label="渠道名称"
        field="name"
        :rules="[{ required: true, message: '请输入渠道名称' }]"
      >
        <a-input
          v-model="form.name"
          placeholder="请输入渠道名称"
          :max-length="100"
        />
      </a-form-item>

      <a-form-item
        label="渠道类型"
        field="type"
        :rules="[{ required: true, message: '请选择渠道类型' }]"
      >
        <a-select
          v-model="form.type"
          placeholder="请选择渠道类型"
        >
          <a-option value="email">邮件</a-option>
          <a-option value="sms">短信</a-option>
          <a-option value="webhook">Webhook</a-option>
          <a-option value="dingtalk">钉钉</a-option>
          <a-option value="wechat">企业微信</a-option>
          <a-option value="feishu">飞书</a-option>
          <a-option value="slack">Slack</a-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="消息模板"
        field="message_template"
      >
        <a-textarea
          v-model="form.message_template"
          placeholder="请输入消息模板，支持变量：{{.Severity}}、{{.RuleName}}、{{.Summary}}、{{.FiredAt}}等"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :max-length="1000"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="限流次数"
            field="rate_limit"
          >
            <a-input-number
              v-model="form.rate_limit"
              placeholder="0表示不限制"
              :min="0"
              :max="10000"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="限流窗口（秒）"
            field="rate_limit_window"
          >
            <a-input-number
              v-model="form.rate_limit_window"
              placeholder="限流时间窗口"
              :min="1"
              :max="86400"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        label="告警级别过滤"
        field="severity_filter"
      >
        <a-select
          v-model="form.severity_filter"
          placeholder="请选择告警级别（可多选）"
          multiple
          allow-clear
          allow-search
          :filter-option="false"
          :loading="severityLoading"
          @search="handleSeveritySearch"
        >
          <a-option
            v-for="level in severityLevels"
            :key="level.code"
            :value="level.code"
          >
            {{ level.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="静默时间段"
        field="quiet_hours"
      >
        <a-space direction="vertical" style="width: 100%">
          <a-switch
            v-model="quietHoursEnabled"
            @change="handleQuietHoursChange"
          >
            <template #checked>启用静默</template>
            <template #unchecked>禁用静默</template>
          </a-switch>
          <a-time-picker
            v-if="quietHoursEnabled"
            v-model="quietHoursStart"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 180px"
            @change="handleQuietHoursChange"
          />
          <span v-if="quietHoursEnabled">至</span>
          <a-time-picker
            v-if="quietHoursEnabled"
            v-model="quietHoursEnd"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 180px"
            @change="handleQuietHoursChange"
          />
        </a-space>
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="重试次数"
            field="retry_times"
          >
            <a-input-number
              v-model="form.retry_times"
              placeholder="发送失败重试次数"
              :min="0"
              :max="10"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="重试间隔（秒）"
            field="retry_interval"
          >
            <a-input-number
              v-model="form.retry_interval"
              placeholder="重试间隔时间"
              :min="1"
              :max="3600"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        label="是否开启"
        field="enabled"
      >
        <a-switch v-model="form.enabled">
          <template #checked>开启</template>
          <template #unchecked>关闭</template>
        </a-switch>
      </a-form-item>

      <a-form-item
        label="描述"
        field="description"
      >
        <a-textarea
          v-model="form.description"
          placeholder="请输入渠道描述"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :max-length="500"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createNoticeChannel, updateNoticeChannel } from '@/api/ops/noticeChannel'
import { fetchAlertLevelOptions } from '@/api/ops/alertLevel'

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
}

interface Props {
  visible: boolean
  channel: NoticeChannel | null
}

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

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

const formRef = ref()
const submitting = ref(false)
const severityLevels = ref<any[]>([])

// 静默时间段相关状态
const quietHoursEnabled = ref(false)
const quietHoursStart = ref('22:00')
const quietHoursEnd = ref('08:00')

// 表单数据
const form = ref({
  name: '',
  type: 'email',
  config: '{}',
  message_template: '',
  rate_limit: 0,
  rate_limit_window: 60,
  severity_filter: [] as string[],
  quiet_hours: '',
  retry_times: 3,
  retry_interval: 60,
  enabled: true,
  description: '',
})

// 是否为编辑模式
const isEdit = computed(() => !!props.channel?.id)

const severityLoading = ref(false)
const baseSeverityLevels = ref<any[]>([])

// 获取告警级别列表（支持 keyword 搜索）
const fetchSeverityLevels = async (keyword?: string) => {
  severityLoading.value = true
  try {
    const res: any = await fetchAlertLevelOptions({
      keyword: keyword || undefined,
      enabled: 'true',
    })

    const list = Array.isArray(res?.details)
      ? res.details
      : res?.details?.data || res?.details?.list || res?.data || res
    const fetchedOptions = Array.isArray(list) ? list : []

    // keyword 为空时缓存“全量可用选项”
    const isBaseLoad = !keyword || keyword.trim().length === 0
    if (isBaseLoad) {
      baseSeverityLevels.value = fetchedOptions
    }

    // 防止搜索后缩小 options 导致已选项标签无法展示
    const selectedCodes = Array.isArray(form.value.severity_filter) ? form.value.severity_filter : []
    const selectedOptions = baseSeverityLevels.value.filter((s) => selectedCodes.includes(s.code))

    const mergedMap = new Map<string, any>()
    ;[...fetchedOptions, ...selectedOptions].forEach((item) => {
      if (item?.code) {
        mergedMap.set(item.code, item)
      }
    })

    severityLevels.value = Array.from(mergedMap.values())
  } catch (error) {
    console.error('获取告警级别列表失败:', error)
  } finally {
    severityLoading.value = false
  }
}

let severitySearchTimer: ReturnType<typeof setTimeout> | null = null
const handleSeveritySearch = (keyword: string) => {
  if (severitySearchTimer) {
    clearTimeout(severitySearchTimer)
  }

  severitySearchTimer = setTimeout(() => {
    fetchSeverityLevels(keyword)
  }, 300)
}

// 处理静默时间段变化
const handleQuietHoursChange = () => {
  if (quietHoursEnabled.value) {
    const quietHoursData = {
      enabled: true,
      start: quietHoursStart.value,
      end: quietHoursEnd.value,
      timezone: 'Asia/Shanghai',
    }
    form.value.quiet_hours = JSON.stringify(quietHoursData)
  } else {
    form.value.quiet_hours = ''
  }
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.channel && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.channel.name || '',
          type: props.channel.type || 'email',
          config: props.channel.config || '{}',
          message_template: props.channel.message_template || '',
          rate_limit: props.channel.rate_limit ?? 0,
          rate_limit_window: props.channel.rate_limit_window ?? 60,
          severity_filter: props.channel.severity_filter 
            ? props.channel.severity_filter.split(',').filter((v: string) => v)
            : [],
          quiet_hours: props.channel.quiet_hours || '',
          retry_times: props.channel.retry_times ?? 3,
          retry_interval: props.channel.retry_interval ?? 60,
          enabled: props.channel.enabled !== undefined ? props.channel.enabled : true,
          description: props.channel.description || '',
        }

        // 解析静默时间段
        if (props.channel.quiet_hours) {
          try {
            const quietHoursData = JSON.parse(props.channel.quiet_hours)
            quietHoursEnabled.value = quietHoursData.enabled
            quietHoursStart.value = quietHoursData.start || '22:00'
            quietHoursEnd.value = quietHoursData.end || '08:00'
          } catch (error) {
            quietHoursEnabled.value = false
          }
        } else {
          quietHoursEnabled.value = false
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          type: 'email',
          config: '{}',
          message_template: '',
          rate_limit: 0,
          rate_limit_window: 60,
          severity_filter: [],
          quiet_hours: '',
          retry_times: 3,
          retry_interval: 60,
          enabled: true,
          description: '',
        }
        quietHoursEnabled.value = false
        quietHoursStart.value = '22:00'
        quietHoursEnd.value = '08:00'
      }
    }
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  submitting.value = true
  try {
    const quietHoursPayload =
      form.value.quiet_hours && form.value.quiet_hours.trim() ? form.value.quiet_hours : '{}'

    const data: any = {
      name: form.value.name,
      type: form.value.type,
      config: form.value.config,
      message_template: form.value.message_template,
      rate_limit: form.value.rate_limit,
      rate_limit_window: form.value.rate_limit_window,
      severity_filter: Array.isArray(form.value.severity_filter)
        ? form.value.severity_filter.join(',')
        : form.value.severity_filter,
      quiet_hours: quietHoursPayload,
      retry_times: form.value.retry_times,
      retry_interval: form.value.retry_interval,
      enabled: form.value.enabled,
      description: form.value.description,
    }

    let res
    if (isEdit.value && props.channel?.id) {
      // 编辑通知渠道
      data.id = props.channel.id
      res = await updateNoticeChannel(data)
    } else {
      // 新建通知渠道
      res = await createNoticeChannel(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '编辑成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || (isEdit.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    Message.error(isEdit.value ? '编辑失败' : '创建失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

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

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

// 初始化加载告警级别
onMounted(() => {
  fetchSeverityLevels()
})
</script>

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

<style scoped lang="less">
</style>
