<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);" class="on">월별통계</a>
        <a href="javascript:void(0);" @click="toMove('dayList')">일별통계</a>
      </div>
      <div class="search_wrap">
        <div class="input_box cal">
          <label for="right" class="label txt">조회기간</label>
          <p> 최대 3개월까지 조회 가능합니다.</p>
          <div class="term">
								<span class="custom_input icon_date">
                    <vuejs-datepicker
                        :language="ko"
                        :format="customFormatter"
                        :disabled-dates="disabledSDate"
                        :minimumView="sDateDiv"
                        :maximumView="sDateDiv"
                        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"
                        :minimumView="sDateDiv"
                        :maximumView="sDateDiv"
                        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.sumYm }}</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";
// import DatePicker from "vue2-datepicker";

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

      startDt: '',
      endDt: '',
      startYear: '',
      startMonth: '',
      endYear: '',
      endMonth: '',
      row: {},
      list: [],
      totalCnt: '',
      pageType: 'MONTH'
    };
  },
  components: {
    commonModal,
    vuejsDatepicker,
  },
  created() {
    this.setPeriodDay(0);
    this.getMonthList();
    this.getExcelHeader();
  },
  destroyed() {
  },
  mounted() {
  },
  methods: {
    async getMonthList() {
      this.row.startMon = moment(this.startDate).format('YYYYMM');
      this.row.endMon = moment(this.endDate).format('YYYYMM');

      if (moment(this.row.startMon).isBefore(moment(this.row.endMon).subtract(2, 'months').format('YYYYMM'))) {
        this.row.title = '발송통계';
        this.row.msg1 = '검색 기간은 최대 3개월까지 선택 가능 합니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false
      }

      try {
        const response = await statsApi.monthList(this.row);
        const result = response.data;
        if (result != null && result.retCode == "0000") {
          this.list = result.data.list;
          this.totalCnt = result.data.list.length;
        } 
      } catch (err) {
      }
    },
    search: function () {
      this.getMonthList();
    },
    toMove(routeName) {
      this.$router.push({name: routeName, params: {}});
    },
    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')) - 3);
      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`;

      var styles = `<style>
        .table{width: 100%;}
        .head-title{border-top: 1px solid #dee2e6; border-bottom: 2px solid #dee2e6;}
        .first-td{background-color: #F2F2F2;}
        .last-td{background-color: #dee2e6;}
        body {
            font-size:12px;
            font-family: 맑은 고딕;
        }
        table {
            font-size:12px;
            text-align:center;
        }
        table th {
            text-align:center;
            height:28px;
            background-color: #f0f0f0;
        }
        table td {
            text-align:left;
            height:26px;
            mso-number-format:"\@";
        }
        .number {
            text-align:right !important;
            mso-number-format:General !important;
            white-space:nowrap !important;
        }
        </style>`;

      let options = {
        header: this.excelHeader,
        dataOrder: 'header'
      };

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