<!--
 Program: UserListPopup.vue
 Author: SDL
 Description: A pop-up screen that queries the user's information and sends the selected user's information.
-->
<template>
  <div class="modal-dialog modal-dialog-centered  modal-dialog-scrollable modal-lg">
    <div class="modal-content" style="height:700px;">
      <!-- contents -->
      <div class="modal-header">
        <h5 class="modal-title h4">{{ $t('sdl.user.label.heading') }} {{ $t('sdl.common.label.search') }}</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="$emit('close')"></button>
      </div>
      <div class="modal-body">
        <!-- SEARCH Area -->
        <div class="ui--search-container clearfix">
          <div class="col-11 float-start">
            <div class="row">
              <div :class="[userStatus ? 'col-7' : 'col']">
                <!-- form -->
                <div class="row">
                  <label
                    :class="[userStatus ? 'col-3 col-form-label text-end' : 'col-2 col-form-label text-end']"
                    >{{ $t('sdl.user.label.userCondition') }}</label
                  >
                  <div class="col-9">
                    <div class="input-group">
                      <!-- dropdown -->
                      <select class="form-select d-block" style="width:40%" 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:60%"
                        v-model="searchParam.searchTxt"
                        @keyup.enter.stop="getUserList()"
                        @keyup.esc="searchParam.searchTxt = ''"
                      />
                    </div>
                  </div>
                </div>
              </div>
              <template v-if="userStatus">
                <div class="col-5">
                  <!-- 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>
              </template>
            </div>
            <!-- //row2 -->
          </div>
          <!-- search button -->
          <div class="col-1 float-end text-end">
            <button class="btn btn-primary btn-search" type="submit" @click="getUserList()">
              {{ $t('sdl.common.label.search') }}
            </button>
          </div>
        </div>
        <!-- TABLE Area-->
        <table class="table table-bordered ui--table">
          <colgroup>
            <col style="width:3%">
            <col style="width:20%">
            <col style="width:17%">
            <col>
            <col style="width:23%">
          </colgroup>
          <thead>
            <tr>
              <th scope="col">
                <input type="checkbox" v-if="!singleMode" @click.stop v-model="selectAll" @change="toggleSelectAll" />
              </th>
              <th scope="col">{{ $t('sdl.user.label.knoxId') }}</th>
              <th scope="col">{{ $t('sdl.common.label.name') }}</th>
              <th scope="col">{{ $t('sdl.user.label.deptName') }}</th>
              <th scope="col">{{ $t('sdl.user.label.mobile') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in userList" :key="user.userId">
              <td class="text-center">
                <input type="checkbox" v-if="!singleMode" v-model="user.selected" @change="selectRow(user)" />
                <input type="radio" v-else name="userCheck" :value="user.userId" v-model="checkUserId" />
              </td>
              <td class="text-left">{{ user.knoxId }}</td>
              <td class="text-left">{{ user.userName }}</td>
              <td class="text-left text-break">{{ user.deptName }}</td>
              <td class="text-left">{{ user.mobile }}</td>
            </tr>
          </tbody>
        </table>
        <!-- TABLE Area-->
        <!-- Pagination Area-->
        <sdl-pagination
          :current-page="current_page"
          :total-rows="total"
          :per-page="per_page"
          @change="handleCurrentChange"
          align="center"
        />
        <!-- Pagination Area-->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="$emit('close')">
          {{ $t('sdl.common.label.cancel') }}
        </button>
        <button type="button" class="btn btn-primary" @click="rtnData">{{ $t('sdl.common.label.confirm') }}</button>
      </div>
      <!-- // contents -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      searchParam: {
        searchColumn: '',
        searchTxt: '',
        searchStatus: '',
        active: '',
      },
      selectAll: false,
      per_page: null,
      current_page: null,
      total: null,
      userTypeList: [],
      userStatList: [],
      userList: [],
      selectUser: [],
      checkUserId: '',
      regExp: {
        email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/,
      },
    };
  },
  props: {
    searchColumn: {
      required: false,
      type: String,
    },
    searchTxt: {
      required: false,
      type: String,
    },
    userStatus: {
      required: false,
      type: Boolean,
    },
    knoxSearch: {
      required: false,
      type: Boolean,
    },
    singleMode: {
      required: false,
      type: Boolean,
    },
    rtnFunc: {
      type: Function,
    },
  },
  mixins: [SDLLocale],
  methods: {
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: User Lookup List Checkbox Click
     */
    selectRow(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.userList.forEach(user => {
        user.selected = this.selectAll;
      });
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: User Lookup
     */
    getUserList(pageIndex = 1) {
      /**
       * Query value must be entered when querying knox
       */
      if (this.knoxSearch) {
        if (this.searchParam.searchTxt === undefined || this.searchParam.searchTxt === '') {
          SDLUtil.alert('sdl.popup.message.enterRequired');
          return;
        }

        if (
          this.searchParam.searchColumn === 'userName'
          && (this.getByte(this.searchParam.searchTxt) > 0 && this.getByte(this.searchParam.searchTxt) < 4)
        ) {
          SDLUtil.alert('sdl.popup.message.enterMore4Byte');
          return;
        }

        if (this.searchParam.searchColumn === 'email' && !this.regExp.email.test(this.searchParam.searchTxt)) {
          SDLUtil.alert('sdl.samsung.validate.email');
          return;
        }
      }

      // Set the page number sent to the current page number
      this.current_page = pageIndex;

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

      /**
       * Activate user selection when present
       */
      if (this.userStatus) {
        if (this.searchParam.searchStatus === 'ALL') {
          this.searchParam.active = '';
        } else {
          this.searchParam.active = this.searchParam.searchStatus;
        }
      }

      let apiUrl = '';

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

      /**
       * User lookup API address branching out and applying
       */
      if (this.knoxSearch) {
        apiUrl = `${SDLUtil.API_URL}/auth/users/ldap?${StringUtil.queryStringfy(params)}`;
      } else {
        apiUrl = `${SDLUtil.API_URL}/auth/users?${StringUtil.queryStringfy(params)}`;
      }

      /**
       * Call user lookup API
       */
      axios
        .get(apiUrl)
        .then(({ data }) => {
          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;

          /**
           * If the paging result is 1 and the query result is one, return and close
           */
          if (this.userList.length === 1 && this.current_page === 1) {
            this.rtnFunc(this.userList);
            this.$emit('close');
          }

          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });

      // Unselect All
      this.selectAll = false;
    },
    /**
     * param: string
     * return: number
     * exception: nothing
     * description: Return string byte length
     */
    getByte(str) {
      return str
        .split('')
        .map(s => s.charCodeAt(0))
        // eslint-disable-next-line no-bitwise,no-nested-ternary
        .reduce((prev, c) => prev + (c === 10 ? 2 : c >> 7 ? 2 : 1), 0);
    },
    /**
     * param: number
     * return: nothing
     * exception: nothing
     * description: paging
     */
    handleCurrentChange(currentPage) {
      // Invoke user lookup method
      this.getUserList(currentPage);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Calling up functions that send selected user information to the screen from which it was recalled
     */
    rtnData() {
      let selectUser = [];

      /**
       * Apply outgoing values by branching out if they are applied on a quarterly basis
       */
      if (this.singleMode) {
        selectUser = this.userList.filter(user => user.userId === this.checkUserId);
      } else {
        selectUser = this.userList.filter(user => user.selected);
      }

      this.rtnFunc(selectUser);
      this.$emit('close');
    },
  },
  created() {
    // Page size - 10 settings
    this.per_page = 10;

    let commonGrpCode = 'USER_SEARCH_TYPE_S';

    if (this.knoxSearch) {
      commonGrpCode = 'USER_SEARCH_TYPE_K';
    }

    // user query condition type common code
    axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/${commonGrpCode}/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;
    });

    /**
     * Query condition setting
     */
    if (this.searchColumn === null || this.searchColumn === undefined) {
      this.searchParam.searchColumn = 'userName';
    } else {
      this.searchParam.searchColumn = this.searchColumn;
    }

    if (this.searchTxt !== null && this.searchTxt !== undefined) {
      this.searchParam.searchTxt = this.searchTxt;
    }

    /**
     * Applying exceptional conditions of inquiry to Knox inquiry
     */
    if (this.knoxSearch) {
      if (this.searchTxt === null || this.searchTxt === undefined) {
        return;
      }
      if (this.searchParam.searchColumn === 'userName' && this.searchParam.searchTxt.length < 2) {
        return;
      }
    }

    // Apply Default Value When User Status Existence
    if (this.userStatus) {
      this.searchParam.searchStatus = 'ALL';
    }

    // If there is no param value to select only one user, apply multiple selections
    if (this.singleMode === undefined) {
      this.singleMode = false;
    }

    /**
     * Apply to lookup only if there is a lookup value when inquiring knox
     */
    if (this.knoxSearch) {
      if (this.searchParam.searchTxt) {
        this.getUserList();
      }
    } else {
      this.getUserList();
    }
  },
};
</script>
<style></style>
