<!--
 Program: RoleFormPopup.vue
 Author: SDL
 Description: popup page for registering and modifying role information
-->
<template>
  <div class="modal-dialog modal-dialog-centered  modal-dialog-scrollable modal-lg">
    <div class="modal-content" style="height:404px;">
      <!-- contents -->
      <div class="modal-header">
        <h5 class="modal-title h4">{{ $t('sdl.role.label.roleReg') }}</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="$emit('close')"></button>
      </div>
      <div class="modal-body">
        <table class="table table-bordered ui--table-form ui--table-form-view mb-3">
          <colgroup>
            <col style="width:30%" />
            <col style="width:70%" />
          </colgroup>
          <tbody>
            <tr>
              <th scope="row">{{ $t('sdl.role.label.heading') }} <span class="ui--text-required">&#42;</span></th>
              <td>
                <input type="text" class="form-control" v-model.trim="roleItem.roleName" v-validation="" errorMessage="sdl.samsung.validate.required" />
              </td>
            </tr>
            <tr>
              <th scope="row">{{ $t('sdl.role.label.roleNameOt') }} <span class="ui--text-required">&#42;</span></th>
              <td>
                <input type="text" class="form-control" v-model.trim="roleItem.label" v-validation="" errorMessage="sdl.samsung.validate.required" />
              </td>
            </tr>
            <tr v-for="locale in $i18n.availableLocales" :key="locale">
              <th scope="row">{{ $t('sdl.role.label.roleName') }}({{ locale }})</th>
              <td>
                <input type="text" class="form-control" v-model.trim="roleItem.labelJson[locale]" />
              </td>
            </tr>
            <tr>
              <th scope="row">{{ $t('sdl.commonCode.label.description') }}</th>
              <td>
                <input type="text" class="form-control" v-model.trim="roleItem.description" />
              </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="saveRole">{{ $t('sdl.common.label.save') }}</button>
      </div>
      <!-- // contents -->
    </div>
  </div>
</template>

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

export default {
  data() {
    return {
      roleItem: {
        labelJson: {},
      },
      insertStatus: true,
    };
  },
  props: {
    roleId: {
      required: false,
      type: String,
    },
    rtnFunc: {
      type: Function,
    },
  },
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Query role information
     */
    getRoleInfo() {
      if (!this.insertStatus) {
        // Launch Loading bar
        SDLUtil.showLoadingBar(true);

        /**
         * Call role details lookup API
         */
        axios
          .get(`${SDLUtil.API_URL}/auth/roles/${this.roleId}`)
          .then(({ data }) => {
            this.roleItem = data;

            // Remove Loading bar
            SDLUtil.showLoadingBar(false);
          })
          .catch(err => {
            // Remove Loading bar
            SDLUtil.showLoadingBar(false);
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Save Role Information
     */
    async saveRole() {
      let chkFlag = false;

      const params = {
        ...this.roleItem,
      };

      // validation
      if (SDLUtil.onSubmitValidation()) return;

      if (this.insertStatus) {
        /**
         * Call Role Registration API
         */
        await axios
          .post(`${SDLUtil.API_URL}/auth/roles`, params, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              chkFlag = true;
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
          });
      } else {
        /**
         * Call role modification API
         */
        await axios
          .put(`${SDLUtil.API_URL}/auth/roles/${this.roleId}`, params, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              chkFlag = true;
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
          });
      }

      this.rtnFunc(chkFlag);
      this.$emit('close');
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Initialization
     */
    init() {
      this.roleItem = {
        labelJson: {},
      };
    },
  },
  created() {
    if (this.roleId !== '' && this.roleId !== undefined) {
      this.insertStatus = false;
      this.getRoleInfo();
    } else {
      this.init();
    }
  },
};
</script>
