<template>
  <!-- 匯出列表modal -->
  <div>
    <!-- 發文列表 -->
    <div class="mainContent" v-show="$route.name === 'PaperPostList'">
      <b-row>
        <b-col cols="10">
          <b-form-group
            label-cols="2"
            label="發文日期:"
            label-for="input-default"
            style="margin-bottom: 0"
          >
            <b-row>
              <b-col style="padding-top: 2px">
                <b-form-datepicker
                  class="mb-3"
                  style="width: 100%; height: 40px"
                  placeholder="請選擇日期"
                  v-model="searchCondition.issueDateStart"
                >
                </b-form-datepicker>
              </b-col>
              <div style="padding-top: 11px">至</div>
              <b-col style="padding-top: 2px">
                <b-form-datepicker
                  class="mb-3"
                  style="width: 100%; height: 40px"
                  placeholder="請選擇日期"
                  v-model="searchCondition.issueDateEnd"
                  @input="formatDate"
                >
                </b-form-datepicker>
              </b-col>
            </b-row>
          </b-form-group>
          <b-form-group
            label-cols="2"
            label="篩選條件:"
            label-for="input-default"
            style="margin-bottom: 0"
          >
            <b-row>
              <b-col style="padding-top: 2px" cols="3">
                <b-form-select
                  v-model="searchCondition.condition"
                  :options="conditions"
                  style="height: 40px"
                >
                </b-form-select>
              </b-col>
              <b-col style="padding-top: 2px" cols="6">
                <multiselect
                  v-model="searchCondition.keyword"
                  tag-placeholder="加入欄位"
                  placeholder="可輸入複合檢索詞、字號、主旨"
                  :options="keywords"
                  :multiple="true"
                  :showNoOptions="false"
                  :taggable="true"
                  @tag="addTagKeyword"
                >
                  <span
                    slot="caret"
                    v-if="!searchCondition.keyword.length"
                  ></span>
                </multiselect>
              </b-col>
              <b-col cols="3" >
                <b-form-select

                  v-model="searchCondition.operator"
                  :options="operators"
                  style="height: 40px;width: 100%;"
                >
                </b-form-select>
              </b-col>
            </b-row>
          </b-form-group>
        </b-col>
        <b-col style="padding-top: 5px" cols="2">
          <b-button
            class="btn_search"
            style="float: right; margin-top: 18%"
            @click="filterList"
            >篩選</b-button
          >
        </b-col>
      </b-row>
      <b-button size="sm" @click="selectAllRows">全選</b-button>
      <b-button size="sm" @click="clearSelected">取消全選</b-button>
      <div style="width: 100%; height: 100%; margin-top: 10px">
        <b-table
          class="text-center"
          thead-class="thClass"
          style="max-height: 100%"
          sticky-header
          no-border-collapse
          responsive
          bordered
          :fields="fields1"
          :items="exportList"
          :per-page="perPage"
          :current-page="currentPage"
          :sort-desc.sync="sortDesc"
          :sort-by.sync="sortBy"
          ref="receiveSelectableTable"
          :select-mode="selectMode"
          selectable
          @row-selected="onRowSelected"
        >
          <!-- HEAD -->
          <template #head()="{ label, field: { key, sortable } }">
            <span style="font-weight: normal; color: white; font-size: 15px">{{
              label
            }}</span>
            <template v-if="sortable">
              <b-icon
                font-scale="1.3"
                v-if="sortBy !== key"
                icon="arrow-down-up"
              ></b-icon>
              <b-icon
                font-scale="1.3"
                v-else-if="sortDesc"
                icon="arrow-down"
              ></b-icon>
              <b-icon font-scale="1.3" v-else icon="arrow-up"></b-icon>
            </template>
          </template>
          <!-- BODY -->
          <template #cell(select)="{ rowSelected }">
            <template v-if="rowSelected">
              <span aria-hidden="true">&check;</span>
              <span class="sr-only"></span>
            </template>
            <template v-else>
              <span aria-hidden="true">&nbsp;</span>
              <span class="sr-only">Not selected</span>
            </template>
          </template>
          <template #cell(issue_date)="data">
            <span style="font-weight: normal; color: black; font-size: 14px">{{
              data.value
            }}</span>
          </template>
          <template #cell(issue_text_number)="data">
            <span style="font-weight: normal; color: black; font-size: 14px">{{
              data.value
            }}</span>
          </template>
          <template #cell(subject)="data">
            <router-link
              :to="{}"
              @click.native="pushTo(data.item)"
              style="font-weight: normal; color: blue; font-size: 14px"
              >{{ data.value }}</router-link
            >
          </template>
        </b-table>
      </div>
      <div style="float: right; margin-top: 20px">
        <b-button class="btn_search" @click="handleExport()">匯出</b-button>
        <b-button class="btn_search" @click="submit">返回</b-button>
      </div>
    </div>
    <!-- 收文列表 -->
    <div class="mainContent" v-show="$route.name === 'PaperReceiveList'">
      <b-row>
        <b-col cols="10">
          <b-form-group
            label-cols="2"
            label="來文日期:"
            label-for="input-default"
            style="margin-bottom: 0"
          >
            <b-row>
              <b-col style="padding-top: 2px">
                <b-form-datepicker
                  class="mb-2"
                  style="width: 100%; height: 40px"
                  placeholder="請選擇日期"
                  v-model="searchCondition.issueDateStart"
                >
                </b-form-datepicker>
              </b-col>
              <div style="padding-top: 10px">至</div>
              <b-col style="padding-top: 2px">
                <b-form-datepicker
                  class="mb-2"
                  style="width: 100%; height: 40px"
                  placeholder="請選擇日期"
                  v-model="searchCondition.issueDateEnd"
                >
                </b-form-datepicker>
              </b-col>
            </b-row>
          </b-form-group>
          <b-form-group
            label-cols="2"
            label="篩選條件:"
            label-for="input-default"
            style="margin-bottom: 0"
          >
            <b-row>
              <b-col style="padding-top: 2px" cols="3">
                <b-form-select
                  v-model="searchCondition.condition"
                  :options="conditions"
                  style="height: 40px"
                >
                </b-form-select>
              </b-col>

              <b-col style="padding-top: 2px" cols="6">
                <multiselect
                  v-model="searchCondition.keyword"
                  style="height:10px"
                  tag-placeholder="加入欄位"
                  placeholder="可輸入複合檢索詞、字號、主旨"
                  :options="keywords"
                  :multiple="true"
                  :showNoOptions="false"
                  :taggable="true"
                  @tag="addTagKeyword"
                >
                  <span
                    slot="caret"
                    v-if="!searchCondition.keyword.length"
                  ></span>
                </multiselect>
              </b-col>
               <b-col cols="3">
                <b-form-select
                  v-model="searchCondition.operator"
                  :options="operators"
                  style="height: 40px"
                >
                </b-form-select>
              </b-col>
            </b-row>
          </b-form-group>
        </b-col>
        <b-col style="padding-top: 5px" cols="2">
          <b-button class="btn_search" style="float: right" @click="filterList"
            >篩選</b-button
          >
        </b-col>
      </b-row>
      <b-button size="sm" @click="selectAllRows">全選</b-button>
      <b-button size="sm" @click="clearSelected">取消全選</b-button>
      <div style="width: 100%; height: 100%; margin-top: 10px">
        <b-table
          class="text-center"
          thead-class="thClass"
          style="max-height: 100%"
          sticky-header
          no-border-collapse
          responsive
          bordered
          :fields="fields2"
          :items="exportList"
          :per-page="perPage"
          :current-page="currentPage"
          :sort-desc.sync="sortDesc"
          :sort-by.sync="sortBy"
          ref="postSelectableTable"
          :select-mode="selectMode"
          selectable
          @row-selected="onRowSelected"
        >
          <!-- HEAD -->
          <template #head()="{ label, field: { key, sortable } }">
            <span style="font-weight: normal; color: white; font-size: 15px">{{
              label
            }}</span>
            <template v-if="sortable">
              <b-icon
                font-scale="1.3"
                v-if="sortBy !== key"
                icon="arrow-down-up"
              ></b-icon>
              <b-icon
                font-scale="1.3"
                v-else-if="sortDesc"
                icon="arrow-down"
              ></b-icon>
              <b-icon font-scale="1.3" v-else icon="arrow-up"></b-icon>
            </template>
          </template>
          <!-- BODY -->
          <template #cell(select)="{ rowSelected }">
            <template v-if="rowSelected">
              <span aria-hidden="true">&check;</span>
              <span class="sr-only"></span>
            </template>
            <template v-else>
              <span aria-hidden="true">&nbsp;</span>
              <span class="sr-only">Not selected</span>
            </template>
          </template>
          <template #cell(issue_date)="data">
            <span style="font-weight: normal; color: black; font-size: 14px">{{
              data.value
            }}</span>
          </template>
          <template #cell(issue_text_number)="data">
            <span style="font-weight: normal; color: black; font-size: 14px">{{
              data.value
            }}</span>
          </template>
          <template #cell(subject)="data">
            <router-link
              :to="{}"
              @click.native="pushTo(data.item)"
              style="font-weight: normal; color: blue; font-size: 14px"
              >{{ data.value }}</router-link
            >
          </template>
        </b-table>
      </div>
      <div style="float: right; margin-top: 20px">
        <b-button class="btn_search" @click="handleExport()">匯出</b-button>
        <b-button class="btn_search" @click="submit">返回</b-button>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapActions } from 'vuex'
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
export default {
  data () {
    return {
      select: null,
      keywords: [],
      selected: [], // Must be an array reference!
      perPage: 12,
      currentPage: 1,
      sortBy: null,
      sortDesc: false,
      conditions: [
        { value: null, text: '請選擇條件' },
        { value: 'keyword', text: '關鍵字' },
        { value: 'issue_text_number', text: '字號' },
        { value: 'subject', text: '主旨' }
      ],
      operators: [
        { value: 'and', text: 'and' },
        { value: 'or', text: 'or' }
      ],
      fields1: [
        {
          key: 'select',
          label: '勾選',
          tdClass: 'align-middle'
        },
        {
          key: 'issue_date',
          label: '發文日期',
          sortable: true,
          tdClass: 'align-middle'
        },
        {
          key: 'issue_text_number',
          label: '發文字號',
          sortable: true,
          tdClass: 'align-middle'
        },
        { key: 'subject', label: '主旨', tdClass: 'truncate' },
        {
          key: 'status',
          label: '辦理狀態',
          sortable: true,
          tdClass: 'align-middle'
        }
      ],
      fields2: [
        {
          key: 'select',
          label: '勾選',
          tdClass: 'align-middle'
        },
        {
          key: 'issue_date',
          label: '來文日期',
          sortable: true,
          tdClass: 'align-middle'
        },
        {
          key: 'issue_text_number',
          label: '收文字號',
          sortable: true,
          tdClass: 'align-middle'
        },
        { key: 'subject', label: '主旨', tdClass: 'truncate' },
        {
          key: 'status',
          label: '辦理狀態',
          sortable: true,
          tdClass: 'align-middle'
        }
      ],
      exportList: [],
      selectedRows: [],
      selectMode: 'multi',
      searchCondition: {
        issueDateStart: '',
        issueDateEnd: '',
        condition: null,
        operator: 'and',
        keyword: []
      },
      formattedDate: '',
      formattedDates: ''
    }
  },
  components: { Multiselect },
  methods: {
    ...mapActions('officialDocument', [
      'lookupSearchList',
      'lookupOfficialDoc'
    ]),
    formatDate () {
      if (this.searchCondition.issueDateEnd) {
        const formattedDate = moment(this.searchCondition.issueDateEnd).format(
          'YYYY-M-D'
        )
        console.log(formattedDate)
      }
    },
    formatDates () {
      if (this.searchCondition.issueDateStart) {
        const formattedDates = moment(this.searchCondition.issueDateStart).format(
          'YYYY-M-D'
        )
        console.log(formattedDates)
      }
    },
    submit () {
      this.$emit('closeEvent')
    },
    addTagKeyword (newTag) {
      this.searchCondition.keyword.push(newTag)
    },
    async filterList () {
      // keyword 還不能用，設計如果word沒有打就不用跳alert  用頁面判斷收發文
      if (this.searchCondition.keyword.length !== 0 && this.searchCondition.condition === null) { alert('請選擇篩選條件！') } else {
        this.exportList = await this.lookupSearchList({
          routeName: this.$route.name,
          issueDateStart: this.formattedDates,
          issueDateEnd: this.formattedDate,
          condition: this.searchCondition.condition,
          operator: this.searchCondition.operator,
          keyword: (this.searchCondition.keyword.length === 0) ? [] : this.searchCondition.keyword
        })
      }
    },
    async pushTo (data) {
      switch (data.distinguish) {
        case '發文':
          this.lookupOfficialDoc(data._id)
          this.$router.push({ name: 'ArchivesPostView' })
          break

        case '來文':
          this.lookupOfficialDoc(data._id)
          this.$router.push({ name: 'ArchivesReceiveView' })
          break
      }
    },
    handleExport () {
      require.ensure([], () => {
        // eslint-disable-next-line camelcase
        const { export_json_to_excel } = require('@/util/Export2Excel')
        const tHeader = ['發文日期', '發文字號', '主旨']
        const filterVal = ['issue_date', 'issue_text_number', 'subject']
        const list = this.selectedRows
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, '列表excel')
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    },
    onRowSelected (items) {
      this.selectedRows = items
    },
    selectAllRows () {
      this.$refs.postSelectableTable.selectAllRows()
      this.$refs.receiveSelectableTable.selectAllRows()
    },
    clearSelected () {
      this.$refs.postSelectableTable.clearSelected()
      this.$refs.receiveSelectableTable.clearSelected()
    }
  },
  computed: {
    rows () {
      return this.exportList.length
    }
  }
}
</script>

<style>
.thClass {
  background-color: #1d325f;
  color: white;
}
.table.b-table > thead > tr > th,
.table.b-table > tfoot > tr > td {
  background-image: none !important;
}
</style>
<style lang="scss" scoped>
/deep/ .table.b-table > thead > tr > th {
  background-color: #1d325f;
  color: white;
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 2;
}
/deep/ .truncate {
  max-width: 400px;
  white-space: normal !important;
  word-wrap: break-word;
  vertical-align: middle !important;
  text-align: left;
}
/deep/ .align-middle {
  max-width: 150px;
  white-space: normal !important;
  word-wrap: break-word;
}
.mainContent {
  height: 500px;
  width: 1000px;
  background-color: rgb(255, 255, 255);
  padding: 0;
}
.btn_search {
  background-color: rgb(75, 102, 255);
  font-size: 15px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 6px;
  padding-bottom: 6px;
  color: white;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
}
.btn_search:hover {
  color: black;
  background-color: rgb(228, 228, 228);
  transform: translateY(1);
}
</style>
