<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="room_id" label="机房ID">
            <a-input v-model="formData.room_id" placeholder="请输入机房ID" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="device_category" label="设备分类">
            <a-select v-model="formData.device_category" placeholder="请选择设备分类">
              <a-option v-for="item in DEVICE_CATEGORY_OPTIONS" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-option>
            </a-select>
          </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-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="采集地址(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-row :gutter="20">
          <a-col :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 :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-form-item field="snmp_oids" label="SNMP OID配置(JSON数组)">
          <a-textarea
            v-model="formData.snmp_oids"
            :rows="3"
            placeholder='可留空使用默认模板，或填写如 [{"oid":"1.3.6.1.2.1.1.3.0","metric_name":"sys_uptime"}]'
          />
        </a-form-item>
      </template>

      <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="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 {
  createRoomDevice,
  updateRoomDevice,
  DEVICE_CATEGORY_OPTIONS,
  type RoomDeviceCreateData,
  type RoomDeviceUpdateData,
} from '@/api/ops/room-device'
import { fetchPolicyOptions, type PolicyOptionItem } from '@/api/ops/alertPolicy'

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

const formData = reactive({
  name: '',
  description: '',
  room_id: '',
  device_category: '',
  agent_config: '',
  collect_method: 'api' as 'api' | 'snmp',
  snmp_target: '',
  snmp_port: 161,
  snmp_community: '',
  snmp_timeout_ms: 3000,
  snmp_retries: 1,
  snmp_oids: '',
  enabled: true,
  collect_on: true,
  collect_interval: 60,
  policy_ids: [] as number[],
})

const rules = {
  name: [{ required: true, message: '请输入服务名称' }],
  room_id: [{ required: true, message: '请输入机房ID' }],
  device_category: [{ 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 = []
  }
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          name: props.record.name || '',
          description: props.record.description || '',
          room_id: props.record.room_id || '',
          device_category: props.record.device_category || '',
          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_community: props.record.snmp_community || '',
          snmp_timeout_ms: props.record.snmp_timeout_ms || 3000,
          snmp_retries: props.record.snmp_retries ?? 1,
          snmp_oids: props.record.snmp_oids || '',
          enabled: props.record.enabled ?? true,
          collect_on: props.record.collect_on ?? true,
          collect_interval: props.record.collect_interval || 60,
          policy_ids: props.record.policy_ids || [],
        })
      } else {
        Object.assign(formData, {
          name: '',
          description: '',
          room_id: '',
          device_category: '',
          agent_config: '',
          collect_method: 'api',
          snmp_target: '',
          snmp_port: 161,
          snmp_community: '',
          snmp_timeout_ms: 3000,
          snmp_retries: 1,
          snmp_oids: '',
          enabled: true,
          collect_on: true,
          collect_interval: 60,
          policy_ids: [],
        })
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    if (formData.collect_method === 'api' && !formData.agent_config?.trim()) {
      Message.warning('API 模式下请填写采集地址')
      return
    }
    if (formData.collect_method === 'snmp') {
      if (!formData.snmp_target?.trim() || !formData.snmp_community?.trim()) {
        Message.warning('SNMP 模式下请填写目标地址和 community')
        return
      }
      if (formData.snmp_oids?.trim()) {
        try {
          JSON.parse(formData.snmp_oids)
        } catch {
          Message.warning('SNMP OID 配置必须是合法 JSON')
          return
        }
      }
    }

    confirmLoading.value = true

    if (isEdit.value) {
      const updateData: RoomDeviceUpdateData = {
        name: formData.name,
        description: formData.description,
        room_id: formData.room_id,
        device_category: formData.device_category,
        agent_config: formData.agent_config,
        collect_method: formData.collect_method,
        snmp_target: formData.snmp_target,
        snmp_port: formData.snmp_port,
        snmp_community: formData.snmp_community,
        snmp_timeout_ms: formData.snmp_timeout_ms,
        snmp_retries: formData.snmp_retries,
        snmp_oids: formData.snmp_oids,
        enabled: formData.enabled,
        collect_on: formData.collect_on,
        collect_interval: formData.collect_interval,
        policy_ids: formData.policy_ids,
      }
      await updateRoomDevice(props.record.id, updateData)
      Message.success('更新成功')
    } else {
      const createData: RoomDeviceCreateData = {
        name: formData.name,
        description: formData.description,
        room_id: formData.room_id,
        device_category: formData.device_category,
        agent_config: formData.agent_config,
        collect_method: formData.collect_method,
        snmp_target: formData.snmp_target,
        snmp_port: formData.snmp_port,
        snmp_community: formData.snmp_community,
        snmp_timeout_ms: formData.snmp_timeout_ms,
        snmp_retries: formData.snmp_retries,
        snmp_oids: formData.snmp_oids,
        enabled: formData.enabled,
        collect_on: formData.collect_on,
        collect_interval: formData.collect_interval,
        policy_ids: formData.policy_ids,
      }
      await createRoomDevice(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()
}

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