<!--
  Program: RoleList.vue
  Author: SDL
  Description: Page to view, add, modify, delete, and download roles
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <!-- SEARCH Area -->
    <div class="ui--search-container clearfix">
      <div class="col-10 float-start">
        <div class="row">
          <div class="col">
            <div class="row">
              <label class="col-2 col-form-label text-end" style="min-width:100px;">{{
                $t('sdl.role.label.heading')
              }}</label>
              <div class="col-8">
                <input
                  type="text"
                  class="form-control"
                  v-model="searchParam.searchRoleName"
                  @keyup.enter="getRoleList()"
                  @keyup.esc="searchParam.searchRoleName = ''"
                />
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row">
              <label class="col-2 col-form-label text-end" style="min-width:100px;">{{
                $t('sdl.role.label.roleName')
              }}</label>
              <div class="col-8">
                <input
                  type="text"
                  class="form-control"
                  v-model="searchParam.searchLabel"
                  @keyup.enter="getRoleList()"
                  @keyup.esc="searchParam.searchLabel = ''"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- search button -->
      <div class="col-2 float-end text-end">
        <button class="btn btn-primary btn-search" type="submit" @click="getRoleList()">
          {{ $t('sdl.common.label.search') }}
        </button>
      </div>
    </div>
    <!-- SEARCH Area -->
    <!-- Total count & buttons -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(total) }}</span>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="deleteRoleBtn" v-authorization="'update'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addRoleBtn" v-authorization="'execute'">
          {{ $t('sdl.common.label.add') }}
        </button>
        <button
          type="button"
          class="btn btn-secondary btn-sm"
          @click="updateRoleBtn"
          v-authorization="['update', 'execute']"
        >
          {{ $t('sdl.common.label.edit') }}
        </button>
      </div>
    </div>
    <!-- Total count & buttons -->
    <!-- TABLE  Area-->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:3%" />
        <col style="width:12%" />
        <col style="width:12%" v-for="locale in $i18n.availableLocales" :key="locale"/>
        <col style="width:12%" />
        <col style="" />
        <col style="width:7%" />
        <col style="width:7%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">
            <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll" />
          </th>
          <th scope="col">{{ $t('sdl.role.label.heading') }}</th>
          <th scope="col">{{ $t('sdl.role.label.roleNameOt') }}</th>
          <th scope="col" v-for="(locale, index) in $i18n.availableLocales" :key="'th' + index">{{ $t('sdl.role.label.roleName') }}({{ locale }})</th>
          <th scope="col">{{ $t('sdl.common.label.description') }}</th>
          <th scope="col">{{ $t('sdl.user.label.heading') }}</th>
          <th scope="col">{{ $t('sdl.workGroup.label.heading') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="role in roleList" :key="role.roleId">
          <td class="text-center"><input type="checkbox" v-model="role.selected" @change="checkBoxClick(role)" /></td>
          <td class="text-left">{{ role.roleName }}</td>
          <td class="text-left">{{ role.label }}</td>
          <td class="text-left" v-for="(locale, index) in $i18n.availableLocales" :key="'td' + index">{{ role.labelJson[locale] }}</td>
          <td class="text-left">{{ $filters.cutString(role.description, 100) }}</td>
          <td class="text-center">
            <button v-on:click="userClick(role.roleId)" class="btn btn-outline-primary ui--btn-xs">{{
              $t('sdl.user.label.heading')
            }}</button>
          </td>
          <td class="text-center">
            <button v-on:click="workGroupClick(role.roleId)" class="btn btn-outline-primary ui--btn-xs">{{
              $t('sdl.workGroup.label.heading')
            }}</button>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- TABLE  Area-->
    <!-- Pagination  Area-->
    <sdl-pagination
      :current-page="current_page"
      :total-rows="total"
      :per-page="per_page"
      @change="handleCurrentChange"
      align="center"
    />
    <!-- Pagination  Area-->
    <!--Contents Area -->
  </div>
  <!-- SUB Contents -->
</template>
<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import RoleFormPopup from '@/components/common/popup/RoleFormPopup.vue';
import StoreParams from '@/mixin/StoreParams';

export default {
  data() {
    return {
      searchParam: {
        searchRoleName: '',
        searchLabel: '',
      },
      selectAll: false,
      per_page: null,
      current_page: null,
      total: null,
      roleList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: Roles lookup
     */
    getRoleList(pageIndex = 1) {
      // Set the page number sent to the current page number
      this.current_page = pageIndex;

      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      /**
       * Set role lookup API enforcement parameter
       */
      const params = {
        roleName: this.searchParam.searchRoleName,
        label: this.searchParam.searchLabel,
        pageIndex: this.current_page,
        pageSize: this.per_page,
        orderBy: 'ROLE_NAME',
      };

      // Save parameter to store
      this.setStoreParameter(params);

      /**
       * Call role lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/roles-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.roleList = data.rows;
          // Apply the page number that was retrieved to the current_page
          this.current_page = data.currentPage;
          // Full Row Count
          this.total = data.records;

          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });

      // Unselect All
      this.selectAll = false;
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: paging
     */
    handleCurrentChange(currentPage) {
      // Invoke role list lookup method
      this.getRoleList(currentPage);
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of roles
     */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.roleList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function to delete a role after verifying that it has been selected
     */
    deleteRoleBtn() {
      const selectedRoleList = this.roleList.filter(role => role.selected);
      const selectCnt = selectedRoleList.length;

      if (selectCnt === 0) {
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteRole(selectedRoleList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function that calls a popup looking up the role
     */
    addRoleBtn() {
      this.openRoleFormPopUp();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function to modify a role after verifying that only one role is selected or that only row
     */
    updateRoleBtn() {
      const selectedRoleList = this.roleList.filter(role => role.selected);
      const selectCnt = selectedRoleList.length;

      if (selectCnt === 0) {
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }
      if (selectCnt > 1) {
        SDLUtil.alert('sdl.common.message.selectOneRow');
        return;
      }

      this.openRoleFormPopUp(selectedRoleList[0].roleId);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Popup calls to register/modify roles
     */
    openRoleFormPopUp(roleId) {
      SDLUtil.show(
        RoleFormPopup,
        {
          roleId,
          rtnFunc: args => {
            if (args) {
              this.getRoleList();
            }
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Delete Role
     */
    deleteRole(roleList) {
      const roleIds = roleList.map(role => role.roleId);

      axios
        .delete(`${SDLUtil.API_URL}/auth/roles`, { data: roleIds })
        .then(response => {
          if (response.status === 200) {
            this.getRoleList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: If you click on the User Label, go to the Role-User page
     */
    userClick(roleId) {
      this.$router.push(`${this.$CONTEXT}/admin/rolemgmt/user/${roleId}`);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: When you click on a workgroup label, go to the Role-to-Workgroup page
     */
    workGroupClick(roleId) {
      this.$router.push(`${this.$CONTEXT}/admin/rolemgmt/workgroup/${roleId}`);
    },
  },
  created() {
    const storeParams = this.getStoreParameter();

    // Restore if there are stored parameters
    if (storeParams) {
      this.searchParam.searchRoleName = storeParams.roleName;
      this.searchParam.searchLabel = storeParams.label;
      this.current_page = storeParams.pageIndex;
      this.per_page = storeParams.pageSize;

      this.getRoleList(this.current_page);
    } else {
      // Page size - 10 settings
      this.per_page = 10;
      // Invoke role lookup method
      this.getRoleList();
    }
  },
};
</script>
