<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);
  };

  // 清除表单验证信息
  const clearValidate = () => {
    formRef.value?.resetFields();
  };

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

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

    .el-form-item {
      margin-bottom: 0;
    }

    :deep(.el-form-item__label) {
      padding: 0;
    }
  }
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
  :deep(.el-cascader) {
    width: 100%;
  }
</style>
