<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 one essential">
            <label for="right" class="label"><span>*</span>발송일</label>           
                <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>            
          </div>
          <div class="select_box id">
            <label for="right" class="label">요청채널</label>
            <select name="" id="" v-model="grid.params.searchType1" @keyup.enter="search">
              <option value="" selected>전체</option>
              <option value="SMS">SMS</option>
              <option value="LMS">LMS</option>
              <option value="MMS">MMS</option>
              <option value="ALIMTALK">알림톡</option>
            </select>
          </div>
        </div>
        <div class="group">
          <div class="input_box essential">
            <label for="right" class="label"><span>*</span>수신번호</label>
            <input class="search-box" type="text" id="search" placeholder="- 자 제외 숫자만 입력" @keyup.enter="search"
                   v-model.trim="grid.params.searchText1" @keypress="onlyNum" @input="onlyNum" maxlength="11"
                   ref="_searchText2">
          </div>
          <div class="input_box essential">
            <label for="right" class="label"><span>*</span>발신번호</label>
            <input class="search-box" type="text" id="search" placeholder="- 자 제외 숫자만 입력" @keyup.enter="search"
                   v-model.trim="grid.params.searchText2" @keypress="onlyNum" @input="onlyNum" maxlength="11"
                   ref="_searchText2">
          </div>
          <div class="input_box">
            <label for="right" class="label">고객사명</label>
            <input class="search-box" type="text" id="search" placeholder="검색어 입력" v-model.trim="grid.params.searchText3"
                   @keypress="onlyText" @input="onlyText" @keyup.enter="search" ref="_searchText3" maxlength="100">
          </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>
      <div class="table">
        <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.headder"

          ></custom-grid>
        </table>
      </div>


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

<script>
import customGrid from '@/components/CustomGrid';
import {utils_mixin, chkPattern2} from '../service/mixins';
import moment from 'moment';
import commonModal from "../components/commonModal";

class CustomATagRenderer {
  constructor(props) {
    this.props = props;
    const el = document.createElement('a');
    el.href = 'javascript:void(0);';
    el.className = 'btn_text';
    el.innerText = String(props.colValue)
    this.el = el;
  }

  getElement() {
    return this.el;
  }

