<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"
                @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="4%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
            <col width="6%" />
          </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>
              <th colspan="2">대체발송SMS</th>
              <th colspan="2">대체발송LMS</th>
              <th colspan="2">대체발송MMS</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>
              <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>
              <td>{{ option.fbSndCntS.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
              <td>
                {{ option.fbSuccCntS.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br />({{ option.succFbRtS }}%)
              </td>
              <td>{{ option.fbSndCntL.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
              <td>
                {{ option.fbSuccCntL.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br />({{ option.succFbRtL }}%)
              </td>
              <td>{{ option.fbSndCntM.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</td>
              <td>
                {{ option.fbSuccCntM.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}<br />({{ option.succFbRtM }}%)
              </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;
      }
      const todayDate = new Date();
      let selectDay = new Date(day);
      let after3Month = new Date(selectDay.setMonth(selectDay.getMonth() + 2));
      if (after3Month > todayDate) {
        this.endDate = new Date();
      } else {
        this.endDate = after3Month;
      }
    },
    selectedEndDate(day) {
      if (day != undefined && day != null) {
        this.periodDay = day;
      }
    },
    closeDate(type) {
      if (type != undefined && type != null) {
        if (type == 'start') {
          this.disabledSDate = { from: new Date() };
          this.disabledEDate = { to: this.startDate, from: this.endDate };
        } else if (type == 'end') {
          let stDate = new Date(this.startDate);
          let fromDate = new Date(stDate.setMonth(stDate.getMonth() + 2));
          let endDate = this.endDate;
          const nowDate = new Date();
          let selectedEndDate = endDate.getMonth() + 2;

          if (Number(selectedEndDate) > Number(nowDate.getMonth())) {
            this.disabledSDate = { from: new Date() };
            this.disabledEDate = { to: this.startDate, from: new Date() };
          } else {
            this.disabledSDate = { from: new Date() };
            this.disabledEDate = { to: this.startDate, from: fromDate };
          }
        }
      }
    },
    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',
      };

      // 월 별 통계 엑셀 데이터 만들기
      var excelList = [];
      for (var i = 0; i < this.list.length; i++) {
        var excelData = {};
        excelData.sumYm = this.list[i].sumYm;
        // 성공 건수
        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;

        // 대체발송 SMS 성공 건수 
        var fbSuccCntS = this.list[i].fbSuccCntS;
        var succFbRtS = this.list[i].succFbRtS;
        fbSuccCntS = fbSuccCntS + '(' + succFbRtS + '%)';
        excelData.fbSndCntS = this.list[i].fbSndCntS;
        excelData.fbSuccCntS = fbSuccCntS;

        // 대체발송 LMS 성공 건수 
        var fbSuccCntL = this.list[i].fbSuccCntL;
        var succFbRtL = this.list[i].succFbRtL;
        fbSuccCntL = fbSuccCntL + '(' + succFbRtL + '%)';
        excelData.fbSndCntL = this.list[i].fbSndCntL;
        excelData.fbSuccCntL = fbSuccCntL;

        // 대체발송 MMS 성공 건수 
        var fbSuccCntM = this.list[i].fbSuccCntM;
        var succFbRtM = this.list[i].succFbRtM;
        fbSuccCntM = fbSuccCntM + '(' + succFbRtM + '%)';
        excelData.fbSndCntM = this.list[i].fbSndCntM;
        excelData.fbSuccCntM = fbSuccCntM;

        excelList.push(excelData);
      }

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