<template>
	<div class="form-group" :class="{'has-error': form.errors.has(input_name)}">
        <label v-if="label" for="name">{{ label }}</label>
		<div class="upload-box">
	        <div class="file-container mb-1">
	        	<i class="fa fa-download"></i>
	            <input type='file'
	        		:name="input_name" 
		            @change="onChange"
		        />
	        </div>
			<div v-if="preview" v-for="(img, $index) in preview" :key="$index">
				<a v-if="mime_type == 'application/pdf'" class="btn btn-xs btn-light"  :href="img" target="_blank">
                  <i class="fa fa-file-pdf"></i>
              	</a>
              	<div v-if="mime_type != 'application/pdf'">
        			<img class="img-fluid" alt='' :src="img"/>
        		</div>
        	</div>
	    </div>
        <div class="text-danger text-left" v-if="form.errors.has(input_name)" v-text="form.errors.get(input_name)"></div>
        <cropper-modal
	    	:img="img"
	    	@clicked="getCropImage"
	    >
		</cropper-modal>
	</div>
</template>

<script>
  	import CropperModal from "../modals/CropperModal";

	export default {
		props: {
			input_name: String,
			form: Object,
			placeholder: String,
			label: String,
			exist_img: Array,
		},
		components: {
			CropperModal
		},
		data() {
			return {
				preview: [],
				img: [],
				mime_type: '',
			}
		},
		methods: {
			onChange(e) {
				let vm = this;
				let files = e.target.files;
				vm.mime_type = files[0].type;

				General.imageBase64(e.target.files).then(data => {
					vm.img = data[0];
					vm.cropperModalToggle();
				});
			},
			cropperModalToggle() {
		        let vm = this;
		        vm.$bvModal.show('cropper-modal');
      		},
      		getCropImage(img) {
      			let vm = this;
      			vm.form[vm.input_name] = [img];
				vm.preview = [img];
      		},
			loadExistingImg() {
				let vm = this;
				if (vm.exist_img[0]) {
					vm.mime_type = vm.exist_img[0].mime_type;
					Array.from(vm.exist_img).forEach(file => { 
						vm.preview.push(file.file_info.original.file);
					});
				}
			}
		},
		watch: {
			'exist_img': 'loadExistingImg',
		},
		created() {
			let vm = this;
			vm.loadExistingImg();
		}
	}
</script>