<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" @change="search">
            <option value="">전체</option>
            <option value="01">서비스</option>
            <option value="02">개발/작업</option>
            <option value="03">정책/약관</option>
            <option value="04">오류/장애</option>
            <option value="05">이벤트</option>
          </select>
        </div>
        <div class="input_box id">
          <label for="id1" class="label">제목</label>
          <input
            class="search-box"
            type="text"
            id="id1"
            placeholder="제목 입력"
            v-model="searchText1"
            @keyup.enter="search"
          />
        </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 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 admin add" @click="ModalOpen()">공지사항 등록</button>
          <button type="button" class="button white del" @click="deleteNotice()">삭제</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>
    </div>
    <NoticePop ref="NoticePop" />
    <NoticeUpdatePop ref="NoticeUpdatePop" />
    <common-modal ref="commmonModal"></common-modal>
  </div>
</template>
<script>
import httpClient from '../../../common/http-client';
import customGrid from '@/components/CustomGrid';
import commonModal from '@/components/modal/commonModal';
import NoticePop from '../components/NoticePop.vue';
import NoticeUpdatePop from '../components/NoticeUpdatePop.vue';
import homeMgtApi from '../service/homeMgtApi';

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: 'notice',
  components: { customGrid, NoticePop, NoticeUpdatePop, commonModal },
  data() {
    return {
      row: {},
      totalItems: 0,
      perPageCnt: 50,
      searchType1: '',
      searchText1: '',
      options: [
        { text: '20', value: 20 },
        { text: '50', value: 50 },
        { text: '100', value: 100 },
      ],
      grid: {
        url: '/api/v1/bo/homeMgt/noticeList',
        pagePerRows: 20,
        pagination: true,
        isCheckbox: true, // true:첫번째 컬럼 앞에 체크박스 생성 / false:체크박스 제거
        initialRequest: true,
        addCls: 'box_OFvis',

        columns: [
          { name: 'no', header: 'No', align: 'center', width: '5%' },
          { name: 'ctgCdNm', header: '분류코드명', align: 'center', width: '10%' },
          {
            name: 'title',
            header: '제목',
            align: 'left',
            width: '45%',
            renderer: {
              type: CustomATagRenderer,
              options: {
                callback: this.noticeDetail,
              },
            },
          },
          {
            name: 'emgYn',
            header: '긴급여부',
            align: 'center',
            width: '10%',
            formatter: (props) => {
              let result = props.emgYn === 'Y' ? '긴급' : '';
              return result;
            },
          },
          {
            name: 'useYn',
            header: '사용여부',
            align: 'center',
            width: '5%',
            formatter: (props) => {
              let result = props.useYn === 'Y' ? '사용' : '사용 안함';
              return result;
            },
          },
          { name: 'regr', header: '등록자', align: 'center', width: '10%' },
          { name: 'regDt', header: '등록일자', align: 'center', width: '10%' },
        ],
        noDataStr: '검색 결과가 없습니다.',
        params: {
          searchType1: '',
          searchType2: '',
          searchText1: '',
          searchText2: '',
        },
        excelHeader: [],
      },
    };
  },
  mounted() {
    // this.fnSelectNoticeList();
    //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: {
    fnSelectNoticeList() {
      const params = { page: 1, pagePerRows: 10 };
      httpClient
        .post('/api/v1/bo/homeMgt/noticeList', params, { headers: { 'Show-Layer': 'Yes' } })
        .then((response) => {
          console.log(response.data);
        });
    },
    ModalOpen() {
      this.$refs.NoticePop.ModalOpen();
    },
    noticeDetail(props) {
      //console.log(props);
      this.$refs.NoticeUpdatePop.ModalOpen(props);
    },
    search: function (isKeep) {
      this.grid.params.searchType1 = this.searchType1;
      this.grid.params.searchText1 = this.searchText1;
      this.$refs.table.search(this.grid.params, isKeep);
      this.sendStoreData();
    },
    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'];
    },
    changePerPage: function () {
      // 페이지당 조회할 개수
      this.grid.pagePerRows = this.perPageCnt;
      this.search(true);
    },
    deleteNotice() {
      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)=>({regReqNo:row.regReqNo} ));
      const param = chkList.map((row) => ({ ntNo: row.ntNo }));
      this.row.list = param;

      this.row.title = '공지사항 관리';
      this.row.msg1 = '삭제 하시겠습니까?';
      this.$refs.commmonModal.confirmModalOpen2(this.row);

      console.log(typeof this.row.list[0].ntNo);
      //this.$refs.commmonModal.confirmModalOpen2(this.row);
    },
    confirmCalbackFnc(props) {
      if (props.result) {
        this.noticeDelete();
      }
    },
    async noticeDelete() {
      try {
        let response = await homeMgtApi.deleteNotice(this.row);
        const result = response.data;
        if (result != null && result.retCode == '0000') {
          this.$refs.table.reloadData();
          return;
        } else {
          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);
      }
    },
  },
};
</script>
