<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">
        <div class="row">
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.common.label.type') }}</label>
              <div class="col-8">
                <!-- dropdown -->
                <select class="form-select" v-model="reqType">
                  <option :value="connectType.code" v-for="connectType in connectTypeList" :key="connectType.codeId">{{ getLabel(connectType) }}</option>
                </select>
              </div>
            </div>
          </div>
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-4 col-form-label text-end">{{ $t('sdl.common.label.name') }}</label>
              <div class="col-8">
                <input class="form-control" type="text" v-model="userName" @keydown.enter="getList()" />
              </div>
            </div>
          </div>
        </div>
        <div class="row mt-2">
          <div class="col-12">
            <!-- form -->
            <div class="row">
              <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.period') }}</label>
              <div class="col-10 form-inline">
                <div class="form-check form-check-inline">
                  <input class="form-check-input" v-model="datePickerUnit" type="radio" name="datePickerUnit" id="rdoMonth" value="month" />
                  <label class="form-check-label" for="rdoMonth">{{ $t('sdl.common.label.month') }}</label>
                </div>
                <div class="form-check form-check-inline">
                  <input class="form-check-input" v-model="datePickerUnit" type="radio" name="datePickerUnit" id="rdoDay" value="day" />
                  <label class="form-check-label" for="rdoDay">{{ $t('sdl.common.label.day') }}</label>
                </div>
                <sdl-datepicker v-model="searchPeriod" :period="searchPeriod" :minimum-view="datePickerUnit"></sdl-datepicker>
              </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="getList()">
          {{ $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(records) }}</span>
      <div class="float-end">
        <sdl-exceldownloadbtn :excelInfo="getExcelInfo()" class="btn btn-secondary btn-sm" />
      </div>
    </div>
    <!-- TABLE  Area-->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width: 5%" />
        <col style="width: 10%" />
        <col style="width: 15%" />
        <col style="width: 15%" />
        <col />
        <col style="width: 10%" />
        <col style="width: 6%" />
        <col style="width: 6%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">{{ $t('sdl.common.label.type') }}</th>
          <th scope="col">{{ $t('sdl.common.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.menu.label.menu') }}</th>
          <th scope="col">{{ $t('sdl.batchLogger.label.useDate') }}</th>
          <th scope="col">{{ $t('sdl.menu.menuHitCount') }}</th>
          <th scope="col">API {{ $t('sdl.menu.menuHitCount') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="log in logList" :key="log.no">
          <td class="text-center">{{ log.reqType }}</td>
          <td>{{ log.compName }}</td>
          <td>{{ log.deptName }}</td>
          <td>{{ log.userName }}</td>
          <td>{{ log.menuFullPath }}</td>
          <td v-if="displayDateUnit === 'month'" class="text-center">
            {{ $filters.dateFormat(log.useFromDate, $t('data-format.date.ym')) }}
          </td>
          <td v-if="displayDateUnit === 'day'" class="text-center">
            {{ $filters.dateFormat(log.useFromDate, $t('data-format.date.ymd')) }}
          </td>
          <td class="text-center">{{ $filters.numberFormat(log.hitCount) }}</td>
          <td class="text-center">
            <button
              class="btn btn-outline-secondary ui--btn-xs"
              @click="
                showApiUseHistory(
                  { menu: log.menuFullPath, type: displayDateUnit, date: log.useFromDate, name: log.userName },
                  { periodType: displayDateUnit, startDate: searchPeriod.startDate, endDate: searchPeriod.endDate, userId: log.userId, menuId: log.menuId },
                )
              "
            >
              {{ $t('sdl.common.label.detailContent') }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- // TABLE  Area-->
    <!-- Pagination Area-->
    <sdl-pagination :current-page="currentPage" :total-rows="records" :per-page="pageSize" @change="movePage" align="center" />
    <!--  // Pagination Area-->
  </div>
</template>

<script>
import axios from 'axios';
import { DateUtil, SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';
import ApiUseHistory from './popup/ApiUseHistory.vue';

export default {
  data() {
    return {
      userName: '',
      datePickerUnit: 'day',
      displayDateUnit: '',
      searchPeriod: {},
      endDate: '',
      reqType: '',
      connectTypeList: [],
      fields: [],
      logList: [],
      records: 0, // total number of data
      currentPage: 1, // current page number
      pageSize: 10, // number of lists per page
    };
  },
  mixins: [SDLLocale],
  methods: {
    /**
     * param:
     * return:
     * exception:
     * description : Initialize Page
     */
    init() {
      this.searchPeriod.startDate = DateUtil.subDate(1, 'M');
      this.searchPeriod.endDate = DateUtil.now();
      this.getList();
    },
    /**
     * param: pageIndex -> Int (default: 1)
     * return:
     * exception:
     * description : Search HistoryList
     */
    getList(pageIndex = 1) {
      const params = {
        pageIndex,
        pageSize: this.pageSize,
        userName: this.userName,
        reqType: this.reqType === 'ALL' ? '' : this.reqType,
        // periodFlag: this.datePickerUnit === 'day' ? 2 : 1,
        ...this.searchPeriod,
      };
      SDLUtil.showLoadingBar(true);

      const apiUrlEndpoint = this.datePickerUnit === 'day' ? 'menu-use-by-date' : 'menu-use-by-month';

      axios
        .get(`${SDLUtil.API_URL}/history/${apiUrlEndpoint}?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.logList = data.rows;
          this.currentPage = pageIndex;
          this.records = data.records;
          this.displayDateUnit = this.datePickerUnit;
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          console.error(err);
          SDLUtil.showLoadingBar(false);
        });
    },
    /**
     * param:
     * return:
     * exception:
     * description : excel file download
     */
    getExcelInfo() {
      return {
        columnInfoFile: 'accessLogExcel',
        fileName: SDLUtil.getMsgProp('sdl.excel.accessLog.title'),
        queryId: this.datePickerUnit === 'day' ? 'selectMenuUseHistoryListByDate' : 'selectMenuUseHistoryListByMonth',
        sheetName: SDLUtil.getMsgProp('sdl.excel.accessLog.title'),
        useNumberField: 'Y',
        param: {
          deleted: '0',
          userName: this.userName,
          reqType: this.reqType === 'ALL' ? '' : this.reqType,
          periodFlag: this.datePickerUnit === 'day' ? 2 : 1,
          ...this.searchPeriod,
        },
      };
    },
    /**
     * param: pageIndex -> Int
     * return:
     * exception:
     * description : Pagination move
     */
    movePage(pageIndex) {
      this.getList(pageIndex);
    },
    showApiUseHistory(info, search) {
      SDLUtil.show(
        ApiUseHistory,
        {
          info,
          search,
        },
        {
          width: '900px',
          height: 'auto',
        },
      );
    },
  },
  mounted() {
    this.$nextTick(() => {
      console.info('initialize MenuUse History Page');

      // connection type
      axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/CONNECT_TYPE/commcodes`).then(({ data }) => {
        this.connectTypeList = data;
      });

      // connection type - all set
      this.reqType = 'ALL';

      this.init();
    });
  },
};
</script>

<style scoped></style>
