<template>
  <a-modal
    :visible="visible"
    title="屏蔽告警"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleCancel"
    :confirm-loading="loading"
    width="600px"
  >
    <a-form :model="form" layout="vertical">
      <a-form-item label="告警ID">
        <a-input v-model="alertId" disabled />
      </a-form-item>
      <a-form-item label="屏蔽时长" required>
        <a-select v-model="form.duration" placeholder="请选择屏蔽时长">
          <a-option :value="3600">1小时</a-option>
          <a-option :value="7200">2小时</a-option>
          <a-option :value="14400">4小时</a-option>
          <a-option :value="28800">8小时</a-option>
          <a-option :value="86400">1天</a-option>
          <a-option :value="172800">2天</a-option>
          <a-option :value="604800">1周</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="屏蔽原因">
        <a-textarea
          v-model="form.silence_reason"
          placeholder="请输入屏蔽原因"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea
          v-model="form.comment"
          placeholder="请输入备注信息（可选）"
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createAlertProcess } from '@/api/ops/alertRecord'

interface Props {
  visible: boolean
  alertRecordId: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

const loading = ref(false)
const form = ref({
  duration: 3600,
  silence_reason: '',
  comment: '',
})

const alertId = ref('')

watch(() => props.visible, (val) => {
  if (val) {
    alertId.value = String(props.alertRecordId)
    form.value.duration = 3600
    form.value.silence_reason = ''
    form.value.comment = ''
  }
})

const handleOk = async () => {
  if (!form.value.silence_reason) {
    Message.error('请输入屏蔽原因')
    return
  }

  loading.value = true
  try {
    const silenceUntil = new Date(Date.now() + form.value.duration * 1000).toISOString()
    
    await createAlertProcess({
      alert_record_id: props.alertRecordId,
      action: 'silence',
      operator: getCurrentUser(),
      silence_until: silenceUntil,
      silence_reason: form.value.silence_reason,
      comment: form.value.comment,
      metadata: '{}',
    })
    Message.success('屏蔽成功')
    emit('success')
    emit('update:visible', false)
  } catch (error) {
    console.error('屏蔽失败:', error)
    Message.error('屏蔽失败')
  } finally {
    loading.value = false
  }
}

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

function getCurrentUser() {
  // TODO: 从全局状态获取当前用户
  return 'admin'
}
</script>
