<!--
  Program: RoleUserInfo.vue
  Author: SDL
  Description: Retrieves the role details and retrieves, registers, modifies, and deletes the role-user 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.user.label.active') }}</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.roleName') }}</th>
            <td>{{ roleItem.label }}</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">
        <h5 class="d-inline-block">{{ $t('sdl.common.label.list') }}</h5>
        <div class="float-end">
          <button type="button" class="btn btn-secondary btn-sm" @click="deleteRoleUserBtn" v-authorization="'update'">
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="updateRoleUserBtn" v-authorization="'update'">
            {{ $t('sdl.common.label.edit') }}
          </button>
        </div>
      </div>
      <!--/ buttons -->
      <!-- Role-User TABLE Area-->
      <table class="table table-bordered ui--table">
        <colgroup>
          <col style="width:3%" />
          <col style="width:30%" />
          <col style="width:17%" />
          <col style="width:20%" />
          <col style="width:15%" />
          <col style="width:15%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll_top" @change="toggleSelectAll('top')" />
            </th>
            <th scope="col">{{ $t('sdl.user.label.deptName') }}</th>
            <th scope="col">{{ $t('sdl.common.label.name') }}</th>
            <th scope="col">{{ $t('sdl.user.label.knoxId') }}</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="user in roleUserList" :key="user.userId">
            <td class="text-center">
              <input type="checkbox" v-model="user.selected" @change="checkBoxClick('top')" />
            </td>
            <td class="text-left">{{ user.deptName }}</td>
            <td class="text-left">{{ user.userName }}</td>
            <td class="text-left">{{ user.knoxId }}</td>
            <td class="text-center">
              <sdl-datepicker v-model="user.fromDate" wrap-class="" :disabled-date="user.disabledDate" @input="dateInput($event, user)"></sdl-datepicker>
            </td>
            <td class="text-center">
              <sdl-datepicker v-model="user.thruDate" wrap-class="" :disabled-date="user.disabledDate" @input="dateInput($event, user)"></sdl-datepicker>
            </td>
          </tr>
        </tbody>
      </table>
      <!--/ Role-User TABLE Area-->
      <!-- Pagination  Area-->
      <sdl-pagination
        :current-page="current_page"
        :total-rows="total"
        :per-page="per_page"
        @change="handleCurrentChange"
        align="center"
      />
      <!-- Pagination  Area-->

      <!-- Total count & buttons -->
      <div class="ui--list-heading clearfix">
        <h5 class="d-inline-block">{{ $t('sdl.common.label.register') }}</h5>
        <div class="float-end">
          <button
            type="button"
            class="btn btn-secondary btn-sm"
            @click="deleteTempRoleUserBtn"
            v-authorization="'update'"
          >
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button
            type="button"
            class="btn btn-secondary btn-sm"
            @click="addTempRoleUserBtn"
            v-authorization="'execute'"
          >
            {{ $t('sdl.common.label.add') }}
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm"
            @click="saveTempRoleUserBtn"
            v-authorization="['update', 'execute']"
          >
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- Total count & buttons -->
      <!-- Role-User TABLE Area-->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:30%" />
          <col style="width:17%" />
          <col style="width:20%" />
          <col style="width:15%" />
          <col style="width:15%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll_bottom" @change="toggleSelectAll('bottom')" />
            </th>
            <th scope="col">{{ $t('sdl.user.label.deptName') }}</th>
            <th scope="col">{{ $t('sdl.common.label.name') }}</th>
            <th scope="col">{{ $t('sdl.user.label.knoxId') }}</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="user in tempRoleUserList" :key="user.userId">
            <td class="text-center">
              <input type="checkbox" v-model="user.selected" @change="checkBoxClick('bottom')" />
            </td>
            <td class="text-left">{{ user.deptName }}</td>
            <td class="text-left">{{ user.userName }}</td>
            <td class="text-left">{{ user.knoxId }}</td>
            <td class="text-center">
              <sdl-datepicker v-model="user.fromDate" wrap-class="" :disabled-date="user.disabledDate" @input="dateInput($event, user)"></sdl-datepicker>
            </td>
            <td class="text-center">
              <sdl-datepicker v-model="user.thruDate" wrap-class="" :disabled-date="user.disabledDate" @input="dateInput($event, user)"></sdl-datepicker>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- Role-User 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, StringUtil } from '@/utils';
