<!--
Program: Approval Management Detail
Author: SDL
Description: Approval Management Detail
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="ui--view-container">
      <h5 class="mb-3">{{ $t('sdl.common.label.detailInfo') }}</h5>
      <table class="table table-bordered ui--table-form mb-4">
        <colgroup>
          <col style="width:15%" />
          <col style="width:35%" />
          <col style="width:15%" />
          <col style="width:35%" />
        </colgroup>
        <tbody>
          <tr>
            <th scope="row">
              {{ $t('sdl.approval.label.approvalId') }}
            </th>
            <td>{{ apprDoc.approvalRequestId }}</td>
            <th scope="row">{{ $t('sdl.approval.label.stronghold') }}</th>
            <td>{{ apprDoc.serverLocale }}</td>
          </tr>
          <tr>
            <th scope="row">
              {{ $t('sdl.approval.label.approvalStatus') }}
            </th>
            <td>
              <span v-if="apprDoc.docApprovalStatusCode === 'SAVED'" class="badge ui--status-primary">{{
                $t('sdl.approval.docStatus.label.SAVED')
              }}</span>
              <span v-else-if="apprDoc.docApprovalStatusCode === 'INPROCESS'" class="badge ui--status-processing">{{
                $t('sdl.approval.docStatus.label.INPROCESS')
              }}</span>
              <span v-else-if="apprDoc.docApprovalStatusCode === 'CANCELLED'" class="badge ui--status-processing">{{
                $t('sdl.approval.label.CANCELLED')
              }}</span>
              <span v-else-if="apprDoc.docApprovalStatusCode === 'REJECTED'" class="badge ui--status-rejected">{{
                $t('sdl.approval.label.REJECTED')
              }}</span>
              <span v-else-if="apprDoc.docApprovalStatusCode === 'COMPLETED'" class="badge ui--status-success">{{
                $t('sdl.approval.docStatus.label.COMPLETED')
              }}</span>
            </td>
            <th scope="row">{{ $t('sdl.approval.label.syncState') }}</th>
            <td v-text="!apprDoc.approvalFault ? $t('sdl.common.label.success') : $t('sdl.common.label.fail')"></td>
          </tr>
          <tr>
            <th scope="row">
              {{ $t('sdl.approval.label.docId') }}
            </th>
            <td>{{ apprDoc.dbDocId }}</td>
            <th scope="row">{{ $t('sdl.approval.label.docType') }}</th>
            <td>{{ apprDoc.docType }}</td>
          </tr>
          <tr>
            <th scope="row">
              {{ $t('sdl.approval.label.docTitle') }}
            </th>
            <td>{{ apprDoc.docTitle }}</td>
            <th scope="row">{{ $t('sdl.approval.label.requester') }}</th>
            <td>{{ apprDoc.requesterName }}</td>
          </tr>
        </tbody>
      </table>

      <div class="ui--list-heading clearfix">
        <div class="float-start">
          <button type="button" class="btn btn-checkbox" @click="apprPathShow = !apprPathShow">
            <span v-show="apprPathShow"
              >{{ $t('sdl.approval.label.hideApprovalPath') }} <i class="bi bi-chevron-up"></i></span
            >
            <span v-show="!apprPathShow"
              >{{ $t('sdl.approval.label.showApprovalPath') }} <i class="bi bi-chevron-down"></i></span
            ></button
          ><!-- keyboard_arrow_down -->
        </div>
      </div>
      <!-- TABLE  Area-->

      <table class="table table-bordered ui--table" v-show="apprPathShow">
        <colgroup>
          <col style="width:5%" />
          <col style="width:10%" />
          <col style="width:20%" />
          <col style="width:20%" />
          <col />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">{{ $t('sdl.approval.label.no') }}</th>
            <th scope="col">{{ $t('sdl.common.label.type') }}</th>
            <th scope="col">{{ $t('sdl.common.label.name') }}</th>
            <th scope="col">{{ $t('sdl.common.label.confirmTime') }}</th>
            <th scope="col">{{ $t('sdl.department.label.departmentName') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(path, idx) in pathList" :key="idx">
            <td class="text-center" :rowspan="path.subflag ? '2' : '1'" v-if="path.showflag">
              {{ path.approvalStepSequence }}
            </td>
            <td
              class="text-center"
              :rowspan="path.subflag ? '2' : '1'"
              v-if="path.showflag"
              :class="[
                {
                  'bg-apv-request':
                    path.approvalStepType === 'DRAFTING' ||
                    path.approvalStepType === 'PARALLEL_AGREEMENT' ||
                    path.approvalStepType === 'PARALLEL_APPROVAL',
                },
                { 'bg-apv-approve': path.approvalStepType === 'APPROVAL' },
                { 'bg-apv-agreement': path.approvalStepType === 'AGREEMENT' },
                { 'bg-apv-notice': path.approvalStepType === 'NOTIFICATION' },
                { 'bg-apv-after': path.approvalStepType === 'EX_POST_APPROVAL' },
              ]"
            >
              {{ replaceApprovalCodeToLabel(path.approvalStepType) }}
            </td>
            <td v-if="path.showflag">{{ path.approvalPersonName }}</td>
            <td class="text-center" v-if="path.showflag && path.approvalStepType === 'DRAFTING'">
              {{ $filters.dateFormat(path.approvalStepFromDatetime, $t('data-format.datetime.ymdhms')) }}
            </td>
            <td class="text-center" v-else-if="path.showflag && path.finishDate">
              {{ $filters.dateFormat(path.finishDate, $t('data-format.datetime.ymdhms')) }}
            </td>
            <td class="text-center" v-else-if="path.showflag && path.approvalStepType === 'NOTIFICATION'">
              {{ $t('sdl.approval.message.unsend') }}
            </td>
            <td class="text-center" v-else-if="path.showflag">
              {{ $t('sdl.approval.label.WAITING') }}
            </td>
            <td v-if="path.showflag">{{ path.approvalPersonDeptName }}</td>
            <td v-if="!path.showflag" colspan="3">{{ path.comment }}</td>
          </tr>
        </tbody>
      </table>

      <h5 class="mb-3" v-show="!apprDoc.internalApproval">{{ $t('sdl.approval.label.approvalSyncFailHistory') }}</h5>
      <table class="table table-bordered ui--table" v-show="!apprDoc.internalApproval">
        <colgroup>
          <col style="width:10%" />
          <col />
          <col style="width:20%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">{{ $t('sdl.approval.label.eventCode') }}</th>
            <th scope="col">{{ $t('sdl.approval.label.eventMessage') }}</th>
            <th scope="col">{{ $t('sdl.approval.label.occuDate') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(failHistory, idx) in apprDoc.approvalEventList" :key="idx">
            <td class="text-center">{{ failHistory.eventCode }}</td>
            <td class="text-left">
              {{ failHistory.eventMessage }}
            </td>
            <td class="text-center">
              {{ $filters.dateFormat(failHistory.firstRegDatetime, $t('data-format.datetime.ymdhms')) }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <hr class="mb-4" />
    <div class="ui--button-container">
      <button class="btn btn-secondary btn-lg" type="button" @click="goBackToList">
        {{ $t('sdl.common.label.list') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="button" @click="onSync" v-show="!apprDoc.internalApproval">
        {{ $t('sdl.approval.label.sync') }}
      </button>
    </div>
    <sdl-approvalpath v-show="false" ref="approvalPath" :approvalStepList="approvalStepList" />
    <!--//Contents Area -->
  </div>
</template>

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

export default {
  data() {
    return {
      apprPathShow: true,
      pathList: [],
      apprDoc: {},
      approvalStepList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : page initialization
     */
    init() {
      this.loadApprDoc();
      this.getApprovalPath();
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Change approval code to label
     */
    replaceApprovalCodeToLabel(code) {
      const { approvalPathStatus } = this.$refs.approvalPath;
      const list = approvalPathStatus.filter(s => s.code === code);
      if (list.length > 0) {
        return SDLUtil.getMsgProp(list[0].label);
      }
      return code;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : approval synchronization
     */
    onSync() {
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/approval/sync/approval-documents/${this.$route.params.approvalRequestId}`)
        .then(response => {
          console.log(response.data);
          if (response.data) {
            SDLUtil.alert('sdl.approval.message.syncCompleted');
          } else {
            SDLUtil.alert('sdl.approval.message.nochange');
          }

          this.loadApprDoc();

          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Approval Path Using Approval Number
     */
    getApprovalPath() {
      // show Loading bar
      SDLUtil.showLoadingBar(true);
      axios
        .get(
          `${SDLUtil.API_URL}/approval/approval-steps/approval-request-id?approvalRequestId=${this.$route.params.approvalRequestId}`,
        )
        .then(response => {
          const r = response.data;
          Object.keys(r).forEach(i => {
            if (r[i].originPersonId) {
              this.pathList.push({ ...r[i], subflag: true, showflag: true });
            } else {
              this.pathList.push({ ...r[i], subflag: false, showflag: true });
            }

            if (r[i].originPersonId) {
              this.pathList.push({
                subflag: false,
                showflag: false,
                comment: `[${this.$t('sdl.offsider.label.agencyAppr')}]${r[i].originPersonName}/${
                  r[i].originPersonPositionName
                }/${r[i].originPersonDeptName}/${r[i].originPersonCompanyName} → ${r[i].approvalPersonName}/${
                  r[i].approvalPersonPositionName
                }/${r[i].approvalPersonDeptName}/${r[i].approvalPersonCompanyName}`,
              });
            }
          });
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Detailed Approval Document
     */
    loadApprDoc() {
      // show Loading bar
      SDLUtil.showLoadingBar(true);
      const { approvalRequestId } = this.$route.params;
      axios
        .get(`${SDLUtil.API_URL}/approval/${approvalRequestId}`)
        .then(response => {
          this.apprDoc = response.data;

          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
        });
    },
  },
  created() {
    this.init();
  },
};
</script>

<style scoped></style>
