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

    <div class="data--list--wrap">
      <!-- <div class="btn--actions--wrap">
        <div class="left--sections">
          <v-btn class="custom-btn bdrs--10" :class="itemType == 'E' ? 'btn-pink' : 'btn-white'" @click="itemType = 'E'"
            ><i class="ico"></i>개별 배송</v-btn
          >
          <v-btn class="custom-btn bdrs--10" :class="itemType == 'E' ? 'btn-white' : 'btn-pink'" @click="itemType = 'G'"
            ><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="cs--list--wrap">
          <div class="cs--header" v-if="memberType !== 'INFLUENCER'">
            <h3>공동구매 등록</h3>
            <v-btn class="custom-btn" @click="addLocated()">신규 등록</v-btn>
          </div>
          <div class="cs--header">
            <h3>나의 공동구매</h3>
          </div>
          
          <!-- 검색 영역 -->
          <div class="cs--search-area">
            <div class="search-controls">
              <div class="search-filter">
                <v-select
                  v-model="filter"
                  :items="filderArr"
                  variant="outlined"
                  density="compact"
                  hide-details
                ></v-select>
              </div>
              <div class="search-input">
                <v-text-field
                  v-model="searchModel"
                  placeholder="검색어를 입력하세요"
                  variant="outlined"
                  density="compact"
                  hide-details
                  prepend-inner-icon="mdi-magnify"
                  @keyup.enter="fnSearch(searchModel, filter)"
                ></v-text-field>
              </div>
              <div class="search-actions">
                <v-btn
                  class="custom-btn mini btn--pp"
                  color="primary"
                  @click="fnSearch(searchModel, filter)"
                >
                  검색
                </v-btn>
                <v-btn
                  class="custom-btn mini btn-white"
                  color="secondary"
                  variant="outlined"
                  @click="resetSearch"
                >
                  초기화
                </v-btn>
              </div>
            </div>
          </div>
          <div class="cs--list" v-if="itemList.length > 0">
            <div v-for="(items, index) in paginatedItems" :key="index" class="">
              <!-- <div v-if="itemType == 'E'" @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.PRICE2).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="itemType == 'G'" @click="toItemDetail(items.SEQ)" class="list">
                <span class="list--seq">{{ items.SEQ }}</span>
                <span class="list--writer">{{ items.COMPANY_NAME }}</span>
                <h3 class="list--title">{{ items.NAME }}</h3>
                <div class="list--circle list--ml" :class="[ items.STATUS == 0 ? 'status--on' : 'status--off' ]">
                  {{ items.STATUS == 0 ? '진행중' : '마감' }}
                </div>
                <span class="list--date">{{ items.ORDER_START_DATE.slice(0, 10) }} ~ {{ items.ORDER_END_DATE.slice(0, 10) }}</span>
              </div>
            </div>
          </div>
          <div class="cs--list" v-else>
            <div class="no-data">
              <h4>등록된 제품이 없습니다</h4>
            </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 "@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 itemType = ref("G");
  const memberType = useAtStore.auth.memberType;
  const searchModel = ref("");
  const selectedRange = ref('all');
  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" },
    { title: "회사명", value: "company" },
  ]);
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = computed(() => {
    return '공동구매';
    //return memberType === 'INFLUENCER' ? '제품 관리 (파트너십)' : '제품 관리 (자사)';
  });
  const itemList = ref([]);
  const allItemList = ref([]); // 전체 데이터 저장용
  const itemsPerPage = 10;
  const currentPage = ref(1);

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

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

  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 = "";
        searchEndDate.value = today.format('YYYY-MM-DD');
        selectedRange.value = 'all';
        break
    }
  }

  const addLocated = () => {
    router.push({
      path: "/view/common/item/add",
    });
    useDtStore.boardInfo.pageType = "I";
    useDtStore.boardInfo.itemType = itemType.value;
  };

  const toItemDetail = (__EVENT) => {
    router.push({
      path: "/view/common/item/detail",
    });
    useDtStore.boardInfo.seq = __EVENT;
    useDtStore.boardInfo.itemType = itemType;
    useDtStore.boardInfo.pageType = "D";
  };

  const itemListGet = async () => {
    let _req = {
      // Y : 노출, N : 비노출
      SHOW_YN: "Y",
      TYPE: itemType.value,
      INF_SEQ: useAtStore.auth.seq,
      MEMBER_TYPE: memberType,
      MEMBER_SEQ: useAtStore.auth.seq,
      STATUS: 0,
    };

    if(memberType !== "INFLUENCER"){
      _req.COMPANY_NUMBER = useAtStore.auth.companyNumber || "1";
    }

    
    await useAxios()
    .post("/item/list", _req)
    .then((res) => {
        allItemList.value = res.data; // 전체 데이터 저장
        itemList.value = res.data; // 초기 표시용
      });
  };

  const fnSearch = (__KEYWORD, __FILTER) => {
    let filteredItems = [...allItemList.value];
    
    // 키워드 검색
    if (__KEYWORD && __KEYWORD.trim() !== '') {
      const keyword = __KEYWORD.toLowerCase();
      filteredItems = filteredItems.filter(item => {
        if (__FILTER === 'name') {
          return item.NAME && item.NAME.toLowerCase().includes(keyword);
        } else if (__FILTER === 'company') {
          return item.COMPANY_NAME && item.COMPANY_NAME.toLowerCase().includes(keyword);
        } else {
          // 전체 검색 (이름 또는 회사명)
          return (item.NAME && item.NAME.toLowerCase().includes(keyword)) ||
                 (item.COMPANY_NAME && item.COMPANY_NAME.toLowerCase().includes(keyword));
        }
      });
    }
    
    // 날짜 필터링 (마감일 기준)
    // if (searchStartDate.value && searchEndDate.value) {
    //   const startDate = dayjs(searchStartDate.value).format('YYYY-MM-DD');
    //   const endDate = dayjs(searchEndDate.value).format('YYYY-MM-DD');
    //   filteredItems = filteredItems.filter(item => {
    //     const orderEndDate = dayjs(item.ORDER_END_DATE).format('YYYY-MM-DD');
    //     return orderEndDate >= startDate && orderEndDate <= endDate;
    //   });
    // }
    
    itemList.value = filteredItems;
    currentPage.value = 1; // 검색 시 첫 페이지로 이동
  };

  // 검색 초기화
  const resetSearch = () => {
    searchModel.value = '';
    searchStartDate.value = null;
    searchEndDate.value = null;
    selectedRange.value = '';
    itemList.value = [...allItemList.value];
    currentPage.value = 1;
  };


  const goToDeliveryDetail = (item) => {
    // 제품 정보를 스토어에 저장
    useDtStore.boardInfo.seq = item.SEQ;
    useDtStore.boardInfo.pageType = "D";
    useDtStore.boardInfo.itemType = itemType.value;
    
    // 배송 관리 페이지로 이동
    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
************************************************************************/

  watch(itemType, () => {
    itemListGet();
  });

  
  onMounted(() => {
    itemType.value = 'G'
    itemListGet();

    // 날짜 초기화
    const today = dayjs();
    searchEndDate.value = today.format('YYYY-MM-DD');
  });
</script>