<template>
  <a-modal
    :visible="visible"
    title="快捷配置"
    :mask-closable="false"
    :ok-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :model="form" layout="vertical">
      <a-form-item label="Agent配置URL">
        <a-input
          v-model="form.agent_config"
          placeholder="请输入完整的 http(s) URL"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="启用采集">
        <a-switch v-model="form.collect_on" />
      </a-form-item>

      <a-form-item v-if="form.collect_on" label="采集间隔(秒)">
        <a-input-number
          v-model="form.collect_interval"
          placeholder="请输入采集间隔"
          :min="10"
          :max="3600"
          style="width: 100%"
        />
      </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 { updatePC, type PCItem } from '@/api/ops/pc'

interface Props {
  visible: boolean
  record: PCItem | null
}

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

const loading = ref(false)

const form = ref({
  agent_config: '',
  collect_on: true,
  collect_interval: 60,
})

watch(
  () => props.visible,
  (val) => {
    if (val && props.record) {
      form.value = {
        agent_config: props.record.agent_config || '',
        collect_on: props.record.collect_on ?? true,
        collect_interval: props.record.collect_interval || 60,
      }
    }
  }
)

const handleSubmit = async () => {
  if (!props.record?.id) return
  
  loading.value = true
  try {
    const res: any = await updatePC(props.record.id, {
      agent_config: form.value.agent_config,
      collect_on: form.value.collect_on,
      collect_interval: form.value.collect_interval,
    })
    
    if (res.code === 0) {
      Message.success('配置成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || '配置失败')
    }
  } catch (error) {
    Message.error('配置失败')
  } finally {
    loading.value = false
  }
}

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