<template>
    <el-form :model="model" :label-width="labelWidth" ref="form" :rules="rules" status-icon v-validate >
        <slot></slot>
    </el-form>
</template>

<script>
    let self;
    export default {
        props: {
            model: {
                type: Object,
            },
            labelWidth: {
                type: String,
                default: '100px',
            }
        },
        data() {
            return {
                rules: {},
            };
        },
        created() {
            self = this;
        },
        directives: {
            validate: {
                bind: function (el) {
                    const list = el.getElementsByClassName('el-form-item');
                    for(const item of list ) {
                        // 使用cmp-form-item做校验的直接跳过
                        if (item.className.indexOf('cmp-form-item') > -1) continue;
                        const label = item.getElementsByClassName('el-form-item__label')[0];
                        let key = label && label.getAttribute('for');
                        if (!key) return; // 获取验证的表单字段名称，如果没有则不进行验证
                        self.rules[key] = [];
                        const validate = (item.getAttribute('validate') || '').split(',');// 获取此字段需要的匹配规则
                        if (item.className.indexOf('cmp-form-item') > -1) validate.unshift('required');
                        const maxlength = item.getAttribute('maxlength');
                        let input = el.getElementsByTagName('input')[0];
                        let textarea = el.getElementsByTagName('textarea')[0];
                        input && input.setAttribute('maxlength', 32 || maxlength);
                        textarea && textarea.setAttribute('maxlength', 256 || maxlength);
                        validate.forEach((row) => {
                            if (!row) return;
                            let cell = Object.assign({}, self.$RULES[row]);// 获取匹配规则
                            const message = item.getAttribute(`${row}-message`);
                            if (message) cell.message = message;// 自定义报错信息
                            self.rules[key].push(cell);
                        });
                    }
                }
            }
        },
        methods: {
            validate(fun) {
                this.$refs.form.validate((valid) => {
                    if (valid) fun(true);
                    else fun();
                });
            },
            resetFields() {
                this.$refs.form.resetFields();
            },
        }
    };
</script>
