<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="远程访问端口">
        <a-input-number v-model="form.remote_port" placeholder="请输入远程访问端口" :min="0" :max="65535" style="width: 100%" allow-clear />
        <template #extra>
          <span style="color: #86909c">SSH/RDP 等远程管理端口，0表示未配置</span>
        </template>
      </a-form-item>

      <a-form-item label="Agent URL配置">
        <a-input v-model="form.agent_config" placeholder="http://192.168.1.100:9100/dc-host/stats" allow-clear />
        <template #extra>
          <span style="color: #86909c">完整 http(s) URL，用于周期性 POST 指令</span>
        </template>
      </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" :min="10" :max="3600" placeholder="默认60秒" 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 { updateServer } from '@/api/ops/server'
import type { ServerItem } from '@/api/ops/server'

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

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

const loading = ref(false)

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

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

const handleSubmit = async () => {
  if (!props.record?.id) {
    Message.error('服务器ID不存在')
    return
  }

  loading.value = true
  try {
    const res: any = await updateServer(props.record.id, {
      remote_port: form.value.remote_port,
      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) {
    console.error('配置失败:', error)
    Message.error('配置失败')
  } finally {
    loading.value = false
  }
}

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