<template>
    <el-form ref="form" :model="model" :label-width="labelWidth" :label-position="labelPosition" size="large">
        <slot></slot>
    </el-form>
</template>

<script>
import {computed} from "@vue/reactivity";

export default {
    name: "st-form",
    emits:["submit","submited"],
    props:{
        api : Function,
        labelWidth : {
            type : String ,
            default : "110px"
        } ,
        labelPosition : {
            type : String ,
            default : "left"
        } ,
        successMsg : {
            type : String ,
            default : "保存成功"
        },
        model:{
            type : Object,
            default(){
                return {}
            }
        }
    },
    provide(){
        return {
            errorKeys : computed(()=> this.errorKeys )
        }
    },
    data(){
        return {
            errorKeys : []
        }
    },
    methods: {
        validate(){
            return new Promise((resolve,reject)=>{
                this.$refs.form.validate((valid,rules={})=>{
                    this.errorKeys = Object.keys(rules);
                    if(valid) {
                        this.$refs.form.clearValidate();
                        resolve();
                    } else {
                        reject();
                    }
                })
            })
        },

        clearValidate(){
            this.$refs.form.clearValidate();
        },
        
        resetFields(){
            this.$refs.form.resetFields();
        },

        async submit(btnRef){
            await this.validate();
            if(!this.api){
                this.$emit("submit" , this.model);
                return ;
            }

            if(btnRef) btnRef.loading();
            await this._submit().finally(()=>{
                if(btnRef) btnRef.loading(false);
            });
        },

        async _submit(){
            let res = await this.api(this.model);
            this.$message.success(this.successMsg);
            this.$emit("submited" , res);
        }

    }
}
</script>
