<!-- 编辑弹窗 -->
<template>
    <pro-form
        class="simple-form"
        v-bind="$attrs"
        ref="proFormRef"
        :model="form"
        :items="items"
        :grid="{ span: grid }"
        @updateValue="setFieldValue"
        @submit="submitForm"
        @reset="resetForm"
    >
        <template
            v-for="(val, key) in $slots"
            #[key]="{ item, model, updateValue }"
        >
            <slot
                :name="key"
                :item="item"
                :model="model"
                :updateValue="updateValue"
            ></slot>
        </template>
    </pro-form>
</template>

<script setup>
    import { ref } from 'vue';
    import { useFormData } from '@/utils/use-form-data';
    import ProForm from '@/components/ProForm/index.vue';
    const slotArray = useSlots();

    const emit = defineEmits(['submit', 'reset']);
    const proFormRef = ref(null);
    const props = defineProps({
        items: {
            type: Array,
            default: () => []
        },
        grid: {
            type: Number,
            default: 24
        }
    });
    let initKeys = [];
    watch(
        () => props.items,
        (values) => {
            initKeys = values.map((item) => item.prop);
        },
        { deep: true, immediate: true }
    );

    const [form, resetFields, assignFields, setFieldValue] = useFormData();
    /** 提交表单 */
    const submitForm = (model) => {
        return new Promise((resolve, reject) => {
            proFormRef.value?.validate?.((valid) => {
                if (valid) {
                    resolve(form);
                    emit('submit', model);
                } else {
                    reject('表单验证失败');
                }
            });
        });
    };

    /** 重置表单 */
    const resetForm = () => {
        // Complete reset - reinitialize the form data object to clear all fields
        Object.keys(form).forEach((key) => {
            form[key] = undefined;
        });
        resetFields();
        nextTick(() => {
            proFormRef.value?.clearValidate?.();
        });
    };

    function setData(data) {
        Object.keys(data).forEach((key) => {
            if (initKeys.includes(key)) {
                setFieldValue(key, data[key]);
            }
        });
        // 延迟清空表单验证，防止表单验证不生效
        setTimeout(() => {
            proFormRef.value?.clearValidate?.();
        }, 50);
    }

    defineExpose({
        resetFields,
        assignFields,
        setData,
        submitForm,
        resetForm
    });
</script>
