<template>
  <div>
    <div style="font-size: 17px; font-weight: 800; color: #5e72e4">
      <div style="float: left; padding-top: 10px">
        <a
          v-show="
            $route.name === 'PaperPostCreate' ||
            $route.name === 'ArchivesPostView'
          "
          @click="isCollapsed = !isCollapsed"
          style="user-select: none"
        >
          用印掃描檔
          <span v-if="isCollapsed">▲</span>
          <span v-else>▼</span>
        </a>
        <a
          v-show="
            $route.name === 'PaperReceiveCreate' ||
            $route.name === 'ArchivesReceiveView'
          "
          @click="isCollapsed = !isCollapsed"
          style="user-select: none"
        >
          掃描檔
          <span v-if="isCollapsed">▲</span>
          <span v-else>▼</span>
        </a>
      </div>
      <div
        style="float: right"
        v-show="$route.name === 'PaperPostCreate' && officialDocument.permission === 2"
      >
        <!-- <b-button
          v-show="deleteRelatedScanDocument === false"
          @click="deleteRelatedScanDocument = true"
          variant="danger"
          class="m-1 p-1 float-right"
          >刪除</b-button
        >
        <b-button
          v-show="deleteRelatedScanDocument === true"
          @click="deleteRelatedScanDocument = false"
          variant="danger"
          class="m-1 p-1 float-right"
          >返回</b-button
        > -->
        <b-button
          @click="checkSave"
          variant="primary"
          class="m-1 p-1 float-right"
          >上傳用印掃描檔</b-button
        >
        <input
          ref="inputFile"
          type="file"
          class="d-none"
          v-on:change="handleFileUpload()"
        />
      </div>
      <div
        style="float: right"
        v-show="$route.name === 'PaperReceiveCreate' && officialDocument.permission === 2"
      >
        <!-- <b-button
          v-show="deleteRelatedScanDocument === false"
          @click="deleteRelatedScanDocument = true"
          variant="danger"
          class="m-1 p-1 float-right"
          >刪除</b-button
        >
        <b-button
          v-show="deleteRelatedScanDocument === true"
          @click="deleteRelatedScanDocument = false"
          variant="danger"
          class="m-1 p-1 float-right"
          >返回</b-button
        > -->
        <b-button
          @click="checkSave"
          variant="primary"
          class="m-1 p-1 float-right"
          >上傳掃描檔</b-button
        >
        <input
          ref="inputFile"
          type="file"
          class="d-none"
          v-on:change="handleFileUpload()"
        />
      </div>
    </div>
    <div style="height: 100px; width: 100%; overflow: auto">
      <hr style="border-top: 1px solid gray; margin-top: 0; margin-bottom: 0" />
      <b-collapse
        style="padding-top: 10px"
        :visible="!isCollapsed"
        id="collapse-2"
      >
        <ul
          class="list-group list-group-flush"
          style="list-style-type: none; font-weight: 600; font-size: 14px"
        >
          <div v-for="(file, index) in scanFile" :key="index">
            <b-button
              :disabled="officialDocument.permission === 1"
              @click="deleteScanDocument(file._id)"
              size="sm"
              variant="danger"
              class="float-right"
            >
              <b-icon icon="trash-fill"></b-icon>
            </b-button>
            <b-row style="margin-right: 15px">
              <b-col cols="8">
                <a
                  class="mb-2"
                  style="
                    display: block;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  :href="file.src"
                  target="_blank"
                >
                  • {{ file.name }}
                </a>
              </b-col>
              <b-col cols="3">
                <b-badge variant="info" style="padding-bottom: 5px">{{
                  new Date(file.uploadTime).toLocaleString("zh-TW", {
                    dateStyle: "long",
                    timeStyle: "short",
                    hour12: false,
                  })
                }}</b-badge>
              </b-col>
            </b-row>
          </div>
        </ul>
      </b-collapse>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  //   name: 'task-related-document',
  data () {
    return {
      // deleteRelatedScanDocument: false,
      isCollapsed: false,
      filesToBeUploaded: [],
      isFix: true,
      officialDocument: {}
    }
  },
  mounted () {
    this.usePermission()
  },
  methods: {
    ...mapActions('officialDocument', ['addRecord']),
    async deleteScanDocument (id) {
      if (!confirm('確定刪除此文件嗎?')) return
      // 刪除寫這裡
      await this.$store.dispatch(
        'officialDocument/deleteOfficialDocScanFile',
        id
      )
      alert('已刪除')
      // this.deleteRelatedScanDocument = false
      await this.$store.dispatch('officialDocument/getScanFile')
      await this.addRecord({
        staffName: this.currentUser.name,
        todo: '刪除掃描檔'
      })
    },
    async checkSave () {
      if (this.officialDoc._id === undefined) {
        alert('請先儲存')
      } else {
        this.$refs.inputFile.click()
      }
    },
    async handleFileUpload () {
      if (window.FileReader && window.Blob) {
        // let fileSize = this.$refs.inputFile.files[0].size / 1024 / 1024 // in MB
        // if (fileSize > 15) {
        //   alert('上傳檔案大小不得超過 15 MB！')
        // }
        let type = this.$refs.inputFile.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.inputFile.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 {
        await this.$store.dispatch('officialDocument/addScanFile', {
          file: file
        })
        alert('上傳成功！')
        await this.$store.dispatch('officialDocument/getScanFile')
        await this.addRecord({
          staffName: this.currentUser.name,
          todo: '上傳掃描檔成功'
        })
      } catch (err) {
        alert('上傳失敗！')
      } finally {
        this.$set(this.filesToBeUploaded, index, file)
      }
    },
    usePermission () { // 確認權限
      Object.values(this.currentUser.tenderPermissions).forEach(obj => {
        if (obj.tenderId === this.currentUser.defaultTender) {
          let permission = obj.permission
            .filter(name => name.title === '公文管理')
            .map(val => { return val.functionItem })
          for (const element of permission) {
            for (const a of element) {
              if (a.name === '收發文') this.officialDocument = a
            }
          }
        }
      })
    }
    // isSaved () {
    //   this.isFix = true
    // },
    // isEdited () {
    //   this.isFix = false
    // }
  },
  computed: {
    ...mapState({
      officialDoc: state => state.officialDocument.officialDoc,
      scanFile: state => state.officialDocument.scanFile,
      currentUser: state => state.user.current
    })
  }
}
</script>
