<template>
  <div class="content-zone">
    <div class="content">
      <div class="scroll">
        <div class="title-zone">
          <div class="page-title">
            <p>일반회원 관리</p>
          </div>
          <PagiNavigationBar />
        </div>
        <div class="search-bar">
            <select class="form-select sm" v-model="search['searchType']">
              <option value="">전체</option>
              <option value="lgn_id">아이디</option>
              <option value="mbr_nm">이름</option>
            </select>
            <input
              type="text"
              class="form-control sm"
              v-model="search['searchText']"
              v-on:keyup.enter="fnViewList"
            />
          <button class="btn sm ico-before ico-sch" @click="fnViewList">검색</button>
        </div>
        <div class="tbl-wrap">
          <ListTable
          :colgroup="colgroup"
          :thead="thead"
          :tbody="tbody"
          :className="'data cursor'"
          @listClick="fnModalOpen"
        >
          <template #button="buttonProps">
            <button
              title="초기화"
              class="btn-ico md ico-refresh"
              @click.stop="fnReset(buttonProps)"
              v-if="pageAuth.mdfcnAuthrt == 'Y'"
            >
            </button>
          </template>
        </ListTable>
        </div>
      </div>
    </div>
  </div>
  <div class="btn-wrap list">
      <div></div>
        <PaginationButton
          :className="'admin-pagination'"
          v-model:currentPage="search['currentPage']"
          :pagination="search"
          :click="fnViewList"
        />

        <button
          class="btn sm primary"
          @click="fnInsert"
          v-if="pageAuth.regAuthrt == 'Y'"
        >
          등록
        </button>
    </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']"
          placeholder="개인 정보 조회 사유를 작성하세요."
          ref="inqRsn"
          class="form-control"
        ></textarea>
      </div>
      <template v-slot:footer>
          <button class="btn sm primary" @click="fnModalInsert">
            등록
          </button>
          <button class="btn sm tertiary" @click="fnModalClose">
            취소
          </button>
      </template>
    </Modal>
</template>

<script>
import { toRaw } from "vue";

// COMPONENT
import Modal from "../../../../component/modal/Modal.vue";
import ListTable from "../../../../component/table/ListTable.vue";
import PaginationButton from "../../../../component/pagination/PaginationButton.vue";
import PagiNavigationBar from "../../../../component/paginavigationbar/PagiNavigationBar.vue";

// RESOURCES
import queryParams from "../../../../../resources/js/queryParams";
import { insertProc } from "../../../../../resources/api/prvcInqHstry";
import { defaultSearchParams } from "../../../../../resources/js/defaultSearchParams";

// API
import { mbrListProc, pswdResetProc } from "../../../../../resources/api/mbrInfo";

export default {
  mixins: [queryParams],
  components: {
    Modal: Modal,
    ListTable: ListTable,
    PaginationButton: PaginationButton,
    PagiNavigationBar: PagiNavigationBar
  },
  data() {
    return {
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth, // 페이지 권한

      isOpen: false,

      colgroup: ["5%", "15%", "10%", "13%", "15%", "10%", "8%"],
      thead: [
        "번호",
        "아이디",
        "이름",
        "이메일",
        "회원상태",
        "등록일",
        "초기화",
      ],
      tbody: [],
      search: { ...defaultSearchParams },
      list: [],
      prvcInqHstry: {
        inqHstryId: null,
        inqTrprId: null,
        inqRsn: null,
        inqIp: null,
        rdr: null,
        inqDt: null,
      },
    };
  },
  created() {
    this.resotreQueryParams("queryParams");
    this.fnViewList();
  },
  methods: {
    // axios: 조회(목록)
    async fnViewList() {
      // 데이터 세팅
      let data = this.search;
      data.cateId = "authrt_cd";
      data.cateValue = "ROLE_USER";
      // 검색조건 저장
      this.saveQueryParams("queryParams", this.search);
      // 실행
      try {
        const response = await mbrListProc(toRaw(data));
        this.mblTelnoSplit(response.data.data.list);
        this.list = response.data.data.list;
        this.search = response.data.data.pagination;
        this.makeTbody();
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },
    // 휴대폰번호 표기 변환
    mblTelnoSplit(data) {
      for (const item of data) {
        const mblTelno = item["mblTelno"];
        const start = mblTelno.substring(0, 3);
        const middle = mblTelno.substring(3, mblTelno.length - 4);
        const end = mblTelno.substring(mblTelno.length - 4, mblTelno.length);
        item["mblTelno"] = start + "-" + middle + "-" + end;
      }
    },
    // tbody 생성
    makeTbody() {
      this.tbody = [];
      this.tbody = this.list.map((member, idx) => ({
        id:
          this.search.totalRecordCount -
          idx -
          (this.search.currentPage - 1) * this.search.pageSize,
        lgnId: member["lgnId"],
        mbrNm: member["mbrNm"],
        eml: member["eml"],
        mbrStts:
          member.mbrStts == "0"
            ? "탈퇴"
            : member.mbrStts == "1"
            ? "승인"
            : member.mbrStts == "2"
            ? "승인대기"
            : member.mbrStts == "3"
            ? "차단"
            : "-",
        regDt: member["regDt"],
      }));
    },

    // 조회(상세)
    fnViewDetail(prvcInqHstry) {
      this.$router.push({
        name: "admUserManagementSelectListOne",
        query: { pageId: prvcInqHstry.inqTrprId },
      });
    },
    // 모달 열기
    fnModalOpen(idx) {
      this.isOpen = true;
      this.prvcInqHstry["inqTrprId"] = this.list[idx]["mbrId"];
    },
    // 모달 닫기
    fnModalClose() {
      this.isOpen = false;
      this.prvcInqHstry = {
        inqHstryId: null,
        inqTrprId: null,
        inqRsn: null,
        inqIp: null,
        rdr: null,
        inqDt: null,
      };
    },
    // axios: 모달 등록
    async fnModalInsert() {
      // 유효성 검사
      if (
        this.prvcInqHstry["inqRsn"] == null ||
        this.prvcInqHstry["inqRsn"] == ""
      ) {
        alert("사유를 입력해주세요.");
        this.$refs.inqRsn.focus();
        return;
      }
      // 데이터 세팅
      const data = this.prvcInqHstry;
      // 실행
      try {
        const response = await insertProc(data);
        alert(response.data["message"]);
        this.fnViewDetail(data);
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        }
      }
    },

    // axios: 비밀번호 초기화
    async fnReset(props) {
      let isCheck = confirm("선택한 계정의 비밀번호를 초기화 하시겠습니까?");
      if (!isCheck) {
        return;
      }

      let index = props["idx"];
      let data = {
        mbrId: this.list[index]["mbrId"],
        pswd: this.list[index]["pswd"],
      };

      try {
        const response = await pswdResetProc(data);
        alert(response.data.message);
        this.fnViewList();
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },

    // 등록
    fnInsert() {
      this.$router.push({
        name: "admUserManagementInsert",
      });
    },
  },
};
</script>
