<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="in_app">站内消息</a-option>
        </a-select>
      </a-form-item>

      <template v-if="form.type === 'email'">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="SMTP 地址" field="email_smtp_host">
              <a-input v-model="form.email_smtp_host" placeholder="请输入 SMTP 服务地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="SMTP 端口" field="email_smtp_port">
              <a-input-number v-model="form.email_smtp_port" placeholder="请输入 SMTP 端口" :min="1" :max="65535" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="SMTP 用户名" field="email_username">
              <a-input v-model="form.email_username" placeholder="请输入 SMTP 用户名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="SMTP 密码/授权码" field="email_password">
              <a-input-password v-model="form.email_password" placeholder="请输入 SMTP 密码或授权码" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="发件人" field="email_from">
          <a-input v-model="form.email_from" placeholder="请输入发件人地址" />
        </a-form-item>
        <a-form-item label="收件人" field="email_to">
          <a-input-tag v-model="form.email_to" placeholder="输入邮箱后回车，至少 1 个" allow-clear />
        </a-form-item>
        <a-form-item label="抄送" field="email_cc">
          <a-input-tag v-model="form.email_cc" placeholder="输入抄送邮箱后回车，可选" allow-clear />
        </a-form-item>
        <a-form-item label="密送" field="email_bcc">
          <a-input-tag v-model="form.email_bcc" placeholder="输入密送邮箱后回车，可选" allow-clear />
        </a-form-item>
        <a-form-item label="启用 TLS" field="email_use_tls">
          <a-switch v-model="form.email_use_tls" />
        </a-form-item>
      </template>

      <template v-if="form.type === 'sms'">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="短信服务商" field="sms_provider">
              <a-input v-model="form.sms_provider" placeholder="请输入服务商标识" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="AccessKey ID" field="sms_access_key_id">
              <a-input v-model="form.sms_access_key_id" placeholder="请输入 AccessKey ID" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="AccessKey Secret" field="sms_access_key_secret">
          <a-input-password v-model="form.sms_access_key_secret" placeholder="请输入 AccessKey Secret" />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="短信签名" field="sms_sign_name">
              <a-input v-model="form.sms_sign_name" placeholder="请输入短信签名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="模板编码" field="sms_template_code">
              <a-input v-model="form.sms_template_code" placeholder="请输入模板编码" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="手机号" field="sms_phones">
          <a-input-tag v-model="form.sms_phones" placeholder="输入手机号后回车，至少 1 个" allow-clear />
        </a-form-item>
      </template>

      <template v-if="form.type === 'in_app'">
        <a-form-item label="站内消息目标" field="in_app_targets">
          <a-input-tag v-model="form.in_app_targets" placeholder="输入目标后回车，如 user:42" allow-clear />
        </a-form-item>
      </template>

      <a-form-item label="消息模板" field="message_template">
        <a-textarea
          v-model="form.message_template"
          placeholder="请输入消息模板，支持变量：{{.RuleName}}、{{.Summary}}、{{.FiredAt}}、{{.Value}}、{{.Threshold}}等"
          :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
  email_smtp_host?: string
  email_smtp_port?: number
  email_username?: string
  email_password?: string
  email_from?: string
  email_to?: string[] | string
  email_cc?: string[] | string
  email_bcc?: string[] | string
  email_use_tls?: boolean
  sms_provider?: string
  sms_access_key_id?: string
  sms_access_key_secret?: string
  sms_sign_name?: string
  sms_template_code?: string
  sms_phones?: string[] | string
  in_app_targets?: string[] | 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: '',
  email_smtp_host: '',
  email_smtp_port: 25,
  email_username: '',
  email_password: '',
  email_from: '',
  email_to: [] as string[],
  email_cc: [] as string[],
  email_bcc: [] as string[],
  email_use_tls: false,
  sms_provider: '',
  sms_access_key_id: '',
  sms_access_key_secret: '',
  sms_sign_name: '',
  sms_template_code: '',
  sms_phones: [] as string[],
  in_app_targets: [] as string[],
})

