<template>
  <div class="container">
     <!-- 警示 -->
     <b-row style="margin-top: -10px">
      <b-col class="hint_label" cols="12">
        <span>警示:發文日期和上傳檔案部分皆須填寫</span>
      </b-col>
    </b-row>
    <!-- 發文日期 -->
    <b-row style="margin-top: 5px">
      <b-col class="label_col" cols="3">
       <span style="color: red">*</span>
        <span>發文日期:</span>
      </b-col>
      <b-col cols="9">
        <div style="width: 98%; margin-left: -20px">
          <b-form-datepicker
          v-model="postFile.postDay"
          placeholder="請選擇日期"
          style="font-size: 16px; width: 95%"
          />
        </div>
      </b-col>
    </b-row>
     <!-- 來文單位 -->
     <b-row style="margin-top: 15px">
      <b-col class="label_col" cols="3">
       <span style="color: red">*</span>
        <span>來文單位:</span>
      </b-col>
      <b-col cols="9">
        <div style="width: 98%; margin-left: -20px">
          <multiselect
            style="width: 95%"
            v-model="postFile.department_classification"
            tag-placeholder="加入欄位"
            caret="openSelect"
            placeholder="請輸入或選擇單位"
            deselect-label="已選擇"
            :options="department.paramsValue"
            :multiple="false"
            :taggable="true"
            @tag="addTagCompany"
            selectLabel="請選擇"
            selectedLabel="已選擇"
            deselectLabel="取消選擇"
          >
          </multiselect>
        </div>
      </b-col>
    </b-row>
    <!-- 上傳檔案 -->
    <b-row style="margin-top: 15px">
      <b-col class="label_col" cols="3">
       <span style="color: red">*</span>
        <span>上傳檔案:</span>
      </b-col>
      <b-col cols="3">
        <div class="upload-wrapper" style="margin-left: -35px;">
          <b-button
             ref="uploadButton"
             class="btn1"
             v-b-popover.hover="'JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'"
             title="支援上傳類型 "
             @click="checkSave"
          >
            <b-icon-file-earmark-plus />選擇檔案
          </b-button>
          <input
             ref="inputPostFiles"
             type="file"
             class="d-none"
             @change="getInputPostFiles"
             />
        </div>
      </b-col>
      <b-col cols="6" class="file_title">
        <div v-if="isLoading" class="loading">上傳中...</div>
        <div v-else>{{ docs.name }}</div>
      </b-col>
    </b-row>
    <div style="float: right; padding-top: 15px">
      <div v-if="isSaveLoading" class="loading">處理中請稍後...</div>
      <b-button class="btn1" style="margin-left: 10px" @click="addOne" v-else>
        確認
      </b-button>
    </div>
  </div>
</template>

<script>
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
import { mapActions, mapState } from 'vuex'
export default {
  data () {
    return {
      isLoading: false,
      isSaveLoading: false,
      selectedFile: null,
      addOneButtonClicked: false,
      filesToBeUploaded: [],
      relateFileList: [],
      docs: [],
      postFileManagement: {
        department_classification: ''
      },
      department: {
        _id: '',
        paramsValue: []
      }
    }
  },
  async mounted () {
    await this.getOtherList(this.currentUser.defaultTender)
    this.department = await this.lookupParam('department')
  },
  components: {
    Multiselect
  },
  methods: {
    ...mapActions('tenders', ['getOtherList', 'addPostFileManagement']),
    ...mapActions('paramsSetting', ['updateParam', 'lookupParam']),
    async addOne () {
      var wasNull = false
      if (
        this.postFile.postDay === undefined ||
        this.$refs.inputPostFiles.files.length === 0 ||
        this.postFile.department_classification === undefined
      ) {
        wasNull = true
      }
      if (wasNull) alert('請檢查是否有未填項目!')
      else {
        var yes = confirm('確定上傳檔案?')
        if (yes) {
          await this.uploadPostFile()
          this.$emit('closeEvent')
          console.log(this.postFile.department_classification)
        } else {
          alert('取消新增')
        }
      }
    },
    async checkSave () {
      this.$refs.inputPostFiles.click()
    },
    async getInputPostFiles () {
      if (window.FileReader && window.Blob) {
        let type = this.$refs.inputPostFiles.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.inputPostFiles.files[0])
          this.docs = this.filesToBeUploaded[this.filesToBeUploaded.length - 1]
          alert('上傳成功！')
        } else {
          alert(
            '不支援的檔案格式！僅支援上傳 JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'
          )
        }
      }
    },
    // post file id
    async uploadPostFile () {
      await this.addPostFileManagement(this.currentUser.defaultTender)
      await this.$store.dispatch(
        'tenders/getPostFileManagement',
        this.currentUser.defaultTender
      )
      const lastObj = this.postFileList.length
      let fileId = this.postFileList[lastObj - 1]._id
      const file = this.docs
      console.log(fileId)
      await this.$store.dispatch('tenders/addPostFile', {
        file: file,
        fileId: fileId
      })
      this.$store.dispatch(
        'tenders/getPostFileManagement',
        this.currentUser.defaultTender
      )
    },
    // 取消modal
    closeModal () {
      this.$emit('closeEvent')
    },
    async addTagCompany (newTag) {
      if (!this.department.paramsValue.includes(newTag)) {
        this.department.paramsValue.push(newTag)
        await this.updateParam({
          id: this.department._id,
          paramsValue: this.department.paramsValue
        })
        this.department = await this.lookupParam(
          'department'
        )
      }
      this.postFileManagement.department_classification = newTag
    }
  },
  computed: {
    ...mapState({
      tenders: state => state.officialDocument,
      currentUser: state => state.user.current,
      postFile: state => state.tenders.postFileManagement,
      postFileList: (state) => state.tenders.postFileManagementList
    })
  }
}
</script>

<style scoped>
.upload-wrapper {
  display: flex;
  align-items: center;
}
.upload-wrapper .btn1 {
  margin-top: 5px;
}
.label_col {
  margin-top: 12px;
  padding-left: 10px;
}
.container {
  margin-right: 20px;
  width: 30vw;
  height:3vh;
}
.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);
}
.hint_label {
  padding-left: 10px;
  color: red;
  font-size:10px;
}

.file_title {
  display: flex;
  justify-content: center;
  align-items: center;
  text-overflow: ellipsis;
  text-align: center;
  padding-left: 0%;
}

.loading {
  background-color: rgba(88, 85, 85, 0.7);
  color: white;
  font-size: 20px;
  font-weight: 600;
  padding: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 3%;
  float: left;
}
</style>