import UserPopup from '@/components/common/popup/UserListPopup.vue';
import StoreParams from '@/mixin/StoreParams';

export default {
  data() {
    return {
      roleId: null,
      roleItem: {},
      selectAll_top: false,
      per_page: null,
      current_page: null,
      total: 0,
      roleUserList: [],
      selectAll_bottom: false,
      tempRoleUserList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Retrieve role details
     */
    getRoleInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      /**
       * Call role details lookup API
       */
      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);
          // 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-user deletion API after verifying that the selected role-user exists
     */
    deleteRoleUserBtn() {
      const selectRoleUser = this.roleUserList.filter(roleUser => roleUser.selected);

      if (selectRoleUser.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.deleteRoleUser(selectRoleUser),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Selected roles-Check for users and call role-user modification function
     */
    updateRoleUserBtn() {
      const selectRoleUser = this.roleUserList.filter(roleUser => roleUser.selected);

      if (selectRoleUser.length === 0) {
        SDLUtil.alert('sdl.common.message.checkModifiedRow');
        return;
      }

      this.updateRoleUser(selectRoleUser);
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: Roles-User Lookup
     */
    getRoleUserList(pageIndex = 1) {
      // Set the page number sent to the current page number
      this.current_page = pageIndex;

      /**
       * Set roles-user lookup API enforcement parameter
       */
      const params = {
        roleId: this.roleId,
        pageIndex: this.current_page,
        pageSize: this.per_page,
        orderBy: 'USER_NAME',
      };

      /**
       * Invoke roles-user lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/roles/DEFAULT_ROLE/users-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.roleUserList = data.rows;
          this.current_page = data.currentPage; // 현재 page number
          this.total = data.records; // 전체 row count

          this.roleUserList.forEach(roleUser => {
            roleUser.fromDate = this.$filters.dateFormat(roleUser.fromDate, 'YYYY-MM-DD');
            roleUser.thruDate = this.$filters.dateFormat(roleUser.thruDate, 'YYYY-MM-DD');
            roleUser.disabledDate = { to: this.$moment().subtract(1, 'd').toDate() };
          });
          this.selectAll_top = false;
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Modify Role-User
     */
    async updateRoleUser(selectRoleUser) {
      // Convert for DB stored format
      selectRoleUser.forEach(roleUser => {
        roleUser.roleId = this.roleId;
        roleUser.fromDate = this.$filters.dateFormat(roleUser.fromDate, 'YYYYMMDD');
        roleUser.thruDate = this.$filters.dateFormat(roleUser.thruDate, 'YYYYMMDD');
      });

      /**
       * Call role-user modification API
       */
      await axios
        .put(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/users`, selectRoleUser, {
          headers: { 'Content-Type': 'application/json' },
        })
        .then(response => {
          if (response.status === 200) {
            SDLUtil.alert('sdl.common.message.updated');
            this.getRoleUserList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Locate the ID of the selected user and delete the appropriate user from the role-user list
     */
    deleteRoleUser(selectRoleUser) {
      const userIds = selectRoleUser.map(user => user.userId);

      /**
       * Call role-user delete API
       */
      axios
        .delete(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/users`, { data: userIds })
        .then(response => {
          if (response.status === 200) {
            this.getRoleUserList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: number
     * return: nothing
     * exception: nothing
     * description: paging
     */
    handleCurrentChange(currentPage) {
      this.getRoleUserList(currentPage);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Temporary Role - Check if the check box is selected in the user list and remove it from the temporary role - user list
     */
    deleteTempRoleUserBtn() {
      const selectRoleUser = this.tempRoleUserList.filter(roleUser => roleUser.selected);

      if (selectRoleUser.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        return;
      }

      // Remove ROW, such as USER _ ID, from the list of temporary role-users selected from the list of users
      selectRoleUser.forEach(selectRoleUserItem => {
        this.tempRoleUserList.splice(
          this.tempRoleUserList.findIndex(tempRoleUserItem => tempRoleUserItem.userId === selectRoleUserItem.userId),
          1,
        );
      });

      // full selection initialization
      this.selectAll_bottom = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the user query popup function
     */
    addTempRoleUserBtn() {
      this.openUserPopUp();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking if there is a temporary role-user list, call the role-user registration function
     */
    saveTempRoleUserBtn() {
      if (this.tempRoleUserList.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.insertRoleUser(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call user lookup popup
     */
    openUserPopUp() {
      SDLUtil.show(
        UserPopup,
        {
          userStatus: true,
          rtnFunc: args => {
            this.checkRoleUserList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Compare with saved role-user lists, and save to role-user lists
     */
    checkRoleUserList(userPopupList) {
      userPopupList.forEach(async userPopupItem => {
        let isExist = true;

        /**
         * Make sure that the user is in the saved role-user list
         */
        await axios
          .get(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/users-existence/${userPopupItem.userId}`)
          .then(({ data }) => {
            isExist = data;
          });

        if (!isExist) {
          // Add only if there is no comparison between added user information and temporary role-user list
          if (!this.tempRoleUserList.find(tempRoleUserItem => tempRoleUserItem.userId === userPopupItem.userId)) {
            this.tempRoleUserList.push({
              roleId: this.roleId,
              knoxId: userPopupItem.knoxId,
              userId: userPopupItem.userId,
              userName: userPopupItem.userName,
              grdName: userPopupItem.grdName,
              deptName: userPopupItem.deptName,
              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() },
            });
          }
        }
      });
    },
    /**
     * 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 - User
     */
    async insertRoleUser() {
      if (this.tempRoleUserList.length > 0) {
        this.tempRoleUserList.forEach(roleUser => {
          roleUser.fromDate = this.$filters.dateFormat(roleUser.fromDate, 'YYYYMMDD');
          roleUser.thruDate = this.$filters.dateFormat(roleUser.thruDate, 'YYYYMMDD');
        });

        await axios
          .post(`${SDLUtil.API_URL}/auth/roles/${this.roleId}/users`, this.tempRoleUserList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              // Delete when it exists in the list of users for registration (remove after registration)
              this.tempRoleUserList = [];
              this.selectAll_bottom = false;

              this.getRoleUserList();
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of workgroup
     */
    checkBoxClick(listFlag) {
      if (listFlag === 'top') {
        this.roleUserList.forEach(roleItem => {
          if (!roleItem.selected) {
            this.selectAll_top = false;
          }
        });
      } else {
        this.tempRoleUserList.forEach(tempRoleItem => {
          if (!tempRoleItem.selected) {
            this.selectAll_bottom = false;
          }
        });
      }
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll(listFlag) {
      if (listFlag === 'top') {
        this.roleUserList.forEach(roleItem => {
          roleItem.selected = this.selectAll_top;
        });
      } else {
        this.tempRoleUserList.forEach(tempRoleitem => {
          tempRoleitem.selected = this.selectAll_bottom;
        });
      }
    },

    dateInput(value, item) {
      if (item.fromDate > item.thruDate) {
        item.thruDate = item.fromDate;
      }
    },
  },
  created() {
    this.per_page = 10;
    this.roleItem = {};
    this.roleId = this.$route.params.roleId;
    this.getRoleInfo();
    this.getRoleUserList();
  },
};
</script>