  addEvent(selEl) {
    selEl.addEventListener("click", () => {
      const {callback} = this.props["cgrido" + this.props.colName].options;
      callback(this.props);
    });
  }
}

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

      statType: [],
      userType: [],
      row: {},
      initMode: false,
      pageType: 'SUBS',

      // 테이블 리스트 데이터
      perPageCnt: 50,
      options: [
        {text: '20', value: 20},
        {text: '50', value: 50},
        {text: '100', value: 100}
      ],
      totalItems: 0,
      grid: {
        url: '/api/v1/bo/mntrng/sendList',
        perPage: 20,
        pagination: true,
        isCheckbox: false,
        initialRequest: false,
        addCls: 'box_OFvis',

        header: [
          [
            {header: 'NO', childNames: []},
            {header: '발송일자', childNames: []},
            {header: '고객사명', childNames: []},
            {header: '발송아이디(사용자ID)', childNames: []},
            {header: '수신번호', childNames: []},
            {header: '발신번호', childNames: []},
            {header: '요청채널', childNames: []},
            {header: '최종채널', childNames: []},
            {header: '이통사', childNames: []},
            {header: '결과(코드)', childNames: []},
            {header: '요청일시', childNames: []},
            {header: '완료일시', childNames: []},
          ]
        ],

        columns: [
          {name: 'no', header: 'NO', align: 'center', width: '5%'},
          {name: 'sentDate', header: '발송일자', align: 'center', width: '11%'},
          {name: 'custNm', header: '고객사명', align: 'center', width: '9%'},
          {name: 'userId', header: '발송아이디(사용자ID)', align: 'center', width: '9%'},
          {name: 'phone', header: '수신번호', align: 'center', width: '11%'},
          {name: 'callbackNumber', header: '발신번호', align: 'center', width: '11%'},
          {name: 'reqProduct', header: '요청채널', align: 'center', width: '5%'},
          {name: 'doneCh', header: '최종채널', align: 'center', width: '5%'},
          {name: 'doneTelco', header: '이통사', align: 'center', width: '5%'},
          {name: 'doneCode', header: '결과(코드)', align: 'center', width: '9%'},
          {name: 'reqDate', header: '요청일시', align: 'center', width: '10%'},
          {name: 'doneDate', header: '완료일시', align: 'center', width: '10%'},

        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          searchType1: '',
          searchText1: '',
          searchText2: '',
          searchText3: '',
          sentDate: '',
        },
        excelHeader: []
      }
    };
  },
  components: {
    customGrid: customGrid,
    commonModal,
    vuejsDatepicker,
  },
  created() {
    // this.setCodeData();
    // this.getExcelHeader();
    this.setPeriodDay(0);
    this.grid.params.searchType1 = '';
    // this.$refs.table.cleanData();
    this.initMode = true;
  },

  destroyed() {
    this.grid.params.searchType1 = '';
    this.grid.params.searchText1 = '';
    this.grid.params.searchText2 = '';
    this.grid.params.searchText3 = '';

  },
  mounted() {
    this.grid.params.searchType1 = '';

    let page = 1;
    // 페이지 정보 및 검색 조건
    const getCondition = this.$store.getters['searchcondition/getSearchCondition'];
    console.log('getCondition : ' + getCondition);

    // 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();
    console.log("==========getP : " + getP._currentPage);
    this.$store.commit('searchcondition/updateSearchCondition', {
      page: getP._currentPage,
      perPage: this.perPageCnt,
      params: this.grid.params
    });
    // 라우트 하기전 실행
    next();
  },
  methods: {
    search: function (isKeep) {
      if (this.initMode) {
        this.grid.params.phone = '';
        this.grid.params.callbackNumber = '';
      } else {
        if (this.doValidate()) {
          this.grid.params.sentDate = moment(this.startDate).format('YYYYMMDD');
          this.grid.params.reqChennel = this.grid.params.searchType1;
          this.grid.params.phone = this.grid.params.searchText1;
          this.grid.params.callbackNumber = this.grid.params.searchText2;
          this.grid.params.custNm = this.grid.params.searchText3;
          console.log(this.grid.params);
        }
      }
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();
      this.initMode = false;
    },
    setPeriodDay(day) {
      this.periodDay = day;
      this.endDate = new Date();
      this.startDate = moment(this.endDate)
          .subtract(day, 'day')
          .toDate();

      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;
      }
      // console.log(this.disabledSDate)
      // this.grid.params.startDt = day
    },
    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');
      }
    },
    changePerPage: function () { 	// 페이지당 조회할 개수
      this.grid.pagePerRows = this.perPageCnt;
      this.search(true);
    },
    sendStoreData: function () {
      const getP = this.$refs.table.getPagination();
      console.log("==========getP : " + getP._currentPage);
      this.$store.commit('searchcondition/updateSearchCondition', {
        page: getP._currentPage,
        perPage: this.perPageCnt,
        params: this.grid.params
      });

      const getCondition = this.$store.getters['searchcondition/getSearchCondition'];
      console.log("getCondition : " + getCondition.perPage);
    },
    doValidate() {
      // 발송일자 필수입력체크
      if (this.isNull(this.startDate)) {
        this.row.title = '발송내역';
        this.row.msg1 = '발송일을 선택해 주세요.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      // 수신번호 필수입력체크
      if (this.isNull(this.grid.params.searchText1)) {
        this.row.title = '발송내역';
        this.row.msg1 = '수신번호를 입력해 주세요.';
        this.row.focusTaget = '1';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      // 발신번호 필수입력체크
      if (this.isNull(this.grid.params.searchText2)) {
        this.row.title = '발송내역';
        this.row.msg1 = '발신번호를 입력해 주세요.';
        this.row.focusTaget = '2';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      return true;

    },
    checkFocus() {
      if (this.row.focusTaget === '1') {
        this.$refs._searchText1.focus();
      } else if (this.row.focusTaget === '2') {
        this.$refs._searchText2.focus();
      }
    },
  }
};
</script>