<template>
  <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
    <el-form-item label="原料名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入原料名称"></el-input>
    </el-form-item>
    <el-form-item label="描述" prop="description">
      <el-input
        v-model="formData.description"
        type="textarea"
        :rows="3"
        placeholder="请输入原料描述"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'RawMaterialForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    initialData: {
      type: Object,
      default: () => ({
        name: '',
        description: '',
      }),
    },
  },
  emits: ['submit', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null);
    const formData = reactive({
      name: '',
      description: '',
    });

    // 监听 initialData 变化，用于编辑模式下初始化表单
    watch(
      () => props.initialData,
      (newVal) => {
        if (newVal) {
          formData.name = newVal.name || '';
          formData.description = newVal.description || '';
        }
      },
      { immediate: true, deep: true }
    );

    const rules = {
      name: [
        { required: true, message: '请输入原料名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
      ],
    };

    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          emit('submit', { ...formData });
        } else {
          ElMessage.error('请检查表单项');
          return false;
        }
      });
    };

    const cancelForm = () => {
      emit('cancel');
      resetForm();
    };

    const resetForm = () => {
      formRef.value.resetFields();
      // 手动重置 formData，因为 resetFields 不会重置未绑定 prop 的字段
      formData.name = '';
      formData.description = '';
    };

    return {
      formRef,
      formData,
      rules,
      submitForm,
      cancelForm,
      resetForm,
    };
  },
};
</script>

<style scoped>
</style>
