<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑URL监控设备' : '新增URL监控设备'"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :confirm-loading="confirmLoading"
    width="800px"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="name" label="服务名称">
            <a-input v-model="formData.name" placeholder="请输入服务名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="target_url" label="目标监控URL">
            <a-input v-model="formData.target_url" placeholder="请输入目标监控URL" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="method" label="HTTP方法">
            <a-select v-model="formData.method" placeholder="请选择HTTP方法">
              <a-option value="GET">GET</a-option>
              <a-option value="POST">POST</a-option>
              <a-option value="PUT">PUT</a-option>
              <a-option value="DELETE">DELETE</a-option>
              <a-option value="HEAD">HEAD</a-option>
              <a-option value="OPTIONS">OPTIONS</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="interval" label="采集间隔(秒)">
            <a-input-number v-model="formData.interval" placeholder="默认60秒" :min="10" :max="3600" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="description" label="描述信息">
        <a-textarea v-model="formData.description" placeholder="请输入描述信息" :rows="2" />
      </a-form-item>

      <a-form-item field="tags" label="标签">
        <a-input v-model="formData.tags" placeholder="多个标签，逗号间隔" />
      </a-form-item>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="enabled" label="启用监控">
            <a-switch v-model="formData.enabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="collect_on" label="参与周期采集">
            <a-switch v-model="formData.collect_on" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <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-col>
      </a-row>

      <a-form-item field="extra" label="额外配置(JSON)">
        <a-textarea v-model="formData.extra" placeholder='JSON格式，如：{"headers":{"Authorization":"Bearer token"}}' :rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { createUrlDevice, updateUrlDevice, type UrlDeviceCreateData, type UrlDeviceUpdateData } from '@/api/ops/url-device'

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 isEdit = computed(() => !!props.record?.id)

const formData = reactive({
  service_identity: '',
  name: '',
  description: '',
  target_url: '',
  method: 'GET',
  enabled: true,
  interval: 60,
  extra: '{}',
  tags: '',
  collect_on: true,
  collect_interval: 60,
})

const rules = {
  name: [{ required: true, message: '请输入服务名称' }],
  target_url: [{ required: true, message: '请输入目标监控URL' }],
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          service_identity: props.record.service_identity || '',
          name: props.record.name || '',
          description: props.record.description || '',
          target_url: props.record.target_url || '',
          method: props.record.method || 'GET',
          enabled: props.record.enabled ?? true,
          interval: props.record.interval || 60,
          extra: props.record.extra || '{}',
          tags: props.record.tags || '',
          collect_on: props.record.collect_on ?? true,
          collect_interval: props.record.collect_interval || 60,
        })
      } else {
        Object.assign(formData, {
          service_identity: '',
          name: '',
          description: '',
          target_url: '',
          method: 'GET',
          enabled: true,
          interval: 60,
          extra: '{}',
          tags: '',
          collect_on: true,
          collect_interval: 60,
        })
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()

    confirmLoading.value = true

    if (isEdit.value) {
      const updateData: UrlDeviceUpdateData = {
        name: formData.name,
        description: formData.description,
        target_url: formData.target_url,
        method: formData.method,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        collect_on: formData.collect_on,
        collect_interval: formData.collect_interval,
      }
      await updateUrlDevice(props.record.id, updateData)
      Message.success('更新成功')
    } else {
      const createData: UrlDeviceCreateData = {
        service_identity: formData.service_identity,
        name: formData.name,
        description: formData.description,
        target_url: formData.target_url,
        method: formData.method,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        collect_on: formData.collect_on,
        collect_interval: formData.collect_interval,
      }
      await createUrlDevice(createData)
      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)
  formRef.value?.resetFields()
}
</script>
