<template>
  <div>
    <!-- 新增發文登記functionBar -->
    <div class="shadow" v-show="$route.name === 'PaperPostCreate'">
      <b-button class="btn1" @click="issueSave" :disabled="isCreate">
        <b-icon-cursor></b-icon-cursor> 儲存
      </b-button>
      <b-button
        class="btn1"
        @click="issueEdit"
        :disabled="isSave || receivePostDocument.permission === 1"
      >
        <b-icon-pencil></b-icon-pencil> 編輯
      </b-button>
      <b-button
        class="btn"
        @click="(SendToEmailSelectModalOpen = true), deleteLocalStorage()"
        :disabled="isSave"
      >
        <b-icon-envelope-open></b-icon-envelope-open> Email傳送
      </b-button>
      <b-button
        class="btn"
        @click="PrintOutFileModalOpen = true"
        :disabled="isSave"
      >
        <b-icon-printer></b-icon-printer> 書函輸出
      </b-button>

      <!-- <b-button
        class="btn"
        @click="ParameterSettingModalOpen = true"
        :disabled="isCreate"
        v-show="
          checkPermission('officialDocumentManagement', 'paramSetting') == 1
        "
      > -->
      <b-button
        v-show="currentUser.projectTitle != '一般成員'"
        class="btn"
        @click="ParameterSettingModalOpen = true"
        :disabled="isCreate || paramSetting.permission === 1"
      >
        <b-icon-tools></b-icon-tools> 參數設置
      </b-button>
      <!-- <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave"
        v-show="
          checkPermission('officialDocumentManagement', 'arraignmentAdd') == 1
        "
      > -->
      <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave || fileManagement.permission === 1"
        v-show="officialDoc.newDocumentStatus === '未新增'"
      >
        <b-icon-caret-up-square></b-icon-caret-up-square> 新增提審
      </b-button>
      <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave || fileManagement.permission === 1"
        v-show="officialDoc.newDocumentStatus === '進行中'"
      >
        <b-icon-file-earmark-play></b-icon-file-earmark-play> 提審中
      </b-button>
      <b-button
        class="btn"
        @click="goToDeliverView()"
        :disabled="isSave"
        v-show="officialDoc.newDocumentStatus === '已結束'"
      >
        <b-icon-file-earmark-check></b-icon-file-earmark-check> 查閱提審
      </b-button>
      <!-- <b-button
        class="btn_delete"
        @click="postCaseClosed()"
        :disabled="isSave"
        v-show="checkPermission('officialDocumentManagement', 'caseEnd') == 1"
      >
        <b-icon icon="file-earmark-excel"></b-icon> 結案
      </b-button> -->
      <b-button
        v-if="this.officialDoc.conferenceId === null"
        @click="AddConference()"
        class="btn"
        :disabled="isSave || conferenceManagement.permission === 1"
      >
        <b-icon-file-earmark-plus /> 建立會議
      </b-button>
      <b-button
        v-else-if="this.officialDoc.conferenceId === undefined"
        @click="AddConference()"
        class="btn"
        :disabled="isSave || conferenceManagement.permission === 1"
      >
        <b-icon-file-earmark-plus /> 建立會議
      </b-button>
      <b-button
        v-else-if="this.officialDoc.conferenceId !== null"
        @click="PushToConference()"
        class="btn"
        :disabled="isSave"
      >
        <span
          :href="
            '/?#/workCollaboration/conferenceManagement/conferenceOverview/Detail' +
            '?fid=' +
            this.officialDoc.conferenceId
          "
        >
          <b-icon-file-earmark-plus /> 查閱會議
        </span>
      </b-button>
      <b-button
        class="btn_delete"
        @click="postCaseClosed()"
        :disabled="isSave || caseEnd.permission === 1"
      >
        <b-icon icon="file-earmark-excel"></b-icon> 結案
      </b-button>
      <b-button
        v-show="$route.query.odid !== undefined"
        class="btn_todo"
        @click="officialTodo"
      >
        <b-icon icon="bookmark-plus" aria-hidden="true" />&nbsp;待辦事項
      </b-button>
    </div>

    <!-- 新增收文登記functionBar -->
    <div class="shadow" v-show="$route.name === 'PaperReceiveCreate'">
      <b-button class="btn" @click="ImportCSVModalOpen = true">
        <b-icon-box-arrow-in-down></b-icon-box-arrow-in-down> 文字匯入
      </b-button>
      <b-button class="btn1" @click="receiveSave" :disabled="isCreate">
        <b-icon-cursor></b-icon-cursor> 儲存
      </b-button>
      <b-button
        class="btn1"
        @click="receiveEdit"
        :disabled="isSave || receivePostDocument.permission === 1"
      >
        <b-icon-cursor></b-icon-cursor> 編輯
      </b-button>
      <b-button
        class="btn"
        @click="(SendToEmailSelectModalOpen = true), deleteLocalStorage()"
        :disabled="isSave"
      >
        <b-icon-envelope-open></b-icon-envelope-open> Email傳送
      </b-button>

      <!-- <b-button
        class="btn"
        @click="ParameterSettingModalOpen = true"
        :disabled="isCreate"
        v-show="
          checkPermission('officialDocumentManagement', 'paramSetting') == 1
        "
      > -->
      <b-button
        v-show="currentUser.projectTitle != '一般成員'"
        class="btn"
        @click="ParameterSettingModalOpen = true"
        :disabled="isCreate || paramSetting.permission === 1"
      >
        <b-icon-tools></b-icon-tools> 參數設置
      </b-button>
      <!-- <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave"
        v-show="
          checkPermission('officialDocumentManagement', 'arraignmentAdd') == 1
        "
      > -->
      <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave || fileManagement.permission === 1"
        v-show="officialDoc.newDocumentStatus === '未新增'"
      >
        <b-icon-caret-up-square></b-icon-caret-up-square> 新增提審
      </b-button>
      <b-button
        class="btn"
        @click="goToDeliver()"
        :disabled="isSave || fileManagement.permission === 1"
        v-show="officialDoc.newDocumentStatus === '進行中'"
      >
        <b-icon-file-earmark-play></b-icon-file-earmark-play> 提審中
      </b-button>
      <b-button
        class="btn"
        @click="goToDeliverView()"
        :disabled="isSave"
        v-show="officialDoc.newDocumentStatus === '已結束'"
      >
        <b-icon-file-earmark-check></b-icon-file-earmark-check> 查閱提審
      </b-button>
      <b-button
        v-if="this.officialDoc.conferenceId === null"
        @click="AddConference()"
        class="btn"
        :disabled="isSave || conferenceManagement.permission === 1"
      >
        <b-icon-file-earmark-plus />建立會議
      </b-button>
      <b-button
        v-else-if="this.officialDoc.conferenceId === undefined"
        @click="AddConference()"
        class="btn"
        :disabled="isSave || conferenceManagement.permission === 1"
      >
        <b-icon-file-earmark-plus />建立會議
      </b-button>
      <b-button
        v-else-if="this.officialDoc.conferenceId !== null"
        @click="PushToConference()"
        class="btn"
        :disabled="isSave"
      >
        <span
          :href="
            '/?#/workCollaboration/conferenceManagement/conferenceOverview/Detail' +
            '?fid=' +
            this.officialDoc.conferenceId
          "
        >
          <b-icon-file-earmark-plus />查閱會議
        </span>
      </b-button>
      <!-- <b-button
        class="btn_delete"
        @click="receiveCaseClosed()"
        :disabled="isSave"
        v-show="checkPermission('officialDocumentManagement', 'caseEnd') == 1"
      >
        <b-icon icon="file-earmark-excel"></b-icon> 結案
      </b-button> -->
      <b-button
        class="btn_delete"
        @click="receiveCaseClosed()"
        :disabled="isSave || caseEnd.permission === 1"
      >
        <b-icon icon="file-earmark-excel"></b-icon> 結案
      </b-button>
      <b-button
        v-show="$route.query.odid !== undefined"
        class="btn_todo"
        @click="officialTodo"
      >
        <b-icon icon="bookmark-plus" aria-hidden="true" />&nbsp;待辦事項
      </b-button>
    </div>

    <!-- 發文登記檢視functionBar -->
    <div class="shadow" v-show="$route.name === 'PaperPostRegister'"></div>

    <!-- 收文登記檢視functionBar -->
    <div class="shadow" v-show="$route.name === 'PaperReceiveRegister'"></div>

    <!-- 發文完成檢視functionBar -->
    <div class="shadow" v-show="$route.name === 'ArchivesPostView'"></div>

    <!-- 收文完成檢視functionBar -->
    <div class="shadow" v-show="$route.name === 'ArchivesReceiveView'"></div>

    <!-- Email傳送 Modal -->
    <modal
      :isOpen="SendToEmailSelectModalOpen"
      title="Email傳送"
      v-on:closeEvent="SendToEmailSelectModalOpen = false"
    >
      <sendToEmailSelect
        @uploadFileReceive="uploadFileReceive"
        :selectedFiles.sync="selectedFiles"
        @closeEvent="SendToEmailSelectModalOpen = false"
      />
    </modal>
    <!-- 上傳附件 Modal -->
    <modal
      :isOpen="UploadFileModalOpen"
      title="上傳附件"
      v-on:closeEvent="UploadFileModalOpen = false"
    >
      <uploadFile
        @addToSendToEmailSelectModal="addToSendToEmailSelectModal"
        @closeEvent="UploadFileModalOpen = false"
      />
    </modal>
    <!-- 參數設置 Modal -->
    <modal
      :isOpen="ParameterSettingModalOpen"
      title="參數設置"
      v-on:closeEvent="ParameterSettingModalOpen = false"
    >
      <parameterSetting @closeEvent="ParameterSettingModalOpen = false" />
    </modal>
    <!-- 新增提審 Modal -->
    <modal
      :isOpen="AddArraignmentModalOpen"
      title="新增提審"
      v-on:closeEvent="AddArraignmentModalOpen = false"
    >
      <addArraignment @closeEvent="AddArraignmentModalOpen = false" />
    </modal>
    <!-- 書函輸出 Modal -->
    <modal
      :isOpen="PrintOutFileModalOpen"
      title="書函輸出"
      v-on:closeEvent="PrintOutFileModalOpen = false"
    >
      <printOutFile @closeEvent="PrintOutFileModalOpen = false" />
    </modal>
    <!-- 文字匯入 Modal -->
    <modal
      :isOpen="ImportCSVModalOpen"
      title="文字匯入"
      v-on:closeEvent="ImportCSVModalOpen = false"
    >
      <importCSV @closeEvent="ImportCSVModalOpen = false" />
    </modal>
    <!-- 建立會議 Modal -->
    <modal
      :is-open="AddConferenceModalOpen"
      title="建立會議"
      @closeEvent="AddConferenceModalOpen = false"
    >
      <addConference @closeEvent="AddConferenceModalOpen = false" />
    </modal>
    <modal
      :is-open="AddTodoListModalOpen"
      title="新增個人待辦事項"
      @closeEvent="AddTodoListModalOpen = false"
    >
      <addTodoList @closeEvent="AddTodoListModalOpen = false" />
    </modal>
  </div>
