<!--
  Program: WorkgroupMenuInfo.vue
  Author: SDL
  Description: Page that functions as adding, modifying, and deleting workgroups
-->
<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.workGroup.label.heading')
              }}</label>
              <div class="col-8">
                <input
                  type="text"
                  class="form-control"
                  v-model="searchParam.searchWorkgroupName"
                  @keyup.enter="getWorkgroupList()"
                  @keyup.esc="searchParam.searchWorkgroupName = ''"
                />
              </div>
            </div>
          </div>
          <div class="col">
            <div class="row">
              <label class="col-2 col-form-label text-end" style="min-width:100px;">{{
                $t('sdl.workGroup.label.workGroupName')
              }}</label>
              <div class="col-8">
                <input
                  type="text"
                  class="form-control"
                  v-model="searchParam.searchLabel"
                  @keyup.enter="getWorkgroupList()"
                  @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="getWorkgroupList()">
          {{ $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="deleteWorkgroupBtn" v-authorization="'update'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addWorkgroupBtn" v-authorization="'execute'">
          {{ $t('sdl.common.label.add') }}
        </button>
        <button
          type="button"
          class="btn btn-secondary btn-sm"
          @click="updateWorkgroupBtn"
          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%" />
        <col style="width:12%" v-for="locale in $i18n.availableLocales" :key="locale"/>
        <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.workGroup.label.heading') }}</th>
          <th scope="col">{{ $t('sdl.workGroup.label.workGroupNameOt') }}</th>
          <th scope="col" v-for="locale in $i18n.availableLocales" :key="locale">{{ $t('sdl.workGroup.label.workGroupName') }}({{ locale }})</th>
          <th scope="col">{{ $t('sdl.common.label.description') }}</th>
          <th scope="col">{{ $t('sdl.menu.label.heading') }}</th>
          <th scope="col">{{ $t('sdl.role.label.heading') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="workgroup in workgroupList" :key="workgroup.workgroupId">
          <td class="text-center">
            <input type="checkbox" v-model="workgroup.selected" @change="checkBoxClick(workgroup)" />
          </td>
          <td class="text-left">{{ workgroup.workgroupName }}</td>
          <td class="text-left">{{ workgroup.label }}</td>
          <td class="text-left" v-for="locale in $i18n.availableLocales" :key="locale">{{ workgroup.labelJson[locale] }}</td>
          <td class="text-left">{{ $filters.cutString(workgroup.description, 100) }}</td>
          <td class="text-center">
            <button v-on:click="menuClick(workgroup.workgroupId)" class="btn btn-outline-primary ui--btn-xs">{{
              $t('sdl.menu.label.heading')
            }}</button>
          </td>
          <td class="text-center cursor-pointer">
            <button v-on:click="roleClick(workgroup.workgroupId)" class="btn btn-outline-primary ui--btn-xs">{{
              $t('sdl.role.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 WorkgroupFormPopup from '@/components/common/popup/WorkgroupFormPopup.vue';
import StoreParams from '@/mixin/StoreParams';

export default {
  data() {
    return {
      searchParam: {
        searchWorkgroupName: '',
        searchLabel: '',
      },
      selectAll: false,
      per_page: null,
      current_page: null,
      total: null,
      workgroupList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: Check workgroup
     */
    async getWorkgroupList(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 = {
        workgroupName: this.searchParam.searchWorkgroupName,
        label: this.searchParam.searchLabel,
        pageIndex: this.current_page,
        pageSize: this.per_page,
        orderBy: 'WORKGROUP_NAME',
      };

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

      /**
       * Invoke workgroup lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/workgroups-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.workgroupList = 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: nothing
     * description: paging
     */
    handleCurrentChange(currentPage) {
      // Invoke workgroup list lookup method
      this.getWorkgroupList(currentPage);
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of workgroup
     */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.workgroupList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function to delete a workgroup after verifying that it has been selected
     */
    deleteWorkgroupBtn() {
      const selectedworkgroupList = this.workgroupList.filter(workgroup => workgroup.selected);
      const selectCnt = selectedworkgroupList.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.deleteWorkgroup(selectedworkgroupList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function that calls a popup looking up the workgroup
     */
    addWorkgroupBtn() {
      this.openWorkgroupFormPopUp();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call up a function to modify a workgroup after verifying that only one workgroup is selected or that only row
     */
    updateWorkgroupBtn() {
      const selectedWorkgroupList = this.workgroupList.filter(workgroup => workgroup.selected);
      const selectCnt = selectedWorkgroupList.length;

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

      this.openWorkgroupFormPopUp(selectedWorkgroupList[0].workgroupId);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Popup calls to register/modify workgroup
     */
    openWorkgroupFormPopUp(workgroupId) {
      SDLUtil.show(
        WorkgroupFormPopup,
        {
          workgroupId,
          rtnFunc: args => {
            if (args) {
              this.getWorkgroupList();
            }
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Delete workgroup
     */
    deleteWorkgroup(workgroupList) {
      const workgroupIds = workgroupList.map(workgroup => workgroup.workgroupId);

      axios
        .delete(`${SDLUtil.API_URL}/auth/workgroups`, { data: workgroupIds })
        .then(response => {
          if (response.status === 200) {
            this.getWorkgroupList();
          }
        })
        .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 Workgroup-Menu page
     */
    menuClick(workgroupId) {
      this.$router.push(`${this.$CONTEXT}/admin/workgroupmgmt/menu/${workgroupId}`);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: When you click on a workgroup label, go to the Workgroup-User/Role page
     */
    roleClick(workgroupId) {
      this.$router.push(`${this.$CONTEXT}/admin/workgroupmgmt/role/${workgroupId}`);
    },
  },
  created() {
    const storeParams = this.getStoreParameter();

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

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