<template>
  <a-modal
    v-model:open="visible"
    :title="title"
    width={600}
    @cancel="handleClose"
    centered
  >
    <supervision-entity-form
      ref="formRef"
      :entity-id="entityId"
      :entity-types="entityTypes"
      @success="handleFormSuccess"
      @cancel="handleCancel"
    />
  </a-modal>
</template>

<script lang="js" setup>
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import SupervisionEntityForm from '@/views/supervision-entities/Form.vue'

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  entityId: {
    type: Number,
    default: null
  },
  entityTypes: {
    type: Array,
    default: () => []
  },
  mode: {
    type: String,
    default: 'create'
  }
})

// 定义组件事件
const emit = defineEmits([
  'cancel',
  'submit'
])

// 表单组件引用
const formRef = ref<any>(null)

// 计算弹窗标题
const title = computed(() => {
  return props.mode === 'create' ? '新增监管实体' : '编辑监管实体'
})

// 监听 visible 变化，当弹窗显示时重置表单
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && formRef.value) {
      // 短暂延迟确保表单组件已更新 entityId
      setTimeout(() => {
        // 如果是创建模式，重置表单
        if (props.mode === 'create' && !props.entityId) {
          formRef.value.resetForm()
        }
      }, 100)
    }
  }
)

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

// 处理表单成功提交
const handleFormSuccess = () => {
  message.success(props.mode === 'create' ? '创建成功' : '更新成功')
  emit('success')
  handleClose()
}

// 处理取消
const handleCancel = () => {
  handleClose()
}

// 暴露方法给父组件调用
defineExpose({
  resetForm: () => {
    if (formRef.value) {
      formRef.value.resetForm()
    }
  }
})
</script>

<style scoped>
/* 弹窗样式可以根据需要调整 */
</style>