<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>관리자 관리</span>
        <span>{{ pageId }}</span>
      </div>
    </div>

    <div class="search--modules">
      <div class="form--cont--filter">
        <v-select
          v-model="filter"
          :items="filderArr"
          variant="outlined"
          class="custom-select"
        >
        </v-select>
      </div>
      <div class="form--cont--text">
        <v-text-field
          v-model="searchModel"
          class="custom-input mini"
          style="width: 100%"
          placeholder="검색어를 입력하세요"
        ></v-text-field>
      </div>
      <v-btn
        class="custom-btn btn-blue mini sch--btn"
        @click="fnSearch(searchModel, filter)"
        >검색</v-btn
      >
    </div>

    <div class="data--list--wrap">
      <div class="btn--actions--wrap">
        <div class="left--sections">
        </div>
        <div class="right--sections">
          <v-btn class="custom-btn mini btn-white" @click="fnDelEvt">선택 삭제</v-btn>
          <v-btn class="custom-btn mini btn-reg ml--10" @click="fnResEvt"
            >선택 복원</v-btn
          >
        </div>
      </div>

      <div class="tbl-wrapper">
        <div class="tbl-wrap">
          <!-- ag grid -->
          <ag-grid-vue
            style="width: 100%; height: calc(10 * 2.94rem)"
            class="ag-theme-quartz"
            :gridOptions="gridOptions"
            :rowData="tblItems"
            rowSelection="multiple"
            :paginationPageSize="pageObj.pageSize"
            :suppressPaginationPanel="true"
            @grid-ready="onGridReady"
          >
          </ag-grid-vue>

          <!-- 페이징 -->
          <div class="ag-grid-custom-pagenations">
            <pagination @chg_page="chgPage" :pageObj="pageObj"></pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { AgGridVue } from "ag-grid-vue3";
