<!--
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">
        <div class="row">
          <label class="col-2 col-form-label text-end">{{
            $t('sdl.approval.label.documentType')
          }}</label>
          <div class="col-3">
            <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.description }}</option>
            </select>
          </div>
          <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.period') }}</label>
          <div class="col-5 form-inline">
            <!-- 기간 -->
            <sdl-datepicker
              v-model="searchPeriod"
              :period="searchPeriod"
              :wrap-class="'wd150'"
            ></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>
    <!-- TABLE  Area-->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:10%" />
        <col style="width:12%" />
        <col />
        <col style="width:12%" />
        <col style="width:12%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">{{ $t('sdl.common.label.status') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.documentType') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.docTitle') }}</th>
          <th scope="col">{{ $t('sdl.approval.label.reporter') }}</th>
          <th scope="col" v-if="listType === 'submit'">{{ $t('sdl.approval.label.submitDate') }}</th>
          <th scope="col" v-if="listType === 'approved'">{{ $t('sdl.approval.label.approvalDate') }}</th>
          <th scope="col" v-if="listType === 'notice' || listType === 'notapprove'">
            {{ $t('sdl.approval.label.arrivalDate') }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="grid in gridList"
          :key="grid.approvalRequestId"
          @click="rowClick(grid.approvalRequestId)"
          class="cursor-pointer"
        >
          <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 class="text-left">{{ $filters.cutString(grid.docTitle, 100) }}</td>
          <td class="text-center">{{ grid.requesterName }}</td>
          <td class="text-center" v-if="listType === 'submit'">
            {{ $filters.dateFormat(grid.draftDatetime, $t('data-format.datetime.ymdhms')) }}
          </td>
          <td class="text-center" v-if="listType === 'approved'">
            {{ $filters.dateFormat(grid.finishDate, $t('data-format.datetime.ymdhms')) }}
          </td>
          <td class="text-center" v-if="listType === 'notice' || listType === 'notapprove'">
            {{ $filters.dateFormat(grid.approvalStepFromDatetime, $t('data-format.datetime.ymdhms')) }}
          </td>
        </tr>
      </tbody>
    </table>
    <!-- // TABLE  Area-->
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="currentPage"
      :total-rows="records"
      :per-page="pageSize"
      @change="onSearch"
      text-align="center"
    />
    <!--  // Pagination Area-->
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
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: {
        docType: '',
      },
      listType: '',
    };
  },
  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.docType = storeParams.docType;

        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.filter(doc => doc.internalApproval);
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 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,
      };
      params = Object.assign(params, this.searchParam);
      this.setStoreParameter(params);

      // eslint-disable-next-line prefer-destructuring
      this.listType = _.replace(this.$router.currentRoute.value.path, `${this.$CONTEXT}/`, '').split('/')[3];

      let listApi = '';
      if (this.listType === 'submit') {
        listApi = '/approval/internal-approvals/submit';
      } else if (this.listType === 'notice') {
        listApi = '/approval/internal-approvals/notice';
      } else if (this.listType === 'approved') {
        listApi = '/approval/internal-approvals/approved';
      } else if (this.listType === 'notapprove') {
        listApi = '/approval/internal-approvals/not-approve';
      }
      // Loading bar execution
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}${listApi}?${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/mypage/approval/${this.listType}/detail/${approvalRequestId}`,
      });
    },
  },
  created() {
    // this.init();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.init();
    });
  },
};
</script>

<style scoped></style>
