<template>
  <div class="w-full flex-1 mb-3">
    <QuickBookingCalender class="w-full" @update:date="onDateSelected" />
    <div v-for="item in commodityGroupDTOList" :key="commodityGroupKey(item.title)">
      <QuickBookingContentList :commodityDTO="item" />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { emitter } from '@/utils/events.ts'
import QuickBookingCalender from "../QuickBookingCalender/index.vue";
import QuickBookingContentList from "../QuickBookingContentList/index.vue";
import { onMounted } from "vue";
import { quickBookingComponent } from "@/api/home";
import { SCROLL_TO_BOTTOM } from "@/constants/constant";

const selectedDate = ref({});

const commodityGroupDTOList = ref([]);
const formattedDate = ref("");

const loadQuickBookingComponent = async () => {
  formattedDate.value = formatDate(selectedDate.value.fullDate || new Date());
  const res = await quickBookingComponent(formattedDate.value);
  if (res.code === 0 && res.data) {
    commodityGroupDTOList.value = res.data.commodityGroupDTOList;
    nextTick(() => {
      setTimeout(() => {
        emitter.emit(SCROLL_TO_BOTTOM, true);
      }, 300);
    });
  }
};

const onDateSelected = (date) => {
  console.log("Selected date:", date);
  selectedDate.value = date;
  loadQuickBookingComponent();
};

// 格式化日期为 yyyy-MM-dd
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const commodityGroupKey = (title) => {
  return `${title}${formattedDate.value}`;
};

onMounted(() => {
  console.log("=============");
  loadQuickBookingComponent();
});
</script>