</template>

<script>
import printPDF from '@/mixins/printPDF.js'
import sendToEmailSelect from '@/views/DocumentManagement/ModalContent/sendToEmailSelect.vue'
import uploadFile from '@/views/DocumentManagement/ModalContent/uploadFile.vue'
import parameterSetting from '@/views/DocumentManagement/ModalContent/parameterSetting.vue'
import addArraignment from '@/views/DocumentManagement/ModalContent/addArraignment.vue'
import printOutFile from '@/views/DocumentManagement/ModalContent/printOutFile.vue'
import addTodoList from '@/views/HomePage/ModalContent/addTodoList.vue'
import importCSV from '@/views/DocumentManagement/ModalContent/importCSV.vue'
import addConference from '@/views/ConferenceManagement/ModalContent/addConference.vue'
import { mapState, mapActions, mapGetters } from 'vuex'

export default {
  mixins: [printPDF.print],
  data () {
    return {
      isSave: false,
      isCreate: true,
      AddTodoListModalOpen: false,
      AddConferenceModalOpen: false,
      SendToEmailSelectModalOpen: false,
      ParameterSettingModalOpen: false,
      AddArraignmentModalOpen: false,
      PrintOutFileModalOpen: false,
      ImportCSVModalOpen: false,
      UploadFileModalOpen: false,
      isCollapsed: false,
      isClose: false,
      selectedFiles: [],
      // 權限
      receivePostDocument: {},
      caseEnd: {},
      paramSetting: {},
      conferenceManagement: {},
      fileManagement: {}
    }
  },
  components: {
    modal: () => import('@/views/Modal/index.vue'),
    addConference,
    sendToEmailSelect,
    uploadFile,
    addTodoList,
    parameterSetting,
    addArraignment,
    printOutFile,
    importCSV
  },
  async created () {
    if (this.$route.query.odid !== undefined) {
      await this.$store.dispatch(
        'officialDocument/getOfficialDocument',
        this.$route.query.odid
      )
    }
  },
  mounted () {
    this.$emit('UploadFileModalOpen')
    this.$emit('SendToEmailSelectModalOpen')
    this.usePermission()
  },
  methods: {
    ...mapActions('officialDocument', [
      'post',
      'patch',
      'getList',
      'download',
      'addRecord',
      'getAmount',
      'getOfficialDocument',
      'lookupRecords'
    ]),
    ...mapActions('conference', ['initConference']),
    async AddConference () { // 新增會議
      await this.initConference()
      this.isTest = true
      this.AddConferenceModalOpen = true
    },
    async PushToConference () {
      let routeData
      routeData = this.$router.resolve({
        name: 'ConferenceDetail',
        query: { fid: this.officialDoc.conferenceId }
      })
      window.open(routeData.href)
    },
    async postCaseClosed () { // 發文結案按鈕
      var wasNull = false
      if (this.scanFile.length === 0) wasNull = true
      if (wasNull) alert('掃描檔未上傳!')
      else {
        var yes = confirm('確定結案?')
        if (yes) {
          alert('結案成功')
          this.officialDoc.status = '已完成'
          await this.patch(this.officialDoc)
          await this.addRecord({
            staffName: this.currentUser.name,
            todo: '結案'
          })
          this.$router.push({ name: 'PaperPostList' })
        } else {
          alert('取消結案')
        }
      }
    },
    async receiveCaseClosed () { // 收文結案按鈕
      var wasNull = false
      if (this.scanFile.length === 0) wasNull = true
      if (wasNull) alert('掃描檔未上傳!')
      else {
        var yes = confirm('確定結案?')
        if (yes) {
          alert('結案成功')
          this.officialDoc.status = '已完成'
          await this.patch(this.officialDoc)
          await this.addRecord({
            staffName: this.currentUser.name,
            todo: '結案'
          })
          this.$router.push({ name: 'PaperReceiveList' })
        } else {
          alert('取消結案')
        }
      }
    },
    async issueSave () {
      // 發文儲存按鈕
      var wasNull = false
      if (
        this.officialDoc.subject === '' ||
        this.officialDoc.original.length === 0
      ) {
        wasNull = true
      }
      if (wasNull) alert('主旨或正本未填!')
      else {
        await this.getList({ distinguish: '發文' })
        const newNumberList = Array.from(this.officialDocList).map((event) => {
          return event.issue_text_number
        })
        if (newNumberList.includes(this.officialDoc.issue_text_number) && this.officialDoc._id === undefined) {
          alert('「發文字號」與發文作業字號相同，請確認後修正！')
        } else {
          var yes = confirm('請再次確認「發文字號」是否正確，在進行儲存')
          if (yes) {
            this.isSave = false
            this.isCreate = true
            this.$emit('isSaved')
            this.$emit('isBySave', this.isSave)
            if (this.officialDoc._id === undefined) {
              this.postOfficialDoc()
            } else {
              this.addUpdateOfficialDocRecord()
            }
          } else {
            alert('取消儲存')
          }
        }
      }
    },
    async postOfficialDoc () {
      // 檢查編號有無被佔用
      console.log(1)
      let nowNumber = await this.getAmount(this.officialDoc.distinguish)
      console.log(2)
      if (this.officialDoc.number <= nowNumber) {
        this.officialDoc.number = nowNumber + 1
        this.issueTextNumberCheck(nowNumber)
        alert('編號已被占用，將自動更改')
      } else if (this.officialDoc.number === nowNumber + 1) {
        if (
          Number(this.officialDoc.issue_text_number.substr(-6)) !==
          nowNumber + 1
        ) {
          this.officialDoc.issue_text_number =
            this.officialDoc.issue_text_number.concat(
              String(nowNumber + 1).padStart(6, '0')
            )
        }
      }
      console.log(3)
      await this.post()
      console.log(4)
      await this.getOfficialDocument(this.officialDoc._id)
      console.log(5)
      this.addRecord({ staffName: this.currentUser.name, todo: '新增' })
      alert('新增成功')
    },
    issueTextNumberCheck (nowNumber) {
      // 檢查編號有無被佔用
      // 待問 多寫的(已記錄 發文字號問題)
      if (Number(this.officialDoc.issue_text_number.substr(-6)) === nowNumber) {
        this.officialDoc.issue_text_number =
          this.officialDoc.issue_text_number.replace(
            this.officialDoc.issue_text_number.substr(-6),
            String(nowNumber + 1).padStart(6, '0')
          )
      } else {
        this.officialDoc.issue_text_number =
          this.officialDoc.issue_text_number.concat(
            String(nowNumber + 1).padStart(6, '0')
          )
      }
    },
    async issueEdit () { // 發文編輯按鈕
      console.log(this.officialDoc)
      this.isSave = true
      this.isCreate = false
      this.$emit('isEdited')
      this.$emit('isBySave', this.isSave)
    },
    async receiveSave () {
      // 收文儲存按鈕
      var wasNull = false
      if (
        this.officialDoc.subject === '' ||
        this.officialDoc.issue_date === '' ||
        this.officialDoc.issue_text_number === ''
      ) {
        wasNull = true
      }
      if (wasNull) alert('來文字號/來文日期/主旨未填!')
      else {
        // 比對是否與所有發文的發文字號有相同
        await this.getList()
        const newNumberList = Array.from(this.officialDocList).map((event) => {
          return event.issue_text_number
        })
        if (newNumberList.includes(this.officialDoc.issue_text_number) && this.officialDoc._id === undefined) {
          alert('「來文字號」與收發文作業字號相同，請確認後修正！')
        } else {
          var yes = confirm('請再次確認「來文字號」是否正確，在進行儲存')
          if (yes) {
            this.isSave = false
            this.isCreate = true
            this.$emit('isSaved')
            this.$emit('isBySave', this.isSave)
            if (this.officialDoc._id === undefined) {
              this.postReceiveOfficialDoc()
            } else {
              this.addUpdateOfficialDocRecord()
            }
          } else {
            alert('取消儲存')
          }
        }
      }
    },
    async postReceiveOfficialDoc () {
      // 檢查編號有無被佔用
      if (
        this.officialDoc.number <=
        (await this.getAmount(this.officialDoc.distinguish))
      ) {
        this.officialDoc.number =
          (await this.getAmount(this.officialDoc.distinguish)) + 1
        alert('編號已被占用，將自動更改')
      }

      await this.post()
      this.addRecord({ staffName: this.currentUser.name, todo: '新增' })
      alert('新增成功')
    },
    async addUpdateOfficialDocRecord () {
      // 公文新增修改記錄
      await this.patch()
      await this.addRecord({ staffName: this.currentUser.name, todo: '修改' })
    },
    async receiveEdit () { // 收文編輯按鈕
      this.isSave = true
      this.isCreate = false
      this.$emit('isEdited')
      this.$emit('isBySave', this.isSave)
    },
    addToSendToEmailSelectModal (selectedFiles) { // 收文-傳送至email->上傳附件-確認上傳按鈕
      this.UploadFileModalOpen = false
      this.SendToEmailSelectModalOpen = true
      this.selectedFiles = selectedFiles
    },
    uploadFileReceive () {
      this.UploadFileModalOpen = true
      this.SendToEmailSelectModalOpen = false
    },
    pageBack () {
      window.history.back()
    },
    async goToDeliver () {
      this.$router.push({
        name: 'Deliver',
        query: { odid: this.officialDoc.id }
      })
    },
    async goToDeliverView () {
      this.$router.push({
        name: 'DeliverView',
        query: { odid: this.officialDoc.id }
      })
    },
    deleteLocalStorage () {
      // localStorage.getItem('internalMembers') && localStorage.removeItem('internalMembers')
      // localStorage.getItem('externalMembers') && localStorage.removeItem('externalMembers')
      // localStorage.getItem('files') && localStorage.removeItem('files')
    },
    officialTodo () { // 公文新增待辦事項
      this.AddTodoListModalOpen = true
      this.$store.commit('staff/resetTodo')
      this.todo.src = `${process.env.WEB_ROOT_URL}${this.$route.fullPath}`
    },
    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.receivePostDocument = a
              if (a.name === '結案') this.caseEnd = a
              if (a.name === '參數設置') this.paramSetting = a
            }
          }
          let permission2 = obj.permission
            .filter(name => name.title === '工作協同')
            .map(val => { return val.functionItem })
          for (const element of permission2) {
            for (const a of element) {
              if (a.name === '會議管理') this.conferenceManagement = a
              if (a.name === '文件提審') this.fileManagement = a
            }
          }
        }
      })
    }
  },
  computed: {
    ...mapState({
      officialDoc: (state) => state.officialDocument.officialDoc,
      officialDocList: (state) => state.officialDocument.list,
      scanFile: (state) => state.officialDocument.scanFile,
      currentUser: (state) => state.user.current,
      todo: (state) => state.staff.todo
    }),
    ...mapGetters('user', ['checkPermission'])
  },
  watch: {
    officialDoc: {
      handler (newName, oldName) {
        if (newName._id === undefined) {
          this.isSave = true
          this.isCreate = false
        } else {
          this.isSave = false
          this.isCreate = true
        }
      }
    }
  }
}
</script>

<style scoped>
.shadow {
  background-color: #ffff;

  height: 65px;
  width: 100%;
  box-shadow: 2px 2px 20px rgba(0, 0, 0, 5);
  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.1);
  border: none;
}

.btn:hover {
  color: black;
  background-color: rgb(228, 228, 228);
  transform: translateY(1);
}

.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.1);
  border: none;
}
.btn1:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(49, 68, 175);
  transform: translateY(1);
}
.btn_todo {
  background-color: #ffc107;
  font-size: 16px;
  margin-top: 15px;
  margin-left: 15px;
  padding: 5px 7px;
  color: #252525;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn_todo:hover {
  color: #252525;
  background-color: #e0a800;
  transform: translateY(1);
}
.btn.btn-secondary[disabled] {
  background-color: rgb(224, 224, 224);
  color: rgb(150, 150, 150);
}
.btn_delete {
  background-color: rgb(255, 0, 0);
  font-size: 16px;
  padding: 5px 7px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn_delete:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(199, 0, 0);
}
</style>
