<template>

  <div class="contents">
    <div class="contents_wrap">
      <div class="top_wrap">
        <h3 class="title">정산이력</h3>
        <p class="breadcrumb">정산 &gt; 정산이력</p>
      </div>
      <div class="search_wrap">
        <div class="group">
          <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')"
                      :picker-options="startDateOptions"
                  ></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')"
                      :picker-options="endDateOptions"
                  ></vuejs-datepicker>
                </span>
            </div>
          </div>
        </div>
        <div class="group">
          <div class="input_box">
            <label for="right" class="label">고객사명</label>
            <input class="search-box" type="text" id="" placeholder="검색어 입력" v-model.trim="grid.params.custNm"
                   maxlength="100" @keyup.enter="search"/>
          </div>
          <div class="input_box">
            <label for="right" class="label">사업자번호</label>
            <input class="search-box" type="text" id="" placeholder="검색어 입력" v-model.trim="grid.params.bizrno"
                   @keypress="onlyNum" @input="onlyNum" maxlength="10" @keyup.enter="search"/>
          </div>
          <button type="button" class="button grey" @click="search">조회</button>
        </div>
      </div>
      <div class="info">
        <div class="count">총 <span>{{ totalItems.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</span>건
          <div class="select_box NumberSe">
            <select name="" id="" v-model="perPageCnt" @change="changePerPage()">
              <option v-for="option in options" v-bind:value="option.value" v-bind:key="option.value">{{
                  option.text
                }}
              </option>
            </select>
          </div>
        </div>
        <div class="button_group">
          <button type="button" class="button blue download" @click="excelDown();">엑셀 다운로드</button>
        </div>

      </div>
      <div class="table calculate scroll">
        <table>
          <custom-grid
              ref="table"
              :totalItems="'totalItems'"
              :url="grid.url"
              :pagePerRows="grid.pagePerRows"
              :initialRequest="grid.initialRequest"
              :pagination="grid.pagination"
              :isCheckbox="grid.isCheckbox"
              :columns="grid.columns"
              :noDataStr="grid.noDataStr"
              :addCls="grid.addCls"
              :header="grid.header"
          ></custom-grid>
        </table>
      </div>

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

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

<script>
import customGrid from '@/components/CustomGrid';
import moment from "moment";
import xlsx from '@/common/excel';
import lodash from 'lodash';
import commonModal from "@/components/modal/commonModal";
import calcMgtApi from "@/modules/calculate/service/calcMgtApi";
import {utils_mixin, chkPattern2} from '../service/mixins';

export default {
  name: 'calcList',
  mixins: [utils_mixin, chkPattern2],
  data() {
    return {
      // 달력 데이터
      ko: vdp_translation_ko.js,
      periodDay: 7,
      sDateDiv: 'month',
      startDate: new Date(),
      endDate: new Date(),
      startDateOptions: {disabledDate: this.disabledStDate},
      endDateOptions: {disabledDate: this.disabledEdDate},
      startDt: '',
      endDt: '',
      startYear: '',
      startMonth: '',
      endYear: '',
      endMonth: '',
      row: {},
      list: [],
      totalCnt: '',

      pageType: 'CALC',

      // 테이블 리스트 데이터
      perPageCnt: 50,
      options: [
        {text: '20', value: 20},
        {text: '50', value: 50},
        {text: '100', value: 100}
      ],
      totalItems: 0,

      grid: {
        url: '/api/v1/bo/calculate/calcList',
        pagePerRows: 20,
        pagination: true,
        isCheckbox: false,        // true:첫번째 컬럼 앞에 체크박스 생성 / false:체크박스 제거
        initialRequest: false,
        addCls: 'box_OFvis',

        header: [
          [
            {header: '날짜', childNames: []},
            {header: '고객사명', childNames: []},
            {header: '사업자번호', childNames: []},
            {header: '요금제', childNames: []},
            {header: '시작금액', childNames: []},
            {header: '사용금액', childNames: []},
            {header: '이월금액', childNames: []},
            {header: '종량금액', childNames: []},
            {header: '소멸금액', childNames: []},
            {header: '청구금액', childNames: []},
            {header: '채널별 발송 건수', childNames: ['totalSndCnt', 'smsSndCnt', 'lmsSndCnt', 'mmsSndCnt', 'atlkSndCnt']},
          ]
        ],

        columns: [
          {name: 'useYm', header: '날짜', align: 'center'},
          {name: 'custNm', header: '고객사명', align: 'center', width: '130px'},
          {
            name: 'bizrno', header: '사업자번호', align: 'center', width: '120px'
            // ,formatter: props => {
            //   let result = props.bizrno.substring(0,3)+'-'+ props.bizrno.substring(3,5)+'-'+ props.bizrno.substring(5,10)
            //   return result;
            // }
          },
          {
            name: 'prodNm', header: '요금제', align: 'center', width: '160px'
            , formatter: props => {
              //let result = "<p>" + props.prodNm + "</p>\n<p>(" + props.prodAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') + ")</p>";
              let result = "<p>" + props.prodNm + "</p>";
              return result;
            }
          },
          {
            name: 'startAmt', header: '시작금액', align: 'center'
            , formatter: props => {
              let result = props.startAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'useAmt', header: '사용금액', align: 'center'
            , formatter: props => {
              let result = props.useAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'cfwdAmt', header: '이월금액', align: 'center'
            , formatter: props => {
              let result = props.cfwdAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'mrtUseAmt', header: '종량금액', align: 'center'
            , formatter: props => {
              let result = props.mrtUseAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'extncAmt', header: '소멸금액', align: 'center'
            , formatter: props => {
              let result = props.extncAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'billingAmt', header: '청구금액', align: 'center'
            , formatter: props => {
              let result = props.billingAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'totalSndCnt', header: '전체', align: 'center', cls: 'td_line'
            , formatter: props => {
              let result = props.totalSndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'smsSndCnt', header: 'SMS', align: 'center', cls: 'td_line'
            , formatter: props => {
              let result = props.smsSndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'lmsSndCnt', header: 'LMS', align: 'center', cls: 'td_line'
            , formatter: props => {
              let result = props.lmsSndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'mmsSndCnt', header: 'MMS', align: 'center', cls: 'td_line'
            , formatter: props => {
              let result = props.mmsSndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
          {
            name: 'atlkSndCnt', header: '알림톡', align: 'center', cls: 'td_line'
            , formatter: props => {
              let result = props.atlkSndCnt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return result;
            }
          },
        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          startMonth: '',
          endMonth: '',
        },
        excelHeader: []
      }

    };
  },
  components: {
    customGrid: customGrid,
    commonModal,
    vuejsDatepicker,
  },
  created() {
    this.setPeriodDay(0);
    this.gridParamSet();
    this.getExcelHeader();
  },
  destroyed() {

  },
  mounted() {
    let page = 1;
    // 페이지 정보 및 검색 조건
    const getCondition = this.$store.getters['searchcondition/getSearchCondition'];

    // store에 저장된 페이지 정보 및 검색 조건을 불러오기
    let isKeep = false;
    if (getCondition) {
      this.grid.pagePerRows = getCondition.perPage;
      this.grid.params = getCondition.params;
      page = getCondition.page;
      isKeep = true;
    }
    this.search(isKeep);
  },
  beforeRouteLeave(to, from, next) {

    const getP = this.$refs.table.getPagination();
    this.$store.commit('searchcondition/updateSearchCondition', {
      page: getP._currentPage,
      perPage: this.perPageCnt,
      params: this.grid.params
    });
    // 라우트 하기전 실행
    next();
  },
  methods: {
    search: function (isKeep) {
      this.$refs.table.search(this.grid.params, isKeep);
      this.grid.params = {
        startMonth: moment(this.startDate).format('YYYYMM'),
        endMonth: moment(this.endDate).format('YYYYMM'),
        custNm: this.grid.params.custNm,
        bizrno: this.grid.params.bizrno
      };    
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();

    },
    setPeriodDay(day) {
      this.periodDay = day;
      this.endDate = new Date();     
      this.initSetStartDate();
      this.initSetEndDate();
      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) {
        let initStartDate = new Date();
        let initEndDate = new Date();
        initStartDate.setMonth(Number(moment(initStartDate).format('MM')) - 4)
        initEndDate.setMonth(Number(moment(initEndDate).format('MM')) - 2)


        if (type == 'start') {
          this.disabledSDate = {to: initStartDate, from: new Date()};
          if (this.startDate !== initStartDate) {
            this.disabledEDate = {to: this.startDate, from: initEndDate};

          }
        } else if (type == 'end') {
          this.disabledEDate = {to: initStartDate, from: initEndDate};
          if (this.endDate !== initEndDate) {
            this.disabledSDate = {from: this.endDate};
            this.disabledSDate = {to: initStartDate, from: initEndDate};
          }
        }
      }
    },
    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');
      }
    },
    changePerPage: function () { 	// 페이지당 조회할 개수
      this.grid.pagePerRows = this.perPageCnt;
      this.search(true);
    },
    sendStoreData: function () {
      const getP = this.$refs.table.getPagination();
      this.$store.commit('searchcondition/updateSearchCondition', {
        page: getP._currentPage,
        perPage: this.perPageCnt,
        params: this.grid.params
      });

      const getCondition = this.$store.getters['searchcondition/getSearchCondition'];
    },
    gridParamSet() {
      this.grid.params = {
        startMonth: moment(this.startDate).format('YYYYMM'),
        endMonth: moment(this.endDate).format('YYYYMM'),
        custNm: this.grid.params.custNm,
        bizrno: this.grid.params.bizrno
      }

    },
    getExcelHeader() {
      // 헤더를 mockup으로 관리한다.
      calcMgtApi.getExcelHeader(this.pageType).then(res => {
        this.excelHeader = res;
      });
    },
    async excelDown() {
      if (this.$refs.table.getData().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`;

      const data = await this.getExcelDataDown();
      let options = {
        header: this.excelHeader,
        dataOrder: 'header'
      };
      xlsx.export(data.list, saveFileName, options).then(() => {
      });
    },
    async getExcelDataDown() {
      try {
        let response;

        response = await calcMgtApi.calcListExcel(this.grid.params);

        const result = response.data;
        // entity code 변환
        result.data.list = result.data.list.map((item) => {
          return {
            ...item,
            custNm: this.fromHtmlEntities(item.custNm)
          }
        });
        if (result != null && result.retCode == "0000") {
          return result.data;
        } else {
          return false;
        }
      } catch (err) {
        return false;
      }
    },
    initSetStartDate() {
      let initStartDate = new Date();
      initStartDate.setMonth(Number(moment(initStartDate).format('MM')) - 4);
      this.startDate = initStartDate;
    },
    initSetEndDate() {
      let initEndDate = new Date();
      initEndDate.setMonth(Number(moment(initEndDate).format('MM')) - 2);
      this.endDate = initEndDate;
    },
    fromHtmlEntities(str) {
      return (str + '').replace(/&#\d+;/gm, function (s) {
        return String.fromCharCode(s.match(/\d+/gm)[0]);
      });
    },
  }
}
;
</script>