<!--
 Program: UserMgmtList.vue
 Author: SDL
 Description: User management screen that performs user lookup and approval, approval cancellation, and deletion functions
-->
<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" style="width:35%" 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"
                    style="width:65%"
                    v-model.trim="searchParam.searchTxt"
                    @keyup.enter="getUserList()"
                    @keyup.esc="searchParam.searchTxt = ''"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.user.label.userStatus') }}</label>
              <div class="col-8">
                <!-- dropdown -->
                <select class="form-select" v-model="searchParam.searchStatus">
                  <option :value="userStat.code" v-for="userStat in userStatList" :key="userStat.codeId">
                    {{ getLabel(userStat) }}
                  </option>
                </select>
              </div>
            </div>
          </div>
        </div>
        <!-- //row1 -->
      </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(userListCnt) }}</span>
      <div class="float-end">
        <sdl-exceldownloadbtn
          :excelInfo="getExcelInfo()"
          class="btn btn-secondary btn-sm"
          v-authorization="'download'"
        ></sdl-exceldownloadbtn>
        <button type="button" class="btn btn-secondary btn-sm" @click="deleteUserBtn" v-authorization="'update'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="updateUserInactiveBtn" v-authorization="'update'">
          {{ $t('sdl.user.label.cancelApproval') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="updateUserComfirmBtn" v-authorization="'update'">
          {{ $t('sdl.approval.label.APPROVED') }}
        </button>
      </div>
    </div>
    <!-- TABLE Area-->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:3%" />
        <col style="width:12%" />
        <col style="width:30%" />
        <col style="width:17%" />
        <col style="width:20%" />
        <col style="width:8%" />
        <col style="width:10%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">
            <input
              type="checkbox"
              @click.stop
              :disabled="this.searchParam.active === 'DELETED'"
              v-model="selectAll"
              @change="toggleSelectAll"
            />
          </th>
          <th scope="col">{{ $t('sdl.user.label.compName') }}</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.user.label.workStatus') }}</th>
          <th scope="col">{{ $t('sdl.user.label.status') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in userList" :key="user.userId" @click="rowClick(user.userId)" class="cursor-pointer">
          <td class="text-center" @click.stop>
            <input
              type="checkbox"
              :disabled="user.userStatus === 'DELETED'"
              v-model="user.selected"
              @change="checkBoxClick(user)"
            />
          </td>
          <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">
            <span v-if="user.expireStatus === 'RETIRE'">{{
              $t('sdl.user.label.retire')
            }}</span>
            <span v-else-if="user.expireStatus === 'MOVE'">{{
              $t('sdl.user.label.move')
            }}</span>
            <span v-else-if="user.expireStatus === 'LONG_TERM'">{{
              $t('sdl.user.label.longTerm')
            }}</span>
            <span v-else-if="user.expireStatus === 'DELETED'">{{
              $t('sdl.common.label.delete')
            }}</span>
            <span v-else-if="user.expireStatus === null">{{
              $t('sdl.user.label.work')
            }}</span>
            <span v-else-if="user.expireStatus === ''">{{
              $t('sdl.user.label.work')
            }}</span>
            <span v-else>{{
              $t('sdl.user.label.work')
            }}</span>
          </td>
          <td class="text-center">
            <span v-if="user.userStatus === 'ACTIVE'" class="badge ui--status-primary">{{
              $t('sdl.user.label.active')
            }}</span>
            <span v-else-if="user.userStatus === 'INACTIVE'" class="badge ui--status-rejected">{{
              $t('sdl.user.label.inactive')
            }}</span>
            <span v-else-if="user.userStatus === 'WAITING'" class="badge ui--status-processing">{{
              $t('sdl.user.label.waiting')
            }}</span>
            <span v-else-if="user.userStatus === 'DELETED'" class="badge ui--status-secondary">{{
              $t('sdl.common.label.delete')
            }}</span>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- TABLE Area-->
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="pageIndex"
      :total-rows="userListCnt"
      :per-page="pageSize"
      @change="handleCurrentChange"
      align="center"
    />
    <!-- Pagination Area-->
  </div>
</template>
<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      // userTypeList: SDLUtil.getCommCodeList({ commCodeTypeId: 'USERGUBUN' }),
      searchParam: {
        searchColumn: '',
        searchTxt: '',
        searchStatus: '',
        active: '',
        isExcel: null,
      },
      pageSize: null,
      pageIndex: null,
      selectAll: false,
      userTypeList: [],
      userStatList: [],
      userList: [],
      userListCnt: null,
      selectUserData: [],
      strIds: '',
    };
  },
  mixins: [SDLLocale, StoreParams],
  methods: {
    /**
     * 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.pageIndex = pageIndex;

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

      /**
       * Input Conditions - Apply active values based on user status
       */
      if (this.searchParam.searchStatus === 'ALL') {
        this.searchParam.active = '';
      } else {
        this.searchParam.active = this.searchParam.searchStatus;
      }

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

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

      /**
       * Call user lookup API
       */
      axios
        .get(`${SDLUtil.API_URL}/auth/users?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.userList = data.rows;
          /**
           * Adding a hold-on status to the userList
           */
          this.userList.forEach(user => {
            if (user.expireStatus === null) {
              user.expireStatusName = SDLUtil.getMsgProp('sdl.user.label.work');
            } else if (user.expireStatus === 'RETIRE') {
              user.expireStatusName = SDLUtil.getMsgProp('sdl.user.label.retire');
            } else if (user.expireStatus === 'MOVE') {
              user.expireStatusName = SDLUtil.getMsgProp('sdl.user.label.move');
            } else if (user.expireStatus === 'LONG_TERM') {
              user.expireStatusName = SDLUtil.getMsgProp('sdl.user.label.longTerm');
            } else {
              user.expireStatusName = SDLUtil.getMsgProp('sdl.user.label.work');
            }
          });

          // Apply the page number that was retrieved to the current_page
          this.pageIndex = data.currentPage;
          // Full Row Count
          this.userListCnt = data.records;

          // Remove Loading bar
          SDLUtil.showLoadingBar(false);

          // Unselect All
          this.selectAll = 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/usermgmt/${userId}`);
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: User Lookup List Checkbox Click
     */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      if (this.userList.length > 0) {
        this.userList.forEach(userItem => {
          userItem.selected = this.selectAll;
        });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Save selected row information to string
     */
    saveSelectList() {
      // Initialize string variable
      this.strIds = '';
      // Filter Selected User List (checkbox)
      const checkList = this.userList.filter(user => user.selected);

      /**
       * Save userId to strIds in selected user list
       */
      checkList.forEach((checkItem, idx) => {
        if (idx !== 0) {
          this.strIds += `,${checkItem.userId}`;
        } else {
          this.strIds = checkItem.userId;
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User Approval Button
     */
    updateUserComfirmBtn() {
      // Verify that the selected user list is present (checkbox)
      if (!this.userList.find(user => user.selected)) {
        SDLUtil.alert('sdl.user.message.selectUser');
        return;
      }

      // Save ID to apply user approval
      this.saveSelectList();

      /**
       * Confirm user approval
       */
      SDLUtil.confirm({
        title: 'sdl.approval.label.APPROVED',
        msg: 'sdl.user.message.approve',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.updateUserComfirm(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User Approval
     */
    updateUserComfirm() {
      /**
       * User-Approved API Callout
       */
      axios
        .put(
          `${SDLUtil.API_URL}/auth/users/status/confirm`,
          { ids: this.strIds },
          { headers: { 'Content-Type': 'application/json' } },
        )
        .then(response => {
          if (response.status === 200) {
            // Invoke user lookup method
            this.getUserList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: User Acceptance Cancellation Button
     */
    updateUserInactiveBtn() {
      /**
       * Verify that the selected user list is present (checkbox)
       */
      if (!this.userList.find(user => user.selected)) {
        SDLUtil.alert('sdl.user.message.selectUser');
        return;
      }

      // Save id to be revoked for approval
      this.saveSelectList();

      /**
       * Confirm user approval cancellation
       */
      SDLUtil.confirm({
        title: 'sdl.user.label.cancelApproval',
        msg: 'sdl.user.message.cancelApproval',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.updateUserInactive(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Cancel User Authorization
     */
    updateUserInactive() {
      /**
       * User Acceptance Cancellation API Callout
       */
      axios
        .put(
          `${SDLUtil.API_URL}/auth/users/status/inactive`,
          { ids: this.strIds },
          { headers: { 'Content-Type': 'application/json' } },
        )
        .then(response => {
          if (response.status === 200) {
            // Invoke user lookup method
            this.getUserList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Delete User button
     */
    deleteUserBtn() {
      /**
       * Verify that the selected user list is present (checkbox)
       */
      if (!this.userList.find(user => user.selected)) {
        SDLUtil.alert('sdl.user.message.selectUser');
        return;
      }

      const selectedUserList = this.userList.filter(user => user.selected);
      /**
       * 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(selectedUserList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Delete User
     */
    deleteUser(selectedUserList) {
      const userIdList = selectedUserList.map(user => user.userId);
      /**
       * User Delete API Callout
       */
      axios
        .delete(`${SDLUtil.API_URL}/auth/users`, { data: userIdList })
        .then(response => {
          if (response.status === 200) {
            // Invoke user lookup method
            this.getUserList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Set condition values required for Excel download
     */
    getExcelInfo() {
      /**
       * User Status
       */
      let searchStatus = {};

      if (this.searchParam.searchStatus === 'ACTIVE') {
        // User Status : User
        searchStatus = { deleted: false, activeFlag: true };
      } else if (this.searchParam.searchStatus === 'INACTIVE') {
        // User Status : Not User
        searchStatus = { deleted: false, activeFlag: false, expireStatusNotNull: '0' };
      } else if (this.searchParam.searchStatus === 'WAITING') {
        // User Status : Standby
        searchStatus = { deleted: false, activeFlag: false, expireStatus: '' };
      } else if (this.searchParam.searchStatus === 'DELETED') {
        // User Status : Delete
        searchStatus = { deleted: true };
      } else {
        // User Status : All
        searchStatus = { deleted: false };
      }

      const name = SDLUtil.getMsgProp('sdl.user.label.userMgmt');
      return {
        columnInfoFile: 'user',
        fileName: name,
        queryId: 'selectUser',
        sheetName: name,
        useNumberField: 'Y',
        param: {
          searchCondition: this.searchParam.searchColumn,
          searchKeyword: this.searchParam.searchTxt,
          active: this.searchParam.active,
          ...searchStatus,
          orderBy: 'FIRST_REG_DATETIME DESC',
          isExcel: 'Y',
        },
      };
    },
  },
  created() {
    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;
    });

    // user status common code
    axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/USER_STAT/commcodes`).then(({ data }) => {
      this.userStatList = data;
    });

    /**
     * Confirm the existence of the previous
     */
    if (storeParams) {
      // Apply previous query input search condition
      this.searchParam.searchColumn = storeParams.searchCondition;
      // Apply previous query text
      this.searchParam.searchTxt = storeParams.searchKeyword;

      /**
       * Apply according to previous query user status values
       */
      if (storeParams.active === '') {
        // Previous Query User Status - Full
        this.searchParam.searchStatus = 'ALL';
      } else {
        // Apply previous query user status
        this.searchParam.searchStatus = storeParams.active;
      }
      // Apply previous lookup page number
      this.pageIndex = storeParams.pageIndex;
      // Apply previous query page size
      this.pageSize = storeParams.pageSize;
      // Apply previous lookup page number to query the user
      this.getUserList(this.pageIndex);
    } else {
      // Query condition - name setting
      this.searchParam.searchColumn = 'userName';
      // User Status - All Settings
      this.searchParam.searchStatus = 'ALL';
      // Page size - 10 settings
      this.pageSize = 10;
      // Invoke user lookup method
      this.getUserList();
    }
  },
  mounted() {
    this.$nextTick(() => {
      // console.info('loaded UserMgmtList.vue');
    });
  },
};
</script>
<style></style>
