<template>
  <div class="content overflow-y">
    <div class="admin-page-title point-font2 mb30">
      <p>로그인 수 통계</p>
    </div>
    <div class="flex justify-between aling-center no-gutters mb30">
      <div class="gd-6 flex justify-start align-center">
        <div class="gd-4 pl0" style="height: 100%">
          <input v-if="search.searchType === 'day'" type="date" class="full-input" v-model="search.startDt" :max="search.endDt"/>
          <input v-else-if="search.searchType === 'month'" type="month" class="full-input" v-model="search.startDt" :max="search.endDt"/>
          <select v-else name="" id="" class="full-select ml0" v-model="search.startDt">
            <option v-for="(year, idx) in years" :key="idx" :value=year>{{ year }}</option>
          </select>
        </div>
        <div>-</div>
        <div class="gd-4" style="height: 100%">
          <input v-if="search.searchType === 'day'" type="date" class="full-input" v-model="search.endDt" :min="search.startDt" :max="today"/>
          <input v-else-if="search.searchType === 'month'" type="month" class="full-input" v-model="search.endDt" :min="search.startDt" :max="thisMonth"/>
          <select v-else name="" id="" class="full-select ml0" v-model="search.endDt">
            <option v-for="(year, idx) in years" :key="idx" :value=year>{{ year }}</option>
          </select>
        </div>
        <div class="gd-2">
          <button class="large-btn blue-border-btn" @click="axiosSelectList">조회</button>
        </div>
      </div>
      <div class="gd-6">
        <ul class="flex justify-end align-center tab-exception">
          <li v-for="(content,idx) in tabObject" :key="idx" :class="{ 'tab-toggle  pd10 detail-text':true,active: viewTab === content.id }"  @click="showTab(content)" >{{content.tabName}}</li>
        </ul>
      </div>
    </div>
    <div class="tab-content mb10">
      <div>
        <div class="chart-zone">
          <div class="chart-info">
          </div>
          <div class="mb30" style="height: 40rem;">
            <div class="chart-wrap mb30" ref="chartdiv">
              <LineChart :chartData="chartData" columnX="date"/>
            </div>
          </div>
          <div class="table-zone">
            <div class="flex justify-end align-center mb10">
              <div class="gd-2 pd0">
                <button
                  class="large-btn green-border-btn"
                  v-if="pageAuth.fileDwnldAuthrtYn == 'Y'"
                  @click="fnDownload"
                >
                  EXCEL 다운로드
                </button>
              </div>
            </div>
            <table class="list-table admin-list complex-table">
                <colgroup>
                  <col width="150px" />
                  <col v-for="(idx) in nameList" :key="idx" :width=colGroup />
                </colgroup>
                <thead>
                  <tr>
                    <th rowspan="2">일자</th>
                    <th :colspan=nameList.length>권한 별 로그인 수</th>
                  </tr>
                  <tr>
                    <th  v-for="(name, idx) in nameList" :key="idx">{{ name }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(data, idx) in chartData" :key="idx">
                    <td class="text-ct sticky" ><p class="pl5 pr5">{{ data.date }}</p></td>
                    <td class="text-rg" v-for="(name, index) in nameList" :key="index"><p class="pl5 pr5">{{ $comma(data[name]) }}</p></td>
                  </tr>
                  <tr>
                    <td class="text-ct sticky"><p class="pl5 pr5"></p>검색기간 총계</td>
                    <td class="text-rg" v-for="(name, index) in nameList" :key="index"><p class="pl5 pr5">{{ $comma(total[name]) }}</p></td>
                    <!-- <td class="text-rg"><p class="pl5 pr5">{{ total.total }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ total.ROLE_CO_USER }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ total.ROLE_USER }}</p></td> -->
                  </tr>
                </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <PaginationButton
      :className="'admin-pagination'"
      v-model:currentPage="search.currentPage"
      :pagination="search"
      :click="axiosSelectList"
    />
  </div>
</template>
<script>
import axios from "axios";
import LineChart from "../../../component/chart/lineChart.vue";
import PaginationButton from '../../../component/pagination/PaginationButton.vue';
import queryParams from "../../../../resources/js/queryParams";
import { defaultSearchParams } from "../../../../resources/js/defaultSearchParams";

