<template>
  <view class="date-selector-card">
    <view class="selector-header">
      <text class="selector-label">历史数据日期</text>
      <text v-if="selectedDate" class="clear-btn" @click="clearDate">清除</text>
    </view>

    <view class="date-input" @click="openDatePicker">
      <text class="date-text">{{ selectedDate ? formatDateDisplay(selectedDate) : '最新数据' }}</text>
      <text class="date-icon">📅</text>
    </view>

    <!-- 自定义日期选择弹窗 -->
    <view v-if="showDatePicker" class="date-picker-mask" @tap="closeDatePicker" @touchmove.stop.prevent>
      <view class="date-picker-popup" @tap.stop @touchmove.stop>
        <view class="picker-header">
          <text class="picker-cancel" @tap="closeDatePicker">取消</text>
          <text class="picker-title">选择日期</text>
          <text class="picker-confirm" @tap="confirmDate">确定</text>
        </view>

        <!-- 年月选择 -->
        <view class="month-selector">
          <view class="month-nav" @tap="prevMonth">
            <text class="nav-arrow">‹</text>
          </view>
          <text class="current-month">{{ tempYear }}年{{ tempMonth }}月</text>
          <view class="month-nav" @tap="nextMonth">
            <text class="nav-arrow">›</text>
          </view>
        </view>

        <!-- 星期标题 -->
        <view class="weekday-row">
          <text class="weekday-item" v-for="day in weekDays" :key="day">{{ day }}</text>
        </view>

        <!-- 日期网格 -->
        <view class="days-grid">
          <view
            v-for="(day, index) in calendarDays"
            :key="index"
            :class="['day-item', {
              'empty': !day,
              'selected': day && isSelected(day),
              'today': day && isToday(day)
            }]"
            @tap="selectDayHandler(day)"
          >
            <text v-if="day" class="day-text">{{ day }}</text>
          </view>
        </view>

        <!-- 底部安全区域占位 -->
        <view class="safe-area-placeholder"></view>
      </view>
    </view>
  </view>
</template>

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

const emit = defineEmits(['dateChange'])

const selectedDate = ref('')
const showDatePicker = ref(false)
const tempYear = ref(0)
const tempMonth = ref(0)
const tempDay = ref(0)

const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 获取今天的日期
const getTodayDate = () => {
  const now = new Date()
  return {
    year: now.getFullYear(),
    month: now.getMonth() + 1,
    day: now.getDate()
  }
}

// 格式化日期显示
const formatDateDisplay = (dateStr) => {
  if (!dateStr) return '最新数据'
  const [year, month, day] = dateStr.split('-')
  return `${year}年${month}月${day}日`
}

// 打开日期选择器
const openDatePicker = () => {
  const today = getTodayDate()
  if (selectedDate.value) {
    const [year, month, day] = selectedDate.value.split('-')
    tempYear.value = parseInt(year)
    tempMonth.value = parseInt(month)
    tempDay.value = parseInt(day)
  } else {
    tempYear.value = today.year
    tempMonth.value = today.month
    tempDay.value = 0
  }
  showDatePicker.value = true

  // 锁定页面滚动
  // #ifdef H5
  document.body.style.overflow = 'hidden'
  document.body.style.position = 'fixed'
  document.body.style.width = '100%'
  // #endif
}

// 关闭日期选择器
const closeDatePicker = () => {
  showDatePicker.value = false

  // 恢复页面滚动
  // #ifdef H5
  document.body.style.overflow = ''
  document.body.style.position = ''
  document.body.style.width = ''
  // #endif
}

// 上一个月
const prevMonth = () => {
  if (tempMonth.value === 1) {
    tempYear.value--
    tempMonth.value = 12
  } else {
    tempMonth.value--
  }
}

// 下一个月
const nextMonth = () => {
  const today = getTodayDate()
  if (tempYear.value === today.year && tempMonth.value === today.month) {
    return
  }
  if (tempMonth.value === 12) {
    tempYear.value++
    tempMonth.value = 1
  } else {
    tempMonth.value++
  }
}

// 生成日历天数
const calendarDays = computed(() => {
  const firstDay = new Date(tempYear.value, tempMonth.value - 1, 1).getDay()
  const daysInMonth = new Date(tempYear.value, tempMonth.value, 0).getDate()
  const days = []

  for (let i = 0; i < firstDay; i++) {
    days.push(null)
  }

  for (let i = 1; i <= daysInMonth; i++) {
    days.push(i)
  }

  return days
})

