<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑服务器/PC' : '新增服务器/PC'"
    @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="unique_id" label="唯一标识">
            <a-input
              v-model="formData.unique_id"
              placeholder="输入为空系统自动生成UUID"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="服务器名称">
            <a-input v-model="formData.name" placeholder="请输入服务器名称" />
          </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="other">其它</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <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-option value="other">其它</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="rack_id" label="数据中心/楼层/机柜">
        <DatacenterSelector
          ref="datacenterSelectorRef"
          v-model:datacenter-id="formData.datacenter_id"
          v-model:floor-id="formData.floor_id"
          v-model:rack-id="formData.rack_id"
        />
      </a-form-item>

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

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="ip" label="IP地址">
            <a-input v-model="formData.ip" placeholder="可以输入多个IP，逗号做分隔" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="remote_access" label="远程访问端口">
            <a-input v-model="formData.remote_access" placeholder="为空则不可远程访问" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="agent_config" label="Agent 配置">
        <a-input v-model="formData.agent_config" placeholder="请输入Agent 配置" />
      </a-form-item>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="data_collection" label="数据采集">
            <a-switch v-model="formData.data_collection" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item v-if="formData.data_collection" field="collection_interval" label="采集时间">
            <a-select v-model="formData.collection_interval" placeholder="请选择采集时间">
              <a-option :value="1">1分钟</a-option>
              <a-option :value="5">5分钟</a-option>
              <a-option :value="10">10分钟</a-option>
              <a-option :value="30">30分钟</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="remark" label="备注信息">
        <a-textarea
          v-model="formData.remark"
          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 { v4 as uuidv4 } from 'uuid'
import type { FormInstance } from '@arco-design/web-vue'
import DatacenterSelector from './DatacenterSelector.vue'
import { createServer, updateServer } from '@/api/ops/server'

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 datacenterSelectorRef = ref<InstanceType<typeof DatacenterSelector>>()

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

const formData = reactive({
  unique_id: '',
  name: '',
  server_type: '',
  os: '',
  kernel: '',
  datacenter_id: undefined as number | undefined,
  floor_id: undefined as number | undefined,
  rack_id: undefined as number | undefined,
  tags: '',
  ip: '',
  remote_access: '',
  agent_config: '',
  data_collection: false,
  collection_interval: 5,
  remark: '',
})

const rules = {
  name: [{ required: true, message: '请输入服务器名称' }],
  server_type: [{ required: true, message: '请选择服务器类型' }],
  os: [{ required: true, message: '请选择操作系统' }],
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          unique_id: props.record.unique_id || '',
          name: props.record.name || '',
          server_type: props.record.server_type || '',
          os: props.record.os || '',
          datacenter_id: props.record.datacenter_id,
          floor_id: props.record.floor_id,
          rack_id: props.record.rack_id,
          tags: props.record.tags || '',
          ip: props.record.ip || '',
          remote_access: props.record.remote_access || '',
          agent_config: props.record.agent_config || '',
          data_collection: props.record.data_collection || false,
          collection_interval: props.record.collection_interval || 5,
          remark: props.record.remark || '',
        })
        
        // 编辑模式下初始化加载下级列表
        if (props.record.datacenter_id) {
          datacenterSelectorRef.value?.initLoad()
        }
      } else {
        Object.assign(formData, {
          unique_id: '',
          name: '',
          server_type: '',
          os: '',
          datacenter_id: undefined,
          floor_id: undefined,
          rack_id: undefined,
          tags: '',
          ip: '',
          remote_access: '',
          agent_config: '',
          data_collection: false,
          collection_interval: 5,
          remark: '',
        })
        datacenterSelectorRef.value?.reset()
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    
    confirmLoading.value = true
    
    // 准备提交数据
    const submitData: any = {
      name: formData.name,
      host: formData.ip,
      ip_address: formData.ip,
      description: formData.remark,
      os: formData.os,
      server_type: formData.server_type,
      kernel: formData.kernel,
      tags: formData.tags,
      remote_access: formData.remote_access,
      agent_config: formData.agent_config,
      collect_on: formData.data_collection,
      collect_interval: formData.collection_interval,
    }
    
    // 编辑模式或唯一标识
    if (isEdit.value && props.record?.id) {
      // 更新服务器
      const res: any = await updateServer(props.record.id, submitData)
      if (res.code === 200 || res.code === 0) {
        Message.success('更新成功')
        emit('success')
        handleCancel()
      } else {
        Message.error(res.message || '更新失败')
      }
    } else {
      // 创建服务器
      if (!formData.unique_id) {
        submitData.server_identity = uuidv4()
      } else {
        submitData.server_identity = formData.unique_id
      }
      
      const res: any = await createServer(submitData)
      if (res.code === 200 || 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>
