<!--
  Program: WorkgroupMenuInfo.vue
  Author: SDL
  Description: Page that retrieves, registers, modifies, and deletes the detailed information of the workgroup and the workgroup-menu.
-->
<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.workGroup.label.heading') }} - {{ $t('sdl.menu.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.workGroup.label.heading') }}</th>
            <td>{{ workgroupItem.workgroupName }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.workGroup.label.workGroupNameOt') }}</th>
            <td>{{ workgroupItem.label }}</td>
          </tr>
          <tr v-for="(locale, index) in $i18n.availableLocales" :key="'tr' + index">
            <th class="text-nowrap" scope="row">{{ $t('sdl.workGroup.label.workGroupName') }}({{ locale }})</th>
            <td colspan="3">{{ workgroupItem.labelJson? workgroupItem.labelJson[locale]: '' }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
            <td colspan="3">{{ workgroupItem.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="deleteWorkgroupMenuBtn"
            v-authorization="'update'"
          >
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addWorkgroupMenuBtn" v-authorization="'execute'">
            {{ $t('sdl.common.label.add') }}
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm"
            @click="saveWorkgroupMenuBtn"
            v-authorization="['update', 'execute']"
          >
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- buttons -->
      <!-- workgroup-menu TABLE Area-->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:49%" />
          <col style="width:12%" />
          <col style="width:12%" />
          <col style="width:12%" />
          <col style="width:12%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll" />
            </th>
            <th scope="col">{{ $t('sdl.menu.label.heading') }}</th>
            <th scope="col">
              <input class="form-check-input me-1" type="checkbox" id="toggle_read" @click.stop v-model="selectAll_READ" @change="toggleSelectAll('READ')" />
              <label class="form-check-label" for="toggle_read">{{ $t('sdl.authorization.label.READ') }}</label>
            </th>
            <th scope="col">
              <input class="form-check-input me-1" type="checkbox" id="toggle_update" @click.stop v-model="selectAll_UPDATE" @change="toggleSelectAll('UPDATE')" />
              <label class="form-check-label" for="toggle_update">{{ $t('sdl.authorization.label.UPDATE') }}</label>
            </th>
            <th scope="col">
              <input class="form-check-input me-1" type="checkbox" id="toggle_execute" @click.stop v-model="selectAll_EXECUTE" @change="toggleSelectAll('EXECUTE')" />
              <label class="form-check-label" for="toggle_execute">{{ $t('sdl.authorization.label.EXECUTE') }}</label>
            </th>
            <th scope="col">
              <input class="form-check-input me-1" type="checkbox" id="toggle_download" @click.stop v-model="selectAll_DOWNLOAD" @change="toggleSelectAll('DOWNLOAD')" />
              <label class="form-check-label" for="toggle_download">{{ $t('sdl.authorization.label.DOWNLOAD') }}</label>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="workgroupMenu in workgroupMenuList" :key="workgroupMenu.menuId">
            <td class="text-center">
              <input type="checkbox" v-model="workgroupMenu.selected" @change="checkBoxClick(workgroupMenu)" />
            </td>
            <td class="text-left">{{ workgroupMenu.menuFullPath }}</td>
            <td class="text-center"><input type="checkbox" v-model="workgroupMenu.read" /></td>
            <td class="text-center"><input type="checkbox" v-model="workgroupMenu.update" /></td>
            <td class="text-center"><input type="checkbox" v-model="workgroupMenu.execute" /></td>
            <td class="text-center"><input type="checkbox" v-model="workgroupMenu.download" /></td>
          </tr>
        </tbody>
      </table>
      <!--/ workgroup-menu TABLE Area-->
      <hr class="mb-4">
      <div class="ui--button-container">
        <button type="button" class="btn btn-secondary btn-lg" @click="returnWorkgroupListBtn">
          {{ $t('sdl.common.label.list') }}
        </button>
      </div>
    </div>
    <!--/Contents Area -->
  </div>
  <!--/SUB Contents -->
</template>
<script>
import { mapActions } from 'vuex';
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';
import MenuPopup from '@/components/common/popup/MenuListPopup.vue';
import StoreParams from '@/mixin/StoreParams';

export default {
  data() {
    return {
      workgroupId: null,
      workgroupItem: {},
      selectAll: false,
      selectAll_READ: false,
      selectAll_UPDATE: false,
      selectAll_EXECUTE: false,
      selectAll_DOWNLOAD: false,
      workgroupMenuList: [],
      tempWorkgroupMenuList: [],
      beforeWorkgroupMenuList: [],
      updateWorkgroupMenuList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    ...mapActions(['clearCache']),
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Retrieve workgroup details
     */
    getWorkgroupInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}`)
        .then(({ data }) => {
          this.workgroupItem = 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: Workgroup-Menu Lookup
     */
    getWorkgroupMenuList() {
      axios
        .get(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/menus`)
        .then(({ data }) => {
          this.workgroupMenuList = data;

          const tempMenuList = [];

          this.workgroupMenuList.forEach(workgroup => {
            tempMenuList.push({
              selected: false,
              menuId: workgroup.menuId,
              menuFullPath: workgroup.menuFullPath,
              read: workgroup.authorizationIdList.findIndex(auth => auth === 'READ') > -1,
              update: workgroup.authorizationIdList.findIndex(auth => auth === 'UPDATE') > -1,
              execute: workgroup.authorizationIdList.findIndex(auth => auth === 'EXECUTE') > -1,
              download: workgroup.authorizationIdList.findIndex(auth => auth === 'DOWNLOAD') > -1,
            });
          });

          this.workgroupMenuList = tempMenuList;
          this.initSelected();
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    initSelected() {
      this.selectAll = false;
      this.selectAll_READ = false;
      this.selectAll_UPDATE = false;
      this.selectAll_EXECUTE = false;
      this.selectAll_DOWNLOAD = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Go to workgroup Management Page
     */
    returnWorkgroupListBtn() {
      this.goBackToList();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call workgroup-menu deletion API after verifying that the selected workgroup-menu exists
     */
    deleteWorkgroupMenuBtn() {
      const selectWorkgroupMenu = this.workgroupMenuList.filter(workgroupMenu => workgroupMenu.selected);

      if (selectWorkgroupMenu.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.deleteWorkgroupMenu(selectWorkgroupMenu),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the menu query popup function
     */
    addWorkgroupMenuBtn() {
      this.openMenuPopup();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking if there is a temporary workgroup-menu list, call the workgroup-menu registration function
     */
    saveWorkgroupMenuBtn() {
      if (this.tempWorkgroupMenuList.length === 0 && this.updateWorkgroupMenuList.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.saveWorkgroupMenu(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Locate the ID of the selected menu and delete the appropriate user from the workgroup-menu list
     */
    deleteWorkgroupMenu(selectWorkgroupMenu) {
      const selectDbWorkgroupMenuIds = [];

      selectWorkgroupMenu.forEach(selectWorkgroupMenuItem => {
        // Check if it is a menu registered in DB
        const tempIdx = this.tempWorkgroupMenuList.findIndex(
          tempWorkgroupMenuItem => tempWorkgroupMenuItem.menuId === selectWorkgroupMenuItem.menuId,
        );

        if (tempIdx === -1) {
          selectDbWorkgroupMenuIds.push(selectWorkgroupMenuItem.menuId);
        } else {
          this.tempWorkgroupMenuList.splice(tempIdx, 1);
        }

        this.workgroupMenuList.splice(
          this.workgroupMenuList.findIndex(workgroupMenuItem => workgroupMenuItem.menuId === selectWorkgroupMenuItem.menuId),
          1,
        );
        this.beforeWorkgroupMenuList.splice(
          this.beforeWorkgroupMenuList.findIndex(beforeItem => beforeItem.menuId === selectWorkgroupMenuItem.menuId),
          1,
        );
        this.updateWorkgroupMenuList.splice(
          this.updateWorkgroupMenuList.findIndex(updateItem => updateItem.menuId === selectWorkgroupMenuItem.menuId),
          1,
        );
      });

      // If it exists in the workgroup-menu registered in DB, it is deleted from the workgroup-menu.
      if (selectDbWorkgroupMenuIds.length > 0) {
        axios
          .delete(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/menus`, { data: selectDbWorkgroupMenuIds })
          .then(response => {
            if (response.status === 200) {
              // console.log('sdl.common.message.deleted');
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
          });
      }
      this.selectAll = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the menu Popup
     */
    openMenuPopup() {
      SDLUtil.show(
        MenuPopup,
        {
          workgroupId: this.workgroupId,
          rtnFunc: args => {
            this.checkWorkgroupMenuList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Compare with saved workgroup-menu lists, and save to workgroup-menu lists
     */
    checkWorkgroupMenuList(menuPopupList) {
      menuPopupList.forEach(menuPopupItem => {
        // Check if it is a menu registered in DB
        if (!this.workgroupMenuList.find(workgroupMenuItem => workgroupMenuItem.menuId === menuPopupItem.menuId)) {
          // Add only if there is no comparison between added user information and temporary workgroup-menu list
          if (
            !this.tempWorkgroupMenuList.find(tempWorkgroupMenuItem => tempWorkgroupMenuItem.menuId === menuPopupItem.menuId)
          ) {
            this.tempWorkgroupMenuList.push({
              selected: false,
              menuId: menuPopupItem.menuId,
              menuFullPath: menuPopupItem.menuFullPath,
              read: true,
              update: false,
              execute: false,
              download: false,
            });
            this.workgroupMenuList.push({
              selected: false,
              menuId: menuPopupItem.menuId,
              menuFullPath: menuPopupItem.menuFullPath,
              read: true,
              update: false,
              execute: false,
              download: false,
            });

            this.setValue();
          }
        }
      });
    },
    /**
     * param: object
     * return: array
     * exception: nothing
     * description: Setting menu permissions
     */
    getMenuAuth(menuItem) {
      const menuAuthArr = [];
      if (menuItem.read) {
        menuAuthArr.push('READ');
      }
      if (menuItem.update) {
        menuAuthArr.push('UPDATE');
      }
      if (menuItem.execute) {
        menuAuthArr.push('EXECUTE');
      }
      if (menuItem.download) {
        menuAuthArr.push('DOWNLOAD');
      }
      return menuAuthArr;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Register and modify workgroup-menu
     */
    async saveWorkgroupMenu() {
      const saveInsertMenuList = [];
      const saveUpdateMenuList = [];
      let check = false;

      if (this.tempWorkgroupMenuList.length > 0) {
        this.workgroupMenuList.forEach(workgroupMenuListItem => {
          const isInsertMenu = this.tempWorkgroupMenuList.find(insert => insert.menuId === workgroupMenuListItem.menuId);

          if (isInsertMenu) {
            const isUpdateMenu = this.updateWorkgroupMenuList.find(
              updateMenuItem => updateMenuItem.menuId === isInsertMenu.menuId,
            );
            if (isUpdateMenu) {
              saveInsertMenuList.push({
                menuId: isUpdateMenu.menuId,
                menuFullPath: isUpdateMenu.menuFullPath,
                authorizationIdList: this.getMenuAuth(isUpdateMenu),
              });
            } else {
              saveInsertMenuList.push({
                menuId: isInsertMenu.menuId,
                menuFullPath: isInsertMenu.menuFullPath,
                authorizationIdList: this.getMenuAuth(isInsertMenu),
              });
            }
          } else {
            const isUpdateMenu = this.updateWorkgroupMenuList.find(
              updateMenuItem => updateMenuItem.menuId === workgroupMenuListItem.menuId,
            );

            if (isUpdateMenu) {
              saveUpdateMenuList.push({
                menuId: isUpdateMenu.menuId,
                menuFullPath: isUpdateMenu.menuFullPath,
                authorizationIdList: this.getMenuAuth(isUpdateMenu),
              });
            }
          }
        });

        /**
         * Call the Workgroup-Menu Registration API
         */
        await axios
          .post(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/menus`, saveInsertMenuList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              check = true;
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
            check = false;
          });
      } else {
        this.updateWorkgroupMenuList.forEach(updateMenuItem => {
          saveUpdateMenuList.push({
            menuId: updateMenuItem.menuId,
            menuFullPath: updateMenuItem.menuFullPath,
            authorizationIdList: this.getMenuAuth(updateMenuItem),
          });
        });
      }

      /**
       * Call the Workgroup-Menu Modification API
       */
      await axios
        .put(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/menus`, saveUpdateMenuList, {
          headers: { 'Content-Type': 'application/json' },
        })
        .then(response => {
          if (response.status === 200) {
            check = true;
          }
        })
        .catch(err => {
          SDLUtil.errorAlert(err);
          check = false;
        });

      if (check) {
        this.clearCache();
        // SDLUtil.alert('sdl.common.message.saved');
        this.getWorkgroupMenuList();

        this.tempWorkgroupMenuList.splice(0);
        this.updateWorkgroupMenuList = [];
      }
    },
    /**
     * 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(auth) {
      this.workgroupMenuList.forEach(item => {
        if (auth === 'READ') {
          item.read = this.selectAll_READ;
        } else if (auth === 'UPDATE') {
          item.update = this.selectAll_UPDATE;
        } else if (auth === 'EXECUTE') {
          item.execute = this.selectAll_EXECUTE;
        } else if (auth === 'DOWNLOAD') {
          item.download = this.selectAll_DOWNLOAD;
        } else {
          item.selected = this.selectAll;
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Save to the pre-change data list to synchronize the pre-change data
     */
    setValue() {
      this.beforeWorkgroupMenuList = _.cloneDeep(this.workgroupMenuList);
    },
  },
  created() {
    this.workgroupItem = {};
    this.workgroupId = this.$route.params.workgroupId;
    this.updateWorkgroupMenuList = [];
    this.getWorkgroupInfo();
    this.getWorkgroupMenuList();
  },
  mounted() {
    this.$nextTick(() => {
      // console.info('loaded UserInfo.vue');
    });

    this.setValue();
  },
  watch: {
    workgroupMenuList: {
      handler(after, before) {
        if (before.length > 0) {
          const changedWorkgroupMenuList = after.filter((p, idx) => Object.keys(p).some(prop => p[prop] !== this.beforeWorkgroupMenuList[idx][prop]));

          for (let i = 0; i < changedWorkgroupMenuList.length; i += 1) {
            const changedWorkgroupMenuItem = changedWorkgroupMenuList[i];
            const isExistIndex = this.updateWorkgroupMenuList.findIndex(
              workgroupMenu => workgroupMenu.menuId === changedWorkgroupMenuItem.menuId,
            );

            if (isExistIndex > -1) {
              this.updateWorkgroupMenuList.splice(isExistIndex, 1);
            }
            this.updateWorkgroupMenuList.push(changedWorkgroupMenuItem);
          }
        }
        this.setValue();
      },
      deep: true,
    },
  },
};
</script>
