<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑告警规则' : '新建告警规则'"
    width="800px"
    :mask-closable="false"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      :style="{ marginBottom: '40px' }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="name" label="规则名称" required>
            <a-input
              v-model="formData.name"
              placeholder="请输入规则名称"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="rule_type" label="规则类型" required>
            <a-select
              v-model="formData.rule_type"
              placeholder="请选择规则类型"
            >
              <a-option value="static">静态规则</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="enabled" label="启用状态">
            <a-switch
              v-model="formData.enabled"
              :checked-value="true"
              :unchecked-value="false"
            >
              <template #checked>
                启用
              </template>
              <template #unchecked>
                禁用
              </template>
            </a-switch>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="severity_id" label="告警级别" required>
            <a-select
              v-model="formData.severity_id"
              placeholder="请选择告警级别"
              :loading="severityLoading"
              allow-search
              :filter-option="false"
              @search="handleSeveritySearch"
            >
              <a-option
                v-for="severity in severityOptions"
                :key="severity.id"
                :value="severity.id"
              >
                <a-tag :color="severity.color">{{ severity.name }}</a-tag>
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      
      <!-- 指标/表达式 -->
      <a-form-item
        v-if="formData.rule_type === 'static'"
        field="metric_name"
        label="指标名称"
        required
      >
        <a-input
          v-model="formData.metric_name"
          placeholder="请输入指标名称，如：cpu_usage"
          allow-clear
        />
      </a-form-item>
      
      <!-- 阈值条件 -->
      <a-row v-if="formData.rule_type !== 'promql'" :gutter="16">
        <a-col :span="6">
          <a-form-item field="compare_op" label="比较操作符" required>
            <a-select v-model="formData.compare_op" placeholder="请选择">
              <a-option value=">">></a-option>
              <a-option value="<"><</a-option>
              <a-option value=">=">&ge;</a-option>
              <a-option value="<=">&le;</a-option>
              <a-option value="==">=</a-option>
              <a-option value="!=">&ne;</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="threshold" label="阈值" required>
            <a-input-number
              v-model="formData.threshold"
              placeholder="请输入阈值"
              :precision="2"
              allow-clear
              :style="{ width: '100%' }"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="duration" label="持续时间（秒）">
            <a-input-number
              v-model="formData.duration"
              placeholder="请输入持续时间"
              :min="0"
              :precision="0"
              allow-clear
              :style="{ width: '100%' }"
            />
            <template #extra>
              持续时间达到设定值才会触发告警
            </template>
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-form-item field="description" label="规则描述">
        <a-textarea
          v-model="formData.description"
          placeholder="请输入规则描述"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          allow-clear
        />
      </a-form-item>
    </a-form>
    
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="handleSubmit">
        保存
      </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import {
  fetchRuleDetail,
  createRule,
  updateRule,
  fetchSeverityOptions,
} from '@/api/ops/alertPolicy'

// Props
interface Props {
  visible: boolean
  ruleId?: number
  policyId?: number
}

const props = defineProps<Props>()
const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const submitLoading = ref(false)
const severityLoading = ref(false)

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

