<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) GET URL"
          allow-clear
        />
        <template #extra>
          <span style="color: #86909c">完整 http(s) GET URL，用于周期采集</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"
          placeholder="为0时使用interval"
          :min="0"
          :max="3600"
          style="width: 100%"
          allow-clear
        />
        <template #extra>
          <span style="color: #86909c">分桶间隔（秒），为 0 时回退 interval</span>
        </template>
      </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 {
  patchMiddlewareCollect,
  type MiddlewareCollectData,
} from '@/api/ops/middleware'

interface Props {
  visible: boolean
  record: any
}

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 || ''
      form.value.collect_on = props.record.collect_on ?? true
      form.value.collect_interval = props.record.collect_interval || 60
    }
  }
)

const handleSubmit = async () => {
  loading.value = true
  try {
    const data: MiddlewareCollectData = {
      collect_on: form.value.collect_on,
      collect_interval: form.value.collect_interval,
    }
    
    await patchMiddlewareCollect(props.record.id, data)
    
    Message.success('配置成功')
    emit('success')
    emit('update:visible', false)
  } catch (error) {
    Message.error('配置失败')
  } finally {
    loading.value = false
  }
}

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