<!--
Program: Approval Management List
Author: SDL
Description: Approval Management List
-->
<template>
  <!-- SUB Contents -->
  <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">
          <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.type') }}</label>
          <div class="col-4">
            <select class="form-select d-block w-100" v-model="searchParam.approvalType">
              <option value="">{{ $t('sdl.common.label.all') }}</option>
              <option value="Internal">{{ $t('sdl.approval.label.internalApproval') }}</option>
              <option value="Knox">{{ $t('sdl.approval.label.knoxApproval') }}</option>
            </select>
          </div>
          <label class="col-2 col-form-label text-end">{{ $t('sdl.user.label.userStatus') }}</label>
          <div class="col-4">
            <select class="form-select d-block w-100" v-model="searchParam.approvalStatus">
              <option value="">{{ $t('sdl.common.label.all') }}</option>
              <option value="INPROCESS">{{ $t('sdl.approval.docStatus.label.INPROCESS') }}</option>
              <option value="COMPLETED">{{ $t('sdl.approval.docStatus.label.COMPLETED') }}</option>
              <option value="EX_POST_COMPLETED">{{ $t('sdl.approval.label.postCompletion') }}</option>
              <option value="REJECTED">{{ $t('sdl.approval.label.REJECTED') }}</option>
              <option value="CANCELLED">{{ $t('sdl.common.label.cancel') }}</option>
            </select>
          </div>
        </div>
        <!-- row2 -->
        <div class="row mt-2">
          <label class="col-2 col-form-label text-end">{{ $t('sdl.approval.label.docName') }}</label>
          <div class="col-4">
            <select class="form-select d-block w-100" v-model="searchParam.docType">
              <option value="">{{ $t('sdl.common.label.all') }}</option>
              <option v-for="code in docList" :value="code.docType" :key="code.docType">{{ code.docType }}</option>
            </select>
          </div>
          <label class="col-2 col-form-label text-end">{{
            $t('sdl.approval.label.reporter')
          }}</label>
          <div class="col-4">
            <div class="input-group">
              <input
                type="text"
                class="form-control"
                placeholder=""
                v-model="searchParam.requesterName"
                @keyup.esc="searchParam.requesterName = ''"
                @keyup.enter.stop="openSearchUser"
              />
                <button class="btn btn-outline-secondary" type="button" @click="openSearchUser">
                  <i class="bi bi-search"></i>
                </button>
            </div>
          </div>
        </div>
        <!-- row3 -->
        <div class="row mt-2">
          <label class="col-2 col-form-label text-end">{{
            $t('sdl.approval.label.syncState')
          }}</label>
          <div class="col-4">
            <select class="form-select d-block w-100" v-model="searchParam.syncStatus">
              <option value="">{{ $t('sdl.common.label.all') }}</option>
              <option value="Success">{{ $t('sdl.common.label.success') }}</option>
              <option value="Fail">{{ $t('sdl.common.label.fail') }}</option>
            </select>
          </div>
        </div>
        <div class="row mt-2">
          <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.period') }}</label>
          <div class="col-10">
            <!-- 기간 -->
            <sdl-datepicker
              v-model="searchPeriod"
              :period="searchPeriod"
              :wrap-class="'input-group input-date-in'"
            ></sdl-datepicker>
            <!-- // 기간 -->
          </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>
    <!-- LIST Header & buttons -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(records) }}</span>
      <div class="float-end">
      </div>
    </div>
    <!-- TABLE  Area-->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:12%" />
        <col style="width:10%" />
        <col style="width:10%" />
        <col />
        <col style="width:12%" />
        <col style="width:15%" />
        <col style="width:10%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">{{ $t('sdl.privacyPolicy.part') }}</th>
          <th scope="col">{{ $t('sdl.common.label.status') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.docName') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.docTitle') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.reporter') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.submitDate') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.syncState') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="grid in gridList"
          :key="grid.approvalRequestId"
          @click="rowClick(grid.approvalRequestId)"
          class="cursor-pointer"
        >
          <td
            class="text-center"
            v-text="
              grid.approvalType === 'Internal'
                ? $t('sdl.approval.label.internalApproval')
                : $t('sdl.approval.label.knoxApproval')
            "
          ></td>
          <td class="text-center">
            <span v-if="grid.docApprovalStatusCode === 'SAVED'" class="badge ui--status-primary">{{
              $t('sdl.approval.docStatus.label.SAVED')
            }}</span>
            <span v-else-if="grid.docApprovalStatusCode === 'INPROCESS'" class="badge ui--status-processing">{{
              $t('sdl.approval.docStatus.label.INPROCESS')
            }}</span>
            <span v-else-if="grid.docApprovalStatusCode === 'CANCELLED'" class="badge ui--status-secondary">{{
              $t('sdl.approval.label.CANCELLED')
            }}</span>
            <span v-else-if="grid.docApprovalStatusCode === 'REJECTED'" class="badge ui--status-rejected">{{
              $t('sdl.approval.label.REJECTED')
            }}</span>
            <span v-else-if="grid.docApprovalStatusCode === 'COMPLETED'" class="badge ui--status-success">{{
              $t('sdl.approval.docStatus.label.COMPLETED')
            }}</span>
          </td>
          <td class="text-center">{{ grid.docType }}</td>
          <td>{{ $filters.cutString(grid.docTitle, 100) }}</td>
          <td>{{ grid.requesterName }}</td>
          <td class="text-center">{{ $filters.dateFormat(grid.firstRegDatetime, $t('data-format.datetime.ymdhms')) }}</td>
          <td
            class="text-center"
            v-text="!grid.approvalFault ? $t('sdl.common.label.success') : $t('sdl.common.label.fail')"
          ></td>
        </tr>
      </tbody>
    </table>
    <!-- // TABLE  Area-->
    <!-- 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 {
      gridList: [],
      docList: [],
      records: 0, // total number of data
      currentPage: 1, // current page number
      pageSize: 10, // Number of lists per page
      searchPeriod: {},
      searchParam: {
        syncStatus: '', // synchronization state
        requesterName: '', // a reporter
        docType: '',
        approvalStatus: '',
        approvalType: '',
      },
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : page initialization
     */
    init() {
      this.getDocList();
      const storeParams = this.getStoreParameter();
      if (storeParams) {
        this.searchPeriod.startDate = storeParams.startDate;
        this.searchPeriod.endDate = storeParams.endDate;
        this.searchParam.requesterName = storeParams.requesterName;
        this.searchParam.syncStatus = storeParams.syncStatus;
        this.searchParam.docType = storeParams.docType;
        this.searchParam.approvalStatus = storeParams.approvalStatus;
        this.searchParam.approvalType = storeParams.approvalType;

        this.onSearch(storeParams.pageIndex);
      } else {
        this.searchPeriod.startDate = DateUtil.subDate(1, 'M');
        this.searchPeriod.endDate = DateUtil.now();
        this.searchParam.requesterName = '';
        this.searchParam.syncStatus = '';
        this.searchParam.docType = '';
        this.searchParam.approvalStatus = '';
        this.searchParam.approvalType = '';
        this.onSearch();
      }
    },
    /**
     * param:
     * return: Array
     * exception:
     * Description : get doc list
     */
    getDocList() {
      axios
        .get(`${SDLUtil.API_URL}/approval/approval-doc-types`)
        .then(response => {
          this.docList = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description :open user search popup
     */
    openSearchUser() {
      if (this.searchParam.requesterName) {
        if (this.searchParam.requesterName.length < 2) {
          SDLUtil.alert('sdl.common.message.enterMoreThan2CharForSearchTerms');
          return;
        }
      }
      SDLUtil.openUserPopup({
        searchColumn: 'userName',
        searchTxt: this.searchParam.requesterName,
        rtnFunc: this.getUserList,
        knoxSearch: true,
        singleMode: true,
      });
    },
    /**
     * param: list -> array
     * return:
     * exception:
     * Description : return user search result
     */
    getUserList(list) {
      if (list.length > 0) {
        this.searchParam.requesterName = list[0].userName;
      }
    },
    /**
     * param: pageIndex -> int
     * return:
     * exception:
     * Description : search
     */
    onSearch(pageIndex = 1) {
      this.currentPage = pageIndex;
      // eslint-disable-next-line no-underscore-dangle
      const _searchPeriod = DateUtil.stdFormat(this.searchPeriod);
      let params = {
        ..._searchPeriod,
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        // orderBy: 'FIRST_REG_DATETIME DESC',
      };
      params = Object.assign(params, this.searchParam);
      this.setStoreParameter(params);
      // Loading bar execution
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/approval/approval-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(response => {
          this.gridList = response.data.rows;
          this.records = response.data.records;

          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : row click
     */
    rowClick(approvalRequestId) {
      this.$router.push({ path: `${this.$CONTEXT}/admin/approval/apprMgmtDtl/${approvalRequestId}` });
    },
  },
  created() {
    this.init();
  },
};
</script>

<style scoped></style>