// 表单数据
const formData = reactive({
  name: '',
  rule_type: 'static',
  enabled: true,
  severity_id: 0 as number,
  metric_name: '',
  query_expr: '',
  threshold: undefined as number | undefined,
  compare_op: '>',
  duration: 60,
  description: '',
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入规则名称' }],
  rule_type: [{ required: true, message: '请选择规则类型' }],
  severity_id: [{ required: true, message: '请选择告警级别' }],
  metric_name: [
    {
      validator: (value: string, callback: any) => {
        if (formData.rule_type !== 'promql' && !value) {
          callback('请输入指标名称')
          return
        }
        callback()
      },
    },
  ],
  query_expr: [
    {
      validator: (value: string, callback: any) => {
        if (formData.rule_type === 'promql' && !value) {
          callback('请输入 PromQL 表达式')
          return
        }
        callback()
      },
    },
  ],
  compare_op: [
    {
      validator: (value: string, callback: any) => {
        if (formData.rule_type !== 'promql' && !value) {
          callback('请选择比较操作符')
          return
        }
        callback()
      },
    },
  ],
  threshold: [
    {
      validator: (value: number, callback: any) => {
        if (formData.rule_type !== 'promql' && value === undefined) {
          callback('请输入阈值')
          return
        }
        callback()
      },
    },
  ],
}

// 告警级别选项
const severityOptions = ref<any[]>([])
const baseSeverityOptions = ref<any[]>([])

// 加载告警级别列表
const loadSeverityOptions = async (keyword?: string) => {
  severityLoading.value = true
  try {
    const res: any = await fetchSeverityOptions({
      keyword,
      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) {
      baseSeverityOptions.value = fetchedOptions
    }

    // 防止搜索后缩小 options 导致当前已选项标签无法展示
    const selectedId = formData.severity_id
    const selectedOptions = baseSeverityOptions.value.filter((s) => s?.id === selectedId)

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

    severityOptions.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(() => {
    loadSeverityOptions(keyword)
  }, 300)
}

// 规则类型变化处理
const handleRuleTypeChange = (value: string) => {
  // 根据规则类型清空相关字段
  if (value === 'promql') {
    formData.metric_name = ''
    formData.compare_op = ''
    formData.threshold = undefined
  } else {
    formData.query_expr = ''
    if (!formData.compare_op) {
      formData.compare_op = '>'
    }
  }
}

// 加载规则详情
const loadRuleDetail = async () => {
  if (!props.ruleId) return
  
  try {
    const res = await fetchRuleDetail(props.ruleId)
    if (res.code === 0 && res.details) {
      const rule = res.details
      
      formData.name = rule.name
      // 当前产品只保留静态规则：强制按 static 渲染
      formData.rule_type = 'static'
      formData.enabled = rule.enabled
      formData.severity_id = rule.severity_id
      formData.metric_name = rule.metric_name || ''
      formData.query_expr = rule.query_expr || ''
      formData.threshold = rule.threshold
      formData.compare_op = rule.compare_op || '>'
      formData.duration = rule.duration || 60
      formData.description = rule.description || ''
    }
  } catch (error) {
    console.error('获取规则详情失败:', error)
    Message.error('获取规则详情失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.name = ''
  formData.rule_type = 'static'
  formData.enabled = true
  formData.severity_id = 0
  formData.metric_name = ''
  formData.query_expr = ''
  formData.threshold = undefined
  formData.compare_op = '>'
  formData.duration = 60
  formData.description = ''
}

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

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

// 提交（Arco Form.validate() 通过时 resolve 为 undefined，不可写成 if (!valid)）
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }

  if (!props.policyId) {
    Message.warning('缺少策略 ID')
    return
  }
  
  submitLoading.value = true
  
  try {
    const data = {
      ...formData,
      policy_id: props.policyId,
      severity_id: formData.severity_id, // 确保 severity_id 是 number 类型
    }
    
    // 按契约：rule/create 不做 jsonb 默认值归一化。
    // 当 jsonb 字段无内容时，必须显式传 "{}"（否则可能反序列化为空串导致 SQLSTATE 22P02）。
    const createPayload = !isEdit.value
      ? {
        ...data,
        baseline_config: '{}',
        labels: '{}',
        annotations: '{}',
      }
      : data
    
    // 编辑模式
    if (isEdit.value && props.ruleId) {
      await updateRule({ id: props.ruleId, ...data })
      Message.success('规则更新成功')
    } else {
      // 新建模式
      await createRule(createPayload)
      Message.success('规则创建成功')
    }
    
    emit('success')
    handleCancel()
  } catch (error: any) {
    console.error('保存规则失败:', error)
    Message.error(error.message || '保存规则失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听 visible 变化
watch(() => props.visible, (visible) => {
  if (visible) {
    if (isEdit.value) {
      loadRuleDetail()
    } else {
      resetForm()
    }
  } else {
    resetForm()
  }
})

// 初始化
loadSeverityOptions()
</script>

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