<template>
  <!-- <view style="width: 100%; height: 100%"> -->
  <!-- 日期选择器 -->
  <wd-popup
    v-model="props.datePickerVisible"
    custom-style="border-radius: 32rpx 32rpx 0 0;"
    position="bottom"
    @close="handleClose"
  >
    <view style="padding: 30rpx">
      <view class="date-picker-title">
        <view class="date-picker-title-left">
          <wd-icon name="caret-left-small" size="22px" @click="previousMonth"></wd-icon>
          <text
            @click="isdatepickertitletext = 0"
            class="date-picker-title-text"
            :class="{ active: isdatepickertitletext === 0 }"
          >
            {{ selectedDate.getFullYear() }}年{{
              selectedDate.getMonth() + 1
            }}月{{ selectedDate.getDate() }}日
          </text>
          <text
            v-if="props.detailedtime ? props.detailedtime : false"
            @click="isdatepickertitletext = 1"
            class="date-picker-title-text"
            :class="{ active: isdatepickertitletext === 1 }"
            >{{
              selectedHour.toString().padStart(2, '0') +
              ':' +
              selectedMinute.toString().padStart(2, '0')
            }}</text>
            <wd-icon name="caret-right-small" size="22px" @click="nextMonth"></wd-icon>
        </view>
        <text class="date-picker-title-right" @click="confirmDate">确定</text>
      </view>
      <view v-if="isdatepickertitletext === 0">
        <!-- 星期标题 -->
        <view class="weekdays">
          <view v-for="name in weekdayNames" :key="name" class="weekday">{{
            name
          }}</view>
        </view>
        <!-- 日期网格 -->
        <view class="calendar-grid">
          <view
            v-for="day in calendarDays"
            :key="day.date.getTime()"
            :class="[
              'day-cell',
              {
                'other-month': day.isOtherMonth,
                today: day.isToday && !day.isOtherMonth,
                selected: day.isSelected,
              },
            ]"
            @click="selectDate(day)"
          >
            <view class="day">{{ day.day }}</view>
          </view>
        </view>
      </view>
      <view v-else-if="isdatepickertitletext === 1" class="time-picker">
        <!-- 小时选择 -->
        <view class="time-column">
          <view
            v-for="hour in hours"
            :key="hour"
            :class="[
              'time-item',
              { 'time-item-selected': hour === selectedHour },
            ]"
            @click="selectHourFn(hour)"
          >
            {{ hour.toString().padStart(2, '0') }}
          </view>
        </view>
        <!-- 分隔符 -->
        <view class="time-separator">:</view>
        <!-- 分钟选择 -->
        <view class="time-column">
          <view
            v-for="minute in minutes"
            :key="minute"
            :class="[
              'time-item',
              { 'time-item-selected': minute === selectedMinute },
            ]"
            @click="selectMinuteFn(minute)"
          >
            {{ minute.toString().padStart(2, '0') }}
          </view>
        </view>
      </view>
    </view>
  </wd-popup>
  <!-- </view> -->
</template>
<script setup lang="ts">
import { ref, defineProps, defineEmits, computed, watch } from 'vue'
const emit = defineEmits(['update:datePickerVisible', 'confirmDate'])
const props = defineProps({
  // 日历弹窗显示
  datePickerVisible: {
    type: Boolean,
    default: false,
  },
  // 是否显示详细时间
  detailedtime: {
    type: Boolean,
    default: false,
  },
  // 初始日期
  date: {
    type: Date,
    default: null,
  },
})
const handleClose = () => {
  emit('update:datePickerVisible', false)
}
const isdatepickertitletext = ref(0)
const currentMonth = ref(new Date())
// 优先使用props传入的日期，如果没有则使用当前时间
const selectedDate = ref(props.date || new Date())
const formatdate = ref('')
const timedate = ref('')

// 时间选择相关数据
const selectedHour = ref(selectedDate.value.getHours())
const selectedMinute = ref(selectedDate.value.getMinutes())

// 生成小时和分钟列表
const hours = Array.from({ length: 24 }, (_, i) => i)
const minutes = Array.from({ length: 60 }, (_, i) => i)

// 监听selectedDate的变化，同步更新小时和分钟
watch(
  selectedDate,
  (newDate) => {
    selectedHour.value = newDate.getHours()
    selectedMinute.value = newDate.getMinutes()
  },
  { immediate: true }
)

// 星期名称
const weekdayNames = ['一', '二', '三', '四', '五', '六', '日']

// 生成月历数据
interface CalendarDay {
  day: number
  date: Date
  isOtherMonth: boolean
  isToday: boolean
  isSelected: boolean
}

