<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto">
    <el-form-item v-for="item in formConfig" :key="item.prop" :label="item.label" :prop="item.prop">
      <!-- 自定义插槽处理 -->
      <slot v-if="item.slot" :name="item.slot" />

      <!-- 组件动态渲染 -->
      <component v-else :is="item.component" v-model="formData[item.prop]" v-bind="item.componentProps">
        <el-option
          v-for="option in item.selectOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </component>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import type { FormConfig } from '@/types/basic-form';
  import type { FormInstance, FormRules } from 'element-plus';
  const formRef = ref<FormInstance>();
  defineProps<{
    formData: Record<string, any>;
    formRules?: FormRules<any>;
    formConfig: FormConfig[];
  }>();

  // 验证表单
  const validateForm = () => {
    return new Promise((resolve) => {
      formRef.value?.validate((valid: boolean) => {
        resolve(valid);
      });
    });
  };

  // 验证表单字段
  const validateField = (field: string) => {
    formRef.value?.validateField(field);
  };

  defineExpose({
    validateForm,
    validateField,
  });
</script>

<style lang="scss" scoped>
  .el-form {
    display: flex;
    flex-direction: column;
    width: 600cpx;
    height: 100%;
    gap: 12cpx;
  }
</style>
