<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>{{ pageId }}</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 elevation="0">오늘</v-btn>
            <v-btn class="actv" elevation="0">7일</v-btn>
            <v-btn elevation="0">1개월</v-btn>
            <v-btn elevation="0">3개월</v-btn>
            <v-btn elevation="0">전체</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 class="right--sections">
          <v-btn class="custom-btn mini btn-reg" @click="addLocated()"
            ><i class="ico"></i>제품 등록</v-btn
          >
        </div>
      </div>
      <div class="item--list--wrap" v-if="itemList.length > 0">
        <div class="item--list">
          <div v-for="(items, index) in paginatedItems" :key="index" @click="toItemDetail(items.SEQ)" class="item">
            <div class="item--img"></div>
            <h3>{{ items.NAME }}</h3>
            <p>공급가: {{ items.PRICE1 }}<br>판매가: {{ items.PRICE2 }}</p>
            <span>등록일: {{ items.REGDATE.slice(0, 10) }}</span>
            <span>업데이트 날짜: {{ items.UDPDATE.slice(0, 10) }}</span>
            <div
              v-if="items.STATUS == 1 || isRecentUpdate(items.UDPDATE)"
              class="sold--out"
              :class="{ 'blue--type': isRecentUpdate(items.UDPDATE) }"
            >
              <span>
                {{ isRecentUpdate(items.UDPDATE) ? '업데이트' : '품절' }}
              </span>
            </div>
          </div>
        </div>
        <div class="item--pagination">
          <v-pagination
            v-model="currentPage"
            :length="Math.ceil(itemList.length / itemsPerPage)"
          ></v-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const searchModel = ref("");
  const searchStartDate = ref("");
  const searchEndDate = ref("");
  const filter = ref("");
  const filderArr = ref([
    { title: "선택하세요", value: "" },
    { title: "제목", value: "title" },
  ]);
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = ref("제품 관리");
  const datePickerFormat = "yyyy-MM-dd";
  const itemList = ref([]);
  const itemsPerPage = 5;
  const currentPage = ref(1);

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

  /************************************************************************
|    함수(METHODS)
************************************************************************/

  const isRecentUpdate = (dateStr) => {
    const today = new Date();
    const updateDate = new Date(dateStr);
    const diffDays = (today - updateDate) / (1000 * 60 * 60 * 24);
    // 업데이트 날짜가 오늘 날짜 기준 최근 7일인지 확인
    return diffDays <= 7;
  }

  const paginatedItems = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return itemList.value.slice(start, start + itemsPerPage);
  });

  const addLocated = () => {
    router.push({
      path: "/view/item/add",
    });
  };

  const detailLocated = (__EVENT) => {
    router.push({
      path: "/view/item/detail",
    });
    useDtStore.boardInfo.seq = __EVENT.data.SEQ;
    useDtStore.boardInfo.pageType = "U";
    useDtStore.boardInfo.status = __EVENT.data.STATUS;
  };

  const evtListGet = async () => {
    let _req = {
      // Y : 노출, N : 비노출
      SHOW_YN: "",
    };

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

  const fnSearch = (__KEYWORD, __FILTER) => {
    let _req = {
      compId: useAuthStore().getCompanyId,
      filter: __FILTER,
      keyword: __KEYWORD,
      status: "",
      // _size: 1000,
      // _index: 0,
      // admin_name:
      //   __FILTER == "admin_name" ? __KEYWORD : __FILTER == "" ? __KEYWORD : null,
      // id: __FILTER == "id" ? __KEYWORD : __FILTER == "" ? __KEYWORD : null,
    };

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

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

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

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

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