<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-col :span="12">
          <a-form-item field="category" label="分类">
            <a-input v-model="formData.category" placeholder="请输入分类" />
          </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-input v-model="formData.server_identity" placeholder="请输入关联服务器标识" />
          </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-form-item field="agent_config" label="Agent配置URL">
        <a-input v-model="formData.agent_config" placeholder="请输入Agent配置地址" />
      </a-form-item>

      <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 } 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'

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 confirmLoading = ref(false)

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

const formData = reactive<StorageCreateData>({
  name: '',
  type: '',
  category: '',
  oid: '',
  server_identity: '',
  description: '',
  enabled: true,
  interval: 60,
  extra: '',
  tags: '',
  agent_config: '',
  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 || '',
          category: props.record.category || '',
          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_on: props.record.collect_on ?? true,
          collect_args: props.record.collect_args || '',
          collect_interval: props.record.collect_interval || 60,
        })
      } else {
        Object.assign(formData, {
          name: '',
          type: '',
          category: '',
          oid: '',
          server_identity: '',
          description: '',
          enabled: true,
          interval: 60,
          extra: '',
          tags: '',
          agent_config: '',
          collect_on: true,
          collect_args: '',
          collect_interval: 60,
        })
      }
    }
  }
)

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

    confirmLoading.value = true

    const submitData: StorageCreateData = {
      name: formData.name,
      type: formData.type,
      category: formData.category,
      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_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()
}
</script>
