<!--
  Program: Entrust approval
  Author: SDL
  Brief: Entrust approval popup
-->
<template>
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
    <div class="modal-content" style="height: 530px">
      <div class="modal-header">
        <h5 class="modal-title">{{ $t('sdl.approval.label.delegateApproval') }}</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="$emit('close')"></button>
      </div>
      <div class="modal-body">
        <!-- 대리결재자 정보 -->
        <div class="mb-4 alert alert-info" v-if="curDelegatorUser.delegatorId">
          <h6>
            <strong>{{ $t('sdl.approval.label.delegateApprovalUser') }}</strong>
            <button class="float-end ui--btn-icon-sm btn-close" :title="$t('sdl.approval.label.delDelegateApprovalUser')" @click="onBeforeDelete"></button>
          </h6>
          {{ curDelegatorUser.delegatorName }}/{{ curDelegatorUser.delegatorPositionName }}/{{ curDelegatorUser.delegatorDeptName }}/{{ curDelegatorUser.delegatorCompanyName }}<br />
          {{ $t('sdl.common.label.period') }} : {{ $filters.dateFormat(curDelegatorUser.startDate) }} ~
          {{ $filters.dateFormat(curDelegatorUser.endDate) }}
        </div>
        <!-- //대리결재자 정보 -->
        <h5 class="mb-3">{{ $t('sdl.approval.label.addDelegateApprovalUser') }}</h5>
        <table class="table table-bordered ui--table-form ui--table-form-view">
          <colgroup>
            <col style="width: 20%" />
            <col style="width: 80%" />
          </colgroup>
          <tbody>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.approval.label.approver') }}<span class="ui--text-required">*</span></th>
              <td>
                <div class="input-group input-date-in">
                  <input
                    type="text"
                    class="form-control"
                    :placeholder="$t('sdl.user.label.userName')"
                    v-model="delegatorUser.userName"
                    @keyup.esc="delegatorUser.userName = ''"
                    @keyup.enter.stop="openSearchUser"
                    v-validation=""
                    errorMessage="sdl.samsung.validate.required"
                  />
                  <button class="btn btn-outline-secondary" type="button" @click="openSearchUser">
                    <i class="bi bi-search"></i>
                  </button>
                </div>
              </td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.period') }}<span class="ui--text-required">*</span></th>
              <td>
                <sdl-datepicker v-model="searchPeriod" :period="searchPeriod" :wrap-class="'input-date-in'"></sdl-datepicker>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="$emit('close')">
          {{ $t('sdl.common.label.cancel') }}
        </button>
        <button type="button" class="btn btn-primary" @click="delegateApproval">
          {{ $t('sdl.common.label.save') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import SDLUtil from '@/utils/SDLUtil';
import DateUtil from '@/utils/DateUtil';

export default {
  props: {},
  data() {
    return {
      delegatorUser: {},
      searchPeriod: {},
      curDelegatorUser: {},
    };
  },
  methods: {
    openSearchUser() {
      if (this.delegatorUser.userName) {
        if (this.delegatorUser.userName.length < 2) {
          SDLUtil.alert('sdl.common.message.enterMoreThan2CharForSearchTerms');
          return;
        }
      }
      SDLUtil.openUserPopup({
        searchColumn: 'userName',
        searchTxt: this.delegatorUser.userName,
        singleMode: true,
        rtnFunc: this.getUserList,
        knoxSearch: true,
      });
    },
    // user search
    getUserList(list) {
      if (list.length > 0) {
        // eslint-disable-next-line prefer-destructuring
        this.delegatorUser = list[0];
      }
    },
    /**
     * param:
     * return:
     * exception:
     * Description : event before Delete
     */
    onBeforeDelete() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doDelete',
        title: 'sdl.common.label.delete',
        onOkEvt: () => {
          this.onDelete();
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : delete
     */
    onDelete() {
      SDLUtil.showLoadingBar(true);
      axios
        .delete(`${SDLUtil.API_URL}/approval/approver-delegate`)
        .then(() => {
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
          this.curDelegatorUser = {};
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : event before Saving
     */
    delegateApproval() {
      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() {
      SDLUtil.showLoadingBar(true);
      const param = {
        delegatorId: this.delegatorUser.userId,
        endDate: DateUtil.stdFormat(this.searchPeriod.endDate),
        startDate: DateUtil.stdFormat(this.searchPeriod.startDate),
        userId: SDLUtil.getLoginedUserInfo().userId,
      };
      axios
        .post(`${SDLUtil.API_URL}/approval/approver-delegate`, param)
        .then(() => {
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
          this.$emit('close');
        })
        .catch(error => {
          console.log(error);
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : get Delegator Approval
     */
    getDelegatorApproval() {
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/approval/approver-delegate`)
        .then(response => {
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
          this.curDelegatorUser = response.data;
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });
    },
  },
  created() {
    this.getDelegatorApproval();
    this.searchPeriod.startDate = DateUtil.now();
    this.searchPeriod.endDate = DateUtil.addDate(1, 'w');
  },
};
</script>
<style scoped>
.vdp-datepicker__calendar {
  position: fixed !important;
  z-index: 100;
  background: #fff;
  width: 300px;
  border: 1px solid #ccc;
}
.v--modal-overlay .v--modal-box {
  overflow: visible;
}
.modal-dialog-scrollable .modal-content {
  overflow: visible;
}
</style>
