<template>
  <div>
    <b-card no-body>
      <b-tabs card v-model="tabIndex">
          <b-card-text>
            <div
              id="dropbox"
              style="
                background-color: #e6e6e6;
                border-style: dashed;
                border-width: 2px;
                height: 200px;
                width: 100%;
              "
            >
              <center>
                <label
                  class="btn btn-primary"
                  style="
                    width: 137px;
                    height: 50px;
                    position: relative;
                    top: 50px;
                    margin-right: 20px;
                  "
                >
                  <input
                    @change="getInputfiles"
                    ref="inputFiles"
                    multiple
                    style="display: none"
                    type="file"
                  />
                  <span style="font-size: 18px; font-weight: bold"
                    >上傳檔案</span
                  >
                </label>
                <div class="mt-6">
                  支援多個文件點擊上傳，單個文件大小不能超過
                  <span class="text-orange">15 MB</span>
                </div>
                <div>上傳檔案為有加密時，將無法進行預覽</div>
              </center>
            </div>

            <div>
              <b-table
                sticky-header
                head-variant="light"
                borderless
                style="max-height: px; overflow: auto; margin-top: 20px"
                :items="projectFileList"
                :fields="[
                  '請勾選',
                  { key: 'icon', label: '檔案類型' },
                  { key: 'name', label: '資源名稱', sortable: true },
                  { key: 'uploadTime', label: '上傳時間', sortable: true },
                  { key: 'size', label: '檔案大小' },
                  { key: 'delete', label: '刪除' },
                ]"
                select-mode="multi"
                responsive="sm"
                ref="selectableTable"
                selectable
                @row-selected="onRowSelected"
              >
                <template v-slot:cell(icon)="data">
                  <img
                    class="ml-3 m-0"
                    style="width: 30px; height: auto; display: inline-block"
                    :src="data.item.icon"
                  />
                </template>
                <template v-slot:cell(uploadTime)="data">
                  <span>{{
                    new Date(data.item.uploadTime).toLocaleString("zh-TW", {
                      dateStyle: "long",
                      timeStyle: "short",
                      hour12: false,
                    })
                  }}</span>
                </template>
                <template v-slot:cell(size)="data">
                  <span v-if="data.value / 1024 / 1024 > 1"
                    >{{ (data.value / 1024 / 1024).toFixed(1) }}&nbsp;MB</span
                  >
                  <span v-else
                    >{{ (data.value / 1024).toFixed(1) }}&nbsp;KB</span
                  >
                </template>
                <template v-slot:cell(delete)="row">
                  <b-button
                    @click="deleteTableRow(row.item._id)"
                    size="sm"
                    variant="danger"
                    class="float-right"
                  >
                    <b-icon icon="trash-fill"></b-icon>
                  </b-button>
                </template>

                <template #cell(請勾選)="{ rowSelected }">
                  <template v-if="rowSelected">
                    <span aria-hidden="true">&check;</span>
                  </template>
                  <template v-else>
                    <span aria-hidden="true">&nbsp;</span>
                  </template>
                </template>
              </b-table>
            </div>
          </b-card-text>
      </b-tabs>

      <div class="preview mt-3">
        <span class="mb-1 pt-2 pb-2" style="font-weight: bold; font-size: 20px"
          >已上傳檔案:</span
        >
        <ul
          class="fileSectionListGroup mt-3"
          style="
            box-shadow: 0px 2.5px 10px #dcdcdc;
            padding-inline-start: 0px;
            max-height: 90px;
            overflow: auto;
          "
        >
          <li
            v-for="(file, index) in selectedFiles"
            :key="index"
            class="ListContent p-2 border-bottom"
            style="list-style-type: none; height: 45px"
          >
            <img
              class="mr-2"
              style="width: 25px; height: auto; display: inline-block"
              :src="file.icon"
            />
            {{ file.name }}
          </li>
        </ul>
      </div>

      <b-button
        v-if="$route.name === 'PaperPostCreate'"
        @click="addToUploadFile"
        class="mt-3 float-right"
        style="width: 100%; height: 40px; margin-top: 10px; font-size: 18px"
        size="sm"
        variant="outline-primary"
      >
        確認上傳
      </b-button>
      <b-button
        v-else
        @click="addToSendToEmailSelectModal"
        class="mt-3 float-right"
        style="width: 100%; height: 40px; margin-top: 10px; font-size: 18px"
        size="sm"
        variant="outline-primary"
      >
        確認上傳
      </b-button>
    </b-card>
  </div>
</template>

<script>
import fileType from '@/util/fileType.js'
import { mapState, mapActions } from 'vuex'

export default {
  data () {
    return {
      UploadFileModalOpen: false,
      tabIndex: 0,
      projectFileList: [],
      filesToBeUploaded: [],
      selectedFiles: [],
      uploadTime: ''
    }
  },
  async mounted () {
    this.projectFileList = await this.$store.dispatch(
      'project/lookupProjectFileList'
    )
  },
  methods: {
    ...mapActions('officialDocument', ['addRecord']),
    async deleteTableRow (id) {
      if (!confirm('確定刪除此文件嗎?')) return
      // 刪除寫這裡
      await this.$store.dispatch('project/deleteProjectFile', id)
      alert('已刪除')
      this.projectFileList = await this.$store.dispatch(
        'project/lookupProjectFileList'
      )
      this.deleteRelatedDocument = false
    },
    onRowSelected (items) {
      this.selectedFiles = items
    },
    async getInputfiles () {
      var today = new Date()
      this.upLoadDate =
        today.getFullYear() +
        '/' +
        (today.getMonth() + 1) +
        '/' +
        today.getDate() +
        ' ' +
        today.getHours() +
        ':' +
        today.getMinutes()
      if (window.FileReader && window.Blob) {
        for (var i = 0; i < this.$refs.inputFiles.files.length; i++) {
          var FileSize = this.$refs.inputFiles.files[i].size / 1024 / 1024 // in MB
          if (FileSize > 15) {
            alert('上傳檔案大小不得超過 15 MB！')
          }
          var type = this.$refs.inputFiles.files[i].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.$refs.inputFiles.files[i].icon = fileType(type[1])
            this.filesToBeUploaded.push(this.$refs.inputFiles.files[i])
            await this.uploadFile(
              this.filesToBeUploaded[this.filesToBeUploaded.length - 1],
              this.filesToBeUploaded.length - 1
            )
            this.projectFileList = await this.$store.dispatch(
              'project/lookupProjectFileList'
            )
          } else {
            alert(
              '不支援的檔案格式！僅支援上傳 JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'
            )
          }
        }
      }
      // this.tabIndex++
    },
    async uploadFile (file, index) {
      try {
        alert('上傳成功！')
        await this.$store.dispatch('file/addFile', { file: file })
        file.isSucceed = true
      } catch (error) {
        file.isSucceed = false
      } finally {
        this.$set(this.filesToBeUploaded, index, file)
      }
    },
    async addToSendToEmailSelectModal () {
      alert('上傳成功！')
      this.$emit('addToSendToEmailSelectModal', this.selectedFiles)
      this.$emit('succeedEvent')
    },
    async addToUploadFile () {
      let files = this.selectedFiles
      this.$store.dispatch('officialDocument/addFiles', { files: files })
      alert('上傳成功！')
      this.$emit('succeedEvent')
      await this.$store.dispatch('officialDocument/getFileList')
      await this.addRecord({
        staffName: this.currentUser.name,
        todo: '上傳附件成功'
      })
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.user.current
    })
  }
}
</script>

<style scoped>
.uploaderContainer {
  min-height: 400px;
  min-width: 700px;
}
</style>
