<template>
  <view class="time-picker">
    <picker mode="date" :value="selectedDate" @change="onDateChange">
      <view class="picker-item">
        <text>{{ formatDate(selectedDate) }}</text>
      </view>
    </picker>

    <picker style="margin-left: 12px" mode="time" :value="selectedTime" @change="onTimeChange">
      <view class="picker-item">
        <text>{{ formatTime(selectedTime) }}</text>
      </view>
    </picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedDate: this.getCurrentDate(),
      selectedTime: this.getCurrentTime(),
    };
  },
  methods: {
    // 获取当前日期，格式为 yyyy-MM-dd
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 获取当前时间，格式为 HH:mm
    getCurrentTime() {
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      return `${hours}:${minutes}`;
    },
    // 日期改变时的回调
    onDateChange(e) {
      this.selectedDate = e.detail.value;
      this.$emit("update", {
        date: this.selectedDate,
        time: this.selectedTime,
      });
    },
    // 时间改变时的回调
    onTimeChange(e) {
      this.selectedTime = e.detail.value;
      this.$emit("update", {
        date: this.selectedDate,
        time: this.selectedTime,
      });
    },
    // 格式化日期为 `yyyy年MM月dd日`
    formatDate(date) {
      const [year, month, day] = date.split("-");
      return `${year}-${month}-${day}`;
    },
    // 格式化时间为 `HH:mm`
    formatTime(time) {
      const [hours, minutes] = time.split(":");
      return `${hours}:${minutes}`;
    },
  },
};
</script>

<style scoped>
.time-picker {
  /* padding: 20px; */
  display: flex;
  align-items: center;
}

.picker-item {
  /* margin-top: 10px; */
  font-size: 16px;
  color: #333;
}
</style>
