<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-textarea
          v-model="form.comment"
          placeholder="请输入评论内容"
          :auto-size="{ minRows: 4, maxRows: 8 }"
        />
      </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: '',
})

const alertId = ref('')

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

const handleOk = async () => {
  if (!form.value.comment) {
    Message.error('请输入评论内容')
    return
  }

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