<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="localFormData"
      :rules="formRules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="localFormData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="localFormData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  level: {
    type: Number,
    default: 1
  },
  formData: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['update:visible', 'confirm'])

const formRef = ref()

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

const visible = ref(props.visible)
const localFormData = ref({ ...props.formData })
watch(() => props.visible, (newVal) => {
  if (newVal) {
    localFormData.value = props.formData
  }
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

function handleConfirm() {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      emit('confirm', valid, { ...localFormData.value })
      visible.value = false
    }
  })
}

function handleCancel() {
  visible.value = false
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>