<!--
 Program: UserInfo.vue
 Author: SDL
 Description: The screen that performs user details and user-role, user-menu registration, modification, and deletion functions.
-->
<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.user.label.userInfoTitle') }}</h4>
      <table class="table table-bordered mb-5 ui--table-form">
        <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.common.label.epId') }}</th>
            <td>{{ epId }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.used') }}</th>
            <td v-if="userInfo.userStatus === 'ACTIVE'">{{ $t('sdl.user.label.heading') }}</td>
            <td v-else-if="userInfo.userStatus === 'INACTIVE'">{{ $t('sdl.user.label.inactive') }}</td>
            <td v-if="userInfo.userStatus === 'WAITING'">{{ $t('sdl.user.label.waiting') }}</td>
            <td v-if="userInfo.userStatus === 'DELETED'">{{ $t('sdl.common.label.delete') }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.name') }}</th>
            <td>{{ userInfo.userName }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.knoxId') }}</th>
            <td>{{ userInfo.knoxId }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.compName') }}</th>
            <td colspan="3">{{ userInfo.compName }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.deptName') }}</th>
            <td>{{ userInfo.deptName }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.empNo') }}</th>
            <td>{{ userInfo.empNo }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.email') }}</th>
            <td>{{ userInfo.email }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.userType') }}</th>
            <td>{{ userInfo.userType }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.compTel') }}</th>
            <td>{{ userInfo.compTel }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.mobile') }}</th>
            <td>{{ userInfo.mobile }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.lastLoginDate') }}</th>
            <td>{{ $filters.dateFormat(userInfo.lastLoginDate, $t('data-format.datetime.ymdhms')) }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.modifyDate') }}</th>
            <td>{{ $filters.dateFormat(userInfo.lastModDatetime, $t('data-format.datetime.ymdhms')) }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
            <td colspan="3">{{ userInfo.description }}</td>
          </tr>
        </tbody>
      </table>

      <!-- role List Table Header & buttons -->
      <div class="ui--form-heading clearfix mb-2">
        <h5 class="d-inline-block">{{ $t('sdl.role.label.heading') }}</h5>
        <div class="float-end">
          <button type="button" class="btn btn-secondary btn-sm" @click="delUserRoleBtn" v-authorization="'update'">
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addUserRoleBtn" v-authorization="'execute'">
            {{ $t('sdl.common.label.add') }}
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm"
            @click="saveUserRoleBtn"
            v-authorization="['update', 'execute']"
          >
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- role List Table -->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:15%" />
          <col style="width:17%" />
          <col style="width:25%" />
          <col style="width:15%" />
          <col style="width:15%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll_role" @change="toggleSelectAll('ROLE')" />
            </th>
            <th scope="col">{{ $t('sdl.role.label.heading') }}</th>
            <th scope="col">{{ $t('sdl.role.label.roleName') }}</th>
            <th scope="col">{{ $t('sdl.common.label.description') }}</th>
            <th scope="col">{{ $t('sdl.common.label.fromDate') }}</th>
            <th scope="col">{{ $t('sdl.common.label.thruDate') }}</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">{{ getLabel(role) }}</td>
            <td class="text-left">{{ role.description }}</td>
            <td class="text-center">
              <sdl-datepicker v-model="role.fromDate" wrap-class="" :disabled-date="role.disabledDate" @input="dateInput($event, role)"></sdl-datepicker>
            </td>
            <td class="text-center">
              <sdl-datepicker v-model="role.thruDate" wrap-class="" :disabled-date="role.disabledDate" @input="dateInput($event, role)"></sdl-datepicker>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Menu List Header & buttons -->
      <div class="ui--form-heading clearfix mb-2">
        <h5 class="d-inline-block">{{ $t('sdl.menu.label.heading') }}</h5>
        <div class="float-end">
          <button type="button" class="btn btn-secondary btn-sm" @click="delUserMenuBtn" v-authorization="'update'">
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addUserMenuBtn" v-authorization="'execute'">
            {{ $t('sdl.common.label.add') }}
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm"
            @click="saveUserMenuBtn"
            v-authorization="['update', 'execute']"
          >
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- Menu List Table -->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:27%" />
          <col style="width:15%" />
          <col style="width:15%" />
          <col style="width:10%" />
          <col style="width:10%" />
          <col style="width:10%" />
          <col style="width:10%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll_menu" @change="toggleSelectAll('MENU')" />
            </th>
            <th scope="col">{{ $t('sdl.batchLogger.label.menu') }}</th>
            <th scope="col">{{ $t('sdl.common.label.fromDate') }}</th>
            <th scope="col">{{ $t('sdl.common.label.thruDate') }}</th>
            <th scope="col">{{ $t('sdl.user.label.read') }}</th>
            <th scope="col">{{ $t('sdl.user.label.update') }}</th>
            <th scope="col">{{ $t('sdl.user.label.execute') }}</th>
            <th scope="col">{{ $t('sdl.user.label.download') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="menu in menuList" :key="menu.menuId">
            <td class="text-center">
              <input type="checkbox" v-model="menu.selected" @change="checkBoxClick('MENU')" />
            </td>
            <td class="text-left">{{ menu.menuName }}</td>
            <td class="text-center">
              <sdl-datepicker v-model="menu.fromDate" wrap-class="" :disabled-date="menu.disabledDate" @input="dateInput($event, menu)"></sdl-datepicker>
            </td>
            <td class="text-center">
              <sdl-datepicker v-model="menu.thruDate" wrap-class="" :disabled-date="menu.disabledDate" @input="dateInput($event, menu)"></sdl-datepicker>
            </td>
            <td class="text-center"><input type="checkbox" v-model="menu.read" /></td>
            <td class="text-center"><input type="checkbox" v-model="menu.update" /></td>
            <td class="text-center"><input type="checkbox" v-model="menu.execute" /></td>
            <td class="text-center"><input type="checkbox" v-model="menu.download" /></td>
          </tr>
        </tbody>
      </table>
      <!-- Menu List Table -->
      <hr class="mb-4">
        <div class="ui--button-container">
          <button type="button" class="btn btn-secondary btn-lg" @click="moveUserMgmtBtn">
            {{ $t('sdl.common.label.list') }}
          </button>
          <button type="button" class="btn btn-secondary btn-lg" @click="deleteUserBtn" v-authorization="'update'">
            {{ $t('sdl.common.label.delete') }}
          </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 RolePopup from '@/components/common/popup/RoleListPopup.vue';
import MenuPopup from '@/components/common/popup/MenuListPopup.vue';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  mixins: [SDLLocale, StoreParams],
  data() {
    return {
      epId: null,
      userInfo: {},
      selectAll_role: false,
      roleList: [],
      beforeRoleList: [],
      updateRoleList: [],
      tempRoleList: [],
      selectAll_menu: false,
      menuList: [],
      beforeMenuList: [],
      updateMenuList: [],
      tempMenuList: [],
      searchDate: '',
    };
  },
  methods: {
    ...mapActions(['clearCache']),
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: User details lookup (by epId)
     */
    getUserInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      /**
       * Call user lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/users/${this.epId}`)
        .then(({ data }) => {
          // Save user details query data
          this.userInfo = 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: User-Role Query
     */
    getUserRole() {
      /**
       * User-Role Query API Callout
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/users/${this.epId}/roles`)
        .then(({ data }) => {
          // Save user-role list
          this.roleList = data;
          const tempRoleList = [];

          /**
           * Extract required user-role list items
           */
          this.roleList.forEach(roleListItem => {
            /**
             * User Required-Save Role Items to tempRoleList
             */
            tempRoleList.push({
              selected: false,
              roleId: roleListItem.roleId,
              roleName: roleListItem.roleName,
              label: roleListItem.label,
              labelJson: roleListItem.labelJson,
              description: roleListItem.description,
              fromDate: this.$filters.dateFormat(roleListItem.fromDate, 'YYYY-MM-DD'),
              thruDate: this.$filters.dateFormat(roleListItem.thruDate, 'YYYY-MM-DD'),
              // Expiration datepicker Duration Limit Parameter Settings
              disabledDate: {
                to: this.$moment().subtract(1, 'd').toDate(),
              },
            });
          });

          // Save tempRoleList data to roleList
          this.roleList = tempRoleList;
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call user-role delete Confirm
     */
    delUserRoleBtn() {
      // Selected user-role list filter
      const selectRoleList = this.roleList.filter(role => role.selected);

      /**
       * Return if there is no user-role selection result
       */
      if (selectRoleList.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        return;
      }

      /**
       * Call user-role delete Confirm
       */
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteUserRole(selectRoleList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Delete User-Role
     */
    deleteUserRole(selectList) {
      const delList = [];

      selectList.forEach(selectItem => {
        // Validate the list of added (new) roles
        const deleteRoleListIndex = this.tempRoleList.findIndex(tempRole => tempRole.roleId === selectItem.roleId);

        if (deleteRoleListIndex > -1) {
          this.tempRoleList.splice(deleteRoleListIndex, 1);
        } else {
          delList.push(selectItem.roleId);
        }
        this.roleList.splice(this.roleList.findIndex(roleItem => roleItem.roleId === selectItem.roleId), 1);
        this.beforeRoleList.splice(
          this.beforeRoleList.findIndex(beforeItem => beforeItem.roleId === selectItem.roleId),
          1,
        );
        this.updateRoleList.splice(
          this.updateRoleList.findIndex(updateItem => updateItem.roleId === selectItem.roleId),
          1,
        );
      });

      /**
       * Validate that user-role deletion is stored in DB
       */
      if (delList.length > 0) {
        /**
         * Call user-role deletion API
         */
        axios
          .delete(`${SDLUtil.API_URL}/auth/users/${this.epId}/roles`, { data: delList })
          .then(response => {
            if (response.status === 200) {
              this.clearCache();
              // console.log('menu delect!!');
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }

      // User-Role Unselect All
      this.selectAll_role = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User-Role Add Button
     */
    addUserRoleBtn() {
      // call role popup
      this.openRolePopUp();
    },
    /**
     * param: nothing
     * return: Function
     * exception: nothing
     * description: call role popup
     */
    openRolePopUp() {
      SDLUtil.show(
        RolePopup,
        {
          roleId: null,
          roleName: null,
          rtnFunc: args => {
            this.checkRoleList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Compare role information and save role object
     */
    checkRoleList(rolePopupList) {
      rolePopupList.forEach(rolePopupItem => {
        /**
         * View list of existing or stored roles or list of added (unstored) roles
         */
        if (
          !(
            this.roleList.find(roleListItem => roleListItem.roleId === rolePopupItem.roleId)
            || this.tempRoleList.find(tempRoleListItem => tempRoleListItem.roleId === rolePopupItem.roleId)
          )
        ) {
          this.tempRoleList.push({
            selected: false,
            roleId: rolePopupItem.roleId,
            roleName: rolePopupItem.roleName,
            label: rolePopupItem.label,
            labelJson: rolePopupItem.labelJson,
            description: rolePopupItem.description,
            fromDate: this.$filters.dateFormat(this.$moment(), 'YYYY-MM-DD'),
            thruDate: this.$filters.dateFormat(this.$moment().add('2', 'Y'), 'YYYY-MM-DD'),
            disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
          });
          this.roleList.push({
            selected: false,
            roleId: rolePopupItem.roleId,
            roleName: rolePopupItem.roleName,
            label: rolePopupItem.label,
            labelJson: rolePopupItem.labelJson,
            description: rolePopupItem.description,
            fromDate: this.$filters.dateFormat(this.$moment(), 'YYYY-MM-DD'),
            thruDate: this.$filters.dateFormat(this.$moment().add('2', 'Y'), 'YYYY-MM-DD'),
            disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
          });

          // User-Role Transfer Sync
          this.setValue('ROLE');
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Click the Save User-Role button
     */
    saveUserRoleBtn() {
      /**
       * Added User-Role/Changed User-Role Verification
       */
      if (this.tempRoleList.length === 0 && this.updateRoleList.length === 0) {
        return;
      }

      /**
       * Call user-role save confirmation Confirm
       */
      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveUserRole(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: User-Role Registration and Modification
     */
    async saveUserRole() {
      const saveInsertRoleList = [];
      const saveUpdateRoleList = [];
      let check = false;

      if (this.tempRoleList.length > 0) {
        // Verify that you have role data to register as new
        this.roleList.forEach(roleListItem => {
          const isInsertRole = this.tempRoleList.find(insert => insert.roleId === roleListItem.roleId);

          /**
           * Confirm New Role
           */
          if (isInsertRole) {
            const isUpdateMenu = this.updateRoleList.find(
              updateRoleItem => updateRoleItem.roleId === isInsertRole.roleId,
            );
            /**
             * Validate that the value has changed
             */
            if (isUpdateMenu) {
              saveInsertRoleList.push({
                userId: this.epId,
                roleId: isUpdateMenu.roleId,
                fromDate: this.$filters.dateFormat(isUpdateMenu.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isUpdateMenu.thruDate, 'YYYYMMDD'),
              });
            } else {
              saveInsertRoleList.push({
                userId: this.epId,
                roleId: isInsertRole.roleId,
                fromDate: this.$filters.dateFormat(isInsertRole.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isInsertRole.thruDate, 'YYYYMMDD'),
              });
            }
          } else {
            const isUpdateRole = this.updateRoleList.find(
              updateRoleItem => updateRoleItem.roleId === roleListItem.roleId,
            );

            /**
             * Validate that the value has changed
             */
            if (isUpdateRole) {
              saveUpdateRoleList.push({
                userId: this.epId,
                roleId: isUpdateRole.roleId,
                fromDate: this.$filters.dateFormat(isUpdateRole.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isUpdateRole.thruDate, 'YYYYMMDD'),
              });
            }
          }
        });

        /**
         * Verify that additional user-role is present
         */
        if (saveInsertRoleList.length > 0) {
          /**
           * Call user-role registration API
           */
          await axios
            .post(`${SDLUtil.API_URL}/auth/users/${this.epId}/roles`, saveInsertRoleList, {
              headers: { 'Content-Type': 'application/json' },
            })
            .then(response => {
              if (response.status === 200) {
                this.clearCache();
                check = true;
              }
            })
            .catch(err => {
              // Call error alert
              SDLUtil.errorAlert(err);
              check = false;
            });
        }
      } else {
        this.updateRoleList.forEach(updateRoleItem => {
          saveUpdateRoleList.push({
            userId: this.epId,
            roleId: updateRoleItem.roleId,
            fromDate: this.$filters.dateFormat(updateRoleItem.fromDate, 'YYYYMMDD'),
            thruDate: this.$filters.dateFormat(updateRoleItem.thruDate, 'YYYYMMDD'),
          });
        });
      }

      /**
       * Validate that there is a user-role whose value has been made
       */
      if (saveUpdateRoleList.length > 0) {
        /**
         * Call user-role modification API
         */
        await axios
          .put(`${SDLUtil.API_URL}/auth/users/${this.epId}/roles`, saveUpdateRoleList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              this.clearCache();
              check = true;
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
            check = false;
          });
      }

      /**
       * Verify that the registration or modification API was called normally
       */
      if (check) {
        // user-role list lookup
        this.getUserRole();

        // Temporary User-Role List Initialization
        this.tempRoleList.splice(0);
        // Initialize Modified User-Role List
        this.updateRoleList = [];
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Call user-menu lookup API
     */
    getUserMenu() {
      /**
       * Call user-menu lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/users/${this.epId}/menus`)
        .then(({ data }) => {
          // Save the inquired data in the menuList
          this.menuList = data;
          const tempMenuList = [];

          /**
           * Change the column of the menuList to match the format
           */
          this.menuList.forEach(menuListItem => {
            tempMenuList.push({
              selected: false, // checkbox
              menuId: menuListItem.menuId,
              menuName: menuListItem.menuName,
              fromDate: this.$filters.dateFormat(menuListItem.fromDate, 'YYYY-MM-DD'),
              thruDate: this.$filters.dateFormat(menuListItem.thruDate, 'YYYY-MM-DD'),
              disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
              read: menuListItem.authorizationIdList.findIndex(auth => auth === 'READ') > -1,
              update: menuListItem.authorizationIdList.findIndex(auth => auth === 'UPDATE') > -1,
              execute: menuListItem.authorizationIdList.findIndex(auth => auth === 'EXECUTE') > -1,
              download: menuListItem.authorizationIdList.findIndex(auth => auth === 'DOWNLOAD') > -1,
            });
          });

          this.menuList = tempMenuList;

          // Unselect User-Menu full
          this.selectAll_menu = false;
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Select List CheckBox All
     */
    toggleSelectAll(listFlag) {
      if (listFlag === 'ROLE') {
        this.roleList.forEach(item => {
          item.selected = this.selectAll_role;
        });
      } else {
        this.menuList.forEach(item => {
          item.selected = this.selectAll_menu;
        });
      }
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Click on List CheckBox
     */
    checkBoxClick(listFlag) {
      if (listFlag === 'ROLE') {
        this.roleList.forEach(roleItem => {
          if (!roleItem.selected) {
            this.selectAll_role = false;
          }
        });
      } else {
        this.menuList.forEach(menuItem => {
          if (!menuItem.selected) {
            this.selectAll_menu = false;
          }
        });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Add User-Menu Button
     */
    addUserMenuBtn() {
      // Menu popup call
      this.openMenuPopUp();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Menu popup call
     */
    openMenuPopUp() {
      SDLUtil.show(
        MenuPopup,
        {
          userId: this.epId,
          rtnFunc: args => {
            this.checkMenuList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Compare menu information and save menu objects
     */
    checkMenuList(menuPopupList) {
      menuPopupList.forEach(menuPopupItem => {
        /**
         * View existing or saved menu lists or added (unstored) menu lists
         */
        if (
          !(
            this.menuList.find(menuListItem => menuListItem.menuId === menuPopupItem.menuId)
            || this.tempMenuList.find(tempMenuListItem => tempMenuListItem.menuId === menuPopupItem.menuId)
          )
        ) {
          this.tempMenuList.push({
            selected: false,
            menuId: menuPopupItem.id,
            menuName: menuPopupItem.label,
            fromDate: this.$filters.dateFormat(this.$moment(), 'YYYY-MM-DD'),
            thruDate: this.$filters.dateFormat(this.$moment().add('2', 'Y'), 'YYYY-MM-DD'),
            disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
            read: true,
            update: false,
            execute: false,
            download: false,
          });
          this.menuList.push({
            selected: false,
            menuId: menuPopupItem.id,
            menuName: menuPopupItem.label,
            fromDate: this.$filters.dateFormat(this.$moment(), 'YYYY-MM-DD'),
            thruDate: this.$filters.dateFormat(this.$moment().add('2', 'Y'), 'YYYY-MM-DD'),
            disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
            read: true,
            update: false,
            execute: false,
            download: false,
          });

          // Synchronize user-menu transfer values
          this.setValue('MENU');
        }
      });
    },
    /**
     * param: object
     * return: array
     * exception: nothing
     * description: Set user-menu permissions before saving
     */
    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: User-Menu Save Button
     */
    saveUserMenuBtn() {
      /**
       * Added User-Role/Changed User-Role Verification
       */
      if (this.tempMenuList.length === 0 && this.updateMenuList.length === 0) {
        return;
      }

      /**
       * Call user-role save confirmation Confirm
       */
      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveUserMenu(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User-Menu Registration and Modification
     */
    async saveUserMenu() {
      const saveInsertMenuList = [];
      const saveUpdateMenuList = [];
      let check = false;

      /**
       * Verify that you have a user-menu to register
       */
      if (this.tempMenuList.length > 0) {
        this.menuList.forEach(menuListItem => {
          const isInsertMenu = this.tempMenuList.find(insert => insert.menuId === menuListItem.menuId);

          /**
           * Verify that additional user-menu is present
           */
          if (isInsertMenu) {
            const isUpdateMenu = this.updateMenuList.find(
              updateMenuItem => updateMenuItem.menuId === isInsertMenu.menuId,
            );
            /**
             * Validate that there is a user-menu whose value has changed
             */
            if (isUpdateMenu) {
              saveInsertMenuList.push({
                menuId: isUpdateMenu.menuId,
                fromDate: this.$filters.dateFormat(isUpdateMenu.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isUpdateMenu.thruDate, 'YYYYMMDD'),
                authorizationIdList: this.getMenuAuth(isUpdateMenu),
              });
            } else {
              saveInsertMenuList.push({
                menuId: isInsertMenu.menuId,
                fromDate: this.$filters.dateFormat(isInsertMenu.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isInsertMenu.thruDate, 'YYYYMMDD'),
                authorizationIdList: this.getMenuAuth(isInsertMenu),
              });
            }
          } else {
            const isUpdateMenu = this.updateMenuList.find(
              updateMenuItem => updateMenuItem.menuId === menuListItem.menuId,
            );

            /**
             * Validate that there is a user-menu whose value has changed
             */
            if (isUpdateMenu) {
              saveUpdateMenuList.push({
                menuId: isUpdateMenu.menuId,
                fromDate: this.$filters.dateFormat(isUpdateMenu.fromDate, 'YYYYMMDD'),
                thruDate: this.$filters.dateFormat(isUpdateMenu.thruDate, 'YYYYMMDD'),
                authorizationIdList: this.getMenuAuth(isUpdateMenu),
              });
            }
          }
        });

        if (saveInsertMenuList.length > 0) {
          /**
           * User-Menu Registration API Callout
           */
          await axios
            .post(`${SDLUtil.API_URL}/auth/users/${this.epId}/menus`, saveInsertMenuList, {
              headers: { 'Content-Type': 'application/json' },
            })
            .then(response => {
              if (response.status === 200) {
                this.clearCache();
                check = true;
              }
            })
            .catch(err => {
              // Call error alert
              SDLUtil.errorAlert(err);
              check = false;
            });
        }
      } else {
        this.updateMenuList.forEach(updateMenuItem => {
          saveUpdateMenuList.push({
            menuId: updateMenuItem.menuId,
            fromDate: this.$filters.dateFormat(updateMenuItem.fromDate, 'YYYYMMDD'),
            thruDate: this.$filters.dateFormat(updateMenuItem.thruDate, 'YYYYMMDD'),
            authorizationIdList: this.getMenuAuth(updateMenuItem),
          });
        });
      }

      if (saveUpdateMenuList.length > 0) {
        /**
         * Call user-menu modification API
         */
        await axios
          .put(`${SDLUtil.API_URL}/auth/users/${this.epId}/menus`, saveUpdateMenuList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              this.clearCache();
              check = true;
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
            check = false;
          });
      }

      /**
       * Verify that the registration or modification API was called normally
       */
      if (check) {
        // User-menu list lookup
        this.getUserMenu();

        // Initialize added user-menu storage list
        this.tempMenuList.splice(0);
        // Initialize Modified User-Menu Storage List
        this.updateMenuList = [];
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User-Menu Delete Confirm Callout
     */
    delUserMenuBtn() {
      const selectMenuList = this.menuList.filter(menu => menu.selected);

      /**
       * Return if there is no user-menu selection result
       */
      if (selectMenuList.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        return;
      }

      /**
       * User-Menu Delete Confirm Callout
       */
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteUserMenu(selectMenuList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Delete User-Menu
     */
    deleteUserMenu(selectList) {
      const delList = [];

      selectList.forEach(selectItem => {
        const deleteMenuListIndex = this.tempMenuList.findIndex(tempMenu => tempMenu.menuId === selectItem.menuId);

        /**
         * Validate that the Added User-Menu
         */
        if (deleteMenuListIndex > -1) {
          this.tempMenuList.splice(deleteMenuListIndex, 1);
        } else {
          delList.push(selectItem.menuId);
        }
        this.menuList.splice(this.menuList.findIndex(menuItem => menuItem.menuId === selectItem.menuId), 1);
        this.beforeMenuList.splice(
          this.beforeMenuList.findIndex(beforeItem => beforeItem.menuId === selectItem.menuId),
          1,
        );
        this.updateMenuList.splice(
          this.updateMenuList.findIndex(updateItem => updateItem.menuId === selectItem.menuId),
          1,
        );
      });

      /**
       * Validate that the purge target is a list of user-menu stored in the DB
       */
      if (delList.length > 0) {
        /**
         * User-Menu Delete API Callout
         */
        axios
          .delete(`${SDLUtil.API_URL}/auth/users/${this.epId}/menus`, { data: delList })
          .then(response => {
            if (response.status === 200) {
              this.clearCache();
              // console.log('menu delect!!');
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
      // Uncheck User-Menu full
      this.selectAll_menu = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Go to the User Management menu
     */
    moveUserMgmtBtn() {
      this.goBackToList();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Delete User button
     */
    deleteUserBtn() {
      /**
       * Confirm user deletion
       */
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteUser(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Delete User
     */
    deleteUser() {
      /**
       * User Delete API Callout
       */
      axios
        .delete(`${SDLUtil.API_URL}/auth/users/${this.epId}`, null)
        .then(response => {
          if (response.status === 200) {
            this.clearCache();
            SDLUtil.alert('sdl.common.message.deleted');
            // Go to the User Management menu
            this.goBackToList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Save user-menu, user-role list previous values
     */
    setValue(flag) {
      if (flag === 'ROLE') {
        this.beforeRoleList = _.cloneDeep(this.roleList);
      } else if (flag === 'MENU') {
        this.beforeMenuList = _.cloneDeep(this.menuList);
      }
    },

    dateInput(value, item) {
      if (item.fromDate > item.thruDate) {
        item.thruDate = item.fromDate;
      }
    },
  },
  created() {
    this.updateRoleList = [];
    this.updateMenuList = [];
    // Values passed from Master Page(epid)
    this.epId = this.$route.params.userId;
    // User Detail Query
    this.getUserInfo();
    // User-Role Query
    this.getUserRole();
    // User-Menu Query
    this.getUserMenu();
  },
  mounted() {
    this.$nextTick(() => {
      // console.info('loaded UserInfo.vue');
    });
  },
  watch: {
    roleList: {
      handler(after, before) {
        if (before.length > 0) {
          // Compare user-role transfers with changed values to extract only different values
          const changedRoleList = after.filter((p, idx) => Object.keys(p).some(prop => p[prop] !== this.beforeRoleList[idx][prop]));

          changedRoleList.forEach(changedRoleItem => {
            const isExistIndex = this.updateRoleList.findIndex(role => role.roleId === changedRoleItem.roleId);

            if (isExistIndex > -1) {
              // Added as modified user-role list
              this.updateRoleList.splice(isExistIndex, 1);
            }
            // Adding to the Modified User-Role List
            this.updateRoleList.push(changedRoleItem);
          });
        }
        // Save user-role transfer value
        this.setValue('ROLE');
      },
      deep: true,
    },
    menuList: {
      handler(after, before) {
        if (before.length > 0) {
          // Compare user-menu transfers with changed values to extract only different values
          const changedMenuList = after.filter((p, idx) => Object.keys(p).some(prop => p[prop] !== this.beforeMenuList[idx][prop]));

          changedMenuList.forEach(changedMenuItem => {
            const isExistIndex = this.updateMenuList.findIndex(menu => menu.menuId === changedMenuItem.menuId);
            if (isExistIndex > -1) {
              // Added as modified user-menu list
              this.updateMenuList.splice(isExistIndex, 1);
            }
            // Adding to the Modified User-Menu List
            this.updateMenuList.push(changedMenuItem);
          });
        }
        // Save user-menu transfer value
        this.setValue('MENU');
      },
      deep: true,
    },
  },
};
</script>
<style></style>
