<template>
  <div class="content-zone">
    <div class="content">
      <div class="scroll">
        <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="fnViewDetail"
          >
            <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="'pagination'"
        v-model:currentPage="search['currentPage']"
        :pagination="search"
        :click="fnViewList"
      />
      <button
        class="btn sm primary"
        @click="fnInsert"
        v-if="pageAuth.regAuthrt == 'Y'"
      >
        등록
      </button>
  </div>
</template>

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

// COMPONENT
import ListTable from "../../../../component/table/ListTable.vue";
import PaginationButton from "../../../../component/pagination/PaginationButton.vue";


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

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

export default {
  mixins: [queryParams],
  components: {
    ListTable: ListTable,
    PaginationButton: PaginationButton,

  },
  data() {
    return {
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth, // 페이지 권한

      colgroup: ["5%", "19%", "19%", "15%", "10%", "8%"],
      thead: [
        "번호",
        "아이디",
        "이름",
        "휴대폰번호",
        "등록일",
        "비밀번호 초기화",
      ],
      tbody: [],
      search: { ...defaultSearchParams },
      list: [],
    };
  },
  created() {
    this.resotreQueryParams("queryParams");
    this.fnViewList();
  },
  methods: {
    // axios: 조회(목록)
    async fnViewList() {
      // 데이터 세팅
      let data = this.search;
      data.cateId = "authrt_cd";
      data.cateValue = "ROLE_ADMIN";
      // 검색조건 저장
      this.saveQueryParams("queryParams", data);
      // 실행
      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"],
        mblTelno: member["mblTelno"],
        regDt: member["regDt"],
      }));
    },

    // 조회(상세)
    fnViewDetail(idx) {
      this.$router.push({
        name: "admAdminManagementSelectListOne",
        query: { pageId: this.list[idx]["mbrId"] },
      });
    },

    // 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: "admAdminManagementInsert",
      });
    },
  },
};
</script>
