<!--
  Program: UserList.vue
  Author: SDL
  Description: User screen performing user lookup function with user status 'ACTIVE'
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- SEARCH Area -->
    <div class="ui--search-container clearfix">
      <div class="col-10 float-start">
        <!-- row1 -->
        <div class="row">
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.user.label.userCondition') }}</label>
              <div class="col-8">
                <div class="input-group">
                  <!-- dropdown -->
                  <select class="form-select" v-model="searchParam.searchColumn">
                    <option :value="userType.code" v-for="userType in userTypeList" :key="userType.codeId">
                      {{ getLabel(userType) }}
                    </option>
                  </select>
                  <input
                    type="text"
                    class="form-control"
                    v-model="searchParam.searchTxt"
                    @keyup.enter="getUserList()"
                    @keyup.esc="searchParam.searchTxt = ''"
                  />
                </div>
              </div>
            </div>
          </div>
          <!-- //row2 -->
        </div>
      </div>
      <!-- search button -->
      <div class="col-2 float-end text-end">
        <button class="btn btn-primary btn-search" type="submit" @click="getUserList()">
          {{ $t('sdl.common.label.search') }}
        </button>
      </div>
    </div>
    <!-- LIST Header & buttons -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(total) }}</span>
    </div>
    <!-- TABLE Area-->
    <table class="table table-bordered">
      <colgroup>
        <col style="width:18%" />
        <col style="width:35%" />
        <col style="width:17%" />
        <col style="width:20%" />
        <col style="width:10%" />
        <col />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">{{ $t('sdl.user.label.compName') }}</th>
          <th scope="col">{{ $t('sdl.common.label.department') }}</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.modifyDate') }}</th>
          <th scope="col"></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in userList" :key="user.userId">
          <td class="text-left">{{ user.compName }}</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">{{ $filters.dateFormat(user.lastModDatetime, $t('data-format.date.ymd')) }}</td>
          <td class="text-center">
            <button class="btn btn-outline-primary ui--btn-xs" type="button" @click="executeImpersonation(user)">
              impersonation
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- TABLE Area-->
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="current_page"
      :total-rows="total"
      :per-page="per_page"
      @change="handleCurrentChange"
    />
    <!-- Pagination Area-->
  </div>
</template>
<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';
import StoreParams from '@/mixin/StoreParams';
import loginService from '@/service/loginService';

export default {
  data() {
    return {
      searchParam: {
        searchColumn: '',
        searchTxt: '',
      },
      per_page: null,
      current_page: null,
      total: null,
      userTypeList: [],
      userList: [],
    };
  },
  mixins: [SDLLocale, StoreParams],
  methods: {
    /**
     * param: userInfo -> Object
     * return:
     * exception:
     * description: impersonator login
     */
    executeImpersonation(userInfo) {
      axios
        .get(`${SDLUtil.API_URL}/impersonation/login?userId=${userInfo.userId}`)
        .then(({ data }) => {
          localStorage.setItem('adminToken', localStorage.getItem('userToken'));
          // console.log(SDLUtil.getLoginedUserInfo());
          axios.defaults.headers.common['original-user-id'] = SDLUtil.getLoginedUserInfo().userId;
          loginService.setToken(data.jwtToken);
          document.location = `${SDLUtil.WEB_CONTEXT_PATH}/`;
        })
        .catch(err => {
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: User Lookup
     */
    getUserList(pageIndex = 1) {
      // Set the page number sent to the current page number
      this.current_page = pageIndex;

      /**
       * Set user lookup API enforcement parameter
       */
      const params = {
        searchCondition: this.searchParam.searchColumn,
        searchKeyword: this.searchParam.searchTxt,
        pageIndex: this.current_page,
        pageSize: this.per_page,
      };

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

      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      /**
       * Call user lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/users/status/active?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          // Apply userList to queried user lookup results
          this.userList = 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);
        });
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: paging
     */
    handleCurrentChange(currentPage) {
      // Invoke user lookup method
      this.getUserList(currentPage);
    },
    /**
     * param: string
     * return: nothing
     * exception: Call error alert
     * description: Select User Lookup List Row
     */
    rowClick(userId) {
      // Move User Detail Query (with router)
      this.$router.push(`${this.$CONTEXT}/admin/users/${userId}`);
    },
  },
  created() {
    // Import Previous Query Parameter
    const storeParams = this.getStoreParameter();

    // user query condition type common code
    axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/USER_SEARCH_TYPE/commcodes`).then(({ data }) => {
      this.userTypeList = data;
    });

    /**
     * Restore previous query parameters if present
     */
    if (storeParams) {
      // Apply previous query input search condition
      this.searchParam.searchColumn = storeParams.searchCondition;
      // Apply previous query text
      this.searchParam.searchTxt = storeParams.searchKeyword;
      // Apply previous lookup page number
      this.current_page = storeParams.pageIndex;
      // Apply previous query page size
      this.per_page = storeParams.pageSize;
      // Invoke user lookup method by applying previous lookup page number
      this.getUserList(this.current_page);
    } else {
      // Query condition - name setting
      this.searchParam.searchColumn = 'userName';
      // Page size - 10 settings
      this.per_page = 10;
      // Invoke user lookup method
      this.getUserList();
    }
  },
};
</script>
<style></style>
