<template>
  <article id="content" class="content">
    <ul class="breadcrumb">
      <li class="home">
        <a href="javascript:void(0);">홈</a>
      </li>
      <li>
        <a href="javascript:void(0);">발송통계</a>
      </li>
      <li>
        <span>상품별통계</span>
      </li>
    </ul>
    <div class="title_area">
      <h2>상품별통계</h2>
    </div>
    <div class="tab_wrap">
      <ul class="tab_nav">
        <li class="active">
          <a href="javascript:void(0);" :style="isAdmin ? '' : 'cursor:default'">상품별통계</a>
        </li>
        <li>
          <a
            href="javascript:void(0);"
            @click="isAdmin ? toMove('tmpltStatics') : ''"
            :style="isAdmin ? '' : 'cursor:default'"
          >포맷ID별통계</a>
        </li>
        <li>
          <a href="javascript:void(0);" @click="toMove('userStatics')">사용자별통계</a>
        </li>
        <li>
          <a href="javascript:void(0);" @click="toMove('campaignStatics')">캠페인ID별통계</a>
        </li>
      </ul>
    </div>

    <div class="box_search_area">
      <div class="filter_bundle_wrap">
        <div class="filter_bundle">
          <strong class="tit_bundle">발송일</strong>
          <div class="cont_bundle center">
            <div class="box_select_period">
              <div class="period_wrap">
                <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="hypen">~</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 class="radio_wrap">
                <span class="custom_radio">
                  <input
                    type="radio"
                    name="radioDate"
                    id="day"
                    v-model="sDateDiv"
                    value="day"
                    checked
                  >
                  <label for="day">일별</label>
                </span>
                <span class="custom_radio">
                  <input type="radio" name="radioDate" id="month" v-model="sDateDiv" value="month">
                  <label for="month">월별</label>
                </span>
                <span class="custom_radio">
                  <input type="radio" name="radioDate" id="year" v-model="sDateDiv" value="year">
                  <label for="year">년별</label>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- end of filter_bundle_wrap -->
      <div class="btn_wrap center">
        <a href="javascript:void(0);" class="btn mid point" @click="searchSummary">
          <span>조회</span>
        </a>
      </div>
    </div>
    <!-- end of box_search_area -->

    <div class="cont_flex_bundle bottom mar_b20">
      <div class="result_date left col_6">
        <span>
          <em class="date">{{ customFormatter(startDate) }}</em> 부터
          <em class="date">{{ customFormatter(endDate) }}</em>까지의 전송/성공/성공률 입니다.
        </span>
      </div>
      <div class="btn_wrap right col_6">
        <a href="javascript:void(0)" class="btn sml bd_gray icon_down_doc" @click="excelDown()">
          <span>엑셀 다운로드</span>
        </a>
      </div>
    </div>

    <custom-grid
      ref="table"
      :url="grid.url"
      :perPage="grid.perPage"
      :pagination="grid.pagination"
      :header="grid.header"
      :columns="grid.columns"
      :noDataStr="grid.noDataStr"
      :initialRequest="grid.initialRequest"
      :addBodyAlign="grid.addAlign"
      :addBodyTmplt="grid.summary"
    ></custom-grid>
  </article>
</template>

<script>
import moment from 'moment';
import customGrid from '@/components/CustomGrid';
import api from '../service/api';
import xlsx from '@/common/excel';

