<template>
  <div class="bg-white rounded-[12px] overflow-hidden mb-[12px]">
    <div class=" text-[16px] font-medium text-black leading-[24px] p-[12px]">
      使用日期
    </div>
    <div class="flex items-center ">
      <scroll-div class="date-scroll" scroll-x>
        <div class="date-list">
          <block v-for="item in openDateRangeList" :key="item.date">
            <div class="date-item" :class="{ selected: isSameDate(selectedDate, item.date) }"
              @click="onDateClick(item)">
              <div class="label text-[12px]">{{ item.weekDesc }}</div>
              <div class="md text-[16px] font-semibold">
                {{ formatMD(item.date) }}
              </div>
              <div class="status text-[12px]">{{ item.canOrder }}</div>
              <div v-if="isSameDate(selectedDate, item.date)" class="check">
                ✔
              </div>
            </div>
          </block>
        </div>
      </scroll-div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
const props = defineProps({
  selectedDate: { type: String, default: null },
  openDateRangeList: { type: Array, default: () => [] },
});
const emit = defineEmits(["update:selectedDate"]);
const selectedDate = ref(props.selectedDate);

watch(
  () => props.selectedDate,
  (v) => {
    selectedDate.value = v;
  },
);

const isSameDate = (a, b) => {
  if (!a || !b) return false;
  return a === b;
};

// 格式化展示日期，将 2026-04-13 转换为 04-13
const formatMD = (dateStr) => {
  if (!dateStr || typeof dateStr !== "string") return "";
  const parts = dateStr.split("-");
  if (parts.length >= 3) {
    return `${parts[1]}-${parts[2]}`;
  }
  return dateStr;
};

const onDateClick = (item) => {
  const date = item.date;
  if (selectedDate.value === date) {
    selectedDate.value = null;
  } else {
    selectedDate.value = date;
  }
  console.log("selectedDate:", selectedDate.value);
  emit("update:selectedDate", selectedDate.value);
};
</script>

<style scoped lang="scss">
@import "./styles/index.scss";
</style>
