<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="select_box">
          <label for="right" class="label">권한</label>
          <select name="" id="right" v-model="searchType1" @keyup.enter="search">
            <option value="">전체</option>
            <option v-for="(option, i) in authType" v-bind:value="option.autCd" v-bind:key="i">
              {{ option.autNm }}
            </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 v-for="(option, i) in statType" v-bind:value="option.code" v-bind:key="i">
              {{ option.codeNm }}
            </option>
          </select>
        </div>
        <div class="input_box id">
          <label for="id1" class="label">ID</label>
          <input
            class="search-box"
            type="text"
            id="id1"
            placeholder="검색어 입력"
            v-model.trim="grid.params.searchText1"
            @keyup.enter="search"
            :readonly="!isFocused"
            @focus="isFocused = true"
            @blur="isFocused = false"
          />
        </div>
        <div class="input_box">
          <label for="name" class="label">이름(대리점명)</label>
          <input
            class="search-box"
            type="text"
            id="name"
            placeholder="검색어 입력"
            v-model.trim="grid.params.searchText2"
            @keyup.enter="search"
            :readonly="!isFocused"
            @focus="isFocused = true"
            @blur="isFocused = false"
          />
        </div>
        <button type="button" class="button grey" @click="search">조회</button>
      </div>
      <div class="info">
        <div class="count">
          총 <span>{{ totalItems.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</span
          >건
        </div>
        <div class="button_group">
          <button type="button" class="button blue admin add" @click="adminRegPopOpen()">관리자 등록</button>
          <button type="button" class="button blue channel add" @click="adminReg2PopOpen()">유치채널 등록</button>
          <button type="button" class="button white delete del" @click="rowDelete()">삭제</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>
      <admin-reg-pop ref="adminRegModal"></admin-reg-pop>
      <admin-detail-pop ref="adminDetailModal"></admin-detail-pop>
      <common-modal ref="commmonModal"></common-modal>
    </div>
  </div>
</template>

<script>
import customGrid from '@/components/CustomGrid';
import AdminRegPop from '../components/AdminRegPop';
import commonModal from '@/components/modal/commonModal';
import AdminDetailPop from '../components/AdminDetailPop';
import api from '@/service/api.js';
import sysMgtApi from '../service/sysMgtApi.js';

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: 'adminList',
  data() {
    return {
      isFocused: false,
      row: {},
      authType: [],
      statType: [],
      cate2Code: '',
      totalItems: 0,
      // 테이블 리스트 데이터
      perPageCnt: 50,
      searchType1: '',
      searchType2: '',
      grid: {
        url: '/api/v1/bo/sysMgt/adminList',
        pagePerRows: 50,
        pagination: true,
        isCheckbox: true, // true:첫번째 컬럼 앞에 체크박스 생성 / false:체크박스 제거
        initialRequest: false,
        addCls: 'box_OFvis',

        columns: [
          { name: 'no', header: 'No', align: 'center', width: '6%' },
          { name: 'auth', header: '권한', align: 'center', width: '18%' },
          { name: 'name', header: '이름(대리점명)', align: 'center', width: '18%' },
          {
            name: 'adminId',
            header: 'ID',
            align: 'center',
            width: '18%',
            renderer: {
              type: CustomATagRenderer,
              options: {
                callback: this.detailPop,
              },
            },
          },
          { name: 'adminStat', header: '상태', align: 'center', width: '18%', cls: 'td_line' },
          { name: 'regDt', header: '등록일', align: 'center', width: '18%' },
        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          searchType1: '',
          searchType2: '',
          searchText1: '',
          searchText2: '',
        },
        excelHeader: [],
      },
    };
  },
  components: {
    customGrid: customGrid,
    // SystemPopup,
    AdminRegPop,
    commonModal,
    AdminDetailPop,
  },
  created() {
    this.setCodeData();
    //let cont = document.querySelector(".wrap");
    //cont.classList.add("main_wrap");
  },
  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.grid.pagePerRows = 50;
    page = 1;
    this.search(isKeep);
  },
  methods: {
    search: function (isKeep) {
      this.grid.params.searchType1 = this.searchType1;
      this.grid.params.searchType2 = this.searchType2;
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();
    },
    detailPop(props) {
      this.$refs.adminDetailModal.adminDetailModalOpen(props);
    },
    ModalOpen: function (target) {},
    adminRegPopOpen: function () {
      this.$refs.adminRegModal.ModalOpen(1);
    },
    adminReg2PopOpen: function () {
      this.$refs.adminRegModal.ModalOpen(2);
    },
    doValidate() {
      //로우데이터 삭제하도록 수정

      if (this.totalItems == 0) {
        this.row.title = '관리자/유치채널 관리';
        this.row.msg1 = '검색 결과가 없습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      var chkList = this.$refs.table.checkedElementDatas();
      if (chkList.length == 0) {
        this.row.title = '관리자/유치채널 관리';
        this.row.msg1 = '삭제대상을 체크 해주세요.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      const param = chkList.map((row) => ({ adminId: row.adminId }));
      this.row.list = param;
      return 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'];
    },
    async setCodeData() {
      // 상태
      try {
        const res = await api.commCode({ grpCd: 'ADM_STTUS_CD' });
        if (res.data.retCode == '0000') {
          this.statType = res.data.data.list;
        }
      } catch (err) {}
      // 권한
      try {
        const response = await api.commAuth();
        if (response.data.retCode == '0000') {
          this.authType = response.data.data.list;
        }
      } catch (err) {}
    },
    rowDelete() {
      if (this.doValidate()) {
        this.row.title = '관리자/유치채널 관리';
        this.row.msg1 = '삭제 하시겠습니까?';
        this.$refs.commmonModal.confirmModalOpen2(this.row);
      }
    },
    async deleteRow() {
      try {
        let response = await sysMgtApi.deleteAdmin(this.row);
        const result = response.data;
        if (result != null && result.retCode == '0000') {
          this.$refs.table.reloadData();
          return;
        }
        this.row.title = '관리자/유치채널 관리';
        this.row.msg1 = '실패 하였습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
      } catch (err) {
        this.row.title = '관리자/유치채널 관리';
        this.row.msg1 = '실패 하였습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
      }
    },
    confirmCalbackFnc(props) {
      if (props.result) {
        this.deleteRow();
      }
    },
  },

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