<template>
  <a-modal
    :visible="visible"
    title="采集配置"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :confirm-loading="confirmLoading"
    width="500px"
  >
    <a-form ref="formRef" :model="formData" layout="vertical">
      <a-form-item field="collect_method" label="采集方式">
        <a-radio-group v-model="formData.collect_method" type="button">
          <a-radio value="api">API</a-radio>
          <a-radio value="snmp">SNMP</a-radio>
        </a-radio-group>
      </a-form-item>

      <template v-if="formData.collect_method === 'api'">
        <a-form-item field="agent_config" label="采集地址(HTTP/HTTPS GET)">
          <a-input v-model="formData.agent_config" placeholder="周期采集地址，返回 JSON 格式指标数组" />
        </a-form-item>
      </template>
      <template v-else>
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item field="snmp_target" label="SNMP目标地址">
              <a-input v-model="formData.snmp_target" placeholder="例如 192.168.1.10" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="snmp_port" label="SNMP端口">
              <a-input-number v-model="formData.snmp_port" :min="1" :max="65535" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="snmp_version" label="SNMP版本">
          <a-radio-group v-model="formData.snmp_version" type="button">
            <a-radio value="v2c">v2c</a-radio>
            <a-radio value="v3">v3</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-row :gutter="20">
          <a-col v-if="formData.snmp_version !== 'v3'" :span="12">
            <a-form-item field="snmp_community" label="Community">
              <a-input v-model="formData.snmp_community" placeholder="SNMP v2c community" />
            </a-form-item>
          </a-col>
          <a-col v-else :span="12">
            <a-form-item field="snmp_v3_security_name" label="Security Name">
              <a-input v-model="formData.snmp_v3_security_name" placeholder="SNMP v3 用户名" />
            </a-form-item>
          </a-col>
          <a-col v-if="formData.snmp_version === 'v3'" :span="12">
            <a-form-item field="snmp_v3_security_level" label="Security Level">
              <a-select v-model="formData.snmp_v3_security_level">
                <a-option value="noAuthNoPriv">noAuthNoPriv</a-option>
                <a-option value="authNoPriv">authNoPriv</a-option>
                <a-option value="authPriv">authPriv</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="snmp_timeout_ms" label="超时(ms)">
              <a-input-number v-model="formData.snmp_timeout_ms" :min="1" :max="60000" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="snmp_retries" label="重试次数">
              <a-input-number v-model="formData.snmp_retries" :min="0" :max="10" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="formData.snmp_version === 'v3'" :gutter="20">
          <a-col :span="8">
            <a-form-item field="snmp_v3_auth_protocol" label="Auth协议">
              <a-select v-model="formData.snmp_v3_auth_protocol">
                <a-option value="SHA">SHA</a-option>
                <a-option value="MD5">MD5</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item field="snmp_v3_auth_password" label="Auth密码">
              <a-input-password v-model="formData.snmp_v3_auth_password" placeholder="authNoPriv/authPriv 必填" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="formData.snmp_version === 'v3' && formData.snmp_v3_security_level === 'authPriv'" :gutter="20">
          <a-col :span="8">
            <a-form-item field="snmp_v3_priv_protocol" label="Priv协议">
              <a-select v-model="formData.snmp_v3_priv_protocol">
                <a-option value="AES">AES</a-option>
                <a-option value="DES">DES</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="snmp_v3_priv_password" label="Priv密码">
              <a-input-password v-model="formData.snmp_v3_priv_password" placeholder="authPriv 必填" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="snmp_v3_context_name" label="Context">
              <a-input v-model="formData.snmp_v3_context_name" placeholder="可选" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

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

      <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-alert type="warning" style="margin-top: 16px">快速修改采集配置，无需编辑完整表单</a-alert>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { patchSecurityServiceCollect, type SecurityServicePatchData } from '@/api/ops/security'

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 formData = reactive({
  collect_method: 'api' as 'api' | 'snmp',
  agent_config: '',
  snmp_target: '',
  snmp_port: 161,
  snmp_version: 'v2c' as 'v2c' | 'v3',
  snmp_community: '',
  snmp_v3_security_level: 'noAuthNoPriv',
  snmp_v3_security_name: '',
  snmp_v3_auth_protocol: 'SHA',
  snmp_v3_auth_password: '',
  snmp_v3_priv_protocol: 'AES',
  snmp_v3_priv_password: '',
  snmp_v3_context_name: '',
  snmp_timeout_ms: 3000,
  snmp_retries: 1,
  collect_on: true,
  collect_interval: 60,
})

