<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="名称" required>
            <a-input v-model="formData.name" placeholder="请输入存储设备名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="type" label="类型" required>
            <a-select v-model="formData.type" placeholder="请选择类型">
              <a-option value="nas">NAS存储</a-option>
              <a-option value="san">SAN存储</a-option>
              <a-option value="das">DAS存储</a-option>
              <a-option value="cloud">云存储</a-option>
              <a-option value="other">其他</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <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-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-row>

      <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="interval" label="检查间隔(秒)">
            <a-input-number v-model="formData.interval" :min="10" :max="3600" placeholder="默认60秒" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="collect_on" label="启用采集">
            <a-switch v-model="formData.collect_on" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item v-if="formData.collect_on" field="collect_interval" label="采集间隔(秒)">
            <a-input-number v-model="formData.collect_interval" :min="10" :max="3600" placeholder="默认60秒" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">采集配置</a-divider>

      <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="Agent配置URL">
          <a-input v-model="formData.agent_config" placeholder="请输入Agent配置地址" />
        </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="请输入SNMP目标地址" />
            </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" placeholder="默认161" 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="SNMP Community">
              <a-input v-model="formData.snmp_community" placeholder="请输入SNMP 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="超时(毫秒)">
              <a-input-number v-model="formData.snmp_timeout_ms" :min="1" :max="60000" placeholder="默认3000" 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" placeholder="默认1" 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>

        <SnmpOidEditor
          ref="snmpOidEditorRef"
          v-model="formData.snmp_oids"
          :reset-key="snmpOidEditorResetKey"
        />
      </template>

      <a-form-item field="collect_args" label="采集参数">
        <a-textarea v-model="formData.collect_args" placeholder="请输入采集参数(JSON格式)" :rows="3" />
      </a-form-item>

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

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

      <a-form-item field="description" label="描述">
        <a-textarea v-model="formData.description" placeholder="请输入描述信息" :rows="4" />
      </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 { createStorage, updateStorage } from '@/api/ops/storage'
import type { StorageCreateData, StorageItem } from '@/api/ops/storage'
import { fetchServerList, type ServerItem } from '@/api/ops/server'
import SnmpOidEditor from '../../components/SnmpOidEditor.vue'

interface Props {
  visible: boolean
  record?: StorageItem | null
}

const props = withDefaults(defineProps<Props>(), {
  record: null,
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref<FormInstance>()
const snmpOidEditorRef = ref<InstanceType<typeof SnmpOidEditor>>()
const snmpOidEditorResetKey = ref(0)
const confirmLoading = ref(false)
const serverOptions = ref<ServerItem[]>([])

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

const formData = reactive<StorageCreateData>({
  name: '',
  type: '',
  oid: '',
  server_identity: '',
  description: '',
  enabled: true,
  interval: 60,
  extra: '',
  tags: '',
  agent_config: '',
  collect_method: 'api' as 'api' | 'snmp',
  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,
  snmp_oids: '',
  collect_on: true,
  collect_args: '',
  collect_interval: 60,
})

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

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          name: props.record.name || '',
          type: props.record.type || '',
          oid: props.record.oid || '',
          server_identity: props.record.server_identity || '',
          description: props.record.description || '',
          enabled: props.record.enabled ?? true,
          interval: props.record.interval || 60,
          extra: props.record.extra || '',
          tags: props.record.tags || '',
          agent_config: props.record.agent_config || '',
          collect_method: props.record.collect_method || 'api',
          snmp_target: props.record.snmp_target || '',
          snmp_port: props.record.snmp_port || 161,
          snmp_version: props.record.snmp_version || 'v2c',
          snmp_community: props.record.snmp_community || '',
          snmp_v3_security_level: props.record.snmp_v3_security_level || 'noAuthNoPriv',
          snmp_v3_security_name: props.record.snmp_v3_security_name || '',
          snmp_v3_auth_protocol: props.record.snmp_v3_auth_protocol || 'SHA',
          snmp_v3_auth_password: '',
          snmp_v3_priv_protocol: props.record.snmp_v3_priv_protocol || 'AES',
          snmp_v3_priv_password: '',
          snmp_v3_context_name: props.record.snmp_v3_context_name || '',
          snmp_timeout_ms: props.record.snmp_timeout_ms || 3000,
          snmp_retries: props.record.snmp_retries ?? 1,
          snmp_oids: props.record.snmp_oids || '',
          collect_on: props.record.collect_on ?? true,
          collect_args: props.record.collect_args || '',
          collect_interval: props.record.collect_interval || 60,
        })
        snmpOidEditorResetKey.value += 1
      } else {
        Object.assign(formData, {
          name: '',
          type: '',
          oid: '',
          server_identity: '',
          description: '',
          enabled: true,
          interval: 60,
          extra: '',
          tags: '',
          agent_config: '',
          collect_method: 'api',
          snmp_target: '',
          snmp_port: 161,
          snmp_version: 'v2c',
          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,
          snmp_oids: '',
          collect_on: true,
          collect_args: '',
          collect_interval: 60,
        })
        snmpOidEditorResetKey.value += 1
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    if (formData.collect_method === 'api' && !formData.agent_config?.trim()) {
      Message.warning('API 模式下请填写 Agent 配置 URL')
      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
      }
      if (!snmpOidEditorRef.value?.validate()) {
        return
      }
    }

    confirmLoading.value = true

    const submitData: StorageCreateData = {
      name: formData.name,
      type: formData.type,
      oid: formData.oid,
      server_identity: formData.server_identity,
      description: formData.description,
      enabled: formData.enabled,
      interval: formData.interval,
      extra: formData.extra,
      tags: formData.tags,
      agent_config: formData.agent_config,
      collect_method: formData.collect_method,
      snmp_target: formData.snmp_target,
      snmp_port: formData.snmp_port,
      snmp_version: formData.snmp_version,
      snmp_community: formData.snmp_community,
      snmp_v3_security_level: formData.snmp_v3_security_level,
      snmp_v3_security_name: formData.snmp_v3_security_name,
      snmp_v3_auth_protocol: formData.snmp_v3_auth_protocol,
      snmp_v3_auth_password: formData.snmp_v3_auth_password,
      snmp_v3_priv_protocol: formData.snmp_v3_priv_protocol,
      snmp_v3_priv_password: formData.snmp_v3_priv_password,
      snmp_v3_context_name: formData.snmp_v3_context_name,
      snmp_timeout_ms: formData.snmp_timeout_ms,
      snmp_retries: formData.snmp_retries,
      snmp_oids: formData.snmp_oids,
      collect_on: formData.collect_on,
      collect_args: formData.collect_args,
      collect_interval: formData.collect_interval,
    }

    if (isEdit.value && props.record?.id) {
      const res: any = await updateStorage(props.record.id, submitData)
      if (res.code === 0) {
        Message.success('更新成功')
        emit('success')
        handleCancel()
      } else {
        Message.error(res.message || '更新失败')
      }
    } else {
      const res: any = await createStorage(submitData)
      if (res.code === 0) {
        Message.success('创建成功')
        emit('success')
        handleCancel()
      } else {
        Message.error(res.message || '创建失败')
      }
    }
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    confirmLoading.value = false
  }
}

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}

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 = []
  }
}

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