<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
              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 btn-pink bdrs--10"
            ><i class="ico"></i>개별 배송</v-btn
          >
          <v-btn class="custom-btn bdrs--10 btn-white" @click="deliLocated()"
            ><i class="ico"></i>공동구매 배송</v-btn
          >
        </div>
        <div class="right--sections">
          <v-btn class="custom-btn mini btn-reg" v-if="memberType !== 'INFLUENCER'" @click="addLocated()"
            ><i class="ico"></i>제품 등록</v-btn
          >
        </div>
      </div>
      <div class="item--list--wrap">
        <div class="no--data" v-if="itemList.length == 0">
          등록된 제품이 없습니다.
        </div>
        <div class="item--list" v-if="itemList.length > 0">
          <div v-for="(items, index) in paginatedItems" :key="index" class="item">
            <div @click="toItemDetail(items.SEQ)" class="item-content">
              <div class="item--img"><img v-if="items.THUMB_FILE" :src="`https://shopdeli.mycafe24.com/writable/uploads/item/thumb/${items.THUMB_FILE}`"></div>
              <h3>{{ items.NAME }}</h3>
              <p>공급가: {{ Number(items.PRICE1).toLocaleString() }}<br>판매가: {{ Number(items.PRICE1).toLocaleString() }}</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) && items.STATUS != 1 }"
              >
                <span>
                  {{ items.STATUS == 1 ? '품절' : '업데이트' }}
                </span>
              </div>
            </div>
            <div v-if="memberType === 'INFLUENCER'" class="item-actions">
              <v-btn 
                class="custom-btn btn-blue mini delivery-btn"
                :disabled="items.STATUS == 1"
                @click.stop="goToDeliveryDetail(items)"
                :aria-label="`${items.NAME} 송장번호 등록`"
              >
                <i class="ico"></i>송장번호 등록
              </v-btn>
            </div>
          </div>
        </div>
        <div class="item--pagination" v-if="itemList.length > 0">
          <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";
import dayjs from 'dayjs';
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const memberType = useAtStore.auth.memberType;
  const searchModel = ref("");
  const selectedRange = ref('all');
  const itemStartDate = ref("");
  const searchStartDate = ref("");
  const searchEndDate = ref("");
  const dateOptions = [
    { label: '오늘', value: 'today' },
    { label: '7일', value: '7d' },
    { label: '1개월', value: '1m' },
    { label: '3개월', value: '3m' },
    { label: '전체', value: 'all' },
  ]
  const datePickerFormat = "yyyy-MM-dd";
  const filter = ref("");
  const filderArr = ref([
    { title: "전체", value: "" },
    { title: "제품명", value: "name" },
  ]);
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = computed(() => {
    return memberType === 'INFLUENCER' ? '제품 관리 (파트너십)' : '제품 관리 (자사)';
  });
  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 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 addLocated = () => {
    router.push({
      path: "/view/common/item/add",
    });
    useDtStore.boardInfo.pageType = "I";
  };

  const toItemDetail = (__EVENT) => {
    router.push({
      path: "/view/common/item/add",
    });
    useDtStore.boardInfo.seq = __EVENT;
    //제품 등록한 벤더의 경우 U로, 인플루언서의 경우 D로
    memberType == 'INFLUENCER' ? useDtStore.boardInfo.pageType = "D" : useDtStore.boardInfo.pageType = "U";
  };

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

    if (memberType === "INFLUENCER") {
      // 인플루언서의 경우: 파트너십이 체결된 제품만 조회 + 노출된 제품만
      _req.SHOW_YN = "Y";
      _req.MEMBER_TYPE = "INFLUENCER";
      _req.MEMBER_SEQ = useAtStore.auth.seq;
    } else {
      // 벤더사의 경우: 자사 제품만 조회
      _req.MEMBER_TYPE = "VENDOR";
      _req.COMPANY_NUMBER = useAtStore.auth.companyNumber || "1";
      console.log('벤더사 제품 조회 - COMPANY_NUMBER:', _req.COMPANY_NUMBER);
    }

    await useAxios()
      .post("/item/list", _req)
      .then((res) => {
        itemList.value = res.data;
        itemStartDate.value = res.data[res.data.length-1].UDPDATE;
        searchStartDate.value = itemStartDate.value;
        searchEndDate.value = dayjs();
      });
  };

  const fnSearch = (__KEYWORD, __FILTER) => {
    let _req = {
      filter: __FILTER,
      keyword: __KEYWORD,
      startDate: searchStartDate.value,
      endDate: searchEndDate.value,
      showYN: ""
    };
    
    if (memberType === "INFLUENCER") {
      // 인플루언서의 경우: 파트너십이 체결된 제품만 검색 + 노출된 제품만
      _req.showYN = "Y";
      _req.MEMBER_TYPE = "INFLUENCER";
      _req.MEMBER_SEQ = useAtStore.auth.seq;
    } else {
      // 벤더사의 경우: 자사 제품만 검색
      _req.MEMBER_TYPE = "VENDOR";
      _req.COMPANY_NUMBER = useAtStore.auth.companyNumber || "1";
    }

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

  const goToDeliveryDetail = (item) => {
    // 제품 정보를 스토어에 저장
    useDtStore.boardInfo.seq = item.SEQ;
    useDtStore.boardInfo.pageType = "D";
    
    // 배송 관리 페이지로 이동
    router.push({
      path: "/view/common/deli/detail",
      query: {
        itemId: item.SEQ,
        itemName: item.NAME,
        price1: item.PRICE1,
        price2: item.PRICE2 || item.PRICE1,
        thumbFile: item.THUMB_FILE || ''
      }
    });
  };

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

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

<style scoped>
.item {
  position: relative;
}

.item-content {
  cursor: pointer;
  padding-bottom: 50px; /* 버튼 공간 확보 */
}

.item-actions {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 20px);
}

.delivery-btn {
  width: 100%;
  margin-top: 8px;
}

.delivery-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.delivery-btn .ico {
  margin-right: 4px;
}
</style>