<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 type="date" class="full-input" v-model="search.startDt" :max="search.endDt"/>
        </div>
        <div>-</div>
        <div class="gd-4" style="height: 100%">
          <input type="date" class="full-input" v-model="search.endDt" :min="search.startDt" :max="today"/>
        </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 ">
          <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 v-if="viewTab === 'tab1'">
        <div class="chart-zone">
          <div class="mb30" style="height: 40rem;">
            <div class="chart-wrap mb30" ref="chartdiv">
              <ClusteredBarChart :chartData="chartData" columnX="date" />
            </div>
          </div>
          <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>
          <div class="table-zone overflow-x " >
            <table class="list-table admin-list complex-table fixed-table" >
                <!-- <colgroup>
                  <col width="150px" />
                  <col v-for="(idx) in menuList" :key="idx" :width=colGroup />
                </colgroup> -->
                <thead>
                  <tr>
                    <th rowspan="2" class="sticky first-th" style="width: 150px;">일자</th>
                    <th :colspan=menuList.length>메뉴별 접속자 수</th>
                  </tr>
                  <tr>
                    <th  v-for="(menu, idx) in menuList" :key="idx">{{ menu }}</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="(menu, index) in menuList" :key="index"><p class="pl5 pr5">{{ $comma(data[menu]) }}</p></td>
                  </tr>
                  <tr>
                    <td class="text-ct sticky"><p class="pl5 pr5"></p>검색기간 총계</td>
                    <td class="text-rg" v-for="(menu, index) in menuList" :key="index"><p class="pl5 pr5">{{ $comma(total[menu]) }}</p></td>
                  </tr>
                </tbody>
            </table>
          </div>
        </div>
      </div>
      <div v-if="viewTab === 'tab2'">
        <div class="chart-zone">
          <div class="mb30" style="height: 40rem;">
            <div class="chart-wrap mb30" ref="chartdiv">
              <ClusteredBarChart :chartData="chartData" columnX="date" />
            </div>
          </div>
          <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>
          <div class="table-zone overflow-x " >
            <table class="list-table admin-list complex-table fixed-table">
                <colgroup>
                  <col v-for="(idx) in menuList.length" :key="idx" :width=colGroup />
                </colgroup>
                <thead>
                  <tr>
                    <th rowspan="2">일자</th>
                    <th :colspan=menuList.length>메뉴별 파일 다운로드 수</th>
                  </tr>
                  <tr>
                    <th v-for="(menu, idx) in menuList" :key="idx">{{ menu }}</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="(menu, index) in menuList" :key="index"><p class="pl5 pr5">{{ data[menu] }}</p></td>
                  </tr>
                  <tr>
                    <td class="text-ct sticky"><p class="pl5 pr5"></p>검색기간 총계</td>
                    <td class="text-rg" v-for="(menu, index) in menuList" :key="index"><p class="pl5 pr5">{{ total[menu] }}</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 ClusteredBarChart from "../../../component/chart/ClusteredBarChart.vue";
import PaginationButton from '../../../component/pagination/PaginationButton.vue';
import queryParams from "../../../../resources/js/queryParams";
import { defaultSearchParams } from "../../../../resources/js/defaultSearchParams";

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

export default {
  mixins: [queryParams],
  components: {
    ClusteredBarChart : ClusteredBarChart,
    PaginationButton
  },
  data() {
    return {
      tabObject:[{id:'tab1',tabName:"방문자수", value:"view"},{id:'tab2',tabName:"다운로드수", value:"dwlnd"}],
      viewTab:'tab1',
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

      // 검색 정보 담는 객체
      search: { ...defaultSearchParams },
      // search: {
      //   startDt: this.$oneWeekAgo(),
      //   endDt: this.$today(),
      //   type: "view"
      // },

      //메뉴명 데이터
      menuList: [],
      colGroup: null,
      // 차트 데이터
      chartData: [],
      // 총계
      total: {},
      //오늘날짜
      today: this.$today(),
    };
  },
  created() {
    // this.search.startDt = this.$today();
    // this.search.endDt = this.$oneWeekAgo();
    // console.log(this.search.startDt)
    this.init();
  },
  methods: {
    async init() {
      this.resotreQueryParams("queryParams");
      this.search.startDt = this.$oneWeekAgo();
      this.search.endDt = this.$today();
      this.search.searchType = "view"
      this.axiosSelectList();
    },

    showTab(tabObject){
      this.viewTab = tabObject.id
      this.search.searchType = tabObject.value
      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 menuCntnStatsProc(data);
        this.search = response.data.data.pagination;
        this.total = response.data.data.total;

        let datas = [];
        //통계 리스트 길이 만큼 반복
        this.menuList = response.data.data.list[0].name;
        
        for (let data of response.data.data.list) {
          let newData = {};
          newData.date = this.$formatUnixToDate(data.dates);
          data.name.unshift("전체");
          data.count.unshift(data.total)
          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.menuList.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 = 'menu'


      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;
        if(vm.viewTab ==='tab2') link.download = '[' + vm.today + ']' + '메뉴별 파일 다운로드 통계'
        else 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>