<template lang="pug">
    form.ocForm(ref="form", :class="{ formSm: isSmall, ocFormInline: isInline }", @submit.prevent="submit($event)")
        slot

</template>

<script>
    import ocToolForm from './js/form'
    export default {
        name: 'oc-form',
        props: {
            isSmall: { type: Boolean, default: false },
            isInline: { type: Boolean, default: false },
            labelWidth: { type: String, default: null },
            isInputBlock: { type: Boolean, default: false }
        },

        updated() {
            this.resetLabel();
        },

        mounted() {
            this.resetLabel();
        },

        methods: {
            resetLabel() {
                let maxWidth = this.labelWidth;

                let labels = this.$refs.form.querySelectorAll('.ocFormLabel');
                
                if(!this.labelWidth && !this.isInline) {
                    maxWidth = 0;
                    [].map.call(labels, ele => {
                        let width = ele.offsetWidth;
                        if(width > maxWidth) {
                            maxWidth = width;
                        }
                        
                        let nextSibling = ele.nextSibling;
                        nextSibling && ele.nextSibling.classList.add('ocFormItemIpt');
                        if(this.isInputBlock) {
                            ele.nextSibling && (ele.nextSibling.classList.add('block'));
                        }
                    })
                    maxWidth = (maxWidth + 20) + 'px';
                }
                [].map.call(labels, ele => {
                    ele.style.width = maxWidth;
                })
            },

            check() {
                return ocToolForm.validity(this.$refs.form);
            },

            getModel(isRemoveEmpty) {
                let form = this.$refs.form;
                if(this.check() !== false) {
                    return ocToolForm.getJson(this.$refs.form, isRemoveEmpty);
                }

                return false;
            },

            fill(model) {
                ocToolForm.fill(this.$refs.form, model);
            },

            clear() {
                ocToolForm.clear(this.$refs.form);
            },

            submit($event) {
                let model = this.getModel();
                if(model !== false) {
                    this.$emit('submit', model, $event);
                }
            }
        }
    }
</script>

            