<template>
    <div>
        <component :is="is"
                   ref="veUpload"
                   @data-change="change"
                   v-bind="$attrs"
                   v-on="$listeners"
        >
            <slot name="trigger" slot="trigger"></slot>
            <slot name="tip" slot="tip"></slot>
            <slot></slot>
        </component>
    </div>
</template>

<script>

let components = {
    SingleButton: () => import("./types/single-button"),
    SingleImage: () => import("./types/single-image"),
    MultipleImage: () => import("./types/multiple-image"),
}
export default {
    name: "su-upload",
    data() {
        return {
            is: null,
            model: null,
        }
    },
    props: {
        type: {
            type: String,
            default: "SingleImage"
        },
        value: {
            type: Object | Array
        },
    },
    model: {
        prop: 'value',
        event: 'change'
    },
    watch: {
        value: {
            immediate: true,
            handler(val, prevVal) {
                if (val !== prevVal && val !== this.oldVal) {
                    this.setValue(val);
                }
            }
        },
    },
    created() {
        this.is = components[this.type] || components['SingleImage'];
    },
    methods: {
        setValue(value){
            this.getRef("veUpload").then(function (veUpload) {
                veUpload.initValue(value);
            })
        },
        change(value) {
            this.oldVal = value;
            this.$emit('change', value);
        },
    }
}
</script>

<style scoped>

</style>
