<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="备注">
        <a-textarea
          v-model="form.comment"
          placeholder="请输入备注信息（可选）"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>
      <a-form-item label="根本原因">
        <a-textarea
          v-model="form.root_cause"
          placeholder="请输入根本原因（可选）"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>
      <a-form-item label="解决方案">
        <a-textarea
          v-model="form.solution"
          placeholder="请输入解决方案（可选）"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </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({
  comment: '',
  root_cause: '',
  solution: '',
})

const alertId = ref('')

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

const handleOk = async () => {
  loading.value = true
  try {
    await createAlertProcess({
      alert_record_id: props.alertRecordId,
      action: 'resolve',
      operator: getCurrentUser(),
      comment: form.value.comment,
      root_cause: form.value.root_cause,
      solution: form.value.solution,
      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>
