<template>
  <div class="time-select-container">
    <div class="time-select-header">
      <div class="time-select-title">请选择参观日期</div>
      <div class="month-selector">
        <div class="arrow prev" @click="prevMonth">&lt;</div>
        <div class="current-month">{{ currentYearMonth }}</div>
        <div class="arrow next" @click="nextMonth">&gt;</div>
      </div>
    </div>
    
    <div class="calendar">
      <!-- 星期标题 -->
      <div class="weekdays">
        <div class="weekday" v-for="(day, index) in weekdays" :key="index">{{ day }}</div>
      </div>
      
      <!-- 日期网格 -->
      <div class="days-grid">
        <div 
          v-for="(day, index) in daysInMonth" 
          :key="index"
          class="day-cell"
          :class="getDayClass(day)"
          @click="selectDay(day)"
          v-show="day.isCurrentMonth"
        >
          <div class="day-number">{{ day.date }}</div>
          <div class="day-status">{{ getDayStatusText(day) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 定义星期几的文本
const weekdays = ['一', '二', '三', '四', '五', '六', '日']

// 当前选择的年月
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1) // JavaScript 月份从 0 开始

// 当前选择的日期
const selectedDate = ref(null)

// 当前日期
const today = new Date()
today.setHours(0, 0, 0, 0)

// 计算开放日期范围（从今天开始的七天）
const openDates = computed(() => {
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  
  // 开始日期是今天
  const start = new Date(now)
  
  // 结束日期是今天+6天（总共7天）
  const end = new Date(now)
  end.setDate(now.getDate() + 6)
  end.setHours(23, 59, 59, 999)
  
  return { start, end }
})

// 格式化当前年月显示
const currentYearMonth = computed(() => {
  return `${currentYear.value}-${currentMonth.value.toString().padStart(2, '0')}`
})

// 计算当月的所有日期
const daysInMonth = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value - 1 // JavaScript 月份从 0 开始
  
  // 获取当月第一天是星期几
  const firstDay = new Date(year, month, 1).getDay() || 7 // 将周日的 0 转换为 7
  
  // 获取当月的总天数
  const totalDays = new Date(year, month + 1, 0).getDate()
  
  // 生成日期数组
  const days = []
  
  // 添加上个月的日期填充第一行
  const prevMonthDays = new Date(year, month, 0).getDate()
  for (let i = 1; i < firstDay; i++) {
    const date = new Date(year, month - 1, prevMonthDays - firstDay + i + 1)
    days.push({
      date: prevMonthDays - firstDay + i + 1,
      fullDate: date,
      isCurrentMonth: false,
      isPast: date < today,
      isToday: false,
      isInOpenRange: isDateInOpenRange(date),
      status: '已结束' // 上个月的日期都已结束
    })
  }
  
  // 添加当月的日期
  for (let i = 1; i <= totalDays; i++) {
    const date = new Date(year, month, i)
    const isToday = date.getDate() === today.getDate() && 
                    date.getMonth() === today.getMonth() && 
                    date.getFullYear() === today.getFullYear()
    
    const isPast = date < today
    const isInOpenRange = isDateInOpenRange(date)
    
    // 判断是否是周一
    const isMonday = date.getDay() === 0
    
    let status = ''
    if (isPast) {
      status = '已结束'
    } else if (isToday) {
      // 如果今天是周一，则不开放
      if (isMonday) {
        status = '未开放'
      } else {
        status = '今天'
      }
    } else if (isInOpenRange) {
      // 开放日期范围内，周一固定不开放，其他日期开放
      if (isMonday) {
        status = '未开放'
      } else {
        // 随机设置一些日期为已约满，这里用日期作为随机种子
        status = (i % 5 === 0) ? '已约满' : '已开放'
      }
    } else {
      status = '未开放'
    }
    
    days.push({
      date: i,
      fullDate: date,
      isCurrentMonth: true,
      isPast,
      isToday,
      isInOpenRange,
      isMonday,
      status
    })
  }
  
  // 添加下个月的日期填充最后一行
  const remainingCells = 42 - days.length // 6行7列 = 42个单元格
  for (let i = 1; i <= remainingCells; i++) {
    const date = new Date(year, month + 1, i)
    days.push({
      date: i,
      fullDate: date,
      isCurrentMonth: false,
      isPast: false,
      isToday: false,
      isInOpenRange: isDateInOpenRange(date),
      status: '未开放' // 下个月的日期都未开放
    })
  }
  
  return days
})

