<template>

    <div class="contents">
      <div class="contents_wrap">
        <div class="top_wrap">
          <h3 class="title">충전관리</h3>
          <p class="breadcrumb">고객관리 &gt; 청약고객관리 &gt; 충전관리</p>
        </div>

        <div class="top_tab">
          <a href="javascript:void(0);" @click="toMove('subsList')">청약고객관리</a>
          <a href="javascript:void(0);" @click="toMove('memberList')">회원관리</a>
          <a href="javascript:void(0);" class="on">충전관리</a>
        </div>
        <div class="search_wrap">
          <div class="group">
            <div class="input_box cal">
              <label for="right" class="label">조회기간</label>
              <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="select_box">
              <label for="right" class="label">상세검색</label>
              <select name="" id="" v-model="searchType1" @keyup.enter="search">
                <option value="01" selected>고객사명</option>
                <option value="02">사업자번호</option>
                <option value="03">ID</option>
              </select>
            </div>
            <div class="input_box">
              <input class="search-box" type="text" id="search" placeholder="검색어 입력" maxlength="100"
                     v-model.trim="grid.params.searchText1" @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 add" @click="insertChrg()">등록</button>
            <button type="button" class="button white del" @click="deleteChrg()">삭제</button>
          </div>
        
        </div>

        <div class="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>
        </div>
        <insert-chrg-modal ref="insertChrgModal"></insert-chrg-modal>
        <chrg-detail-pop ref="chrgDetailPop" />
        <common-modal ref="commonModal" />
      </div>
    </div>
</template>


<script>
import customGrid from '@/components/CustomGrid';
import moment from 'moment';
import InsertChrgModal from '../components/InsertChrgModal';
import chrgDetailPop from '../components/ChrgDetailPop.vue';
import commonModal from "@/components/modal/commonModal";
import custMgtApi from '../service/custMgtApi';

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: 'chrgList',
  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: {},
      searchType1: '01',
      chrgSeq : '',
      useYn: '',

      // 테이블 리스트 데이터
      perPageCnt: 50,
      options: [
        {text: '20', value: 20},
        {text: '50', value: 50},
        {text: '100', value: 100}
      ],
      totalItems: 0,
      grid:{
        url: '/api/v1/bo/custMgt/chrgList',
        pagePerRows: 50,
        pagination: true,
        isCheckbox: true,        // true:첫번째 컬럼 앞에 체크박스 생성 / false:체크박스 제거
        initialRequest: false,
        addCls: 'box_OFvis',

        columns:[
          {name: 'no', header: 'No', align: 'center', width: 60},
          {
            name: 'custNm', header: '고객사명', align: 'center', width: 130,
            renderer: {type: CustomATagRenderer, options: {callback: this.inDetailPop}}
          },
          {name: 'userId', header: '고객명', align: 'center', width: 130},
          {name: 'chrgDiv', header: '충전구분', align: 'center', width: 130},
          {name: 'chrgDate', header: '기간', align: 'center', width: 130},
          {name: 'chrgAmt', header: '충전금액', align: 'center', width: 130},
        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          searchType1: '',
          searchText1: '',
          startMonth: '',
          endMonth: '',
        },
      },
    };
  },
  components: {
    customGrid: customGrid,
    vuejsDatepicker,
    InsertChrgModal,
    chrgDetailPop,
    commonModal,
  },
  created() {
    this.setPeriodDay(0);
  },
  destroyed() {
    this.$store.commit('searchcondition/updateSearchCondition', {
      page: 1,
      perPage: 50,
      params: {
        searchType1: '',
        searchText1: '',
        startMonth: '',
        endMonth: '',
      },
    });
  },
  mounted() {

    // 달력 세팅
    let page = 1;

    // 페이지 정보 및 검색 조건
    const getCondition = this.$store.getters['searchcondition/getSearchCondition'];

    // store에 저장된 페이지 정보 및 검색 조건을 불러오기
    let isKeep = false;
    this.grid.pagePerRows = 50;
    page = 1;
    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: {
    toMove(routeName) {
      this.$router.push({name: routeName, params: {page: 1, searchText: ''}});
    },

    search: function (isKeep) {
      this.grid.params.startDt = moment(this.startDate).format('YYYYMM');
      this.grid.params.endDt = moment(this.endDate).format('YYYYMM');
      this.grid.params.searchType1 = this.searchType1;
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();
       
    },

    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'];
    },

    inDetailPop(props){
      this.$refs.chrgDetailPop.ChrgDetailModalOpen(props);
    },
  
    //달력 셋팅
    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')) -100)
        initEndDate.setMonth(Number(moment(initEndDate).format('MM')) + 100)
        

        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: this.startDate, from: initEndDate};
          if (this.endDate !== initEndDate) {
            this.disabledSDate = {from: this.endDate};
            this.disabledSDate = {to: initStartDate, from: this.endDate};
          }
        }
      }
    },
    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');
      }
    },
    gridParamSet() {
      this.grid.params = {
        startMonth: moment(this.startDate).format('YYYYMM'),
        endMonth: moment(this.endDate).format('YYYYMM'),
      }
  },
  initSetStartDate() {
      let initStartDate = new Date();
      initStartDate.setMonth(Number(moment(initStartDate).format('MM')) -1);
      this.startDate = initStartDate;
    },
    initSetEndDate() {
      let initEndDate = new Date();
      initEndDate.setMonth(Number(moment(initEndDate).format('MM')) );
      this.endDate = initEndDate;
    },

    insertChrg () {
      this.$refs.insertChrgModal.insertChrgOpen();
    },
    deleteChrg(){
      if (this.doValidate()) {
        this.row.title = '충전금 관리';
        this.row.msg1 = '삭제 하시겠습니까?';
        this.$refs.commonModal.confirmModalOpen2(this.row);
      }
    },

    async chrgdelete() {
      try {
        let respose = await custMgtApi.deleteChrg(this.row);
       
        const result = respose.data;
        if (result != null && result.retCode == '0000') {
          this.$refs.table.reloadData();
          return;
        } else {
          this.row.title = '충전금 관리';
          this.row.msg1 = '실패 하였습니다.';
          this.$refs.commonModal.alertModalOpen(this.row);
        }
      } catch (error) {
        this.row.title = '충전금 관리';
        this.row.msg1 = '실패 하였습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
      }
    },

    alertInsert(props) {
      this.$refs.commonModal.alertModalOpen(props);
    },

    doValidate() {
      //로우데이터 삭제하도록 수정
      // this.totalItems==1
      // if (this.totalItems == 0) {
      //   this.row.title = '충전금 관리';
      //   this.row.msg1 = '검색 결과가 없습니다.';
      //   this.$refs.commonModal.alertModalOpen(this.row);
      //   return false;
      // }
      var chkList = this.$refs.table.checkedElementDatas();
      if (chkList.length == 0) {
        this.row.title = '충전금 관리';
        this.row.msg1 = '삭제대상을 체크를 해주세요.';
        this.$refs.commonModal.alertModalOpen(this.row);
        return false;
      }
      const param = chkList.map((row) => ({ chrgSeq: row.chrgSeq }));
      this.row.list = param;
      return true;
    },
    confirmCalbackFnc(props) {
      if (props.result) {
        this.chrgdelete();
      }
    },
  }
}
</script>
