<template>
  <b-container fluid>
    <b-row style="padding-top: 10px;margin-top: 20px ;margin-left: 10px">
      <b-col cols="4">
        <b-row style="display: flex; align-items: center;">
          <span style="font-size: 30px; font-weight: 900; flex: 1;">契約文件</span>
          <div style="margin-right: 25px">
          <b-icon
            class="btn w-15 p-1"
            icon="box-arrow-up"
            aria-hidden="true"
            v-b-popover.hover="'JPG, PNG, PDF, DOCX, DOC, XLSX 檔案'"
            title="支援上傳類型 "
            size="sm"
            @click="checkSave"
            v-show="deleteContract.permission === 2"
          ></b-icon>
          <input
            ref="inputFiles"
            type="file"
            class="d-none"
            v-on:change="getInputFiles()"
          />
          <b-icon
            class="btn_delete w-15 p-1"
            icon="trash-fill"
            v-b-popover.hover="'刪除檔案'"
            title="支援刪除契約檔案類型 "
            size="sm"
            @click="deleteContractSearchListModalOpen = true "
            v-show="deleteContract.permission === 2"
            >
          </b-icon>
        </div>
        <!-- 上傳中的提示 -->
        <div v-if="isLoading" class="loading">上傳中...</div>
        </b-row>
      </b-col>

      <b-col cols="8">
        <b-row style="display: flex;">
         <span style="font-size: 20px; font-weight: 900; margin-top: 7px; margin-left: 200px">契約條文搜尋</span>
          <b-col cols="2" style="padding-right: 3px">
            <b-form-select
             :options="operators"
             v-model="searchCondition.operator"
            ></b-form-select>
           </b-col>
           <b-col cols="4" style="display: flex;">
            <multiselect
             v-model="searchCondition.keyword"
             tag-placeholder="加入欄位"
             placeholder="可輸入複合檢索詞"
             :options="keywords"
             :multiple="true"
             :showNoOptions="false"
             :taggable="true"
             @tag="addTagKeyword"
              >
            </multiselect>
           </b-col>
           <b-col cols="1">
             <b-button
             style="white-space: nowrap;margin-top: 0.2vh;margin-left: -1vw;padding-left: -2px;"
                class="btn_search"
                @click="filterList">搜尋</b-button>
            </b-col>
        </b-row>
      </b-col>
    </b-row>

    <b-row>
      <b-col cols="4"  style="margin-top: 22px;">
        <hr style="margin-top: -7px; margin-bottom: 10px;margin-left: -10px;" />
      </b-col>
      <b-col cols="8" style="position: relative;margin-top: 15px;padding-left: 10px; ">
        <b-col cols="12">
        <hr style="margin-top: 0px; margin-bottom: 20px;" />
        <!-- <div style="position: relative; text-align: left; margin-top: -8px; font-size: 20px; font-weight: 900; margin-left: 500px;">搜尋結果</div> -->
        </b-col>
      </b-col>
    </b-row>

    <b-row>
      <b-col cols="4" style="height: 500px; margin-top: -20px;">
        <div style="max-height: 500px; overflow-y: auto">
        <ul v-for="(item, i) in fileList" :key="i">
            <a
              class="mb-2"
              style="
                display: block;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                color: #525f7f;
                margin-left: -30px
              "
              :href="item.src"
              target="_blank"
            >
              <span style="cursor: pointer"> • {{ item.name }} </span>
            </a>
          </ul>
        </div>

          <modal
           :isOpen="deleteContractSearchListModalOpen"
            title="刪除契約"
           v-on:closeEvent="deleteContractSearchListModalOpen = false"
          >
          <deleteContractSearchList @closeEvent="deleteContractSearchListModalOpen = false"
          />
          </modal>

      </b-col>
      <b-col cols="8" style="height: auto;overflow: auto; top: 0; z-index: 1;">
        <b-table
          v-if="isSearch === false"
          :fields="fields"
          :filter="filter"
          class="text-center"
          thead-class="thClass"
          ref="selectableTable"
          no-border-collapse
          :items="contractList.contract"
          text-align="center"
          striped
          sticky-header="calc(80vh - 50px)"
          fixed
        >
          <!-- HEAD -->
          <template #head()="{ label, field: { key } }">
            <span style="font-weight: bold; color: white; font-size: 18px">{{
              label
            }}</span>
          </template>

          <!-- 條文章節 -->
          <template #cell(contract_chapter)="data">
            <span style="font-weight: normal; font-size: 16px">{{
              data.value
            }}</span>
          </template>

          <!-- 條文內容 -->
          <template #cell(contract_clause)="data">
            <span style="font-weight: normal; font-size: 16px">{{
              data.value
            }}</span>
          </template>
        </b-table>

        <b-table
          v-else
          :filter="filter"
          class="text-center"
          thead-class="thClass"
          ref="selectableTable"
          no-border-collapse
          :fields="fields"
          :items="contractList"
          text-align="center"
          striped
          sticky-header="calc(90vh - 50px)"
          fixed
        >
          <template #head()="{ label, field: { key } }">
            <span style="font-weight: bold; color: white; font-size: 18px">{{
              label
            }}</span>
          </template>
          <template #cell(contract_chapter)="data">
            <span style="font-weight: normal; font-size: 16px">{{
              data.value
            }}</span>
          </template>
          <template #cell(contract_clause)="data">
            <span style="font-weight: normal; font-size: 16px">{{
              data.value
            }}</span>
          </template>
        </b-table>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
