<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>{{ pageId }}</span>
        <span v-if="pageIdSub">{{ pageIdSub }}</span>
      </div>
    </div>

    <div class="search--modules type2">
      <div class="search--inner">
        <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>
      </div>
      <div class="search--inner">
        <div class="calendar-wrap ml--0">
          <div class="calendar">
            <VueDatePicker
              :format="datePickerFormat"
              v-model="searchStartDate"
              placeholder="날짜를 선택하세요"
              :auto-apply="true"
              week-start="0"
            ></VueDatePicker>
          </div>
          <span class="text">~</span>
          <div class="calendar">
            <VueDatePicker
              v-model="searchEndDate"
              :format="datePickerFormat"
              placeholder="날짜를 선택하세요"
              :auto-apply="true"
              week-start="0"
            ></VueDatePicker>
          </div>
          <div class="month--selector">
            <v-btn
              v-for="option in dateOptions"
              :key="option.value"
              :class="{ actv: selectedRange === option.value }"
              @click="setDateRange(option.value)"
              elevation="0"
            >
              {{ option.label }}
            </v-btn>
          </div>
        </div>
      </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">
          <!-- <v-btn class="custom-btn mini btn-white">선택 삭제</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"
            :paginationPageSize="pageObj.pageSize"
            :suppressPaginationPanel="true"
            @grid-ready="onGridReady"
            @rowClicked="detailLocated"
          >
          </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 VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
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 filter = ref("");
const filderArr = ref([
  { title: "전체", value: "" },
  { title: "벤더사", value: "title" },
]);
const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
const router = useRouter();
const pageId = ref("정산 관리");
const pageIdSub = ref();
const searchModel = ref("");
const selectedRange = ref('all');
const itemStartDate = ref("");
const searchStartDate = ref("");
const searchEndDate = ref("");
const datePickerFormat = "yyyy-MM-dd";
const dateOptions = [
  { label: '오늘', value: 'today' },
  { label: '7일', value: '7d' },
  { label: '1개월', value: '1m' },
  { label: '3개월', value: '3m' },
  { label: '전체', value: 'all' },
]
let pageObj = ref({
  page: 1, // 현재 페이지
  pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
  pageSize: 10, // 테이블 조회 데이터 개수
  totalCnt: 0, // 전체 페이지
});
const tblItems = ref([]); // stat 데이터

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

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

// gridOption
const gridOptions = {
  columnDefs: [
    {
      headerName: "No",
      valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
      sortable: false,
      width: 70,
    },
    { headerName: "벤더사", field: "brd_lang", sortable: true, width: 150 },
    { headerName: "제품 총수량", field: "title", sortable: false, width: 70 },
    { headerName: "판매금액", field: "show_yn", sortable: true, width: 70 },
    { headerName: "정산기간", field: "crt_dtime", sortable: false, width: 120 },
  ],
  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/media/irAdd",
  });
  useDtStore.boardInfo.seq = __EVENT.data.seq;
  useDtStore.boardInfo.pageType = "U";
};

const newsListGet = () => {
  let _req = {
    _size: 1000,
    _index: 0,
    brd_lang: "",
    brd_cd: "BR02",
  };

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

const setDateRange = (range) => {
  const today = dayjs();

  switch(range) {
    case 'today' :
      searchStartDate.value = today.format('YYYY-MM-DD');
      searchEndDate.value = today.format('YYYY-MM-DD');
      selectedRange.value = 'today';
      break;
    case '7d':
      searchStartDate.value = today.subtract(7, 'day').format('YYYY-MM-DD');
      searchEndDate.value = today.format('YYYY-MM-DD');
      selectedRange.value = '7d';
      break;
    case '1m':
      searchStartDate.value = today.subtract(1, 'month').format('YYYY-MM-DD');
      searchEndDate.value = today.format('YYYY-MM-DD');
      selectedRange.value = '1m';
      break;
    case '3m':
      searchStartDate.value = today.subtract(3, 'month').format('YYYY-MM-DD');
      searchEndDate.value = today.format('YYYY-MM-DD');
      selectedRange.value = '3m';
      break;
    case 'all':
      searchStartDate.value = itemStartDate.value;
      searchEndDate.value = today.format('YYYY-MM-DD');
      selectedRange.value = 'all';
      break
  }
}

const fnSearch = (__KEYWORD, __FILTER) => {
  let _req = {
    filter: __FILTER,
    keyword: __KEYWORD,
    startDate: searchStartDate.value,
    endDate: searchEndDate.value,
    //인플루언서의 경우 showYN 추가
    //showYN: "Y"
  };

  useAxios()
    .post("/item/search", _req)
    .then((res) => {
      itemList.value = res.data;
    })
    .catch((error) => {});
};

/************************************************************************
|    WATCH
************************************************************************/

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