<template>
  <div class="search-wrap">
    <div></div>
    <div class="search-bar">
        <div class="form-control sm cal">
          <VueDatePicker
            InlineOptions   
            placeholder="시작일"
            locale="ko"
            :enable-time-picker="false"
            :format="formatDate"
            v-model="search['startDt']"
              />
        </div>  
        <div class="mark">~</div>
        <div  class="form-control sm cal">
          <VueDatePicker
            InlineOptions
            placeholder="종료일"
            locale="ko"
            :enable-time-picker="false"
            :format="formatDate"
            v-model="search['endDt']"
          />
      </div>
      <div class="search-bar border ml10">
        <select
          name="selectType"
          id="selectType"
          class="form-select sm border-none"
          v-model="search['searchType']"
        >
          <option value="">전체</option>
          <option
            v-for="(item, idx) in codeList"
            :key="idx"
            :value="item.cd"
          >
            {{ item.cdNm }}
          </option>
        </select>
        <input
          type="text"
          class="form-control sm border-none"
          v-model="search['searchText']"
          v-on:keyup.enter="fnViewList"
          placeholder="검색어를 입력하세요."
        />
        <button class="btn-ico xsm ico-sch" @click="fnViewList">
          <span class="sr-only">검색</span>
        </button>
      </div>
    </div>
  </div>
  <div class="content-zone">
    <div class="content">
      <div class="scroll">
        <div class="tbl-wrap">
          <ListTable
            :colgroup="colgroup"
            :thead="thead"
            :tbody="tbody"
            :className="'data cursor'"
            @listClick="fnViewDetail"
          />
        </div>
      </div>
    </div>
  </div>
  <div class="btn-wrap list">
    <div></div>
      <PaginationButton
        :className="'admin-pagination'"
        v-model:currentPage="search['currentPage']"
        :pagination="search"
        :click="fnViewList"
      />
      <div></div>
  </div>
  <!-- 개인 정보 조회 사유 모달 -->
  <Modal :showModal="isOpen">
    <template v-slot:header>
      <div class="modal-title">
        <p>개인 정보 조회 사유</p>
      </div>
      <button class="btn-close" @click="fnModalClose"></button>
    </template>
    <div>
      <textarea v-model="prvcInqHstry['inqRsn']" disabled class="form-control"></textarea>
    </div>
    <template v-slot:footer>
      <button class="btn sm tertiary" @click="fnModalClose">
        확인
      </button>
    </template>
  </Modal>
</template>

<script>
import Modal from "../../../component/modal/Modal.vue";
import ListTable from "../../../component/table/ListTable.vue";
import PaginationButton from "../../../component/pagination/PaginationButton.vue";
import { defaultSearchParams } from "../../../../resources/js/defaultSearchParams";

// API
import { listProc, detailProc } from "../../../../resources/api/prvcInqHstry";

export default {
  components: {
    Modal: Modal,
    ListTable: ListTable,
    PaginationButton: PaginationButton,
  },
  data() {
    return {
      isOpen: false,

      colgroup: ["5%", "23.75%", "23.75%", "23.75%", "23.75%"],
      thead: ["NO", "조회일", "조회자", "조회 대상 아이디", "접속IP"],
      tbody: [],

      search: { ...defaultSearchParams },

      list: [],
      pagination: {},

      prvcInqHstry: {},
    };
  },
  created() {
    this.fnViewList();
  },
  methods: {
    // 조회(목록)
    fnViewList() {
      let data = this.search;
      if (this.search["startDt"] != null && this.search["startDt"] != "") {
        this.search["startDt"] = this.dateFormat(
          new Date(this.search["startDt"])
        );
      }
      if (this.search["endDt"] != null && this.search["endDt"] != "") {
        this.search["endDt"] = this.dateFormat(new Date(this.search["endDt"]));
      }
      this.axiosViewList(data);
    },
    // 조회(상세)
    fnViewDetail(idx) {
      let data = { inqHstryId: this.list[idx]["inqHstryId"] };
      this.axiosViewDetail(data);
    },

    // 모달 열기
    fnModalOpen() {
      this.isOpen = true;
    },
    // 모달 닫기
    fnModalClose() {
      this.isOpen = false;
    },

    // tbody 생성
    makeTbody() {
      this.tbody = [];
      this.tbody = this.list.map((prvcInqHstry, idx) => ({
        id:
          this.search.totalRecordCount -
          idx -
          (this.search.currentPage - 1) * this.search.recordSize,
        inqDt: prvcInqHstry.inqDt,
        mbrNm: prvcInqHstry.mbrNm,
        lgnId: prvcInqHstry.lgnId,
        inqIp: prvcInqHstry.inqIp,
      }));
    },

    // 날짜 형식 변경
    dateFormat(date) {
      // console.log(date);
      return (
        date.getFullYear() +
        "-" +
        (date.getMonth() + 1 < 9
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) +
        "-" +
        (date.getDate() < 9 ? "0" + date.getDate() : date.getDate())
      );
    },

    //─────axios─────┐
    // 목록 조회
    async axiosViewList(data) {
      try {
        const response = await listProc(data);
        this.list = response.data.data.list;
        this.search = response.data.data.pagination;
        this.codeList = response.data.data.codeList;
        this.makeTbody();
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        }
      }
    },
    // 상세 조회
    async axiosViewDetail(data) {
      try {
        const response = await detailProc(data);
        this.prvcInqHstry = response.data.data;
        this.fnModalOpen();
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        }
      }
    },
    //─────axios─────┘},
    // 날짜포맷
    formatDate(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();

      // 날짜 앞에 0을 붙여야 하는 경우
      if (month || day < 10) {
        const zeroDay = ('00' + day).slice(-2);
        const zeroMonth = ('00' + month).slice(-2);

        return `${year}-${zeroMonth}-${zeroDay}`;
      } else {

        return `${year}-${month}-${day}`;
      }
    }
  },
};
</script>