import deleteContractSearchList from '@/views/ContractManagement/ModalContent/deleteContractSearchList.vue'
import functionBar from '@/views/ContractManagement/MainPage/functionBar.vue'

export default {
  data () {
    return {
      isLoading: false,
      isSearch: false,
      deleteContractSearchListModalOpen: false,
      keywords: [],
      filter: null,
      filter1: null,
      operators: [
        { value: 'and', text: 'and' },
        { value: 'or', text: 'or' }
      ],
      searchCondition: {
        operator: 'and',
        keyword: []
      },
      fields: [
        {
          key: 'contract_chapter',
          label: '條文章節',
          tdClass: 'align-middle',
          thStyle: { width: '100px' }
        },
        {
          key: 'contract_clause',
          label: '條文內容',
          tdClass: 'align-middle',
          thStyle: { width: '500px' }
        }
      ],
      filesToBeUploaded: [],
      selectMode: 'single',
      deletedContractCount: 0,
      // 權限
      deleteContract: {}
    }
  },
  async mounted () {
    await this.usePermission()
    await this.lookupTender(this.currentUser.defaultTender)
    await this.getOtherList(this.currentUser.defaultTender)
    await this.$store.dispatch(
      'tenders/getContractFile',
      this.currentUser.defaultTender
    )
  },
  methods: {
    ...mapActions('tenders', ['getOtherList', 'lookupSearch', 'lookupTender']),
    addTagKeyword (newTag) {
      this.searchCondition.keyword.push(newTag)
    },
    async filterList () {
      if (this.searchCondition.keyword.length === 0) {
        alert('輸入關鍵字')
        this.isSearch = false
        await this.getOtherList(this.currentUser.defaultTender)
      } else {
        let searchList = await this.lookupSearch({
          operator: this.searchCondition.operator,
          keyword:
            this.searchCondition.keyword.length === 0
              ? []
              : this.searchCondition.keyword
        })
        this.isSearch = true
        if (searchList.length !== 0) {
          this.$store.commit('tenders/setTendersList', searchList)
        }
      }
    },
    async checkSave () {
      this.$refs.inputFiles.click()
    },
    async getInputFiles () {
      if (window.FileReader && window.Blob) {
        let type = this.$refs.inputFiles.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.inputFiles.files[0])
          this.isLoading = true
          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 {
        // console.log(file)
        await this.$store.dispatch('tenders/addContractFile', {
          id: this.currentUser.defaultTender,
          file: file
        })
        await this.$store.dispatch(
          'tenders/getContractFile',
          this.currentUser.defaultTender
        )
        this.isLoading = false
        alert('上傳成功！')
        this.$emit('getList')
      } 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.deleteContract = a
            }
          }
        }
      })
    }
  },
  components: {
    deleteContractSearchList,
    modal: () => import('@/views/Modal/index.vue'),
    Multiselect,
    functionBar
  },
  computed: {
    ...mapState({
      currentUser: (state) => state.user.current,
      tender: (state) => state.tenders.tenders,
      contractList: (state) => state.tenders.tenderList,
      fileList: (state) => state.tenders.fileList
    }),
    rows () {
      return this.list.length
    }
  }
}
</script>

<style>
.thClass {
  position: sticky;
  top: 0;
  background-color: #1d325f;
  z-index: 999;
  color: white;
}
.table.b-table > thead > tr > th,
.table.b-table > tfoot > tr > td {
  background-image: none !important;
}
</style>
<style lang="scss" scoped>
.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%;
}
::-webkit-scrollbar {
  width: 3px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
  border-radius: 15px;
  background: #f1f1f1;
}
::-webkit-scrollbar-thumb:hover {
  background: #555;
}
.custom-select {
  color: black !important;
  box-shadow: none;
  -webkit-box-shadow: none;
}

// /deep/ .table.b-table > thead > tr > th {
//   background-color: #1d325f;
//   color: black;
//   position: sticky;
//   position: -webkit-sticky;
//   top: 0;
//   z-index: 2;
// }
.word {
  margin-top: 20px;
  font-weight: bold;
  font-size: 18px;
  padding-bottom: 10px;
}
.btn_search {
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  padding-left: 5px;
  padding-right: 5px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: white;
  box-shadow: 0.25vw 0.25vw 1.25vw rgba(0, 0, 0, 0.1);
}
.btn_search:hover {
  color: black;
  background-color: rgb(228, 228, 228);
  transform: translateY(1);
}
.btn {
  height: 30px;
  width: auto;
  color: #1d325f;
  position: relative;
}
.btn:hover {
  color: #1d325f(255, 0, 0);
  background-color: rgb(255, 255, 255);
  transform: translateY(0);
}
.btn_delete {
  height: 30px;
  width: auto;
  color: red;
  position: relative;
  cursor: pointer;
}
.btn_delete:hover {
  color: rgb(255, 0, 0);
  background-color: rgb(255, 255, 255);
  transform: translateY(0);
}
.text-center {
  height: 95%;
  margin-top: 5px;
}
/deep/ .align-middle {
  max-width: 200px;
  white-space: normal !important;
}
.mark {
  background: orange;
  color: black;
}
</style>
