<!--
  Program: RoleWorkgroupInfo.vue
  Author: SDL
  Description: Retrieves the role details and retrieves, registers, modifies, and deletes the role-workgroup list.
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="ui--view-container">
      <h4 class="mb-3">{{ $t('sdl.role.label.heading') }} - {{ $t('sdl.workGroup.label.heading') }}</h4>
      <table class="table table-bordered ui--table-form mb-5">
        <colgroup>
          <col style="width:12.5%" />
          <col style="width:35.5%" />
          <col style="width:12.5%" />
          <col style="width:35.5%" />
        </colgroup>
        <tbody>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.role.label.heading') }}</th>
            <td>{{ roleItem.roleName }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.role.label.roleNameOt') }}</th>
            <td>{{ roleItem.label }}</td>
          </tr>
          <tr v-for="(locale, index) in $i18n.availableLocales" :key="'tr' + index">
            <th class="text-nowrap" scope="row">{{ $t('sdl.role.label.roleName') }}({{ locale }})</th>
            <td colspan="3">{{ roleItem.labelJson? roleItem.labelJson[locale]: '' }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
            <td colspan="3">{{ roleItem.description }}</td>
          </tr>
        </tbody>
      </table>

      <!-- buttons -->
      <div class="ui--list-heading clearfix">
        <div class="float-end">
          <button
            type="button"
            class="btn btn-secondary btn-sm"
            @click="deleteRoleWorkgroupBtn"
            v-authorization="'update'"
          >
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addRoleWorkgroupBtn" v-authorization="'execute'">
            {{ $t('sdl.common.label.add') }}
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm"
            @click="saveRoleWorkgroupBtn"
            v-authorization="['update', 'execute']"
          >
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- buttons -->
      <!-- role-workgroup TABLE Area-->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:27%" />
          <col style="width:30%" />
          <col style="width:40%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll" />
            </th>
            <th scope="col">{{ $t('sdl.workGroup.label.heading') }}</th>
            <th scope="col">{{ $t('sdl.workGroup.label.workGroupName') }}</th>
            <th scope="col">{{ $t('sdl.board.label.description') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="workgroup in roleWorkgroupList" :key="workgroup.workgroupId">
            <td class="text-center">
              <input type="checkbox" v-model="workgroup.selected" @change="checkBoxClick()" />
            </td>
            <td class="text-left">{{ workgroup.workgroupName }}</td>
            <td class="text-left">{{ getLabel(workgroup) }}</td>
            <td class="text-left">{{ workgroup.description }}</td>
          </tr>
        </tbody>
      </table>
      <!--/ role-workgroup TABLE Area-->
      <hr class="mb-4">
      <div class="ui--button-container">
          <button type="button" class="btn btn-secondary btn-lg" @click="returnRoleListBtn">
            {{ $t('sdl.common.label.list') }}
          </button>
      </div>
    </div>
    <!--/Contents Area -->
  </div>
  <!--/SUB Contents -->
</template>
<script>
import axios from 'axios';
import SDLUtil from '@/utils/SDLUtil';
import WorkgroupPopup from '@/components/common/popup/WorkgroupListPopup.vue';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      roleId: null,
      roleItem: {},
      selectAll: false,
      roleWorkgroupList: [],
      tempRoleWorkgroupList: [],
    };
  },
  mixins: [StoreParams, SDLLocale],
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Retrieve role details
     */
    getRoleInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);
      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);
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Roles-Workgroup Lookup
     */
    getRoleWorkgroupList() {
      axios
        .get(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/workgroups`)
        .then(({ data }) => {
          this.roleWorkgroupList = data;
          this.selectAll = false;
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Go to Role Management Page
     */
    returnRoleListBtn() {
      this.goBackToList();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call role-workgroup deletion API after verifying that the selected role-workgroup exists
     */
    deleteRoleWorkgroupBtn() {
      const selectRoleWorkgroup = this.roleWorkgroupList.filter(roleWorkgroup => roleWorkgroup.selected);

      if (selectRoleWorkgroup.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        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.deleteRoleWorkgroup(selectRoleWorkgroup),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the workgroup query popup function
     */
    addRoleWorkgroupBtn() {
      this.openWorkgroupPopup();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking if there is a temporary role-workgroup list, call the role-workgroup registration function
     */
    saveRoleWorkgroupBtn() {
      if (this.tempRoleWorkgroupList.length === 0) {
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.insertRoleWorkgroup(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Locate the ID of the selected workgroup and delete the appropriate user from the role-workgroup list
     */
    deleteRoleWorkgroup(selectRoleWorkgroup) {
      const selectDbRoleWorkgroupIds = [];

      selectRoleWorkgroup.forEach(selectRoleWorkgroupItem => {
        // Check if it is a workgroup registered in DB
        const tempIdx = this.tempRoleWorkgroupList.findIndex(
          tempRoleWorkgroupItem => tempRoleWorkgroupItem.workgroupId === selectRoleWorkgroupItem.workgroupId,
        );

        if (tempIdx === -1) {
          selectDbRoleWorkgroupIds.push(selectRoleWorkgroupItem.workgroupId);
        } else {
          this.tempRoleWorkgroupList.splice(tempIdx, 1);
        }

        this.roleWorkgroupList.splice(
          this.roleWorkgroupList.findIndex(
            roleWorkgroupItem => roleWorkgroupItem.workgroupId === selectRoleWorkgroupItem.workgroupId,
          ),
          1,
        );
      });

      // If it exists in the role-workgroup registered in DB, it is deleted from the role-workgroup.
      if (selectDbRoleWorkgroupIds.length > 0) {
        axios
          .delete(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/workgroups`, { data: selectDbRoleWorkgroupIds })
          .then(response => {
            if (response.status === 200) {
              // console.log('sdl.common.message.deleted');
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the workgroup Popup
     */
    openWorkgroupPopup() {
      SDLUtil.show(
        WorkgroupPopup,
        {
          rtnFunc: args => {
            this.checkRoleWorkgroupList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Compare with saved role-workgroup lists, and save to role-workgroup lists
     */
    checkRoleWorkgroupList(workgroupPopupList) {
      workgroupPopupList.forEach(workgroupPopupItem => {
        // Check if it is a workgroup registered in DB
        if (
          !this.roleWorkgroupList.find(roleWorkgroupItem => roleWorkgroupItem.workgroupId === workgroupPopupItem.workgroupId)
        ) {
          // Add only if there is no comparison between added user information and temporary role-workgroup list
          if (
            !this.tempRoleWorkgroupList.find(
              tempRoleWorkgroupItem => tempRoleWorkgroupItem.workgroupId === workgroupPopupItem.workgroupId,
            )
          ) {
            this.tempRoleWorkgroupList.push({
              roleId: this.roleId,
              workgroupId: workgroupPopupItem.workgroupId,
              workgroupName: workgroupPopupItem.workgroupName,
              label: workgroupPopupItem.label,
              labelJson: workgroupPopupItem.labelJson,
              description: workgroupPopupItem.description,
            });
            this.roleWorkgroupList.push({
              roleId: this.roleId,
              workgroupId: workgroupPopupItem.workgroupId,
              workgroupName: workgroupPopupItem.workgroupName,
              label: workgroupPopupItem.label,
              labelJson: workgroupPopupItem.labelJson,
              description: workgroupPopupItem.description,
            });
          }
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Temporary Role - After checking if there is a row to be added to the user list, save it to Role - Workgroup
     */
    async insertRoleWorkgroup() {
      if (this.tempRoleWorkgroupList.length > 0) {
        await axios
          .post(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/workgroups`, this.tempRoleWorkgroupList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              // SDLUtil.alert('sdl.common.message.saved');

              this.tempRoleWorkgroupList = [];
              this.getRoleWorkgroupList();
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of workgroup
     */
    checkBoxClick() {
      this.roleWorkgroupList.forEach(item => {
        if (!item.selected) {
          this.selectAll = false;
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.roleWorkgroupList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
  },
  created() {
    this.roleItem = {};
    this.roleId = this.$route.params.roleId;
    this.getRoleInfo();
    this.getRoleWorkgroupList();
  },
};
</script>
