<template>
  <a-modal
    v-model:visible="modalVisible"
    :title="title"
    :width="1000"
    :ok-loading="submitting"
    @before-ok="handleSubmit"
    @cancel="handleClose"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
      <!-- 基础信息区 -->
      <a-divider orientation="left">基础信息</a-divider>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="模板名称" field="name" required>
            <a-input v-model="formData.name" placeholder="请输入模板名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="模板分类" field="category" required>
            <a-select v-model="formData.category" placeholder="请选择分类" @change="handleCategoryChange">
              <a-option v-for="item in TEMPLATE_CATEGORIES" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否启用" field="enabled">
            <a-switch v-model="formData.enabled" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="标签" field="tagsList" required>
            <a-input-tag v-model="formData.tagsList" placeholder="输入后按回车添加" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="描述" field="description">
            <a-textarea
              v-model="formData.description"
              placeholder="请输入模板描述"
              :max-length="500"
              :auto-size="{ minRows: 2, maxRows: 4 }"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 规则配置区 -->
      <a-divider orientation="left">
        规则配置
        <a-button type="text" size="small" @click="handleAddRule">
          <template #icon><icon-plus /></template>
          添加规则
        </a-button>
      </a-divider>

      <RuleEditor v-model:rules="formData.rules" :severity-options="severityOptions" @remove="handleRemoveRule" />

      <!-- 通知渠道区 -->
      <a-divider orientation="left">通知渠道</a-divider>
      <a-form-item label="选择通知渠道" field="selectedChannelIds" required>
        <a-select
          v-model="formData.selectedChannelIds"
          placeholder="请选择通知渠道（可搜索）"
          multiple
          allow-search
          :filter-option="false"
          @search="handleChannelSearch"
          @dropdown-visible-change="handleChannelDropdownChange"
        >
          <a-option v-for="item in channelOptions" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <!-- 抑制规则区 -->
      <a-divider orientation="left">抑制规则</a-divider>
      <a-form-item label="选择抑制规则" field="suppression_rule_ids" required>
        <a-select
          v-model="formData.suppression_rule_ids"
          placeholder="请选择抑制规则（可搜索）"
          multiple
          allow-search
          :filter-option="false"
          @search="handleSuppressionSearch"
          @dropdown-visible-change="handleSuppressionDropdownChange"
        >
          <a-option v-for="item in suppressionOptions" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import RuleEditor from './RuleEditor.vue'
import {
  createTemplate,
  updateTemplate,
  fetchChannelList,
  fetchSuppressionList,
  fetchMetricsMeta,
  TEMPLATE_CATEGORIES,
  type AlertTemplate,
  type AlertRule,
  type NotificationChannel,
  type SuppressionRule,
  type AlertSeverity,
  type MetricMeta,
} from '@/api/ops/alertTemplate'

interface RuleItem extends AlertRule {
  _metrics?: MetricMeta[]
  _metricsLoading?: boolean
}

interface FormData {
  name: string
  category: string
  description: string
  enabled: boolean
  tagsList: string[]
  rules: RuleItem[]
  selectedChannelIds: number[]
  suppression_rule_ids: number[]
}

const props = defineProps<{
  visible: boolean
  title: string
  isEdit: boolean
  editData?: AlertTemplate | null
  severityOptions: AlertSeverity[]
}>()

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

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

// 状态
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 下拉选项
const channelOptions = ref<NotificationChannel[]>([])
const suppressionOptions = ref<SuppressionRule[]>([])

// 表单数据
const formData = ref<FormData>({
  name: '',
  category: '',
  description: '',
  enabled: true,
  tagsList: [],
  rules: [],
  selectedChannelIds: [],
  suppression_rule_ids: [],
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入模板名称' },
    { minLength: 2, message: '模板名称至少2个字符' },
    { maxLength: 100, message: '模板名称最多100个字符' },
  ],
  category: [{ required: true, message: '请选择模板分类' }],
  tagsList: [{ required: true, message: '请添加标签' }],
  selectedChannelIds: [{ required: true, message: '请选择通知渠道' }],
  suppression_rule_ids: [{ required: true, message: '请选择抑制规则' }],
}