// 是否为编辑模式
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 || '',
          email_smtp_host: props.channel.email_smtp_host || '',
          email_smtp_port: props.channel.email_smtp_port ?? 25,
          email_username: props.channel.email_username || '',
          email_password: props.channel.email_password || '',
          email_from: props.channel.email_from || '',
          email_to: parseStringArray(props.channel.email_to),
          email_cc: parseStringArray(props.channel.email_cc),
          email_bcc: parseStringArray(props.channel.email_bcc),
          email_use_tls: props.channel.email_use_tls || false,
          sms_provider: props.channel.sms_provider || '',
          sms_access_key_id: props.channel.sms_access_key_id || '',
          sms_access_key_secret: props.channel.sms_access_key_secret || '',
          sms_sign_name: props.channel.sms_sign_name || '',
          sms_template_code: props.channel.sms_template_code || '',
          sms_phones: parseStringArray(props.channel.sms_phones),
          in_app_targets: parseStringArray(props.channel.in_app_targets),
        }

        // 解析静默时间段
        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: '',
          email_smtp_host: '',
          email_smtp_port: 25,
          email_username: '',
          email_password: '',
          email_from: '',
          email_to: [],
          email_cc: [],
          email_bcc: [],
          email_use_tls: false,
          sms_provider: '',
          sms_access_key_id: '',
          sms_access_key_secret: '',
          sms_sign_name: '',
          sms_template_code: '',
          sms_phones: [],
          in_app_targets: [],
        }
        quietHoursEnabled.value = false
        quietHoursStart.value = '22:00'
        quietHoursEnd.value = '08:00'
      }
    }
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return
  const channelError = validateChannelConfig()
  if (channelError) {
    Message.error(channelError)
    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,
    }
    appendChannelPayload(data)

    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 parseStringArray = (value?: string[] | string) => {
  if (!value) return []
  if (Array.isArray(value)) return value
  try {
    const parsed = JSON.parse(value)
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    return value
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean)
  }
}

const isMaskedSecret = (value?: string) => {
  return value === '******'
}

const validateChannelConfig = () => {
  if (form.value.type === 'email') {
    if (!form.value.email_smtp_host || !form.value.email_smtp_port || !form.value.email_username || !form.value.email_from || !form.value.email_to.length) {
      return '请补齐邮件渠道必填字段'
    }
    if (!form.value.email_password) return '请输入 SMTP 密码/授权码'
  }
  if (form.value.type === 'sms') {
    if (
      !form.value.sms_provider ||
      !form.value.sms_access_key_id ||
      !form.value.sms_sign_name ||
      !form.value.sms_template_code ||
      !form.value.sms_phones.length
    ) {
      return '请补齐短信渠道必填字段'
    }
    if (!form.value.sms_access_key_secret) return '请输入 AccessKey Secret'
  }
  if (form.value.type === 'in_app' && !form.value.in_app_targets.length) {
    return '请至少配置一个站内消息目标'
  }
  return ''
}

const appendChannelPayload = (data: any) => {
  if (form.value.type === 'email') {
    data.email_smtp_host = form.value.email_smtp_host
    data.email_smtp_port = form.value.email_smtp_port
    data.email_username = form.value.email_username
    if (!isMaskedSecret(form.value.email_password)) {
      data.email_password = form.value.email_password
    }
    data.email_from = form.value.email_from
    data.email_to = form.value.email_to
    data.email_cc = form.value.email_cc
    data.email_bcc = form.value.email_bcc
    data.email_use_tls = form.value.email_use_tls
  }
  if (form.value.type === 'sms') {
    data.sms_provider = form.value.sms_provider
    data.sms_access_key_id = form.value.sms_access_key_id
    if (!isMaskedSecret(form.value.sms_access_key_secret)) {
      data.sms_access_key_secret = form.value.sms_access_key_secret
    }
    data.sms_sign_name = form.value.sms_sign_name
    data.sms_template_code = form.value.sms_template_code
    data.sms_phones = form.value.sms_phones
  }
  if (form.value.type === 'in_app') {
    data.in_app_targets = form.value.in_app_targets
  }
}

// 取消
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>
