<!--
 as is 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">Sold To Code {{ $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>
        <div class="ui--list-heading clearfix">
          <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat_de(total) }} </span>
        </div>
        <div class="grid-wrap" style="height:" id="grd_main_div">
          <div class="realgrid" id="grid" style="width: 100%; height: 350px"></div>
        </div>
        <!-- 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 _ from 'lodash';
import { SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';
import GridCommon from '@/mixin/GridCommon';
import RealGrid from 'realgrid';

export default {
  mixins: [SDLLocale, GridCommon],
  data() {
    return {
      searchParam: {
        searchColumn: '',
        searchTxt: '',
        searchStatus: '',
        active: '',
      },

      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}))$/,
      },
      //-- grid
      dataProvider: null,
      gridView: null,
      gridList: [],
      checkedItems: [],
    };
  },
  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,
    },
  },
  methods: {
    init() {},
    initGrid() {
      this.dataProvider = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용
      this.gridView = new RealGrid.GridView('grid'); // GridView 사용
      this.gridView.setDataSource(this.dataProvider); // setDataSource 사용

      //set grid edit option
      const options = { options: { checkBar: { visible: true, showAll: true } }, displayOptions: { columnMovable: true, rowHeight: 25 } };

     
      this.grid_setGridOptions(this.gridView, options);

       if (this.singleMode) {
        //console.info('singleMode',this.singleMode);
        this.gridView.setCheckBar({
          exclusive: true,
        });
      }

      // 그리드 데이터 설정
      this.dataProvider.setFields([{ fieldName: 'knoxId' }, { fieldName: 'userName' }, { fieldName: 'deptName' }, { fieldName: 'mobile' }]);

      this.gridView.setColumns([
        { fieldName: 'knoxId', header: 'knoxId', width: 150 },
        { fieldName: 'userName', header: 'userName', width: 200 },
        { fieldName: 'deptName', header: 'deptName', width: 250 },
        { fieldName: 'mobile', header: 'mobile', width: 150 },
      ]);

      // set grid event
      this.gridView.onCellClicked = (grid, clickData) => {
        if (clickData.column == 'fmName') {
          let row = this.dataProvider.getJsonRow(clickData.dataRow);
          //console.log('row', row);
          //this.moveRegistPage(row.fmId);
        }
      };

      this.gridView.onItemChecked = (grid, itemIndex, checked) => {
        this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
      };

      this.gridView.onItemAllChecked = (grid, checked) => {
        this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
      };
    },

    /**
     * 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.gridList = data.rows;
          this.dataProvider.setRows(this.gridList);

          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);
        });
    },
    /**
     * 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.checkedItems;
      } else {
        selectUser = this.checkedItems;
      }

      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();
    }

    this.init();
  },
  mounted() {
    this.initGrid();

    this.$nextTick(() => {
      //console.info('initialize Page');
    });
  },
  unmounted() {
    //alert('The component is removed (unmounted)!');
    this.dataProvider.clearRows();
    this.gridView.destroy();
    this.dataProvider.destroy();
    this.gridView = null;
    this.dataProvider = null;
  },
};
</script>
<style></style>