// 监听visible变化，初始化表单
watch(
  () => props.visible,
  async (val) => {
    if (val) {
      loadChannelOptions()
      loadSuppressionOptions()

      if (props.isEdit && props.editData) {
        // 编辑模式
        const tagsList = (props.editData.tags || '').split(',').filter(Boolean)
        const selectedChannelIds = (props.editData.channels || []).map((c) => c.channel_id)

        // 初始化规则数据
        const rules = (props.editData.rules || []).map((r) => ({
          ...r,
          _metrics: [],
          _metricsLoading: false,
        }))

        formData.value = {
          name: props.editData.name,
          category: props.editData.category,
          description: props.editData.description || '',
          enabled: props.editData.enabled ?? true,
          tagsList,
          rules,
          selectedChannelIds,
          suppression_rule_ids: props.editData.suppression_rule_ids || [],
        }

        // 为已有规则加载指标数据
        for (let i = 0; i < rules.length; i++) {
          if (rules[i].data_source) {
            await loadMetricsForRule(i)
          }
        }
      } else {
        // 新建模式
        formData.value = {
          name: '',
          category: '',
          description: '',
          enabled: true,
          tagsList: [],
          rules: [],
          selectedChannelIds: [],
          suppression_rule_ids: [],
        }
      }
    }
  }
)

// 为规则加载指标数据
const loadMetricsForRule = async (index: number) => {
  const rule = formData.value.rules[index]
  if (!rule.data_source || rule._metrics?.length) return

  rule._metricsLoading = true
  try {
    const res: any = await fetchMetricsMeta({
      data_source: rule.data_source,
      limit: 500,
    })
    if (res.code === 0) {
      rule._metrics = res.details?.metrics || []
    }
  } catch (error) {
    console.error('加载指标失败:', error)
  } finally {
    rule._metricsLoading = false
  }
}