// 判断是否选中（临时选择状态）
const isSelected = (day) => {
  return day === tempDay.value
}

// 判断是否今天
const isToday = (day) => {
  const today = getTodayDate()
  return day === today.day &&
         tempYear.value === today.year &&
         tempMonth.value === today.month
}

// 选择日期
const selectDay = (day) => {
  tempDay.value = day
}

// 日期选择处理函数（用于模板）
const selectDayHandler = (day) => {
  if (!day) return
  tempDay.value = day
  console.log('选择日期:', day)
}

// 确认日期
const confirmDate = () => {
  if (!tempDay.value) {
    uni.showToast({ title: '请选择日期', icon: 'none' })
    return
  }

  const dateStr = `${tempYear.value}-${String(tempMonth.value).padStart(2, '0')}-${String(tempDay.value).padStart(2, '0')}`
  selectedDate.value = dateStr
  showDatePicker.value = false

  // 恢复页面滚动
  // #ifdef H5
  document.body.style.overflow = ''
  document.body.style.position = ''
  document.body.style.width = ''
  // #endif

  emit('dateChange', dateStr)
}

// 清除日期
const clearDate = () => {
  selectedDate.value = ''
  emit('dateChange', '')
}
</script>

<style scoped>
.date-selector-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(37, 52, 94, 0.04);
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.selector-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #222222;
}

.clear-btn {
  font-size: 24rpx;
  color: #ef4444;
  padding: 8rpx 16rpx;
  background: rgba(239, 68, 68, 0.1);
  border-radius: 8rpx;
}

.date-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 24rpx;
  background: #f7f8fc;
  border-radius: 12rpx;
  border: 2rpx solid #e5e7eb;
}

.date-text {
  font-size: 28rpx;
  color: #222222;
}

.date-icon {
  font-size: 32rpx;
}

/* 日期选择器弹窗 */
.date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 99999 !important;
  box-sizing: border-box;
  /* 阻止触摸事件穿透 */
  overflow: hidden;
  touch-action: none;
}

.date-picker-popup {
  width: 100%;
  max-width: 600rpx;
  background: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  padding-bottom: calc(32rpx + 120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(32rpx + 120rpx + env(safe-area-inset-bottom));
  overflow-y: auto;
  box-sizing: border-box;
  position: relative;
  z-index: 100000 !important;
  /* 限制最大高度，确保不会太高 */
  max-height: 65vh;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  /* 允许弹窗内部滚动 */
  -webkit-overflow-scrolling: touch;
  touch-action: pan-y;
}

.date-picker-popup::-webkit-scrollbar {
  display: none; /* Chrome/Safari/Opera */
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.picker-cancel, .picker-confirm {
  font-size: 28rpx;
  color: #5d55e8;
  padding: 8rpx 16rpx;
}

.picker-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
}

.month-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 16rpx 0;
}

.month-nav {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f8fc;
  border-radius: 50%;
}

.nav-arrow {
  font-size: 48rpx;
  color: #5d55e8;
  font-weight: bold;
}

.current-month {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
}

.weekday-row {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.weekday-item {
  text-align: center;
  font-size: 24rpx;
  color: #9ca3af;
  padding: 12rpx 0;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
  /* 确保网格底部有足够的内边距，让最后一行日期完全可见 */
  padding-bottom: 80rpx;
}

.day-item {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  cursor: pointer;
  transition: background-color 0.2s;
}

.day-item:active {
  background: #f0f0f0;
}

.day-item.empty {
  visibility: hidden;
  pointer-events: none;
}

.day-text {
  font-size: 28rpx;
  color: #222222;
}

.day-item.selected {
  background: #5d55e8;
}

.day-item.selected .day-text {
  color: #ffffff;
  font-weight: 600;
}

.day-item.today .day-text {
  color: #5d55e8;
  font-weight: 600;
}

.day-item.today.selected .day-text {
  color: #ffffff;
}

/* 底部安全区域占位 */
.safe-area-placeholder {
  /* 移除占位元素，改用 padding-bottom 处理 */
  height: 0;
}
</style>
