<!--
Program: Approval Sample registration
Author: SDL
Description: Approval Sample registration
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="ui--form-container" v-show="apprDoc.docStatus === '' || apprDoc.docStatus === 'SAVED'">
      <h4 class="mb-3">{{ $t('sdl.approval.label.apprReq') }}</h4>
      <form name="approvalSample" class="needs-validation" novalidate="" @submit.prevent>
        <div class="mb-2" style="position:relative;">
          <label for="title">{{ $t('sdl.approval.label.title') }} <span class="ui--text-required">&#42;</span></label>
          <input
            id="title"
            type="text"
            class="form-control"
            v-model="apprDoc.title"
            :readonly="apprDoc.docStatus !== ''"
            v-validation=""
            errorMessage="sdl.samsung.validate.required"
          />
        </div>

        <!--
        <div class="form-control" style="overflow:scroll; height:250px;max-height:250px" contenteditable="true">
        </div>
        -->
        <div class="mb-2">
          <textarea
            style="width:100%; overflow:scroll; height:250px;max-height:250px"
            class="form-control"
            v-model="apprDoc.contents"
            :readonly="apprDoc.docStatus !== ''"
            v-validation=""
            errorMessage="sdl.samsung.validate.required"
          ></textarea>
        </div>
        <hr class="mb-4" />

        <h4 class="mb-3">{{ $t('sdl.common.label.attachments') }}</h4>
        <!-- upload -->
        <sdl-fileuploader
          ref="uploader"
          :fileList="attachments"
          @complete="rtnUploadList"
          downloadType="A"
          :maxTotalSize="1073741824"
          :modifyFlag="modifyFlag"
          useExtList="zip|pdf|png"
          :multiFileNm="apprDoc.title"
        ></sdl-fileuploader>
        <!-- //upload -->

        <div v-show="apprDoc.docStatus === 'SAVED'">
          <h4 class="mb-3">{{ $t('sdl.approval.label.addApprovalPerson') }}</h4>
          <sdl-approvalpath
            ref="approvalPath"
            :approvalStepList="approvalStepList"
            :showRequired="apprDoc.existRequiredApprovalUser"
            :requiredApprovalUserList="apprDoc.requiredApprovalUserList"
            :internalFlag="false"
          />
        </div>
      </form>
    </div>
    <div class="ui--view-container" v-show="apprDoc.docStatus !== '' && apprDoc.docStatus !== 'SAVED'">
      <h4 class="mb-3">[{{ replaceApprovalStatusToLabel(apprDoc.docStatus) }}] {{ apprDoc.title }}</h4>
      <div class="ui--view-heading d-flex mb-3">
        <span
          >{{ $t('sdl.approval.label.requester') }} : {{ apprDocCreater.approvalPersonName }}
          {{ apprDocCreater.approvalPersonPositionName }}/{{ apprDocCreater.approvalPersonDeptName }} /{{
            apprDocCreater.approvalPersonCompanyName
          }}</span
        >
        <div class="ms-auto">
          {{ $t('sdl.approval.label.approvalId') }} :<span class="ms-1">{{ apprDoc.docId }}</span>
        </div>
      </div>
      <!-- LIST Header & buttons -->
      <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 class="float-end text-danger">{{ $t('sdl.approval.message.notice') }}</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.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) }}
            </td>
            <td v-if="path.showflag">{{ path.approvalPersonName }} / {{ path.approvalPersonPositionName }}</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'">
              미발송
            </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>
      <sdl-fileuploader
        ref="downloader"
        :fileList="attachments"
        downloadType="A"
        :modifyFlag="false"
        :multiFileNm="apprDoc.title"
        v-show="attachments.length > 0"
      ></sdl-fileuploader>
      <article class="viewer-1" v-html="$filters.nl2br(apprDoc.contents)"></article>
    </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" v-if="apprDoc.docStatus === 'SAVED'" @click="onPreview">
        {{ $t('sdl.board.label.preView') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="button" v-if="apprDoc.docStatus === 'SAVED'" @click="onDelete">
        {{ $t('sdl.common.label.delete') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="button" v-if="apprDoc.docStatus === 'SAVED'" @click="onEdit">
        {{ $t('sdl.common.label.edit') }}
      </button>
      <button class="btn btn-primary btn-lg" type="button" v-if="apprDoc.docStatus === ''" @click="onBeforeSave">
        {{ $t('sdl.common.label.save') }}
      </button>
      <button
        class="btn btn-primary btn-lg"
        type="button"
        v-if="apprDoc.docStatus === 'SAVED'"
        @click="onBeforeApproval"
      >
        {{ $t('sdl.common.label.submit') }}
      </button>
    </div>

    <!--//Contents Area -->
  </div>
</template>

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

export default {
  data() {
    return {
      modifyFlag: true,
      pathList: [],
      apprDoc: {
        docId: '',
        contents: '',
        title: '',
        docStatus: '',
        existRequiredApprovalUser: false,
        // attachments: [],
      },
      attachments: [],
      approvalStepList: [],
      apprPathShow: true,
      apprDocCreater: {},
      apprType: _.replace(this.$route.path, `${this.$CONTEXT}/`, '').split('/')[2],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : page initialization
     */
    init() {
      if (this.$route.params.docId || this.apprDoc.docId) {
        this.loadApprDoc();
      }
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Change approval code to label
     */
    replaceApprovalCodeToLabel(path) {
      const { approvalPathStatus } = this.$refs.approvalPath;
      const list = approvalPathStatus.filter(s => s.code === path.approvalStepType);
      if (list.length > 0) {
        if (path.approvalStepType === 'APPROVAL' && path.approvalStatus === '1') {
          return SDLUtil.getMsgProp('sdl.approval.label.APPROVED');
        }
        return SDLUtil.getMsgProp(list[0].label);
      }
      return path.approvalStepType;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Change approval status code to label
     */
    replaceApprovalStatusToLabel(code) {
      const approvalStatus = [
        { code: 'SAVED', label: 'sdl.approval.docStatus.label.SAVED' },
        { code: 'INPROCESS', label: 'sdl.approval.docStatus.label.INPROCESS' },
        { code: 'CANCEL', label: 'sdl.approval.label.CANCELLED' },
        { code: 'REJECT', label: 'sdl.approval.label.REJECTED' },
        { code: 'COMPLETE', label: 'sdl.approval.docStatus.label.COMPLETED' },
        { code: 'CANCELLED', label: 'sdl.approval.label.CANCELLED' },
      ];
      const list = approvalStatus.filter(s => s.code === code);
      if (list.length > 0) {
        return SDLUtil.getMsgProp(list[0].label);
      }
      return code;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : File upload and run
     */
    // eslint-disable-next-line no-unused-vars
    rtnUploadList(downloadType, fileList) {
      SDLUtil.showLoadingBar(false);
      this.$router.replace({
        path: `${SDLUtil.WEB_CONTEXT_PATH}/admin/sample/approval/knox/apprSampleWrite/${this.apprDoc.docId}`,
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Run before saving
     */
    onBeforeSave() {
      if (SDLUtil.onSubmitValidation()) return;

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        onOkEvt: () => {
          this.onSave();
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : save
     */
    onSave() {
      const param = {
        ...this.apprDoc,
      };
      const formData = new FormData();

      Object.keys(param).forEach(val => {
        formData.append(val, param[val]);
      });

      const apiUrl = `${SDLUtil.API_URL}/sample/approval/knox/sample-documents`;
      SDLUtil.showLoadingBar(true, { msg: 'sdl.common.message.uploading' });
      axios
        .post(apiUrl, formData)
        .then(response => {
          // console.log(response);
          this.apprDoc = response.data;
          // In case of approval, the file is uploaded after saving because the downloadType is docId. (General payment uses default)
          this.$refs.uploader.onUpload(this.apprDoc.docId);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Run
     */
    onEdit() {
      this.$router.push({
        path: `${SDLUtil.WEB_CONTEXT_PATH}/admin/sample/approval/knox/apprSampleEdit/${this.apprDoc.docId}`,
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : delete
     */
    onDelete() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doDelete',
        title: 'sdl.common.label.delete',
        onOkEvt: () => {
          SDLUtil.showLoadingBar(true);
          axios
            .delete(`${SDLUtil.API_URL}/sample/approval/knox/sample-documents/${this.apprDoc.docId}`)
            .then(() => {
              this.goBackToList();
              // Loading bar hidden
              SDLUtil.showLoadingBar(false);
            })
            .catch(error => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(error);
              console.log(error);
            });
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Approval Path Using Document Number
     */
    getApprovalPath() {
      // show Loading bar
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/approval/approval-steps/doc-id?docId=${this.$route.params.docId}`)
        .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}`,
              });
            }
          });
          // eslint-disable-next-line prefer-destructuring
          this.apprDocCreater = this.pathList[0];
          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Retrieving Detailed Approval Documents
     */
    loadApprDoc() {
      // show Loading bar
      SDLUtil.showLoadingBar(true);
      const docId = this.$route.params.docId || this.apprDoc.docId;
      const apiUrl = `${SDLUtil.API_URL}/sample/approval/knox/sample-documents/${docId}`;
      axios
        .get(apiUrl)
        .then(response => {
          this.apprDoc = response.data;
          this.modifyFlag = false; // change attachment readonly

          this.attachments.splice(0); // delete all
          for (let i = 0; i < response.data.attachments.length; i += 1) {
            this.attachments.push(response.data.attachments[i]);
          }

          if (this.apprDoc.docStatus !== 'SAVED') {
            // If it is not in the writing state
            this.getApprovalPath();
            // Only the download for approval is wrong so it is used as follows. General use default
            this.$refs.downloader.init(this.apprDoc.docId);
          } else {
            // Only the download for approval is wrong so it is used as follows. General use default
            this.$refs.uploader.init(this.apprDoc.docId);

            // Set drafter if you are writing
            const userInfo = SDLUtil.getLoginedUserInfo();
            // console.log('userInfo:', userInfo);
            this.approvalStepList.splice(0); // delete all
            // When testing, if the drafter does not have a stage knox ID, there is an error even if it does not match the actual token.
            this.approvalStepList.push({
              approvalPersonId: userInfo.userId,
              approvalPersonName: userInfo.userName,
              approvalStepType: 'DRAFTING',
              approvalStepSequence: 0,
              approvalPersonCompanyName: userInfo.compName,
              approvalPersonDeptName: userInfo.deptName,
              approvalPersonPositionName: userInfo.grdName,
              parallelProcess: false,
              arbitrary: false,
              routemodify: false,
              bodymodify: false,
            });

            // Add the list in the balance sheet
            const { dynamicApprovalUserList } = this.apprDoc;
            for (let i = 0; i < dynamicApprovalUserList.length; i += 1) {
              this.approvalStepList.push({
                approvalPersonId: dynamicApprovalUserList[i].userId,
                approvalPersonName: dynamicApprovalUserList[i].userName,
                approvalStepType: dynamicApprovalUserList[i].approvalStepType,
                approvalStepSequence: i + 1,
                approvalPersonCompanyName: dynamicApprovalUserList[i].user.compName,
                approvalPersonDeptName: dynamicApprovalUserList[i].user.deptName,
                approvalPersonPositionName: dynamicApprovalUserList[i].user.grdName,
                parallelProcess: !!(
                  dynamicApprovalUserList[i].approvalStepType === 'PARALLEL_APPROVAL'
                  || dynamicApprovalUserList[i].approvalStepType === 'PARALLEL_AGREEMENT'
                ),
                arbitrary: false,
                routemodify: false,
                bodymodify: false,
                apprPathFlag: true,
                docType: dynamicApprovalUserList[i].docType,
                approverChangeAllowed: false,
              });
            }
            this.$refs.approvalPath.init();
          }
          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Click the report button
     */
    onBeforeApproval() {
      if (this.$refs.approvalPath.getApprovalList().length <= 1) {
        SDLUtil.alert('sdl.approval.message.checkApproveUser');
        return;
      }

      if (this.apprDoc.existRequiredApprovalUser) {
        let existRequired = false;
        for (let user of this.$refs.approvalPath.getApprovalList()) {
          existRequired = this.apprDoc.requiredApprovalUserList.some(requiredUser => requiredUser.userId === user.approvalPersonId);
          if (existRequired) break;
        }
        if (!existRequired) {
          SDLUtil.alert('sdl.approval.message.selectRequiredApprovalUser');
          return;
        }
      }

      SDLUtil.confirm({
        msg: 'sdl.approval.docStatus.message.APPROVAL',
        title: 'sdl.common.label.save',
        onOkEvt: () => {
          this.onApproval();
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : approval
     */
    onApproval() {
      const param = {
        docId: this.apprDoc.docId,
        comment: '',
        approvalStepList: this.$refs.approvalPath.getApprovalList(),
      };
      const apprApi = `${SDLUtil.API_URL}/sample/approval/knox/submit/sample-document`;
      SDLUtil.showLoadingBar(true);
      axios
        .post(apprApi, param)
        .then(response => {
          console.log(response);
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
          this.$router.push({ path: `${this.$CONTEXT}/admin/sample/approval/knox/apprSampleList` });
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          console.log(err.data.error.message);
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : preview
     */
    onPreview() {
      SDLUtil.show(
        ApprPreviewPopup,
        {
          docId: this.apprDoc.docId,
        },
        {
          width: '900px',
          height: 'auto',
        },
      );
    },
  },
  created() {
    this.init();
  },
};
</script>

<style scoped></style>
