<template>
  <a-modal
    :visible="visible"
    :title="mode === 'create' ? '新增拓扑' : '编辑拓扑'"
    @ok="handleSubmit"
    @cancel="handleClose"
    @update:visible="handleUpdateVisible"
    :confirm-loading="submitting"
  >
    <a-form :model="formData" layout="vertical" :label-col-props="{ span: 24 }" :wrapper-col-props="{ span: 24 }">
      <a-form-item label="拓扑名称" required>
        <a-input v-model="formData.name" placeholder="请输入拓扑名称" :max-length="100" allow-clear />
      </a-form-item>

      <a-form-item label="是否启用">
        <a-select v-model="formData.enable" placeholder="请选择">
          <a-option :value="true">是</a-option>
          <a-option :value="false">否</a-option>
        </a-select>
      </a-form-item>

      <a-form-item label="描述">
        <a-textarea
          v-model="formData.description"
          placeholder="请输入描述（可选）"
          :max-length="500"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { Topology } from '@/api/ops/netarchTopo'

interface Props {
  visible: boolean
  mode: 'create' | 'edit'
  initialValues?: Topology | null
  groupId?: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', values: any): Promise<void>
}

const props = withDefaults(defineProps<Props>(), {
  initialValues: null,
  groupId: 0,
})

const emit = defineEmits<Emits>()

const submitting = ref(false)

const formData = reactive({
  name: '',
  type: 'layer2' as 'layer2' | 'layer3' | 'physical',
  description: '',
  enable: true,
})

// 监听 visible 变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (props.mode === 'edit' && props.initialValues) {
        formData.name = props.initialValues.name || ''
        formData.type = props.initialValues.type || 'layer2'
        formData.description = props.initialValues.description || ''
        formData.enable = props.initialValues.enable ?? true
      } else {
        formData.name = ''
        formData.type = 'layer2'
        formData.description = ''
        formData.enable = true
      }
    }
  }
)

// 更新可见性
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formData.name.trim()) {
    Message.warning('请输入拓扑名称')
    return
  }

  submitting.value = true
  try {
    await emit('submit', { ...formData })
  } finally {
    submitting.value = false
  }
}
</script>

<script lang="ts">
export default {
  name: 'TopologyFormDialog',
}
</script>
