<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="server_identity" label="唯一标识">
            <a-input
              v-model="formData.server_identity"
              placeholder="输入为空系统自动生成ULID"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="服务器名称" required>
            <a-input v-model="formData.name" placeholder="请输入服务器名称" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="host" label="主机地址" required>
            <a-input v-model="formData.host" placeholder="请输入主机地址" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="ip_address" label="IP地址">
            <a-input v-model="formData.ip_address" placeholder="请输入IP地址" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="8">
          <a-form-item field="server_type" label="服务器类型">
            <a-select v-model="formData.server_type" placeholder="请选择服务器类型">
              <a-option value="physical">物理服务器</a-option>
              <a-option value="virtual">虚拟服务器</a-option>
              <a-option value="cloud">云服务器</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="os" label="操作系统">
            <a-select v-model="formData.os" placeholder="请选择操作系统">
              <a-option value="Windows">Windows</a-option>
              <a-option value="Linux">Linux</a-option>
              <a-option value="Mac">Mac</a-option>
              <a-option value="Other">其它</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="os_version" label="系统版本">
            <a-input v-model="formData.os_version" placeholder="如: 22.04" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="8">
          <a-form-item field="kernel" label="内核类型">
            <a-select v-model="formData.kernel" placeholder="请选择内核类型">
              <a-option value="x86">x86</a-option>
              <a-option value="arm">ARM</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="location" label="位置/机房">
            <a-input v-model="formData.location" placeholder="机房A-机架01" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="tags" label="标签">
            <a-input v-model="formData.tags" placeholder="多个标签逗号分隔" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="remote_access" label="远程访问">
            <a-input v-model="formData.remote_access" placeholder="ssh://user@host" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="remote_port" label="远程端口">
            <a-input-number v-model="formData.remote_port" placeholder="SSH/RDP端口" :min="0" :max="65535" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="agent_config" label="Agent 配置 URL">
        <a-input v-model="formData.agent_config" placeholder="http://192.168.1.100:9100/dc-host/v1/control/command" />
      </a-form-item>

      <a-row :gutter="20">
        <a-col :span="8">
          <a-form-item field="status" label="状态">
            <a-select v-model="formData.status" placeholder="请选择状态">
              <a-option value="online">在线</a-option>
              <a-option value="offline">离线</a-option>
              <a-option value="unknown">未知</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="collect_on" label="启用采集">
            <a-switch v-model="formData.collect_on" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <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="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 { createServer, updateServer } from '@/api/ops/server'
import type { ServerFormData, ServerItem } from '@/api/ops/server'

interface Props {
  visible: boolean
  record?: ServerItem | 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<ServerFormData>({
  server_identity: '',
  name: '',
  host: '',
  ip_address: '',
  description: '',
  os: '',
  os_version: '',
  kernel: '',
  server_type: '',
  tags: '',
  location: '',
  remote_access: '',
  remote_port: 0,
  agent_config: '',
  status: 'unknown',
  collect_on: true,
  collect_interval: 60,
})

const rules = {
  name: [{ required: true, message: '请输入服务器名称' }],
  host: [{ required: true, message: '请输入主机地址' }],
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          server_identity: props.record.server_identity || '',
          name: props.record.name || '',
          host: props.record.host || '',
          ip_address: props.record.ip_address || '',
          description: props.record.description || '',
          os: props.record.os || '',
          os_version: props.record.os_version || '',
          kernel: props.record.kernel || '',
          server_type: props.record.server_type || '',
          tags: props.record.tags || '',
          location: props.record.location || '',
          remote_access: props.record.remote_access || '',
          remote_port: props.record.remote_port || 0,
          agent_config: props.record.agent_config || '',
          status: props.record.status || 'unknown',
          collect_on: props.record.collect_on ?? true,
          collect_interval: props.record.collect_interval || 60,
        })
      } else {
        Object.assign(formData, {
          server_identity: '',
          name: '',
          host: '',
          ip_address: '',
          description: '',
          os: '',
          os_version: '',
          kernel: '',
          server_type: '',
          tags: '',
          location: '',
          remote_access: '',
          remote_port: 0,
          agent_config: '',
          status: 'unknown',
          collect_on: true,
          collect_interval: 60,
        })
      }
    }
  },
)

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

    confirmLoading.value = true

    const submitData: ServerFormData = {
      server_identity: formData.server_identity || undefined,
      name: formData.name,
      host: formData.host,
      ip_address: formData.ip_address,
      description: formData.description,
      os: formData.os,
      os_version: formData.os_version,
      kernel: formData.kernel,
      server_type: formData.server_type,
      tags: formData.tags,
      location: formData.location,
      remote_access: formData.remote_access,
      remote_port: formData.remote_port,
      agent_config: formData.agent_config,
      status: formData.status,
      collect_on: formData.collect_on,
      collect_interval: formData.collect_interval,
    }

    if (isEdit.value && props.record?.id) {
      const res: any = await updateServer(props.record.id, submitData)
      if (res.code === 0) {
        Message.success('更新成功')
        emit('success')
        handleCancel()
      } else {
        Message.error(res.message || '更新失败')
      }
    } else {
      const res: any = await createServer(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>
