<template>
  <div>
  <div class="upload-image">
    <div
      class="
        upload-image__drag-area d-flex
        justify-content-center
        d-flex
        flex-column
        align-items-center"
      @dragover.prevent
      @drop.prevent="$_onDrop"
    >
    <div class="
      d-flex
      align-items-center
      justify-content-center
      flex-column
      max-middle-text"
    >
      <b-button class="btn-default btn-blue btn shadow-none border-0" @click="$_onClick">
        Escolher aquivo
      </b-button>
      <span class="min-middle-text mt-1">Tamanho máximo de upload de arquivo: 10MB</span>
    </div>
    </div>

    <div
      
      v-if="image "
      class="d-block w-100 mh-100 d-flex flex-wrap justify-content-center upload-image__preview"
      :class="preview_modifiers"
    >
        <img class="w-100" v-show="type != null && type == 'application/pdf'" src="@/assets/pdf-icon.png" alt="image-preview" />
        <img class="w-100" v-show="type != null && type != 'application/pdf'" :src="image" alt="image-preview" />
    </div>
  </div>
      <message-modal :title="title" :message="message"></message-modal>
  </div>
</template>

<script>
import NProgress from 'nprogress/nprogress';
import { readFile, compressImage } from '../../utils/image';
import MessageModal from '@/components/modals/MessageModal.vue';

const AVAILABLE_ENDPOINTS = ['/docs/upload-generic', '/docs'];

export default {
  name: 'upload-image',
  components:{
    MessageModal
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    autoUpload: {
      type: Boolean,
      default: false,
    },
    fileUploadProps: {
      type: Object,
      default: () => ({}),
    },
    fileUploadEndpoint: {
      type: String,
      default: '/docs/upload-generic',
      validator: value => AVAILABLE_ENDPOINTS.includes(value),
    },
    fileUploadName: {
      type: String,
      default: 'file',
    },
    value: {
      type: [String, Object],
    },
    attachment:{
      type: Object,
      default: () => ({
        attachment:{
          attachment_id: -1
        }
      }),
    },
    maxSize:{
      type: Number,
      default: 10
    }
  },
  computed: {
    preview_modifiers() {
      return {
        'upload-image__preview--loading': this.loading,
      };
    },
    is_doc() {
      return this.fileUploadEndpoint === '/docs';
    },
  },
  data: () => ({
    title: '',
    message: '',
    image: null,
    type: null,
    loading: false,
  }),
  mounted() {
    if (this.value.length > 0) {
      if(this.attachment.extension == 'pdf'){
        this.type = 'application/pdf';
        this.image = '@/assets/pdf-icon.png';
      }else{
        this.type = 'image';
        this.image = 'data:image/jpeg;base64,' + this.value;
      }
      
    }
  },
  methods: {
    async $_setImage(file) {
      if (this.autoUpload) {
        this.loading = true;
      }
      
      this.type = file.type;

      var size = file.size / 1000000;

      if(size > this.maxSize){
        this.title = 'Imagem grande';
        this.message = 'Este arquivo ultrapassa o tamanho máximo ('+ this.maxSize +' MB). Por favor, selecione outro';
        this.$bvModal.show('message-modal');
        return;
      }

      var data = {
        file: file,
        attachment_id: this.attachment.attachment_id,
        id: this.attachment.id
      };
      this.$emit('change', data);

      if(file.type == 'application/pdf'){
        this.image = '@/assets/pdf-icon.png';
        return;
      }

      try {
        const image = await compressImage(await readFile(file));
        this.type = 'image';
        this.image = image;

      } catch (e) {
        console.error(e);
        throw new Error(e);
      }
    },
    async $_upload(file, fileProps = {}) {  
      NProgress.inc();
      const formData = new FormData();
      formData.append(this.fileUploadName, file);

      Object.keys(fileProps).forEach((item) => {
        formData.append(item, fileProps[item]);
      });

      return fetch(`${process.env.YOUR_APY}${this.fileUploadEndpoint}`, {
        method: 'POST',
        body: formData,
      }).then((result) => {
        NProgress.done();
        return result.json();
      });
    },
    $_onDrop(event) {
      const { dataTransfer } = event;
      const { files } = dataTransfer;

      this.$_setImage(files[0]);
    },
    $_onClick() {
      const elFile = document.createElement('input');
      elFile.type = 'file';
      elFile.accept = 'image/*, application/pdf';
      elFile.click();

      elFile.onchange = () => {
        this.$_setImage(elFile.files[0]);
      };
    },
  },
};
</script>

<style scoped lang="scss">
.upload-image {
  width: 100%;
  position: relative;
  min-height: 150px;

  &__drag-area {
    // cursor: pointer;
    width: 100%;
    border: 2px gray dashed;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 10px;
    height: 100%;
    position: absolute;
  }

  &__preview {
    &--loading {
      opacity: 0.5;
      pointer-events: none;
    }
  }
}

.btn-default {
  border-radius: 20px;
  width: 100%;
  max-width: 192px;
  height: 35px;
  background: #278937;
}

.btn-blue {
  background: #FF9B64;
}

.cloud-icon {
  color: #FF9B64;
}

.min-middle-text {
  font-size: 9px;
  letter-spacing: 0.23px;
  color: #444;
}

.max-middle-text {
  letter-spacing: 0.35px;
}

</style>
