<template>
  <div class="contents">
    <div class="contents_wrap">
      <div class="top_wrap">
        <h3 class="title">날짜별 통계</h3>
        <p class="breadcrumb">발송통계 &gt; 날짜별 통계</p>
      </div>
      <div class="top_tab">
        <a href="javascript:void(0);" @click="toMove('monthList')">월별통계</a>
        <a href="javascript:void(0);" class="on">일별통계</a>
      </div>
      <div class="search_wrap">
        <div class="input_box cal">
          <label for="right" class="label txt">조회기간</label>
          <p> 최대 1개월까지 조회 가능합니다.</p>
          <div class="term">
              <span class="custom_input icon_date">
                <vuejs-datepicker
                    :language="ko"
                    :format="customFormatter"
                    :disabled-dates="disabledSDate"
                    v-model="startDate"
                    @selected="selectedStartDate(0)"
                    @closed="closeDate('start')"
                ></vuejs-datepicker>
              </span>~
            <span class="custom_input icon_date">
                  <vuejs-datepicker
                      :language="ko"
                      :format="customFormatter"
                      :disabled-dates="disabledEDate"
                      v-model="endDate"
                      @selected="selectedEndDate(0)"
                      @closed="closeDate('end')"
                  ></vuejs-datepicker>
              </span>
          </div>
        </div>
        <button type="button" class="button grey" @click="search">조회</button>
      </div>
      <div class="info">
        <div class="count">집계결과</div>
        <div class="button_group">
          <button type="button" class="button blue download" @click="excelDown();">엑셀 다운로드</button>
        </div>

      </div>
      <div class="table calculate">
        <table>
          <colgroup>
            <col width="7%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
            <col width="9.3%">
          </colgroup>
          <thead>
          <tr>
            <th rowspan="2">날짜</th>
            <th colspan="2">전체</th>
            <th colspan="2">SMS</th>
            <th colspan="2">LMS</th>
            <th colspan="2">MMS</th>
            <th colspan="2">알림톡</th>
          </tr>
          <tr class="total">
            <th>발송건수</th>
            <th>성공건수/(%)</th>
            <th>발송건수</th>
            <th>성공건수/(%)</th>
            <th>발송건수</th>
            <th>성공건수/(%)</th>
            <th>발송건수</th>
            <th>성공건수/(%)</th>
            <th>발송건수</th>
            <th>성공건수/(%)</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(option, i) in list" v-bind:key="i">
            <td>{{ option.sumYmd }}</td>
            <td>{{ option.sndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
            <td>{{ option.succCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br>({{ option.succRt }}%)</td>
            <td>{{ option.sndCntS.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
            <td>{{ option.succCntS.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br>({{ option.succRtS }}%)</td>
            <td>{{ option.sndCntL.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
            <td>{{ option.succCntL.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br>({{ option.succRtL }}%)</td>
            <td>{{ option.sndCntM.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
            <td>{{ option.succCntM.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br>({{ option.succRtM }}%)</td>
            <td>{{ option.sndCntR.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
            <td>{{ option.succCntR.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br>({{ option.succRtR }}%)</td>
          </tr>

          </tbody>
        </table>
      </div>

      <common-modal ref="commmonModal"></common-modal>

    </div>
  </div>
</template>

<script>
import moment from 'moment';
import statsApi from "../service/statsApi.js";
import xlsx from '@/common/excel';
import commonModal from "@/components/modal/commonModal";

export default {
  name: 'dayList',
  data() {
    return {
      // 달력 데이터
      ko: vdp_translation_ko.js,
      periodDay: 7,
      sDateDiv: 'day',
      startDate: new Date(),
      endDate: new Date(),

      startDt: '',
      endDt: '',

      pageType: 'DAY',

      row: {},
      list: [],
      totalCnt: '',
    };
  },
  components: {
    commonModal,
    vuejsDatepicker,
  },
  created() {
    // this.startDt = moment().format('YYYY-MM-DD');
    // this.endDt = moment().format('YYYY-MM-DD');
    this.setPeriodDay(0);
    this.getDayList();
    this.getExcelHeader();
  },
  destroyed() {

  },
  mounted() {

  },
  methods: {
    async getDayList() {
      this.row.startDay = moment(this.startDate).format('YYYYMMDD');
      this.row.endDay = moment(this.endDate).format('YYYYMMDD');
      if (moment(this.row.startDay).isBefore(moment(this.row.endDay).subtract(1, 'months').format('YYYYMMDD'))) {
        this.row.title = '발송통계';
        this.row.msg1 = '검색 기간은 최대 1개월까지 선택 가능 합니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false
      }

      try {
        const response = await statsApi.dayList(this.row);
        const result = response.data;
        if (result != null && result.retCode == "0000") {
          if (result.data.list.length > 0) {
            this.list = result.data.list;
          }
          this.totalCnt = result.data.list.length;
        } else {
        }
      } catch (err) {
      }
    },
    toMove(routeName) {
      this.$router.push({name: routeName, params: {page: 1, searchText: ''}});
    },
    search: function () {
      this.getDayList();
    },    

    setPeriodDay(day) {
      this.periodDay = day;
      this.endDate = new Date();
      this.initSetStartDate();

      this.closeDate('start');
      this.closeDate('end');
    },
    selectedStartDate(day) {
      if (day != undefined && day != null) {
        this.periodDay = day;
      }
      if (this.startDate > this.endDate) {
        this.startDate = this.endDate;
      }
    },
    selectedEndDate(day) {
      if (day != undefined && day != null) {
        this.periodDay = day;
      }
    },
    closeDate(type) {
      if (type != undefined && type != null) {
        if (type == 'start') {
          this.disabledSDate = {from: this.endDate};
          this.disabledEDate = {to: this.startDate, from: this.endDate};
        } else if (type == 'end') {
          this.disabledSDate = {from: this.endDate};
          this.disabledEDate = {to: this.startDate, from: new Date()};
        }
      }
    },
    customFormatter: function (date) {
      if (this.sDateDiv == 'month') {
        return moment(date).format('YYYY-MM');
      } else if (this.sDateDiv == 'year') {
        return moment(date).format('YYYY');
      } else {
        return moment(date).format('YYYY-MM-DD');
      }
    },
    initSetStartDate() {
      let initStartDate = new Date();
      initStartDate.setMonth(Number(moment(initStartDate).format('MM')) - 2);
      this.startDate = initStartDate;
    },

    excelDown() {
      if (this.list.length <= 0) {
        this.row.title = '일별통계';
        this.row.msg1 = '조회된 데이터가 없습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);

        return false;
      }

      let today = moment().format('YYYYMMDDHHmmss');
      const saveFileName = `일별통계_${today}.xls`;

      let options = {
        header: this.excelHeader,
        dataOrder: 'header'
      };
      console.log(this.list);
      // 일 별 통계 엑셀 데이터 만들기
      
      var excelList = [];
      for(var i=0; i<this.list.length; i++){
        var excelData = {};
        excelData.sumYmd = this.list[i].sumYmd;
        // 성공 건수
        var succCnt = this.list[i].succCnt; 
        var succRt = this.list[i].succRt;
        succCnt = succCnt + '(' + succRt + '%)'
        excelData.sndCnt = this.list[i].sndCnt;
        excelData.succCnt = succCnt;


        // SMS 성공 건수
        var succCntS = this.list[i].succCntS; 
        var succRtS = this.list[i].succRtS;
        succCntS = succCntS + '(' + succRtS + '%)'
        excelData.sndCntS = this.list[i].sndCntS;
        excelData.succCntS = succCntS;

        // LMS 성공 건수
        var succCntL = this.list[i].succCntL; 
        var succRtL = this.list[i].succRtL;
        succCntL = succCntL + '(' + succRtL + '%)'
        excelData.sndCntL = this.list[i].sndCntL;
        excelData.succCntL = succCntL;

        // MMS 성공 건수
        var succCntM = this.list[i].succCntM; 
        var succRtM = this.list[i].succRtM;
        succCntM = succCntM + '(' + succRtM + '%)'
        excelData.sndCntM = this.list[i].sndCntM;
        excelData.succCntM = succCntM;

        // ALIMTALK 성공 건수
        var succCntR = this.list[i].succCntR; 
        var succRtR = this.list[i].succRtR;
        succCntR = succCntR + '(' + succRtR + '%)'
        excelData.sndCntR = this.list[i].sndCntR;
        excelData.succCntR = succCntR;

        excelList.push(excelData);
      }

      xlsx.export(excelList, saveFileName, options).then(() => {
      });
    },
    getExcelHeader() {
      // 헤더를 mockup으로 관리한다.
      statsApi.getExcelHeader(this.pageType).then(res => {
        this.excelHeader = res;
      });
    },
  }
};
</script>