<template>
  <div class="bg-white rounded-[12px] overflow-hidden mb-[12px]">
    <div class=" text-[16px] font-medium text-black leading-[24px] p-[12px]">
      {{ t("common.dateRange.useDate") }}
    </div>
    <div class="flex items-center">
      <div class="w-full" overflow-x-auto>
        <div class="flex pt-2 px-3 pb-3">
          <div v-for="item in openDateRangeList" :key="item.date">
            <div
              class="relative flex flex-col items-center justify-center w-[76px] min-w-[76px] h-[86px] bg-white rounded-[10px] [box-shadow:0_0_0_1px_rgba(0,0,0,0.04)] mr-3 px-[10px] py-2 overflow-hidden"
              :class="{ 'border border-[#0ccd58] bg-[#f0f8f3]': isSameDate(selectedDate, item.date) }"
              @click="onDateClick(item)">
              <div
                :class="['mb-[6px] text-[12px]', isSameDate(selectedDate, item.date) ? 'text-[#0ccd58]' : 'text-[#999]']">
                {{ item.weekDesc }}</div>
              <div
                :class="['mb-[6px] text-[16px] font-semibold', isSameDate(selectedDate, item.date) ? 'text-[#0ccd58]' : 'text-black']">
                {{ formatMD(item.date) }}
              </div>
              <div class="text-[#999] text-[12px]">{{ item.canOrder }}</div>
              <div v-if="isSameDate(selectedDate, item.date)"
                class="absolute right-0 bottom-0 text-[11px] text-white w-[18px] h-[18px] rounded-tl-[10px] rounded-br-[8px] flex items-center justify-center">
                ✔
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
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>
