<template>
  <a-modal
    :visible="visible"
    :title="isNewEdge ? '添加链路' : '编辑链路'"
    @ok="handleSave"
    @cancel="handleCancel"
    @update:visible="emit('update:visible', $event)"
    ok-text="确定"
    cancel-text="取消"
  >
    <a-form :model="formData" layout="vertical">
      <a-form-item label="链路类型 *" required>
        <a-select v-model="formData.type" placeholder="请选择链路类型">
          <a-option value="physical">物理链路 (蓝色实线)</a-option>
          <a-option value="virtual">虚拟链路 (橙色虚线)</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="链路标签">
        <a-input v-model="formData.label" placeholder="选填，如: 主干网络, 备用链路等" allow-clear />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import type { Edge } from '@vue-flow/core'

interface Props {
  visible: boolean
  edge: Edge | null
  isNewEdge: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'change', edge: Edge): void
  (e: 'save'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formData = reactive({
  type: 'physical',
  label: '',
})

watch(
  () => props.edge,
  (edge) => {
    if (edge) {
      formData.type = edge.data?.type || 'physical'
      formData.label = edge.data?.label || ''
    }
  },
  { immediate: true }
)

watch(
  () => [formData.type, formData.label],
  () => {
    if (props.edge) {
      emit('change', {
        ...props.edge,
        data: { ...props.edge.data, type: formData.type, label: formData.label },
      })
    }
  }
)

const handleSave = () => {
  emit('save')
  emit('update:visible', false)
}

const handleCancel = () => {
  emit('update:visible', false)
}
</script>
