<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">
      </div>
    </div>
      <div>
        <div class="chart-zone">
          <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="25%" />
                  <col width="25%" />
                  <col width="25%" />
                  <col width="25%" />
                </colgroup>
                <thead>
                  <tr>
                    <th rowspan="2">일자</th>
                    <th colspan="6">메일발송건수</th>
                  </tr>
                  <tr>
                    <th>전체</th>
                    <th>성공건수</th>
                    <th>실패건수</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(data, idx) in chartData" :key="idx">
                    <td class="text-ct"><p class="pl5 pr5">{{ data.date }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ $comma(data.전체) }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5"></p>{{ $comma(data.성공건수) }}</td>
                    <td class="text-rg"><p class="pl5 pr5"></p>{{ $comma(data.실패건수) }}</td>
                  </tr>
                  <tr>
                    <td class="text-ct"><p class="pl5 pr5">검색기간 총계</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ $comma(total.전체) }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ $comma(total.성공건수) }}</p></td>
                    <td class="text-rg"><p class="pl5 pr5">{{ $comma(total.실패건수) }}</p></td>
                  </tr>
                </tbody>
            </table>
          </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 { mailCntnStatsProc } from "../../../../resources/api/cntnStats";
import { keyBy } from "lodash";

export default {
  mixins: [queryParams],
  components: {
    PaginationButton,
    LineChart,
  },
  data() {
    return {
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

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

      // search: {
      //   startDt: null,
      //   endDt: null,
      // },
      // 차트 데이터
      chartData: [],
      // 차트 데이터 키
      keys:[],
      // 총계
      total: {},
      //오늘날짜
      today: this.$today(),
    };
  },
  created() {
    this.init();
    this.$store.commit('setLoading', false);
  },
  methods: {
    async init() {
      this.resotreQueryParams("queryParams");
      this.search.startDt = this.$oneWeekAgo();
      this.search.endDt = this.$today();
      this.axiosSelectList();
    },

    // 이메일 통계
    async axiosSelectList() {
      let data = this.search;

      try {
        const response = await mailCntnStatsProc(data);
        this.search = response.data.data.pagination;
        this.chartData = response.data.data.list;
        this.total = response.data.data.total;

        // 통계 리스트 길이 만큼 반복
        for (let i = 0; i < this.chartData.length; i++) {
          this.chartData[i].date = this.$formatUnixToDate(this.chartData[i].date);
        }
      } catch (error) {
        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        alert(this.$getCmmnMessage('err005'));
      }
    },
    // 다운로드
    fnDownload() {
      const vm = this;
      let data = Object.assign({}, this.search);
      data.searchStatus = 'Y'
      data.searchFilter = 'mail'

      // this.$store.commit('setLoading', true);
      axios({
          url: "/stats/excel.json",
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
            Authorization: this.$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 = '[' + this.today + ']' + '메일 발송 통계';
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
      })
      .catch((error) => {
        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        alert(vm.$getCmmnMessage('err005'));
      }).finally(function () {
        // this.$store.commit('setLoading', false);
      });
    },
  },
};
</script>