<!--
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>
      <div v-html="apprDoc.lobDetail"></div>

      <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-->
      <sdl-fileuploader
        ref="downloader"
        :fileList="apprDoc.attachmentList"
        downloadType="A"
        :modifyFlag="false"
        :multiFileNm="apprDoc.docTitle"
        v-show="apprDoc.attachmentList.length > 0"
      ></sdl-fileuploader>
      <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.privacyPolicy.part') }}</th>
            <th scope="col">{{ $t('sdl.user.label.userName') }}</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>
    </div>

    <hr class="mb-4" />
    <div class="ui--button-container">
      <!-- 상신취소 -->
      <button
        class="btn btn-secondary btn-lg"
        type="button"
        @click="onComment('CANCELLED')"
        v-show="listType === 'submit' && apprDoc.approvalDocStatus === 'INPROCESS'"
      >
        {{ $t('sdl.approval.docStatus.label.CANCELLED') }}
      </button>
      <!-- 승인/합의 -->
      <button
        class="btn btn-secondary btn-lg"
        type="button"
        @click="onComment('CONFIRM')"
        v-show="listType === 'notapprove'"
      >
        {{ $t('sdl.approval.label.APPROVED') }}/{{ $t('sdl.approval.label.AGREEMENT') }}
      </button>
      <!-- 반려 -->
      <button
        class="btn btn-secondary btn-lg"
        type="button"
        @click="onComment('REJECTED')"
        v-show="listType === 'notapprove'"
      >
        {{ $t('sdl.approval.docStatus.label.REJECTED') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="button" @click="goBackToList">
        {{ $t('sdl.common.label.list') }}
      </button>
    </div>
    <!--//Contents Area -->
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import CommentPopup from './popup/CommentPopup.vue';

export default {
  data() {
    return {
      apprPathShow: true,
      apprDoc: { approvalStepList: [], attachmentList: [] },
      listType: '',
      myApprType: '',
      pathList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : page initialization
     */
    init() {
      this.loadApprDoc();
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Change approval code to label
     */
    replaceApprovalCodeToLabel(code) {
      const approvalPathStatus = [
        { code: 'DRAFTING', label: 'sdl.approval.label.REQUEST' },
        { code: 'APPROVAL', label: 'sdl.approval.label.APPROVE' },
        { code: 'CANCEL', label: 'sdl.approval.label.CANCELLED' },
        { code: 'AGREEMENT', label: 'sdl.approval.label.AGREEMENT' },
        { code: 'NOTIFICATION', label: 'sdl.approval.label.NOTIFY' },
        { code: 'EX_POST_APPROVAL', label: 'sdl.approval.label.SKIP' },
        { code: 'PARALLEL_AGREEMENT', label: 'sdl.approval.label.PARALLEL_AGREEMENT' },
        { code: 'PARALLEL_APPROVAL', label: 'sdl.approval.label.PARALLEL_APPROVE' },
        { code: 'REJECT', label: 'sdl.approval.label.REJECTED' },
      ];
      const list = approvalPathStatus.filter(s => s.code === code);
      if (list.length > 0) {
        return SDLUtil.getMsgProp(list[0].label);
      }
      return code;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : show comment popup Approval
     */
    onComment(commentType) {
      SDLUtil.show(
        CommentPopup,
        {
          apprDoc: this.apprDoc,
          commentType,
          execFunc: () => {
            if (this.listType === 'notapprove') {
              this.goBackToList();
            } else {
              this.loadApprDoc();
            }
          },
        },
        {
          width: '500px',
          height: 'auto',
        },
      );
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Approval Path Using Approval Number
     */
    getApprovalPath() {
      // show Loading bar
      this.pathList = [];
      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);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Detailed Approval Document
     */
    loadApprDoc() {
      // eslint-disable-next-line prefer-destructuring
      this.listType = _.replace(this.$route.path, `${this.$CONTEXT}/`, '').split('/')[3];
      // show Loading bar
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/approval/internal-approvals/${this.$route.params.approvalRequestId}`)
        .then(response => {
          this.apprDoc = response.data;
          this.getApprovalPath();
          this.$refs.downloader.init(this.apprDoc.userDocId);

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

<style scoped></style>
