<!--
 Program: AttachMgmt.vue
 Author: SDL
 Description: Attach management
-->
<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- SEARCH Area -->
    <div class="ui--search-container clearfix">
      <div class="col-10 float-start">
        <!-- row1 -->
        <div class="row">
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.common.label.fileName') }}</label>
              <div class="col-8">
                <input class="form-control" type="text" v-model="searchKeyword" @keydown.enter="onSearch()" />
              </div>
            </div>
          </div>
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.board.label.sort') }}</label>
              <div class="col-8 form-inline">
                <select class="form-select" v-model="selectedOrderBy">
                  <option value="0">{{ $t('sdl.attach.label.fileSize') }} {{ $t('sdl.board.label.asc') }}</option>
                  <option value="1">{{ $t('sdl.attach.label.fileSize') }} {{ $t('sdl.board.label.desc') }}</option>
                  <option value="2">{{ $t('sdl.privacyPolicy.createDate') }} {{ $t('sdl.board.label.asc') }}</option>
                  <option value="3">{{ $t('sdl.privacyPolicy.createDate') }} {{ $t('sdl.board.label.desc') }}</option>
                </select>
              </div>
            </div>
          </div>
        </div>
        <!-- //row1 -->
        <div class="row mt-2">
          <div class="col-12">
            <!-- form -->
            <div class="row">
              <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.period') }}</label>
              <div class="col-10 form-inline">
                <sdl-datepicker v-model="searchPeriod" :period="searchPeriod"></sdl-datepicker>
              </div>
            </div>
          </div>

        </div>
      </div>
      <!-- search button -->
      <div class="col-2 float-end text-end">
        <button class="btn btn-primary btn-search" type="button" @click="onSearch()">
          {{ $t('sdl.common.label.search') }}
        </button>
      </div>
    </div>
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(attachFileList.length) }}</span>
      <div class="float-end">
        <button
          type="button"
          class="btn btn-secondary btn-sm"
          @click="deleteAttachFileBtn()"
          v-authorization="'execute'"
        >
          {{ $t('sdl.common.label.delete') }}
        </button>
      </div>
    </div>
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:5%" />
        <col style="" />
        <col style="width:10%" />
        <col style="width:10%" />
        <col style="width:10%" />
        <col style="width:20%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col"><input type="checkbox" v-model="selectAll" @click="toggleCheckBoxAll" /></th>
          <th scope="col">{{ $t('sdl.common.label.fileName') }}</th>
          <th scope="col">{{ $t('sdl.attach.label.fileExists') }}</th>
          <th scope="col">{{ $t('sdl.attach.label.fileSize') }}</th>
          <th scope="col">{{ $t('sdl.privacyPolicy.createDate') }}</th>
          <th scope="col">{{ $t('sdl.privacyPolicy.createUser') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in attachFileList" :key="item.fileId">
          <td class="text-center">
            <input type="checkbox" :id="item.fileId" :value="item" v-model="selectedAttachFileList" />
          </td>
          <td>{{ item.fileName }}</td>
          <td class="text-center"><i v-if="item.fileExists" class="bi bi-paperclip"></i></td>
          <td class="text-end">{{ $filters.numberFormat(item.fileSize) }}</td>
          <td class="text-center">{{ $filters.dateFormat(item.firstRegDatetime) }}</td>
          <td class="text-center">{{ item.firstRegrId }}</td>
        </tr>
      </tbody>
    </table>
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="currentPage"
      :total-rows="records"
      :per-page="pageSize"
      @change="onSearch"
      align="center"
    />
    <!--  // Pagination Area-->
  </div>
</template>

<script>
import axios from 'axios';
import { DateUtil, SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';

export default {
  data() {
    return {
      selectAll: false,
      attachFileList: [],
      selectedAttachFileList: [],
      records: 0, // total number of data
      currentPage: 1, // current page number
      pageSize: 10, // Number of lists per page
      searchKeyword: '',
      searchPeriod: {},
      orderBy: '',
      selectedOrderBy: 2, // init order by
      orderByList: ['FILE_SIZE', 'FILE_SIZE DESC', 'FIRST_REG_DATETIME', 'FIRST_REG_DATETIME DESC'],
    };
  },
  created() {
    this.init();
  },
  mixins: [StoreParams],
  methods: {
    init() {
      this.searchPeriod.startDate = DateUtil.subDate(12, 'd');
      this.searchPeriod.endDate = DateUtil.now();
      const storeParams = this.getStoreParameter();
      if (storeParams) {
        this.searchKeyword = storeParams.searchKeyword;
        this.onSearch(storeParams.pageIndex);
      } else {
        this.onSearch();
      }
    },
    onSearch(pageIndex = 1) {
      this.currentPage = pageIndex;
      // eslint-disable-next-line no-underscore-dangle
      const _searchPeriod = DateUtil.stdFormat(this.searchPeriod);
      const params = {
        fileName: this.searchKeyword,
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        ..._searchPeriod,
        orderBy: this.orderByList[this.selectedOrderBy].concat(', FIRST_REGR_ID, FILE_NAME, FILE_ID'),
      };
      this.setStoreParameter(params);
      // Loading bar execution
      SDLUtil.showLoadingBar(true);

      axios
        .get(`${SDLUtil.API_URL}/resource/attachments/file-mgmt?${StringUtil.queryStringfy(params)}`)
        .then(response => {
          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
          this.selectAll = false;
          this.selectedAttachFileList = [];
          this.attachFileList = response.data.rows;
          this.records = response.data.records;
          this.currentPage = response.data.currentPage;
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    selectOrderBy(section) {
      section *= 2;
      const modSOB = this.selectedOrderBy % 2;
      this.selectedOrderBy = modSOB === 0 ? section + 1 : section;
      this.onSearch();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select List CheckBox All
     */
    toggleCheckBoxAll() {
      this.selectedAttachFileList = [];
      if (!this.selectAll) {
        this.selectedAttachFileList = this.attachFileList;
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking whether there is a checked row in the checkbox and checking whether to execute it, call the delete method
     */
    deleteAttachFileBtn() {
      if (this.selectedAttachFileList.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteFile(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Delete a row checked in the checkbox among newly added and saved items
     */
    deleteFile() {
      SDLUtil.showLoadingBar(true);
      axios
        .delete(`${SDLUtil.API_URL}/resource/attachments/file-mgmt`, { data: this.selectedAttachFileList })
        .then(() => {
          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
          this.onSearch(this.currentPage);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
  },
};
</script>
