<template>
  <v-card
    class="mx-auto"
    width="280px"
    height="320px"
    flat>
    <v-img
      :src="imgWithDefault"
      width="280px"
      height="300px">
      <v-fade-transition>
        <div
          class="d-flex flex-column w-100 h-100 justify-center align-center action-overlay">
          <svg-camera
            width="50"
            fill="#ffffff" />
          <div>
            <v-btn
              :for="`payment-upload`"
              class="snt-checkout__upload"
              tag="label"
              text
              dark>
              เลือกรูปภาพ
            </v-btn>
            <file-upload
              ref="paymentUpload"
              v-model="files"
              :name="`payment-upload`"
              :drop="!edit"
              extensions="gif,jpg,jpeg,png,webp"
              accept="image/png,image/gif,image/jpeg,image/webp"
              @input-filter="inputFileFilter"
              @input-file="inputFile" />
          </div>
        </div>
      </v-fade-transition>
    </v-img>
  </v-card>
</template>

<script>
import imgEmpty from '@/assets/img/img-empty.png'

export default {
  props: {
    value: {
      type: Object,
      default: undefined
    }
  },
  data () {
    return {
      imageLocalUrl: null,
      files: [],
      edit: false
    }
  },
  computed: {
    imgWithDefault () {
      return this.imageLocalUrl || imgEmpty
    }
  },
  methods: {
    inputFile (newFile, oldFile) {
      if (newFile && !oldFile) {
        this.$nextTick(() => {
          const fileObj = this.files[0]
          this.imageLocalUrl = fileObj.url
          this.$emit('input', fileObj.file)
        })
      }
    },
    inputFileFilter (newFile, oldFile, prevent) {
      this.error = null
      if (newFile && !oldFile) {
        if (!/\.(gif|jpg|jpeg|png|webp)$/i.test(newFile.name)) {
          this.error = '* Your choice is not a picture'
          return prevent()
        }
      }
      if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
        // eslint-disable-next-line no-param-reassign
        newFile.url = ''
        const URL = window.URL || window.webkitURL
        if (URL && URL.createObjectURL) {
          // eslint-disable-next-line no-param-reassign
          newFile.url = URL.createObjectURL(newFile.file)
        }
      }
      return null
    }
  }
}
</script>

<style scoped>
  .snt-checkout__upload {
    cursor: pointer;
    margin: 4px;
  }
</style>