watch(
  () => props.visible,
  (val) => {
    if (val && props.record) {
      formData.collect_method = props.record.collect_method || 'api'
      formData.agent_config = props.record.agent_config || ''
      formData.snmp_target = props.record.snmp_target || ''
      formData.snmp_port = props.record.snmp_port || 161
      formData.snmp_version = props.record.snmp_version || 'v2c'
      formData.snmp_community = props.record.snmp_community || ''
      formData.snmp_v3_security_level = props.record.snmp_v3_security_level || 'noAuthNoPriv'
      formData.snmp_v3_security_name = props.record.snmp_v3_security_name || ''
      formData.snmp_v3_auth_protocol = props.record.snmp_v3_auth_protocol || 'SHA'
      formData.snmp_v3_auth_password = ''
      formData.snmp_v3_priv_protocol = props.record.snmp_v3_priv_protocol || 'AES'
      formData.snmp_v3_priv_password = ''
      formData.snmp_v3_context_name = props.record.snmp_v3_context_name || ''
      formData.snmp_timeout_ms = props.record.snmp_timeout_ms || 3000
      formData.snmp_retries = props.record.snmp_retries ?? 1
      formData.collect_on = props.record.collect_on ?? true
      formData.collect_interval = props.record.collect_interval || 60
    }
  }
)

const handleOk = async () => {
  try {
    if (formData.collect_method === 'api' && !formData.agent_config?.trim()) {
      Message.warning('API 模式下请填写采集地址')
      return
    }
    if (formData.collect_method === 'snmp') {
      if (!formData.snmp_target?.trim()) {
        Message.warning('SNMP 模式下请填写目标地址')
        return
      }
      if (formData.snmp_version === 'v3') {
        if (!formData.snmp_v3_security_name?.trim()) {
          Message.warning('SNMP v3 请填写 Security Name')
          return
        }
        if (formData.snmp_v3_security_level !== 'noAuthNoPriv' && !formData.snmp_v3_auth_password?.trim()) {
          Message.warning('SNMP v3 认证级别请填写 Auth 密码')
          return
        }
        if (formData.snmp_v3_security_level === 'authPriv' && !formData.snmp_v3_priv_password?.trim()) {
          Message.warning('SNMP v3 authPriv 请填写 Priv 密码')
          return
        }
      } else if (!formData.snmp_community?.trim()) {
        Message.warning('SNMP v2c 模式下请填写 community')
        return
      }
    }
    confirmLoading.value = true

    const patchData: SecurityServicePatchData = {
      collect_method: formData.collect_method,
      agent_config: formData.collect_method === 'api' ? formData.agent_config : undefined,
      snmp_target: formData.collect_method === 'snmp' ? formData.snmp_target : undefined,
      snmp_port: formData.collect_method === 'snmp' ? formData.snmp_port : undefined,
      snmp_version: formData.collect_method === 'snmp' ? formData.snmp_version : undefined,
      snmp_community: formData.collect_method === 'snmp' ? formData.snmp_community : undefined,
      snmp_v3_security_level: formData.collect_method === 'snmp' ? formData.snmp_v3_security_level : undefined,
      snmp_v3_security_name: formData.collect_method === 'snmp' ? formData.snmp_v3_security_name : undefined,
      snmp_v3_auth_protocol: formData.collect_method === 'snmp' ? formData.snmp_v3_auth_protocol : undefined,
      snmp_v3_auth_password: formData.collect_method === 'snmp' ? formData.snmp_v3_auth_password : undefined,
      snmp_v3_priv_protocol: formData.collect_method === 'snmp' ? formData.snmp_v3_priv_protocol : undefined,
      snmp_v3_priv_password: formData.collect_method === 'snmp' ? formData.snmp_v3_priv_password : undefined,
      snmp_v3_context_name: formData.collect_method === 'snmp' ? formData.snmp_v3_context_name : undefined,
      snmp_timeout_ms: formData.collect_method === 'snmp' ? formData.snmp_timeout_ms : undefined,
      snmp_retries: formData.collect_method === 'snmp' ? formData.snmp_retries : undefined,
      collect_on: formData.collect_on,
      collect_interval: formData.collect_interval,
    }

    await patchSecurityServiceCollect(props.record.id, patchData)
    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)
}
</script>
