<template>
  <view class="date-picker">
    <view class="date-list">
      <view
        v-for="(item, index) in dates"
        :key="index"
        class="date-item"
        :class="{ active: index === activeIndex }"
        @click="selectDate(index)"
      >
        <text class="label">{{ item.label }}</text>
        <text class="date">{{ item.date }}</text>
      </view>

      <!-- 日历按钮 -->
      <view class="calendar-btn btn-bom" @click="openCalendar">
        <image
          src="https://oss.nianxx.cn/mp/static/booking_calendar.png"
          mode="widthFix"
          class="calendar-img"
        />
        <text class="calendar-text">日历</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
const emit = defineEmits(["update:date"]); // 声明事件

const activeIndex = ref(2); // 默认今天
const dates = ref([]);

// 初始化日期（前天、昨天、今天、明天、后天）
const initDates = () => {
  const today = new Date();
  const labels = ["前天", "昨天", "今天", "明天", "后天"];
  for (let i = -2; i <= 2; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    const month = d.getMonth() + 1;
    const day = d.getDate();
    dates.value.push({
      label: labels[i + 2],
      date: `${month}/${day}`,
      fullDate: `${d.getFullYear()}-${String(month).padStart(2, "0")}-${String(
        day
      ).padStart(2, "0")}`,
    });
  }
};

const selectDate = (index) => {
  activeIndex.value = index;
  emit("update:date", dates.value[index]); // 传回父组件
};

const openCalendar = () => {
  uni.$emit("openCalendar");

  uni.$on("selectCalendarDate", (date) => {
    emit("update:date", { fullDate: date });
    uni.$off("selectCalendarDate");
  });
};

onMounted(() => {
  initDates();
});
</script>

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