// 判断日期是否在开放日期范围内
function isDateInOpenRange(date) {
  return date >= openDates.value.start && date <= openDates.value.end
}

// 获取日期单元格的 CSS 类
function getDayClass(day) {
  const isSelected = selectedDate.value && 
                    day.fullDate.getDate() === selectedDate.value.getDate() && 
                    day.fullDate.getMonth() === selectedDate.value.getMonth() && 
                    day.fullDate.getFullYear() === selectedDate.value.getFullYear()
  
  return {
    'other-month': !day.isCurrentMonth,
    'today': day.isToday && day.status !== '未开放',
    'past': day.isPast,
    'selectable': day.isInOpenRange && !day.isPast && day.status !== '已约满' && day.status !== '未开放',
    'selected': isSelected && day.status !== '未开放',
    'available': day.status === '已开放' || day.status === '今天',
    'unavailable': day.status === '未开放',
    'full': day.status === '已约满'
  }
}

// 获取日期状态文本
function getDayStatusText(day) {
  return day.status
}

// 选择日期
function selectDay(day) {
  // 只有开放日期范围内且未过期且未约满且不是未开放的日期才可选择
  if (day.isInOpenRange && !day.isPast && day.status !== '已约满' && day.status !== '未开放') {
    selectedDate.value = day.fullDate
    // 这里可以添加选择日期后的回调函数
    console.log('选择的日期:', day.fullDate)
  }
}

// 上个月
function prevMonth() {
  if (currentMonth.value === 1) {
    currentYear.value--
    currentMonth.value = 12
  } else {
    currentMonth.value--
  }
}

// 下个月
function nextMonth() {
  if (currentMonth.value === 12) {
    currentYear.value++
    currentMonth.value = 1
  } else {
    currentMonth.value++
  }
}

onMounted(() => {
  // 初始化时默认选中今天（如果今天可选）
  const todayDate = new Date()
  const isMonday = todayDate.getDay() === 1
  const isPast = todayDate < today
  
  // 如果今天不是周一且不是过去的日期，则默认选中今天
  if (!isMonday && !isPast) {
    selectedDate.value = todayDate
  }
})
</script>

<style lang="scss" scoped>
.time-select-container {
  width: 100%;
  max-width: 100%;
  border-radius: 8px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  overflow-x: hidden;
}

.time-select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.time-select-title {
  font-size: 16px;
  color: #584735;
  font-weight: bold;
}

.month-selector {
  display: flex;
  align-items: center;
  color: #94765A;
}

.current-month {
  margin: 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.arrow {
  cursor: pointer;
  font-size: 18px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8B5D3B;
  
  &:hover {
    opacity: 0.8;
  }
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 10px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.weekday {
  font-size: clamp(14px, 3vw, 14px);
  color: #584735;
  font-weight: bold;
  padding: 5px 2px;
  text-align: center;
  min-width: 0;
  box-sizing: border-box;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.day-cell {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: default;
  position: relative;
  padding: 3px 1px;
  min-width: 0;
  box-sizing: border-box;
  overflow: hidden;

  .day-number {
    font-size: clamp(12px, 3vw, 14px);
    font-weight: 500;
    margin-bottom: 1px;
    color: #584735;
    text-align: center;
    line-height: 1.2;
  }

  .day-status {
    font-size: clamp(12px, 2.5vw, 12px);
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
    line-height: 1.2;
    padding: 0 1px;
  }
  &.other-month {
    color: #ccc;
    display: none; /* 不显示非当前月的日期 */
  }
  
  &.past {
    color: #999;
  }
  
  &.selectable {
    cursor: pointer;
    // &:hover {
    //   background-color: rgba(177, 150, 123, 0.1);
    // }
  }
  &.available {
    .data-number, .day-status {
      color: #8B5D3B;
    }
  }
  
  &.unavailable {
    .day-status {
      color: rgba(88, 71, 53, 0.5);
    }
  }
  
  &.full {
    .day-status {
      color: #B1967B;
    }
  }
  &.selected {
    background-color: #B1967B;
    color: #fff;
    .day-status {
      color: #fff;
    }
  }
}
</style>