export default {
  name: 'staticsList',  
  data() {
    return {
      ko: vdp_translation_ko.js,
      bbsCategoryType: 'PROD',

      sDateDiv: 'day',
      startDate: new Date(),
      endDate: new Date(),

      disabledSDate: { from: new Date() },
      disabledEDate: { from: new Date() },

      isAdmin: true,

      grid: {
        url: '/api/statics/list',

        initialRequest: false,
        pagination: true,
        perPage: 10,

        header: [
          [
            { header: 'NO', childNames: [] },
            { header: '날짜', childNames: [] },
            { header: '스타일 템플릿', childNames: ['cellTmpltTot', 'cellTmpltRateStr'] },
            { header: '서술 템플릿', childNames: ['descTmpltTot', 'descTmpltRateStr'] },
            { header: '기본 템플릿', childNames: ['freeTmpltTot', 'freeTmpltRateStr'] },
            { header: '템플릿 소계', childNames: ['subSumTmpltTot', 'subSumTmpltRateStr'] },
            { header: 'RCS SMS', childNames: ['smsTot', 'smsRateStr'] },
            { header: 'RCS LMS', childNames: ['lmsTot', 'lmsRateStr'] },
            { header: 'RCS MMS', childNames: ['mmsTot', 'mmsRateStr'] },
            { header: '포맷 소계', childNames: ['formatTot', 'formatRateStr'] },
            { header: 'Fallback SMS', childNames: ['fbSmsTot', 'fbSmsRateStr'] },
            { header: 'Fallback LMS', childNames: ['fbLmsTot', 'fbLmsRateStr'] }
          ]
        ],

        columns: [
          { name: 'seq', header: 'NO', width: 100 },
          { name: 'ymd', header: '날짜', width: 100 },
          { name: 'cellTmpltTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'cellTmpltRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'descTmpltTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'descTmpltRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'freeTmpltTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'freeTmpltRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'subSumTmpltTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'subSumTmpltRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },

          { name: 'smsTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'smsRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'lmsTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'lmsRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'mmsTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'mmsRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'formatTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'formatRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },

          { name: 'fbSmsTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'fbSmsRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' },
          { name: 'fbLmsTot', header: '발송', width: 90, cls: 'td_line' },
          { name: 'fbLmsRateStr', header: '성공<br>(성공률)', width: 90, cls: 'td_line' }
        ],

        summary: '',
        addAlign: '',

        noDataStr: '검색 결과가 없습니다.',
        params: {},
        excelHeader: []
      }
    };
  },
  created() {
    api.selectUserRoleInfo().then(response => {
      const respList = response.data.data;
      if (response.data.success && respList != null && respList.length > 0) {
        let adminStr = respList[0].selIsAdmin;
        if (typeof adminStr != undefined && adminStr != null && adminStr == 'false') {
          this.isAdmin = false;
        }
      } else {
        this.isAdmin = true;
      }
    });

    this.getExcelHeader();
  },
  mounted() {
    // 합계 조회
    this.searchSummary();
  },

  components: {
    'vuejs-datepicker': vuejsDatepicker,
    customGrid: customGrid
  },
  methods: {
    getExcelHeader() {
      // 헤더를 mockup으로 관리한다.
      api.getExcelHeader(this.bbsCategoryType).then(res => {
        this.excelHeader = res;
      });
    },
    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');
      }
    },
    toPage(lifeCycle) {
      const page = this.isNull(this.$route.params.page) ? 1 : this.$route.params.page;
      try {
        this.$refs.table.readData(page, this.grid.params);
      } catch (error) {
        console.log(lifeCycle, error);
      }
    },

    toMove(routeName) {
      this.$router.push({ name: routeName, params: { page: 1, searchText: '' } });
    },

    search: function(data) {
      this.grid.params = {
        sDate: moment(this.startDate).format('YYYYMMDD'),
        eDate: moment(this.endDate).format('YYYYMMDD'),
        dateDiv: this.sDateDiv
      };

      this.$refs.table.search(this.grid.params);
    },

    searchSummary: function(data) {
      let summaryList = {};

      this.grid.params = {
        sDate: moment(this.startDate).format('YYYYMMDD'),
        eDate: moment(this.endDate).format('YYYYMMDD'),
        dateDiv: this.sDateDiv
      };

      api
        .selectStaticsSummary(this.grid.params)
        .then(response => {
          const respList = response.data.data;
          if (response.data.success && respList != null && respList.length > 0) {
            summaryList = respList[0];

            this.grid.addAlign = 'TOP';
            let addBody = '';
            addBody += '<tr>';
            addBody += '<td colspan="2">합계</td>';
            addBody += '<td>' + summaryList.cellTmpltTot + '</td>';
            addBody += '<td>' + summaryList.cellTmpltSucc + '<br>(' + summaryList.cellTmpltRate + '%)</td>';

            addBody += '<td>' + summaryList.descTmpltTot + '</td>';
            addBody += '<td>' + summaryList.descTmpltSucc + '<br>(' + summaryList.descTmpltRate + '%)</td>';

            addBody += '<td>' + summaryList.freeTmpltTot + '</td>';
            addBody += '<td>' + summaryList.freeTmpltSucc + '<br>(' + summaryList.freeTmpltRate + '%)</td>';

            addBody += '<td>' + summaryList.subSumTmpltTot + '</td>';
            addBody += '<td>' + summaryList.subSumTmpltSucc + '<br>(' + summaryList.subSumTmpltRate + '%)</td>';

            addBody += '<td>' + summaryList.smsTot + '</td>';
            addBody += '<td>' + summaryList.smsSucc + '<br>(' + summaryList.smsRate + '%)</td>';

            addBody += '<td>' + summaryList.lmsTot + '</td>';
            addBody += '<td>' + summaryList.lmsSucc + '<br>(' + summaryList.lmsRate + '%)</td>';

            addBody += '<td>' + summaryList.mmsTot + '</td>';
            addBody += '<td>' + summaryList.mmsSucc + '<br>(' + summaryList.mmsRate + '%)</td>';

            addBody += '<td>' + summaryList.formatTot + '</td>';
            addBody += '<td>' + summaryList.formatSucc + '<br>(' + summaryList.formatRate + '%)</td>';

            addBody += '<td>' + summaryList.fbSmsTot + '</td>';
            addBody += '<td>' + summaryList.fbSmsSucc + '<br>(' + summaryList.fbSmsRate + '%)</td>';

            addBody += '<td>' + summaryList.fbLmsTot + '</td>';
            addBody += '<td>' + summaryList.fbLmsSucc + '<br>(' + summaryList.fbLmsRate + '%)</td>';
            addBody += '</tr>';

            this.grid.summary = addBody;
          } else {
            this.grid.addAlign = '';
            this.grid.summary = '';
          }
        })
        .finally(() => {
          this.search();
        });
    },

    selectedStartDate(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() };
        }
      }
    },

    async getExcelDataDown() {
      try {
        let response;
        const params = {
          startDtXls: moment(this.startDate).format('YYYYMMDD'),
          endDtXls: moment(this.endDate).format('YYYYMMDD'),
          sDate: this.startDate,
          eDate: this.endDate,
          dateDiv: this.sDateDiv
        };

        response = await api.selectStaticsXls(params);

        const result = response.data;
        if (result != null && result.success) {
          if (!this.isNull(result.data)) {
            return result.data;
          }
        }
        return false;
      } catch (err) {
        return false;
      }
    }, // end of getExcelDataDown

    async getExcelSumData() {
      // let sumBody = '';
      try {
        let response = await api.selectStaticsSummary(this.grid.params);
        const result = response.data;

        if (result != null && result.success) {
          if (!this.isNull(result.data)) {
            return result.data;
          }
        }
        return false;
      } catch (err) {
        return false;
      }
    },
    async excelDown() {
      if (this.$refs.table.getData().length <= 0) {
        alert('조회된 데이터가 없습니다.');
        return false;
      }

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

      const data = await this.getExcelDataDown();
      const sumData = await this.getExcelSumData();

      let options = {
        header: this.excelHeader,
        summary: {
          isUse: true,
          position: 'first',
          data: sumData,
          title: { replaceKeys: ['seq', 'ymd'], name: '합계' }
        },
        dataOrder: 'header' // header, data, ['no', 'sendnum', 'errorDesc']
      };

      xlsx.export(data, saveFileName, options).then(() => {});
    }
  }
};
</script>