import pagination from "../components/common/pagination.vue";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const searchModel = ref("");
  const filter = ref("");
  const filderArr = ref([
    { title: "선택하세요", value: "" },
    { title: "이름", value: "name" },
    { title: "아이디", value: "id" },
  ]);
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = ref("삭제 관리자 리스트");
  let pageObj = ref({
    page: 1, // 현재 페이지
    pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
    pageSize: 10, // 테이블 조회 데이터 개수
    totalCnt: 0, // 전체 페이지
  });
  const tblItems = ref([]); // stat 데이터

  /* eslint-disable */
  /* prettier-ignore */

  pageObj.value.totalCnt = tblItems.value.length;

  const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
  const rowHeightRem = 2.65; // 원하는 rem 값
  const rowHeightPx = rowHeightRem * remToPx();
  const gridApi = shallowRef();

  // gridOption
  const gridOptions = {
    columnDefs: [
      { checkboxSelection: true, headerCheckboxSelection: true, width: 0 },
      {
        headerName: "No",
        valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
        sortable: false,
        width: 70,
      },
      // { headerName: "번호", field: "NO", sortable: false },
      { headerName: "아이디", field: "ID", sortable: false },
      { headerName: "이름", field: "NAME", sortable: false },
      { headerName: "이메일", field: "EMAIL", sortable: false },
      { headerName: "상태",
        field: "STATUS",
        sortable: false,
        width: 140,
        cellRenderer: (params) => {
          return params.value == 0 ? '사용중' : params.value == 1 ? '정지' : '삭제';
        }
      },
      { headerName: "삭제일", field: "REGDATE", sortable: false, width: 140 },
      // {
      //   headerName: "알림 메일 수신 여부",
      //   field: "mail_recp_yn",
      //   sortable: false,
      //   width: 130,
      // },
    ],
    rowData: tblItems.value, // 테이블 데이터
    autoSizeStrategy: {
      type: "fitGridWidth", // width맞춤
    },
    suppressMovableColumns: true,
    headerHeight: rowHeightPx,
    rowHeight: rowHeightPx,
    pagination: true,
    suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
    //rowSelection: {
    // checkboxes: true,
    // headerCheckbox: true,
    // enableClickSelection: false,
    // mode: "multiRow",
    //},
  };

  /************************************************************************
|    함수(METHODS)
************************************************************************/
  const onGridReady = (__PARAMS) => {
    gridApi.value = __PARAMS.api;
  };

  const chgPage = (__PAGE) => {
    pageObj.value.page = __PAGE;
    gridApi.value.paginationGoToPage(__PAGE - 1);
  };

  // const detailLocated = (__EVENT) => {
  //   router.push({
  //     path: "/view/mng/mngAdd",
  //   });
  //   useDtStore.adminInfo.adminId = __EVENT.data.ID;
  //   useDtStore.adminInfo.pageType = "U";
  // };

  const adminListGet = () => {
    let _req = {
      _size: 1000,
      _index: 0,
      status: "-1",
    };

    useAxios()
      .post("/mng/list", _req)
      .then((res) => {
        _req._size = res.data.length;
        tblItems.value = res.data;
        pageObj.value.totalCnt = tblItems.value.length;
      });
  };

  const fnSearch = (__KEYWORD, __FILTER) => {
    let _req = {
      _size: 1000,
      _index: 0,
      filter: __FILTER,
      keyword: __KEYWORD,
      status: "-1"
    };

    useAxios()
      .post("/mng/search", _req)
      .then((res) => {
        _req._size = res.data.length;

        tblItems.value = res.data;
        pageObj.value.totalCnt = tblItems.value.length;
      })
      .catch((error) => {});
  };

  const fnRestore = async (idArr) => {
    if (!idArr.length) return;
    
    for (const id of idArr) {
      await useAxios().post(`mng/stupdate/${id}`);
    }
    window.location.reload();
  };

  const fnResEvt = () => {
    const selected = gridApi.value.getSelectedRows();
    if(selected.length ===  0){
      let param = {
        id: pageId,
        title: "관리자 복원",
        content: "복원할 관리자를 선택하세요.",
        yes: {
          text: "확인",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    } else{
      let param = {
        id: pageId,
        title: "관리자 복원",
        content: "복원하시겠습니까?",
        yes: {
          text: "확인",
          isProc: true,
          event: "FN_RESTORE",
          param: selected,
        },
        no: {
          text: "취소",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    }
  };

  const fnDelete = async (idArr) => {
    if (!idArr.length) return;
    
    for (const id of idArr) {
      await useAxios().post(`mng/delete/${id}`);
    }
    window.location.reload();
  };

  const fnDelEvt = () => {
    const selected = gridApi.value.getSelectedRows();
    if(selected.length ===  0){
      let param = {
        id: pageId,
        title: "관리자 삭제",
        content: "삭제할 관리자를 선택하세요.",
        yes: {
          text: "확인",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    } else{
      let param = {
        id: pageId,
        title: "관리자 삭제",
        content: "삭제하시겠습니까?",
        yes: {
          text: "확인",
          isProc: true,
          event: "FN_DELETE",
          param: selected,
        },
        no: {
          text: "취소",
          isProc: false,
        },
      };
      $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
    }
  };
/************************************************************************
|    팝업 이벤트버스 정의
************************************************************************/
$eventBus.off("FN_RESTORE");
$eventBus.on("FN_RESTORE", (selected) => {
  const idList = selected.map(row => row.ID);
  fnRestore(idList);
});
$eventBus.off("FN_DELETE");
$eventBus.on("FN_DELETE", (selected) => {
  const idList = selected.map(row => row.ID);
  fnDelete(idList);
});
/************************************************************************
|    WATCH
************************************************************************/

  watch(
    () => props,
    () => {
      searchObj.value = props.propsData;
      fnGetStat();
    },
    { deep: true }
  );

  onMounted(() => {
    adminListGet();
  });
</script>
