<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-8 flex justify-start align-center">
        <div class="gd-3 pl0" style="height: 100%">
          <select  class="full-select" v-model="search.searchCtgry" @change="axiosSelectList">
            <option v-for="(bbs, idx) in bbsList" :key="idx" :value="bbs.bbs_mng_id">{{ bbs.bbs_nm }}</option>
          </select>
        </div>
        <div class="gd-3 pl0" style="height: 100%">
          <input type="date" class="full-input" v-model="search.startDt" :max="search.endDt"/>
        </div>
        <div>-</div>
        <div class="gd-3" 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-4">
        <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" ref="chartdiv">
                <ClusteredBarChart :chartData="chartData" columnX="ttl" />
              </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="20%">
                  <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-lf sticky" :title="data.ttl "><p class="pl5 pr5 ellipsis">{{ data.ttl }}</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>
                  </tr>
                  <tr v-if="chartData.length === 0 && search.totalRecordCount === 0">
                    <td colspan="3" ><p class="text-ct pd10">등록된 정보가 존재하지 않습니다.</p></td>
                  </tr>
                </tbody>
            </table>
          </div>
        </div>
      </div>
      <div v-if="viewTab === 'tab2'">
        <div class="chart-zone">
          <div class="chart-info">
          </div>
          <div class="mb30" style="height: 40rem;">
            <div class="chart-wrap mb30" ref="chartdiv">
              <ClusteredBarChart :chartData="chartData" columnX="fileNm" />
            </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="25%" />
                  <col width="25%" />
                  <col v-for="(idx) in nameList" :key="idx" :width=colGroup />
                </colgroup>
                <thead>
                  <tr>
                    <th rowspan="2">제목</th>
                    <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-lf sticky" :title="data.ttl"><p class="pl5 pr5 ellipsis">{{ data.ttl }}</p></td>
                    <td class="text-lf sticky" :title="data.fileNm "><p class="pl5 pr5 ellipsis">{{ data.fileNm }}</p></td>
                    <td class="text-rg" v-for="(name, index) in nameList" :key="index"><p class="pl5 pr5">{{ data[name] }}</p></td>
                  </tr>
                  <tr v-if="chartData.length !== 0 && search.totalRecordCount !== 0">
                    <td class="text-ct sticky" colspan="2"><p class="pl5 pr5"></p>검색기간 총계</td>
                    <td class="text-rg" v-for="(name, index) in nameList" :key="index"><p class="pl5 pr5">{{ total[name] }}</p></td>
                  </tr>
                  <tr v-if="chartData.length === 0 && search.totalRecordCount === 0">
                    <td colspan="3" ><p class="text-ct pd10">등록된 정보가 존재하지 않습니다.</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 { bbsCntnStatsProc, findAllBbs } from "../../../../resources/api/cntnStats";
import { keyBy } from "lodash";

export default {
  mixins: [queryParams],
  components: {
    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: null,
      //   endDt: null,
      // },

      //권한명 데이터
      nameList: [],
      colGroup: null,
      // 차트 데이터
      chartData: [],
      // 총계
      total: {},
      //오늘날짜
      today: this.$today(),
      //게시판 목록
      bbsList: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      this.resotreQueryParams("queryParams");
      this.search.startDt = this.$oneWeekAgo();
      this.search.endDt = this.$today();
      this.search.searchType = "view"
      this.search.searchCtgry = "BBS_MNG_0000000001"
      this.axiosSelectList();
      this.findAllBbs();
    },

    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 bbsCntnStatsProc(data);
        this.search = response.data.data.pagination;
        this.total = response.data.data.total;

        let datas = [];
        
        if(response.data.data.list.length > 0) {
          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)

            newData.ttl = data.bbs_ttl;

            if(this.viewTab ==='tab2') {
              newData.fileNm = data.file_nm
            }

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

    // 게시판 목록 불러오기
    async findAllBbs() {

      try {
        const response = await findAllBbs();
        this.bbsList = response.data.data;
      } catch (error) {
        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        alert(this.$getCmmnMessage('err005'));
      }
    },

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

      let data = Object.assign({}, vm.search);
      data.searchStatus = 'Y'
      
      if(vm.viewTab ==='tab2') data.searchFilter = 'dwnld'
      else data.searchFilter = 'bbs'


      const bbsNm = vm.bbsList.filter(bbs => data.searchCtgry === bbs.bbs_mng_id).map(bbs => bbs.bbs_nm)
      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 + ']' + bbsNm + ' 파일 다운로드 통계';
        else link.download = '[' + vm.today + ']' + bbsNm + ' 접속 통계';
        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>