<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);" class="on">회원관리</a>
      </div>

<!--      <div class="search_form">-->
        <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"
                      v-model="startDate"
                      @selected="selectedStartDate(0)"
                      @closed="closeDate('start')"
                  ></vuejs-datepicker>
                </span>~
                <span class="custom_input icon_date">
                  <vuejs-datepicker
                      :language="ko"
                      :format="customFormatter"
                      :disabled-dates="disabledEDate"
                      v-model="endDate"
                      @selected="selectedEndDate(0)"
                      @closed="closeDate('end')"
                  ></vuejs-datepicker>
                </span>
              </div>
            </div>
            <div class="select_box id">
              <label for="right" class="label">상태</label>
              <select name="" id="" v-model="searchType1" @keyup.enter="search">
                <option value="" selected>전체</option>
                <option v-for="(option, i) in statType" v-bind:value="option.code" v-bind:key="i">
                  {{ option.codeNm }}
                </option>
              </select>
            </div>
            <div class="select_box">
              <label for="right" class="label">구분</label>
              <select name="" id="" v-model="searchType2" @keyup.enter="search">
                <option value="" selected>전체</option>
                <option value="01" selected>관리자</option>
                <option value="02">사용자</option>
                <option value="03">테스트</option>
              </select>
            </div>
          </div>
          <div class="group">
            <div class="select_box">
              <label for="right" class="label">상세검색</label>
              <select name="" id="" v-model="searchType3" @keyup.enter="search">
                <option value="01" selected>ID</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>-->

      <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" @click="ModalOpen();">테스트 ID 생성</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>

      <testId-reg-pop ref="testIdRegPop"></testId-reg-pop>
      <common-modal ref="commmonModal"></common-modal>

    </div>
  </div>

</template>

<script>
import customGrid from '@/components/CustomGrid';
import TestIdRegPop from '../components/TestIdRegPop';
import moment from 'moment';
import api from '@/service/api.js';
import commonModal from "@/components/modal/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: 'memberList',
  data() {
    return {
      // 달력 데이터      
      ko: vdp_translation_ko.js,
      periodDay: 7,
      sDateDiv: 'day',
      startDate: new Date(),
      endDate: new Date(),

      statType: [],
      userType: [],
      searchType1: '',
      searchType2: '',
      searchType3: '01',
      row: {},

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

        columns: [
          {name: 'no', header: 'No', align: 'center', width: 60},
          {name: 'userNm', header: '이름', align: 'center', width: 130},
          {name: 'userType', header: '구분', align: 'center', width: 130},
          {name: 'adminId', header: '관리자ID', align: 'center', width: 130, cls: 'td_line'},
          {
            name: 'userId', header: 'ID', align: 'center', width: 130, renderer: {
              type: CustomATagRenderer
              , options: {
                callback: this.memberDetail,
              }
            }
          },
          {name: 'regDt', header: '등록일', align: 'center', width: 130},
          {name: 'userStat', header: '상태', align: 'center', width: 130}
        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          searchType1: '',
          searchType2: '',
          searchType3: '',
          searchText1: '',
          startDt: '',
          endDt: ''
        },
        excelHeader: []
      }
    };
  },
  components: {
    customGrid: customGrid,
    TestIdRegPop,
    commonModal,
    vuejsDatepicker,
  },
  created() {
    this.setCodeData();
    this.setPeriodDay(0);
  },
  destroyed() {
    this.$store.commit('searchcondition/updateSearchCondition', {
      page: 1,
      perPage: 50,
      params: {
        searchType1: '',
        searchType2: '',
        searchType3: '',
        searchText1: '',
        startDt: '',
        endDt: ''
      }
    });
  },
  mounted() {
    // 달력 세팅
    // this.grid.params.startDt = this.customFormatter(new Date());
    // this.grid.params.endDt = this.customFormatter(new Date());

    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.grid.params.startDt = moment(this.startDate).format('YYYYMMDD');
      this.grid.params.endDt = moment(this.endDate).format('YYYYMMDD');
      this.grid.params.searchType1 = this.searchType1;
      this.grid.params.searchType2 = this.searchType2;
      this.grid.params.searchType3 = this.searchType3;
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();
    },
    toMove(routeName) {
      this.$router.push({name: routeName, params: {page: 1, searchText: ''}});
    },
    ModalOpen: function () {
      this.$refs.testIdRegPop.ModalOpen();
    },
    memberDetail: function (props) {
      this.row.serviceId = props.userId;
      if (props.userType == '관리자 ID' || props.userType == '테스트 ID') {
        // 관리자 ID용 상세페이지 이동
        this.$router.push({name: 'memberAdminDetail', params: {serviceId: this.row.serviceId}});
      } else {
        // 사용자 ID용 상세페이지 이동
        this.$router.push({name: 'memberDetail', params: {serviceId: this.row.serviceId}});
      }
    },
    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'];
    },

    setCodeData() {
      // 상태 옵션 셋팅.
      api.commCode({'grpCd': 'SVCUSER_STTUS_CD'}).then(response => {
        this.statType = response.data.data.list;
      });
      // 
      api.commCode({'grpCd': 'SVCUSER_TP_CD'}).then(response => {
        this.userType = response.data.data.list;
      });
    },
    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;
      }
    },
    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');
      }
    },
    initSetStartDate() {
      let setYear = Number(moment(new Date()).format('YYYY'));
      let initStartDate = new Date(setYear, 0, 1);
      this.startDate = initStartDate;
    },
  },


};
</script>