const generateCalendarDays = () => {
  const days: CalendarDay[] = []
  const year = currentMonth.value.getFullYear()
  const month = currentMonth.value.getMonth()
  const today = new Date()

  // 当月第一天
  const firstDay = new Date(year, month, 1)
  // 第一周的开始（周一）
  const startDate = new Date(firstDay)
  const dayOfWeek = firstDay.getDay() || 7 // 将周日(0)转为7
  startDate.setDate(startDate.getDate() - dayOfWeek + 1)

  // 生成6周数据
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)

    const isToday = date.toDateString() === today.toDateString()
    const isOtherMonth = date.getMonth() !== month
    const isSelected = date.toDateString() === selectedDate.value.toDateString()

    days.push({
      day: date.getDate(),
      date: date,
      isOtherMonth: isOtherMonth,
      isToday: isToday,
      isSelected: isSelected,
    })
  }

  return days
}
const calendarDays = computed(() => generateCalendarDays())
function confirmDate() {
  // 确保selectedDate包含当前选择的小时和分钟
  selectedDate.value.setHours(selectedHour.value)
  selectedDate.value.setMinutes(selectedMinute.value)

  // 格式化日期时间为 YYYY-MM-DD HH:MM 格式
  const year = selectedDate.value.getFullYear()
  const month = String(selectedDate.value.getMonth() + 1).padStart(2, '0')
  const day = String(selectedDate.value.getDate()).padStart(2, '0')
  const hour = String(selectedHour.value).padStart(2, '0')
  const minute = String(selectedMinute.value).padStart(2, '0')
  formatdate.value = `${year}-${month}-${day}`
  timedate.value = `${hour}:${minute}`
  if (props.detailedtime) {
    emit('confirmDate', `${formatdate.value} ${timedate.value}`)
  } else {
    emit('confirmDate', formatdate.value)
  }
  handleClose()
}

function selectDate(day: CalendarDay | Date) {
  // 检查参数类型，如果是Date对象直接使用，如果是CalendarDay对象则使用其date属性
  if (day instanceof Date) {
    selectedDate.value = new Date(day)
  } else {
    selectedDate.value = new Date(day.date)
  }
}

// 选择小时
function selectHourFn(hour: number) {
  selectedHour.value = hour
  selectedDate.value.setHours(hour)
}

// 选择分钟
function selectMinuteFn(minute: number) {
  selectedMinute.value = minute
  selectedDate.value.setMinutes(minute)
}

function previousMonth() {
  currentMonth.value = new Date(
    currentMonth.value.getFullYear(),
    currentMonth.value.getMonth() - 1,
    1
  )
  selectDate(currentMonth.value)
}

function nextMonth() {
  currentMonth.value = new Date(
    currentMonth.value.getFullYear(),
    currentMonth.value.getMonth() + 1,
    1
  )
  selectDate(currentMonth.value)
}
</script>
<style lang="scss" scoped>
// .month-navigator {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   margin-bottom: 20rpx;
//   padding: 0 10rpx;
// }
.date-picker-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  width: 100%;
  // border: 1px solid red;
  .date-picker-title-left {
    // border: 1px solid red;
    flex: 1;
    // width: 40%;
    display: flex;
    gap: 14rpx;
    .date-picker-title-text {
      font-size: 30rpx;
      color: #4e5969;
      font-weight: 500;
      text-align: left;
    }
    .active {
      color: #31373d;
      font-weight: 600;
    }
  }
  .date-picker-title-right {
    font-size: 30rpx;
    color: #1989fa;
    font-weight: 500;
  }
}
.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.weekday {
  font-size: 26rpx;
  color: #606266;
  padding: 10rpx 0;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
  padding: 0 10rpx;
}

.day-cell {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  border-radius: 50%;
  margin: 0 auto;
}

.day-cell .day {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20rpx;
  font-size: 28rpx;
}

.day-cell.other-month .day {
  color: #c0c4cc !important;
  opacity: 0.5;
}

.day-cell.today .day {
  // border: 1px solid #1989fa !important;
  // color: #1989fa !important;
  background-color: #215acd !important;
  color: #fff !important;
}

.day-cell.selected .day {
  // background-color: #1989fa !important;
  // color: #fff !important;
  color: #215acd !important;
}

/* 确保样式能够正确应用 */
:deep(.day-cell) {
  &.other-month .day {
    color: #c0c4cc !important;
    opacity: 0.5;
  }
  &.today .day {
    // border: 1px solid #215ACD !important;
    background-color: #215acd !important;
    color: #fff !important;
  }
  &.selected .day {
    // background-color: #215ACD !important;
    // color: #215ACD !important;
  }
}

/* 时间选择器样式 */
.time-picker {
  height: 604rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  // height: 360rpx;
  gap: 20rpx;
}

.time-column {
  width: 120rpx;
  height: 100%;
  overflow-y: auto;
  scrollbar-width: none; /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE/Edge */
}

.time-column::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}

.time-item {
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  color: #86909c;
  transition: all 0.2s;
}

.time-item-selected {
  font-size: 32rpx;
  font-weight: 600;
  color: #31373d;
}

.time-separator {
  font-size: 40rpx;
  font-weight: 600;
  color: #31373d;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