// 加载通知渠道
const loadChannelOptions = async () => {
  try {
    const res: any = await fetchChannelList({ enabled: true })
    if (res.code === 0) {
      channelOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('加载通知渠道失败:', error)
  }
}

// 加载抑制规则
const loadSuppressionOptions = async () => {
  try {
    const res: any = await fetchSuppressionList({ enabled: true })
    if (res.code === 0) {
      suppressionOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('加载抑制规则失败:', error)
  }
}

// 通知渠道搜索
const handleChannelSearch = async (keyword: string) => {
  try {
    const res: any = await fetchChannelList({ enabled: true, keyword })
    if (res.code === 0) {
      channelOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('搜索通知渠道失败:', error)
  }
}

const handleChannelDropdownChange = (visible: boolean) => {
  if (visible && channelOptions.value.length === 0) {
    loadChannelOptions()
  }
}

// 抑制规则搜索
const handleSuppressionSearch = async (keyword: string) => {
  try {
    const res: any = await fetchSuppressionList({ enabled: true, keyword })
    if (res.code === 0) {
      suppressionOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('搜索抑制规则失败:', error)
  }
}

const handleSuppressionDropdownChange = (visible: boolean) => {
  if (visible && suppressionOptions.value.length === 0) {
    loadSuppressionOptions()
  }
}

// 分类变化时加载默认规则
const handleCategoryChange = (category: string) => {
  if (!props.isEdit && formData.value.rules.length === 0) {
    const defaultRules = getDefaultRules(category)
    formData.value.rules = defaultRules.map((r) => ({
      ...r,
      _enabled: true,
      _metrics: [],
      _metricsLoading: false,
    }))
  }
}

// 获取默认规则
const getDefaultRules = (category: string): AlertRule[] => {
  const defaultRulesMap: Record<string, AlertRule[]> = {
    os: [
      {
        name: 'CPU使用率过高',
        data_source: 'dc-host',
        metric_name: 'cpu_usage',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 80,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
      {
        name: '内存使用率过高',
        data_source: 'dc-host',
        metric_name: 'memory_usage',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 80,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
      {
        name: '磁盘使用率过高',
        data_source: 'dc-host',
        metric_name: 'disk_usage',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 85,
        duration: 600,
        eval_interval: 60,
        severity_code: 'warning',
      },
    ],
    server_hardware: [
      {
        name: 'CPU温度过高',
        data_source: 'dc-hardware',
        metric_name: 'server_temperature_cpu',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 75,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
      {
        name: '风扇转速异常',
        data_source: 'dc-hardware',
        metric_name: 'fan_speed',
        rule_type: 'static',
        compare_op: '<=',
        threshold: 800,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
    ],
    network_device: [
      {
        name: '接口Down告警',
        data_source: 'dc-network',
        metric_name: 'interface_status',
        rule_type: 'static',
        compare_op: '==',
        threshold: 'down',
        duration: 60,
        eval_interval: 30,
        severity_code: 'critical',
      },
      {
        name: '端口带宽利用率过高',
        data_source: 'dc-network',
        metric_name: 'interface_usage_percent',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 80,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
    ],
    database: [
      {
        name: '数据库连接数使用率过高',
        data_source: 'dc-database',
        metric_name: 'db_conn_usage_percent',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 80,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
      {
        name: '慢查询次数过多',
        data_source: 'dc-database',
        metric_name: 'slow_query_count',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 50,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
    ],
    middleware: [
      {
        name: '请求错误率过高',
        data_source: 'dc-middleware',
        metric_name: 'error_rate',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 1,
        duration: 300,
        eval_interval: 60,
        severity_code: 'warning',
      },
      {
        name: '队列消息堆积',
        data_source: 'dc-middleware',
        metric_name: 'queue_depth',
        rule_type: 'static',
        compare_op: '>=',
        threshold: 10000,
        duration: 600,
        eval_interval: 60,
        severity_code: 'critical',
      },
    ],
  }

  return defaultRulesMap[category] || []
}

// 添加规则
const handleAddRule = () => {
  formData.value.rules.push({
    name: '',
    data_source: formData.value.category ? getDefaultDataSource(formData.value.category) : 'dc-host',
    metric_name: '',
    rule_type: 'static',
    compare_op: '>=',
    threshold: 0,
    duration: 300,
    eval_interval: 60,
    severity_code: 'warning',
    _metrics: [],
    _metricsLoading: false,
  })
}

// 获取默认数据源
const getDefaultDataSource = (category: string): string => {
  const map: Record<string, string> = {
    os: 'dc-host',
    server_hardware: 'dc-hardware',
    network_device: 'dc-network',
    database: 'dc-database',
    middleware: 'dc-middleware',
    virtualization: 'dc-virtualization',
    power_env: 'dc-env',
    safety_env: 'dc-env',
  }
  return map[category] || 'dc-host'
}

// 移除规则
const handleRemoveRule = (index: number) => {
  formData.value.rules.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (valid) {
    return false // 校验失败，阻止弹窗关闭
  }

  submitting.value = true
  try {
    // 提取规则数据
    const submitRules = formData.value.rules.map((r) => {
      const { _metrics, _metricsLoading, ...rest } = r as any
      if (rest.rule_type === 'dynamic' && ['==', '!='].includes(rest.compare_op)) {
        rest.compare_op = '>'
      }
      return rest
    })

    const submitData: AlertTemplate = {
      name: formData.value.name,
      category: formData.value.category,
      description: formData.value.description,
      enabled: formData.value.enabled,
      tags: formData.value.tagsList.join(','),
      rules: submitRules,
      channels: formData.value.selectedChannelIds.map((id) => ({ channel_id: id })),
      suppression_rule_ids: formData.value.suppression_rule_ids,
    }

    if (props.isEdit && props.editData?.id) {
      submitData.id = props.editData.id
      const res: any = await updateTemplate(submitData)
      if (res.code === 0) {
        Message.success('模板更新成功')
        emit('success')
        return true // 成功，允许关闭弹窗
      } else {
        Message.error(res.msg || '更新失败')
        return false
      }
    } else {
      const res: any = await createTemplate(submitData)
      if (res.code === 0) {
        Message.success('模板创建成功')
        emit('success')
        return true // 成功，允许关闭弹窗
      } else {
        Message.error(res.msg || '创建失败')
        return false
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error.message || '操作失败')
    return false
  } finally {
    submitting.value = false
  }
}

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

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