<!--
Program: Approval Sample edit
Author: SDL
Description: Approval Sample edit
-->
<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"
            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"
            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="true"
          useExtList="zip|pdf|png"
          :multiFileNm="apprDoc.title"
        ></sdl-fileuploader>
        <!-- //upload -->
      </form>
    </div>

    <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="onBeforeCancel" v-authorization="['update']">
        {{ $t('sdl.common.label.cancel') }}
      </button>
      <button class="btn btn-primary btn-lg" type="button" @click="onBeforeSave" v-authorization="['update']">
        {{ $t('sdl.common.label.save') }}
      </button>
    </div>

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

<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil } from '@/utils';
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 : File upload and run
     */
    // eslint-disable-next-line no-unused-vars
    rtnUploadList(downloadType, fileList) {
      this.attachments = fileList.map(file => ({ ...file }));
      this.onSave();
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Run before editing
     */
    onBeforeSave() {
      if (SDLUtil.onSubmitValidation()) return;

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        onOkEvt: () => {
          SDLUtil.showLoadingBar(true, { msg: 'sdl.common.message.uploading' });
          this.$refs.uploader.onUpload(this.apprDoc.docId);
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : save
     */
    onSave() {
      const param = {
        ...this.apprDoc,
        attachments: this.attachments,
      };

      axios
        .put(`${SDLUtil.API_URL}/sample/approval/knox/sample-documents/${this.apprDoc.docId}`, param)
        .then(() => {
          // Loading bar hidden
          SDLUtil.showLoadingBar(false);

          this.$router.push({
            path: `${SDLUtil.WEB_CONTEXT_PATH}/admin/sample/approval/knox/apprSampleWrite/${this.apprDoc.docId}`,
          });
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Run before saving
     */
    onBeforeCancel() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doCancel',
        title: 'sdl.common.label.cancel',
        onOkEvt: () => {
          this.$router.push({ path: `${this.$CONTEXT}/admin/sample/approval/knox/apprSampleWrite/${this.apprDoc.docId}` });
        },
      });
    },
    /**
     * 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.attachments.splice(0); // delete all
          for (let i = 0; i < response.data.attachments.length; i += 1) {
            this.attachments.push(response.data.attachments[i]);
          }

          // Only the download for approval is wrong so it is used as follows. General use default
          this.$refs.uploader.init(this.apprDoc.docId);

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

<style scoped></style>
