<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑安全设备服务' : '新增安全设备服务'"
    @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="type" label="设备类型">
            <a-select v-model="formData.type" placeholder="请选择设备类型">
              <a-option v-for="item in SECURITY_TYPE_OPTIONS" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="server_identity" label="服务器">
            <a-select v-model="formData.server_identity" placeholder="请选择服务器" allow-search allow-clear>
              <a-option v-for="server in serverOptions" :key="server.server_identity" :value="server.server_identity">
                {{ server.name }} ({{ server.server_identity }})
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="oid" label="OID">
            <a-input v-model="formData.oid" placeholder="请输入OID" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <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="agent_config" label="采集地址(HTTP/HTTPS GET)">
        <a-input v-model="formData.agent_config" placeholder="周期采集地址，返回 JSON 格式指标数组" />
      </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-col :span="12">
          <a-form-item field="collect_args" label="采集参数">
            <a-input v-model="formData.collect_args" placeholder="JSON 格式采集参数" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="extra" label="扩展配置(JSON)">
        <a-textarea v-model="formData.extra" placeholder="请输入 JSON 格式扩展配置" :rows="2" />
      </a-form-item>

      <a-form-item field="policy_ids" label="告警策略">
        <a-select v-model="formData.policy_ids" placeholder="请选择告警策略" multiple allow-clear>
          <a-option v-for="policy in policyOptions" :key="policy.id" :value="policy.id">
            {{ policy.name }}
          </a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { createSecurityService, updateSecurityService, SECURITY_TYPE_OPTIONS, type SecurityServiceFormData } from '@/api/ops/security'
import { fetchPolicyOptions, type PolicyOptionItem } from '@/api/ops/alertPolicy'
import { fetchServerList, type ServerItem } from '@/api/ops/server'

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 policyOptions = ref<PolicyOptionItem[]>([])
const serverOptions = ref<ServerItem[]>([])

const isEdit = computed(() => !!props.record?.id)

const formData = reactive({
  service_identity: '',
  name: '',
  type: '',
  server_identity: '',
  oid: '',
  interval: 60,
  description: '',
  agent_config: '',
  enabled: true,
  collect_on: true,
  collect_interval: 60,
  collect_args: '',
  extra: '',
  policy_ids: [] as number[],
})

const rules = {
  name: [{ required: true, message: '请输入服务名称' }],
  type: [{ required: true, message: '请选择设备类型' }],
}

const loadPolicyOptions = async () => {
  try {
    const response: any = await fetchPolicyOptions({ enabled: true })
    if (Array.isArray(response)) {
      policyOptions.value = response
    } else if (response && response.details) {
      policyOptions.value = Array.isArray(response.details) ? response.details : response.details.data || []
    } else {
      policyOptions.value = []
    }
  } catch (error) {
    console.error('加载告警策略列表失败:', error)
    policyOptions.value = []
  }
}

const loadServerOptions = async () => {
  try {
    const response: any = await fetchServerList({ page: 1, size: 1000 })
    if (response && response.details) {
      serverOptions.value = response.details.data || []
    } else {
      serverOptions.value = []
    }
  } catch (error) {
    console.error('加载服务器列表失败:', error)
    serverOptions.value = []
  }
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          service_identity: props.record.service_identity || '',
          name: props.record.name || '',
          type: props.record.type || '',
          server_identity: props.record.server_identity || '',
          oid: props.record.oid || '',
          interval: props.record.interval || 60,
          description: props.record.description || '',
          agent_config: props.record.agent_config || '',
          enabled: props.record.enabled ?? true,
          collect_on: props.record.collect_on ?? true,
          collect_interval: props.record.collect_interval || 60,
          collect_args: props.record.collect_args || '',
          extra: props.record.extra || '',
          policy_ids: props.record.policy_ids || [],
        })
      } else {
        Object.assign(formData, {
          service_identity: '',
          name: '',
          type: '',
          server_identity: '',
          oid: '',
          interval: 60,
          description: '',
          agent_config: '',
          enabled: true,
          collect_on: true,
          collect_interval: 60,
          collect_args: '',
          extra: '',
          policy_ids: [],
        })
      }
    }
  }
)

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

    confirmLoading.value = true

    const submitData: SecurityServiceFormData = {
      service_identity: formData.service_identity,
      name: formData.name,
      type: formData.type,
      server_identity: formData.server_identity,
      oid: formData.oid,
      interval: formData.interval,
      description: formData.description,
      agent_config: formData.agent_config,
      enabled: formData.enabled,
      collect_on: formData.collect_on,
      collect_interval: formData.collect_interval,
      collect_args: formData.collect_args,
      extra: formData.extra,
      policy_ids: formData.policy_ids,
    }

    if (isEdit.value) {
      await updateSecurityService(props.record.id, submitData)
      Message.success('更新成功')
    } else {
      await createSecurityService(submitData)
      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()
}

onMounted(() => {
  loadPolicyOptions()
  loadServerOptions()
})
</script>
