<template>
    <div>
        <vue-dropzone ref="myVueDropzone" id="dropzone" :destroyDropzone="false" @vdropzone-sending="setParams" @vdropzone-removed-file="removeFile" :options="dropzoneOptions" @vdropzone-success="responseSuccess"></vue-dropzone>
    </div>
</template>

<script>
import vue2Dropzone from 'vue2-dropzone'
import { TokenService } from '@Global/services/storage.services'
import commonState from '@Global/store/modules/common/state';
import { url } from '@Common/mixins/urls';
import axios from 'axios';
import 'vue2-dropzone/dist/vue2Dropzone.min.css'
export default {
	props: {
        defaultMessage: { default: "<i class='fa fa-cloud-upload'></i>آپلود فایل" },
        value: { default: "" },
        id:  { default: null },
        loadeFiles: {default:() => ([])},
        batch_id: { required: true, type: String }
	},
	components: {
    	vueDropzone: vue2Dropzone
  	},
	data() {
        return {
            dropzoneOptions: {
                url: url('storeFile'),
                thumbnailWidth: 200,
                headers: { "Authorization":  `Bearer ${TokenService.getToken()}`, "Module": `${commonState.current_module}` },
                addRemoveLinks: true,
                dictDefaultMessage: this.defaultMessage,
                sendingMultiple: true,
            },
        }
    },
    computed: {
        batchId() {
            return this.batch_id;
        },
    },
    methods: {
        responseSuccess(file, response) {
            if (response.data && response.data.id) {
                file['id'] = response.data.id;
            }
        },
        removeFile(file, error, xhr) {
            if(this.dropzoneOptions.removeType == "server") {
                axios.delete(url('deleteFile', {file: file.id}));
            }
        },
        manuallyLoadFiles(files) { //file =[ {size: 123, name: "Icon", type: "image/png", url: "https://myvizo.com/img/logo_sm.png"}]
            for (const file of files) {
                this.$refs.myVueDropzone.manuallyAddFile(file, file.url);
            }
        },
        setParams(file, xhr, formData) {
            formData.append('batch_id', this.batchId);
        },
    },
    watch: {
        loadFiles(files) {
            this.manuallyLoadFiles(files);
        }
    },
};
</script>
