<template>
  <b-container fluid>
    <b-row style="padding-top: 20px">
      <b-col cols="4">
        <b-row style="padding-left: 15px">
          <span style="font-size: 24px; font-weight: 900">契約文件</span>
          <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="支援上傳類型 "
            style="height: 30px; width: auto; margin-left: 5px; color: #1d325f"
            size="sm"
            @click="checkSave"
          ></b-icon>
          <input
            ref="inputFiles"
            type="file"
            class="d-none"
            v-on:change="getInputFiles()"
          />
        </b-row>
      </b-col>
      <b-col cols="8">
        <span style="font-size: 24px; font-weight: 900">搜尋結果</span>
      </b-col>
      <b-col cols="4">
        <hr style="margin-top: 10px; margin-bottom: 10px;" />
      </b-col>
      <b-col cols="8">
        <hr style="margin-top: 10px; margin-bottom: 10px;" />
      </b-col>
    </b-row>
    <b-row>
      <b-col cols="4" style="padding-top: 10px; height: 800px">
        <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>
        <div class="word">契約條文搜尋：</div>
          <b-row>
            <b-col cols="3" style="padding-right: 3px">
              <b-form-select
                :options="operators"
                v-model="searchCondition.operator"
              ></b-form-select>
            </b-col>
            <b-col cols="9">
              <multiselect
                v-model="searchCondition.keyword"
                tag-placeholder="加入欄位"
                placeholder="可輸入複合檢索詞"
                :options="keywords"
                :multiple="true"
                :showNoOptions="false"
                :taggable="true"
                @tag="addTagKeyword"
              >
              </multiselect>
            </b-col>
          </b-row>
          <div class="float-right mt-1">
            <b-button class="btn1" @click="filterList">搜尋</b-button>
          </div>
      </b-col>
      <b-col cols="8" style="height: 800px">
        <b-table
          v-if="isSearch === false"
          :filter="filter"
          class="text-center"
          thead-class="thClass"
          ref="selectableTable"
          no-border-collapse
          :fields="fields"
          :items="contractList.contract"
          text-align="center"
          striped
          sticky-header="calc(90vh - 50px)"
          fixed
        >
          <template #head()="{ label, field: { key } }">
            <span style="font-weight: bold; color: black; 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: normal; color: black; 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'

export default {
  data () {
    return {
      isSearch: false, // 這個非常爛
      keywords: [],
      filter: null,
      filter1: null,
      operators: [
        // and & or
        { 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: []
    }
  },
  async mounted () {
    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)
          // for (const index of this.contractList) {
          //   index.contract_clause = index.contract_clause.replace(
          //     `/${this.searchCondition.keyword}/gi`,
          //     (match) => `<span style="color: red">${match}</span>`
          //   )
          //   return
          // }
        }
      }
    },
    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])
          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
        )
        alert('上傳成功！')
        this.$emit('getList')
      } catch (err) {
        alert('上傳失敗！')
      } finally {
        this.$set(this.filesToBeUploaded, index, file)
      }
    }
  },
  components: {
    Multiselect
  },
  computed: {
    ...mapState({
      currentUser: (state) => state.user.current,
      tender: (state) => state.tenders.tenders,
      contractList: (state) => state.tenders.tenderList,
      fileList: (state) => state.tenders.fileList
    })
  }
}
</script>

<style>
.table.b-table > thead > tr > th,
.table.b-table > tfoot > tr > td {
  background-image: none !important;
}
</style>
<style lang="scss" scoped>
::-webkit-scrollbar {
  width: 3px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
  border-radius: 15px;
  background: #888;
}
::-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: #ffffff;
  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;
}
.btn1 {
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 10px;
  padding-bottom: 5px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
  text-align: justify;
  margin-top: 10px;
  margin-left: 17px;
}
.text-center {
  height: 95%;
  margin-top: 5px;
}
/deep/ .align-middle {
  max-width: 200px;
  white-space: normal !important;
}
.mark {
  background: orange;
  color: black;
}
</style>
