<template>
  <a-modal
    :visible="visible"
    title="采集配置"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :confirm-loading="confirmLoading"
    width="500px"
  >
    <a-form ref="formRef" :model="formData" layout="vertical">
      <a-form-item field="collect_on" label="启用周期采集">
        <a-switch v-model="formData.collect_on" />
      </a-form-item>

      <a-form-item v-if="formData.collect_on" field="collect_interval" label="采集间隔(秒)">
        <a-input-number v-model="formData.collect_interval" placeholder="默认60秒" :min="10" :max="3600" style="width: 100%" />
      </a-form-item>

      <a-alert type="warning" style="margin-top: 16px">快速修改采集配置，无需编辑完整表单</a-alert>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { patchSecurityServiceCollect, type SecurityServicePatchData } from '@/api/ops/security'

interface Props {
  visible: boolean
  record?: any
}

const props = withDefaults(defineProps<Props>(), {
  record: () => ({}),
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref<FormInstance>()
const confirmLoading = ref(false)

const formData = reactive({
  collect_on: true,
  collect_interval: 60,
})

watch(
  () => props.visible,
  (val) => {
    if (val && props.record) {
      formData.collect_on = props.record.collect_on ?? true
      formData.collect_interval = props.record.collect_interval || 60
    }
  }
)

const handleOk = async () => {
  try {
    confirmLoading.value = true

    const patchData: SecurityServicePatchData = {
      collect_on: formData.collect_on,
      collect_interval: formData.collect_interval,
    }

    await patchSecurityServiceCollect(props.record.id, patchData)
    Message.success('采集配置已更新')
    emit('success')
    handleCancel()
  } catch (error) {
    console.error('更新采集配置失败:', error)
    Message.error('更新失败')
  } finally {
    confirmLoading.value = false
  }
}

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

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