<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑办公PC' : '新增办公PC'"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirm-loading="confirmLoading"
    :mask-closable="false"
    width="800px"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <!-- 编辑时显示唯一标识（只读） -->
      <!-- <a-row v-if="isEdit" :gutter="20">
        <a-col :span="12">
          <a-form-item label="唯一标识">
            <a-input
              :model-value="formData.pc_identity"
              disabled
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="办公PC名称">
            <a-input v-model="formData.name" placeholder="请输入办公PC名称" />
          </a-form-item>
        </a-col>
      </a-row> -->
      <!-- 新建时不显示唯一标识 -->
      <a-row v-if="!isEdit" :gutter="20">
        <a-col :span="24">
          <a-form-item field="name" label="办公PC名称">
            <a-input v-model="formData.name" placeholder="请输入办公PC名称" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="host" label="主机地址">
            <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="12">
          <a-form-item field="os" label="操作系统">
            <a-select v-model="formData.os" placeholder="请选择操作系统" allow-clear>
              <a-option value="Windows">Windows</a-option>
              <a-option value="Linux">Linux</a-option>
              <a-option value="macOS">macOS</a-option>
              <a-option value="Other">其它</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="os_version" label="系统版本">
            <a-input v-model="formData.os_version" placeholder="请输入系统版本" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="kernel" label="内核类型">
            <a-select v-model="formData.kernel" placeholder="请选择内核类型" allow-clear>
              <a-option value="x86">x86</a-option>
              <a-option value="arm">ARM</a-option>
              <a-option value="x64">x64</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="server_type" label="类型">
            <a-select v-model="formData.server_type" placeholder="请选择类型" allow-clear>
              <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-row>

      <a-form-item field="location" label="位置">
        <a-input v-model="formData.location" placeholder="请输入位置信息" />
      </a-form-item>

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

      <a-form-item field="description" label="描述">
        <a-textarea v-model="formData.description" placeholder="请输入描述" :rows="3" />
      </a-form-item>

      <a-divider>远程访问配置</a-divider>

      <a-row :gutter="20">
        <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-col :span="12">
          <a-form-item field="remote_port" label="远程管理端口">
            <a-input-number v-model="formData.remote_port" placeholder="请输入端口" :min="0" :max="65535" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider>Agent 配置</a-divider>

      <a-form-item field="agent_config" label="Agent配置URL">
        <a-input v-model="formData.agent_config" placeholder="请输入完整的 http(s) URL" />
      </a-form-item>

      <a-divider>采集配置</a-divider>

      <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" placeholder="请输入采集间隔" :min="10" :max="3600" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

    </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 { createPC, updatePC, type PCItem } from '@/api/ops/pc'

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

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

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

const handleOk = async () => {
  try {
    const vilid = await formRef.value?.validate()
    if (vilid) {
      return
    }
    
    confirmLoading.value = true
    
    // 基础提交数据
    const baseData = {
      name: formData.name,
      host: formData.host,
      ip_address: formData.ip_address,
      os: formData.os,
      os_version: formData.os_version,
      kernel: formData.kernel,
      server_type: formData.server_type,
      location: formData.location,
      tags: formData.tags,
      description: formData.description,
      remote_access: formData.remote_access,
      remote_port: formData.remote_port,
      agent_config: formData.agent_config,
      collect_on: formData.collect_on,
      collect_interval: formData.collect_interval,
    }
    
    if (isEdit.value && props.record?.id) {
      // 编辑时包含 pc_identity
      const submitData = {
        ...baseData,
        pc_identity: formData.pc_identity,
      }
      const res: any = await updatePC(props.record.id, submitData)
      
      if (res.code === 0) {
        Message.success('更新成功')
        emit('success')
        handleCancel()
      } else {
        Message.error(res.message || '更新失败')
      }
    } else {
      // 新建时不传 pc_identity，由后端生成
      const res: any = await createPC(baseData)
      
      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>
