<template>
  <div class="bg-white rounded-12 overflow-hidden mb-12">
    <div class="border-box font-size-16 font-500 color-000 line-height-24 p-12">
      使用日期
    </div>
    <div class="flex flex-items-center border-box">
      <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 font-size-12">{{ item.weekDesc }}</div>
              <div class="md font-size-16 font-600">
                {{ formatMD(item.date) }}
              </div>
              <div class="status font-size-12">{{ 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>
