<template>
    <el-form-item :label="label" :prop="prop" :rules="rules" ref="formItem" v-validate :label-width="labelWidth" class="cmp-form-item">
        <slot></slot>
    </el-form-item>
</template>

<script>
let self;
export default {
    props: {
        label: {
            type: String,
            default: ''
        },
        prop: {
            type: String,
            default: ''
        },
        labelWidth: {
            type: String
        },
        validate: {
            type: String,
            default: ''
        },
        rule: {
            type: Array,
            default: function () {
                return [];
            }
        }
    },
    data () {
        return {
            rules: []
        };
    },
    directives: {
        validate: {
            bind: function (el) {
                self.$nextTick(() => {
                    const maxlength = el.getAttribute('maxlength');
                    let input = el.getElementsByTagName('input')[0];
                    let textarea = el.getElementsByTagName('textarea')[0];
                    input && input.setAttribute('maxlength', maxlength || 32);
                    textarea && textarea.setAttribute('maxlength', maxlength || 256);
                });
                if (!self.validate) return;
                const validate = self.validate.split(',');
                validate.forEach((name) => {
                    const item = Object.assign({}, self.$RULES[name]);// 获取匹配规则
                    self.$nextTick(() => {
                        const message = el.getAttribute(`${name}-message`);
                        if (message) item.message = message;// 自定义报错信息
                    });
                    self.rules.push(item);
                });
            }
        }
    },
    created() {
        self = this;
        this.rules.push(...this.rule);
    },
    methods: {
    }
};
</script>
