<template>
      <div>
            <!-- 審查新增文件頁面 -->
            <div
              v-show="$route.name === 'FileReviewCreate'"
              class="shadow"
            >
            <b-button
              @click="backToList()"
              class="btn1"
              v-show="$route.params.toName == 'Deliver'"
            >
            <b-icon-caret-up />返回
            </b-button>
            <b-button
              class="btn1"
              @click="docSave"
              :disabled='isCreate'
            >
              <b-icon-cursor /> 儲存
            </b-button>
            <b-button
              class="btn"
              @click="ImportCSVModalOpen = true"
            >
            <b-icon-box-arrow-in-down />文件匯入
            </b-button>
            </div>
            <!-- 提送新增文件頁面 -->
            <div
            v-show="$route.name === 'FileSubmitCreate'"
            class="shadow"
            >
            <b-button
              @click="backToList()"
              class="btn1"
              v-show="$route.params.toName == 'Deliver'"
            >
            <b-icon-caret-up />返回
            </b-button>
            <b-button
              class="btn1"
              @click="docSave"
              :disabled='isCreate'
            >
              <b-icon-cursor /> 儲存
            </b-button>
            <b-button
              class="btn"
              @click="ImportCSVModalOpen = true"
            >
            <b-icon-box-arrow-in-down />文件匯入
            </b-button>
            </div>
            <!-- 審查文件資料檢視 -->
            <div
            v-show="$route.name === 'FileReviewEdit'"
            class="shadow"
            >
            <b-button
              @click="backToReview()"
              class="btn1"
            >
            <b-icon-caret-up />返回列表
            </b-button>
              <b-button
                @click="deleteDoc()"
                class="btn2"
                :disabled="deleteFile.permission === 1"
              >
                <b-icon-trash />刪除
              </b-button>
            </div>
            <!-- 提送文件資料檢視 -->
            <div
            v-show="$route.name === 'FileSubmitEdit'"
            class="shadow"
            >
            <b-button
              @click="backToSubmit()"
              class="btn1"
            >
            <b-icon-caret-up />返回列表
            </b-button>
              <b-button
                @click="deleteDoc()"
                class="btn2"
                :disabled="deleteFile.permission === 1"
              >
              <b-icon-trash />刪除
              </b-button>
            </div>
            <!-- 審查文件上傳 -->
            <div
            v-show="$route.name === 'FileReviewUpload'"
            class="shadow"
            >
            <b-button
              @click="backToReviewEdit()"
              class="btn1"
            >
            <b-icon-caret-up />返回列表
            </b-button>
            <b-button
              class="btn1"
              @click="checkSave"
              v-b-popover.hover="'JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'" title="支援上傳類型 "
            >
            <b-icon-box-arrow-up />上傳檔案
            </b-button>
            <input
             ref="inputFiles"
             type="file"
             class="d-none"
             v-on:change="getInputFiles()"
             />
            </div>
            <!-- 提送文件上傳 -->
            <div
            v-show="$route.name === 'FileSubmitUpload'"
            class="shadow"
            >
            <b-button
              @click="backToSubmitEdit()"
              class="btn1"
            >
            <b-icon-caret-up />返回列表
            </b-button>
            <b-button
              class="btn1"
              @click="checkSave"
              v-b-popover.hover="'JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'" title="支援上傳類型 "
            >
            <b-icon-box-arrow-up />上傳檔案
            </b-button>
            <input
             ref="inputFiles"
             type="file"
             class="d-none"
             v-on:change="getInputFiles()"
             />
            </div>
            <!-- 新增提審頁面 -->
            <div
            v-show="$route.name === 'Deliver'"
            class="shadow">
              <b-button
                class="btn1"
                @click="backToDocument()"
              >
              <b-icon-caret-up />返回
              </b-button>
              <b-button variant="primary" class="btn1" @click="addReview()">
                <b-icon-clipboard-plus />新增審查文件
              </b-button>
              <b-button variant="primary" class="btn1" @click="addSubmit()">
                <b-icon-clipboard-plus />新增提送文件
              </b-button>
              <b-button
                variant="danger"
                class="btn2"
                @click="finishDeliver()"
                :disabled="finishedDeliver.permission === 1"
              >
                <b-icon-file-earmark-excel />結束提審
              </b-button>
            </div>
            <div
            v-show="$route.name === 'DeliverView'"
            class="shadow">
              <b-button
                class="btn1"
                @click="backToDocument()"
              >
              <b-icon-caret-up />返回
              </b-button>
            </div>
            <!-- 編輯頁面 -->
            <div
              v-show="$route.name === 'FileEdit'"
              class="shadow"
            >
            <b-button
              @click="backToControl()"
              class="btn1"
            >
            <b-icon-caret-up />返回
            </b-button>
            <b-button
              class="btn1"
              @click="docSave"
              :disabled='isCreate'
            >
              <b-icon-cursor /> 儲存
            </b-button>
            </div>
            <!-- 文件匯入 Modal -->
            <modal
              :is-open="ImportCSVModalOpen"
              title="文件匯入"
              @closeEvent="ImportCSVModalOpen = false"
            >
            <importCSV @closeEvent="ImportCSVModalOpen = false" />
            </modal>
      </div>