// API
import { lgnCntnStatsProc } from "../../../../resources/api/cntnStats";
import { keyBy } from "lodash";

export default {
  mixins: [queryParams],
  components: {
    LineChart,
    PaginationButton,
  },
  data() {
    return {
      tabObject:[{id:'tab1',tabName:"일별", value:"day"},{id:'tab2',tabName:"월별", value:"month"},{id:'tab3',tabName:"연도별", value:"year"}],
      viewTab:'tab1',
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

      // 검색 정보 담는 객체
      search: { ...defaultSearchParams },

      // search: {
      //   startDt: this.$oneWeekAgo(),
      //   endDt: this.$today(),
      //   type: "day"
      // },

      //메뉴명 데이터
      nameList: [],
      //테이블넓이
      colGroup: null,
      // 차트 데이터
      chartData: [],
      // 총계
      total: {},
      //오늘날짜
      today: this.$today(),
      //이번 달
      thisMonth: this.$nMonthAgo(this.$today(), 0).substring(0, 7),
      //연도
      years:[],
    };
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.resotreQueryParams("queryParams");
      this.search.startDt = this.$oneWeekAgo();
      this.search.endDt = this.$today();
      this.search.searchType = "day"
      this.axiosSelectList();
    },

    showTab(tabObject){
      this.viewTab = tabObject.id
      this.search.searchType = tabObject.value
      if(tabObject.value === 'day') {
        this.search.startDt = this.$oneWeekAgo();
        this.search.endDt = this.$today()
      } else if(tabObject.value === 'month'){
        this.search.startDt = this.$nMonthAgo(this.$today(), 6).substring(0, 7);
        this.search.endDt = this.$nMonthAgo(this.$today(), 0).substring(0, 7);
      } else {
        this.search.startDt = this.years[0]
        this.search.endDt = this.years[this.years.length - 1]
      }
      this.axiosSelectList();
    },

    // 메뉴별 접속 통계
    async axiosSelectList() {
      if(this.$isEmpty(this.search.startDt)) {
        alert("시작일을 선택하세요.")
        return
      }

      if(this.$isEmpty(this.search.endDt)) {
        alert("종료일을 선택하세요.")
        return 
      }
      
      let data = this.search;

      try {
        const response = await lgnCntnStatsProc(data);
        this.search = response.data.data.pagination;
        this.total = response.data.data.total;
        this.years = response.data.data.years;

        let datas = [];
        this.nameList = response.data.data.list[0].name;

        //통계 리스트 길이 만큼 반복
        for (let data of response.data.data.list) {
          let newData = {};

          data.name.unshift("전체");
          data.count.unshift(data.total);

          if(this.search.searchType === 'day') {
            newData.date = this.$formatUnixToDate(data.dates);
          } else {
            newData.date = data.dates;
          }
          
          
          for (let i = 0; i < data.name.length; i++) {
            newData[data.name[i]] = data.count[i];
          }
          
          datas.push(newData);
        }
        this.chartData = datas;
        this.colGroup = 100 / (this.nameList.length + 1) + '%'
        // this.totalCnt = response.data.data.totalCnt;
      } catch (error) {
        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        alert(this.$getCmmnMessage('err005'));
      }
    },

    // 다운로드
    fnDownload() {
      const vm = this;

      let data = Object.assign({}, vm.search);
      data.searchStatus = 'Y'
      data.searchFilter = 'login'

      vm.$store.commit('setLoading', true);
      axios({
          url: "/stats/excel.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
            Authorization: vm.$store.state.authorization,
          },
          data: data,
          responseType: "arraybuffer",
      })
      .then((response) => {
        const url = window.URL.createObjectURL(
          new Blob([response.data], {
            type: response.headers["content-type"],
          })
        );

        const link = document.createElement("a");
        link.href = url;
        link.download = '[' + vm.today + ']' + '로그인 통계';
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
      })
      .catch((error) => {
        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        alert(vm.$getCmmnMessage('err005'));
      }).finally(function () {
        vm.$store.commit('setLoading', false);
      });
    },
  },
};
</script>
