<template>
  <a-modal
    :visible="visible"
    :title="title"
    :width="800"
    :ok-loading="submitting"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <!-- 基本信息 -->
        <a-col :span="12">
          <a-form-item label="规则名称" field="name" :rules="[{ required: true, message: '请输入规则名称' }]">
            <a-input v-model="formData.name" placeholder="请输入规则名称" :max-length="100" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="抑制类型" field="type" :rules="[{ required: true, message: '请选择抑制类型' }]">
            <a-select v-model="formData.type" placeholder="请选择抑制类型" :disabled="isEdit">
              <a-option v-for="item in SUPPRESSION_TYPE_OPTIONS" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="优先级" field="priority">
            <a-input-number v-model="formData.priority" placeholder="数值越小越先匹配" :min="1" :max="10000" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="关联策略" field="policy_id">
            <a-select v-model="formData.policy_id" placeholder="选择策略或留空表示全局" allow-clear allow-search>
              <a-option :value="0">
                <a-tag color="gray">全局</a-tag>
              </a-option>
              <a-option v-for="policy in policyOptions" :key="policy.id" :value="policy.id">
                {{ policy.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="启用状态" field="enabled">
            <a-switch v-model="formData.enabled" />
          </a-form-item>
        </a-col>
      </a-row>

      <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-form-item label="匹配条件 (JSON)" field="matchers">
        <a-textarea
          v-model="formData.matchers"
          placeholder="JSON 格式的匹配条件，如 {} 表示全部告警"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>

      <!-- dedup 类型配置 -->
      <template v-if="formData.type === 'dedup'">
        <a-divider>去重配置</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="去重窗口 (秒)" field="dedup_window">
              <a-input-number v-model="formData.dedup_window" placeholder="请输入去重窗口时间" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="去重键" field="dedup_keys">
              <a-input v-model="formData.dedup_keys" placeholder="逗号分隔，如 fingerprint,alert_name" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <!-- aggregate 类型配置 -->
      <template v-if="formData.type === 'aggregate'">
        <a-divider>聚合配置</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="聚合窗口 (秒)" field="aggregate_window">
              <a-input-number v-model="formData.aggregate_window" placeholder="请输入聚合窗口时间" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="分组字段" field="group_by">
              <a-input v-model="formData.group_by" placeholder="逗号分隔" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="聚合阈值" field="aggregate_count">
              <a-input-number v-model="formData.aggregate_count" placeholder="触发阈值" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <!-- dependency 类型配置 -->
      <template v-if="formData.type === 'dependency'">
        <a-divider>依赖抑制配置</a-divider>
        <a-form-item label="源匹配器 (JSON)" field="source_matchers">
          <a-textarea v-model="formData.source_matchers" placeholder="JSON 格式的源匹配条件" :auto-size="{ minRows: 3, maxRows: 6 }" />
        </a-form-item>
        <a-form-item label="目标匹配器 (JSON)" field="target_matchers">
          <a-textarea v-model="formData.target_matchers" placeholder="JSON 格式的目标匹配条件" :auto-size="{ minRows: 3, maxRows: 6 }" />
        </a-form-item>
      </template>

      <!-- throttle 类型配置 -->
      <template v-if="formData.type === 'throttle'">
        <a-divider>限流配置</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="限流次数" field="throttle_count">
              <a-input-number v-model="formData.throttle_count" placeholder="允许发送次数" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="限流窗口 (秒)" field="throttle_window">
              <a-input-number v-model="formData.throttle_window" placeholder="限流时间窗口" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <!-- schedule 类型配置 -->
      <template v-if="formData.type === 'schedule'">
        <a-divider>定时屏蔽配置</a-divider>
        <a-form-item label="时间计划 (JSON)" field="schedule">
          <a-textarea v-model="formData.schedule" placeholder="JSON 格式的时间计划配置" :auto-size="{ minRows: 5, maxRows: 10 }" />
        </a-form-item>
      </template>

      <!-- 编辑时显示统计信息 -->
      <template v-if="isEdit">
        <a-divider>运行统计</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-statistic title="命中次数" :value="formData.hit_count || 0" />
          </a-col>
          <a-col :span="8">
            <a-statistic title="已抑制数量" :value="formData.suppressed_count || 0" />
          </a-col>
          <a-col :span="8">
            <a-descriptions :column="1">
              <a-descriptions-item label="最后命中时间">
                {{ formData.last_hit_at ? formatDateTime(formData.last_hit_at) : '-' }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
      </template>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { SUPPRESSION_TYPE_OPTIONS, type SuppressionRule } from '@/api/ops/suppression'
import type { PolicyOption, SuppressionFormData } from '../types'
import { DEFAULT_FORM_DATA, FORM_RULES } from '../constants'
import { formatDateTime, validateJsonFields, buildUpdateData, buildCreateData } from '../utils'
import { createSuppression, updateSuppression } from '@/api/ops/suppression'
import { Message } from '@arco-design/web-vue'

interface Props {
  visible: boolean
  isEdit: boolean
  data: SuppressionFormData
  policyOptions: PolicyOption[]
  submitting: boolean
}

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

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

const formRef = ref()
const formData = ref<SuppressionFormData>({ ...DEFAULT_FORM_DATA })
const rules = FORM_RULES

// 弹窗标题
const title = computed(() => (props.isEdit ? `编辑抑制规则 - ${formData.value.name}` : '新建抑制规则'))

// 监听外部数据变化
watch(
  () => props.data,
  (newData) => {
    if (newData) {
      formData.value = { ...newData }
    }
  },
  { immediate: true, deep: true }
)

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

// 提交表单
const handleOk = async () => {
  // 先进行表单验证
  try {
    const valid = await formRef.value?.validate()
    if (valid) return false
  } catch (validateError) {
    console.log('表单验证失败:', validateError)
    return false
  }

  // 校验 JSON 字段
  const jsonFields = ['matchers', 'source_matchers', 'target_matchers', 'schedule']
  const jsonError = validateJsonFields(formData.value, jsonFields)
  if (jsonError) {
    Message.error(jsonError)
    return false
  }

  try {
    emit('update:submitting', true)

    if (props.isEdit) {
      // 更新
      const updateData = buildUpdateData(formData.value)
      const res = await updateSuppression(updateData)
      if (res.code === 0) {
        Message.success('更新成功')
        handleCancel()
        emit('success')
        return true
      } else {
        Message.error(res.message || '更新失败')
        return false
      }
    } else {
      // 创建
      const createData = buildCreateData(formData.value)
      const res = await createSuppression(createData)
      if (res.code === 0) {
        Message.success('创建成功')
        handleCancel()
        emit('success')
        return true
      } else {
        Message.error(res.message || '创建失败')
        return false
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error.message || '提交失败')
    return false
  } finally {
    emit('update:submitting', false)
  }
}

// 暴露方法供父组件调用
defineExpose({
  resetFields: () => formRef.value?.resetFields(),
})
</script>

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