</template>

<script>
import fileType from '@/util/fileType.js'
import importCSV from '@/views/FileManagement/ModalContent/importCSV.vue'
import { mapState, mapActions, mapMutations } from 'vuex'

export default {
  // props: ['routerName'],
  components: {
    modal: () => import('@/views/Modal/index.vue'),
    importCSV
  },
  data () {
    return {
      isCreate: false,
      ImportCSVModalOpen: false,
      filesToBeUploaded: [],
      documentRecordList: [],
      deleteFile: {},
      finishedDeliver: {}
    }
  },
  async mounted () {
    await this.checkRecordList()
    this.usePermission()
  },
  methods: {
    ...mapActions('newDocument', ['post', 'patch', 'addFileRecord', 'lookupDoc', 'getList', 'getRecordList']),
    ...mapActions('officialDocument', ['addRecord', 'patch']),
    ...mapMutations('newDocument', ['resetNewDoc']),

    // 文件儲存按鈕
    async docSave () {
      let wasNull = false
      if (this.NewDoc.document_number === '' || this.NewDoc.document_name === '') wasNull = true
      if (wasNull) alert('文件編號或文件名稱未填寫！')
      else {
        let yes = (window.confirm('確定儲存？'))
        if (yes) {
          this.isCreate = true
          this.$emit('isSaved', this.isCreate)
          if (this.NewDoc._id === undefined) {
            await this.postDoc()
          }
        } else {
          alert('取消儲存')
        }
      }
    },
    async postDoc () {
      alert('新增成功')
      await this.post(this.NewDoc)
      this.$router.back()
      // await this.addRecord({ staffName: this.currentUser.name, todo: '新增' })
      // await this.$store.dispatch('officialDocument/getRecordList')
    },
    async deleteDoc (id) {
      if (!confirm('確定刪除此文件嗎？')) return
      await this.$store.dispatch('newDocument/deleteDoc', id)
      this.$router.back()
      alert('已刪除')
    },
    backToControl () {
      // if (this.routerName === 'Deliver') {
      //   this.$router.back()
      // } else {
      //   if (this.$route.params.toName) {
      //     this.$router.push({
      //       name: this.routerName,
      //       params: {
      //         toName: this.$route.params.toName
      //       }
      //     })
      //   } else {
      //     this.$router.push({
      //       name: this.routerName
      //     })
      //   }
      // }
      // this.$router.push(
      //   {
      //     name: 'FileReviewEdit',
      //     params: {
      //       toName: this.$route.params.toName
      //     }
      //   }
      // )
      if (this.NewDoc.document_distinguish === '審查文件') {
        this.$router.push(
          {
            name: 'FileReviewEdit',
            params: {
              toName: this.$route.params.toName
            }
          }
        )
      } else if (this.NewDoc.document_distinguish === '提送文件') {
        this.$router.push(
          {
            name: 'FileSubmitEdit',
            params: {
              toName: this.$route.params.toName
            }
          }
        )
      }
    },
    backToReview () {
      this.$router.push({name: 'FileReviewList'})
    },
    backToSubmit () {
      this.$router.push({ name: 'FileSubmitList' })
    },
    async backToReviewEdit () { // 相關檔案的返回列表(審查文件)
      await this.lookupDoc(this.$route.query.fid)
      this.$router.push({
        name: 'FileReviewEdit',
        query: { fid: this.$route.query.fid },
        params: {
          toName: this.$route.params.toName
        }
      })
    },
    async backToSubmitEdit () { // 相關檔案的返回列表(提送文件)
      await this.lookupDoc(this.$route.query.fid)
      this.$router.push({
        name: 'FileSubmitEdit',
        query: { fid: this.$route.query.fid },
        params: {
          toName: this.$route.params.toName
        }
      })
    },
    addReview () {
      this.resetNewDoc()
      this.$router.push({
        name: 'FileReviewCreate',
        params: {
          toName: 'Deliver'
        }
      })
    },
    addSubmit () {
      this.resetNewDoc()
      this.$router.push({
        name: 'FileSubmitCreate',
        params: {
          toName: 'Deliver'
        }
      })
    },
    backToDocument () {
      // this.$router.back()
      if (this.officialDoc.distinguish === '發文') {
        this.$router.push({
          name: 'PaperPostCreate',
          query: {odid: this.officialDoc.id}
        })
      } else {
        this.$router.push({
          name: 'PaperReceiveCreate',
          query: {odid: this.officialDoc.id}
        })
      }
    },
    backToList () {
      this.$router.back()
    },
    // 上傳檔案
    async checkSave () {
      this.$refs.inputFiles.click()
    },
    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
            )
          } else {
            alert(
              '不支援的檔案格式！僅支援上傳 JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'
            )
          }
        }
      }
    },
    async uploadFile (file, index) {
      let fid = this.$route.query.fid
      let fileId = this.$route.query.relatedFile
      try {
        await this.$store.dispatch('newDocument/addControlWorkFile', {
          file: file, docId: fid, fileId: fileId
        })
        alert('上傳成功！')
        await this.$store.dispatch('newDocument/getFileList', {
          DocId: fid, controlWorkId: fileId
        })
        await this.addFileRecord({
          fid: fid,
          fileId: fileId,
          recordData: {
            fileName: file.name,
            staffName: this.currentUser.name,
            todo: '上傳成功'
          }
        })
        file.isSucceed = true
      } catch (error) {
        file.isSucceed = false
      } finally {
        this.$set(this.filesToBeUploaded, index, file)
      }
    },
    async finishDeliver () {
      let wasNull = false
      if (this.documentRecordList.length === 0) wasNull = true
      if (wasNull) {
        alert('未新增提審紀錄!')
        this.officialDoc.newDocumentStatus = '未新增'
        await this.patch(this.officialDoc)
      } else {
        let yes = confirm('確定結案?')
        if (yes) {
          alert('結案成功')
          this.officialDoc.newDocumentStatus = '已結束'
          await this.patch(this.officialDoc)
          await this.addRecord({
            staffName: this.currentUser.name,
            todo: '結案提審'
          })
          if (this.officialDoc.distinguish === '發文') {
            this.$router.push({
              name: 'PaperPostCreate',
              query: {odid: this.officialDoc.id}
            })
          } else {
            this.$router.push({
              name: 'PaperReceiveCreate',
              query: {odid: this.officialDoc.id}
            })
          }
        } else {
          alert('取消結案')
        }
      }
    },
    async checkRecordList () {
      await this.getList()
      await this.getRecordList()
      const list = []
      this.controlWorkRecordList.forEach((item, i) => {
        list[i] = { ...item.controlWork }
      })
      const reloadList = []
      for (let i = 0; i < list.length; i++) {
        const a = list[i]
        for (let i = 0; i < Object.values(a).length; i++) {
          const b = Object.values(a)[i]
          if (b.officialDocId !== null) {
            reloadList.push(b)
          }
        }
      }
      this.documentRecordList = []
      reloadList.forEach((obj) => {
        if (obj.officialDocId.id === this.officialDoc.id) {
          this.documentRecordList.push(obj)
        }
      })
    },
    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.deleteFile = a
              if (a.name === '結束提審') this.finishedDeliver = a
            }
          }
        }
      })
    }
  },
  computed: {
    ...mapState({
      officialDoc: (state) => state.officialDocument.officialDoc,
      NewDoc: (state) => state.newDocument.NewDoc,
      currentUser: state => state.user.current,
      controlWorkFile: state => state.newDocument.controlWorkFile,
      allList: (state) => state.newDocument.allList,
      controlWorkRecordList: (state) => state.newDocument.recordList
    })
  }
}
</script>

<style lang="scss" 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;
}
.btn {
  background-color: white;
  font-size: 16px;
  margin-top: 15px;
  margin-left: 15px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #383838;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
  border: none;
  hover{
    color: black;
    background-color: rgb(228, 228, 228);
  }
}
.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;
  hover{
    color: rgb(255, 255, 255);
    background-color: rgb(49, 68, 175);
  }
}
.btn2 {
  background-color: rgb(255, 0, 0);
  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;
  hover{
    color: rgb(255, 255, 255);
    background-color: rgb(255, 0, 0);
  }
}
</style>
