<template>
  <div>
    <div class="shadow">
      <b-button
        class="btn1"
        v-b-popover.hover="'JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'"
        title="支援上傳類型 "
        @click="checkSave"
      >
        <b-icon-box-arrow-up />上傳檔案
      </b-button>
      <input
        ref="inputFiles"
        type="file"
        class="d-none"
        v-on:change="getInputFiles()"
      />
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      filesToBeUploaded: []
    }
  },
  async mounted () {
    await this.$store.dispatch('tenders/getOtherList', this.currentUser.defaultTender)
  },
  methods: {
    async checkSave () {
      this.$refs.inputFiles.click()
    },
    async getInputFiles () {
      if (window.FileReader && window.Blob) {
        let type = this.$refs.inputFiles.files[0].type
        if (
          type === 'image/png' ||
          type === 'application/pdf' ||
          type === 'image/jpeg' ||
          type === 'image/jpg' ||
          type ===
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
          type ===
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          type === 'application/msword'
        ) {
          this.filesToBeUploaded.push(this.$refs.inputFiles.files[0])
          await this.uploadFile(
            this.filesToBeUploaded[this.filesToBeUploaded.length - 1],
            this.filesToBeUploaded.length - 1
          )
        } else {
          alert(
            '不支援的檔案格式！僅支援上傳 JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'
          )
        }
      }
    },
    async uploadFile (file, index) {
      try {
        console.log(file)
        await this.$store.dispatch('tenders/addRelatedManagement', {
          id: this.currentUser.defaultTender, file: file
        })
        alert('上傳成功！')
        await this.$store.dispatch('tenders/getRelatedManagement', this.currentUser.defaultTender)
        this.$emit('getList')
      } catch (err) {
        alert('上傳失敗！')
      } finally {
        this.$set(this.filesToBeUploaded, index, file)
      }
    }
  },
  computed: {
    ...mapState({
      currentUser: (state) => state.user.current
    })
  }
}
</script>
<style scoped>
.shadow {
  background-color: #ffff;
  height: 65px;
  width: 100%;
  box-shadow: 2px 2px 20px rgba(0, 0, 0, 40);
  /* border-bottom-width:3px;
    border-bottom-color:#1D325F;
    border-bottom-style:solid */
  position: fixed;
  top: 55px;
  z-index: 500;
}
.btn1 {
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  margin-top: 15px;
  margin-left: 15px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
  border: none;
}
.btn1:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(49, 68, 175);
}
</style>
