<template>
  <el-form ref="editDescriptionFormRef" :model="formData" label-width="120px">
    <el-form-item label="题干描述" prop="question_description">
      <el-input
        v-model="formData.question_description"
        type="textarea"
        placeholder="请输入题干描述"
        :rows="6"
      />
    </el-form-item>
  </el-form>
  <!-- 添加取消和保存按钮 -->
  <div class="form-actions">
    <el-button @click="handleCancel">取消</el-button>
    <el-button type="primary" @click="handleSave">保存</el-button>
  </div>
</template>

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

// 定义props
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
    default: () => ({})
  }
});

// 定义emits - 添加onCancel事件
const emit = defineEmits(['update:modelValue', 'submit', 'onCancel']);

// 表单ref
const editDescriptionFormRef = ref(null);

// 表单数据
const formData = ref({ ...props.modelValue });

// 监听modelValue变化，更新表单数据
watch(
  () => props.modelValue,
  (newValue) => {
    formData.value = { ...newValue };
  },
  { deep: true }
);

// 验证并提交表单
const validateAndSubmit = async () => {
  try {
    // 触发表单验证
    const valid = await editDescriptionFormRef.value.validate();
    if (valid) {
      // 发出submit事件
      emit('submit', formData.value);
      // 返回表单数据
      return formData.value;
    }
    return null;
  } catch (error) {
    console.error('表单验证失败:', error);
    return null;
  }
};

// 暴露方法给父组件
defineExpose({
  validateAndSubmit
});

// 取消按钮方法
const handleCancel = () => {
  emit('onCancel');
};

// 保存按钮方法
const handleSave = async () => {
  try {
    // 验证表单
    const validatedData = await validateAndSubmit();
    // 如果验证通过，submit事件已经发出
  } catch (error) {
    console.error('表单提交失败:', error);
  }
};
</script>

<style scoped>
.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>