<template>
  <view v-if="visible" class="popup-mask" @tap="close">
    <view class="picker-panel" @tap.stop>
      <view class="picker-header">
        <text class="picker-cancel" @tap="close">取消</text>
        <text class="picker-title">选择入住日期</text>
        <text class="picker-confirm" @tap="confirmDates">确定</text>
      </view>

      <!-- 月份切换 -->
      <view class="month-nav">
        <text class="nav-btn" @tap="prevMonth">‹</text>
        <text class="month-title">{{ currentMonthLabel }}</text>
        <text class="nav-btn" @tap="nextMonth">›</text>
      </view>

      <!-- 星期标题 -->
      <view class="week-header">
        <text class="week-item" v-for="w in weekDays" :key="w">{{ w }}</text>
      </view>

      <!-- 日期网格 -->
      <view class="calendar-grid">
        <view
          v-for="(day, idx) in calendarDays"
          :key="idx"
          class="day-cell"
          :class="{
            'empty': !day.date,
            'disabled': day.disabled,
            'selected-start': day.date === tempCheckIn,
            'selected-end': day.date === tempCheckOut,
            'in-range': day.inRange,
            'full': day.isFull,
          }"
          @tap="handleDayTap(day)"
        >
          <text class="day-num" v-if="day.date">{{ day.dayNum }}</text>
          <text class="day-price" v-if="day.date && !day.disabled">¥{{ day.price }}</text>
          <text class="day-stock" v-if="day.date && !day.disabled && !day.isFull">{{ day.stock }}间</text>
          <text class="day-full" v-if="day.isFull">满</text>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="picker-footer">
        <view class="summary-row">
          <text class="summary-text">入住: {{ tempCheckIn || '请选择' }} ~ 离店: {{ tempCheckOut || '请选择' }}</text>
          <text class="summary-nights" v-if="tempNights > 0">共{{ tempNights }}晚</text>
        </view>
        <view class="tip-row">
          <text class="tip-text">点击日期选择入住/离店时间</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { getRoomCalendar } from '@/api/user/room';

const props = defineProps<{
  roomId: number;
  checkIn: string;
  checkOut: string;
}>();

const emit = defineEmits<{
  (e: 'change', checkIn: string, checkOut: string): void;
}>();

const visible = ref(false);
const tempCheckIn = ref(props.checkIn);
const tempCheckOut = ref(props.checkOut);
const currentMonth = ref(new Date().getMonth());
const currentYear = ref(new Date().getFullYear());
const calendarData = ref<Map<string, { price: number; stock: number; status: string }>>(new Map());

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

const currentMonthLabel = computed(() => {
  return `${currentYear.value}年${currentMonth.value + 1}月`;
});

const tempNights = computed(() => {
  if (!tempCheckIn.value || !tempCheckOut.value) return 0;
  const diff = new Date(tempCheckOut.value).getTime() - new Date(tempCheckIn.value).getTime();
  return Math.max(0, Math.ceil(diff / (1000 * 60 * 60 * 24)));
});

// 生成日历网格数据
const calendarDays = computed(() => {
  const year = currentYear.value;
  const month = currentMonth.value;
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const startWeekday = firstDay.getDay();
  const totalDays = lastDay.getDate();

  const days: any[] = [];

  // 前面空白填充
  for (let i = 0; i < startWeekday; i++) {
    days.push({ date: null });
  }

  // 当月每一天
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  for (let d = 1; d <= totalDays; d++) {
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
    const dateObj = new Date(year, month, d);
    const calData = calendarData.value.get(dateStr);

    // 判断是否可选（今天及以后，且有库存）
    const isPast = dateObj < today;
    const isFull = calData ? (calData.status === 'unavailable' || calData.stock <= 0) : true;

    // 判断是否在选中范围内
    const inRange = tempCheckIn.value && tempCheckOut.value &&
      dateStr > tempCheckIn.value && dateStr < tempCheckOut.value;

    days.push({
      date: dateStr,
      dayNum: d,
      price: calData?.price ?? 0,
      stock: calData?.stock ?? 0,
      status: calData?.status ?? 'available',
      disabled: isPast,
      isFull,
      inRange,
    });
  }

  return days;
});

watch(() => [props.checkIn, props.checkOut], ([ci, co]) => {
  tempCheckIn.value = ci;
  tempCheckOut.value = co;
});

function open() {
  tempCheckIn.value = props.checkIn;
  tempCheckOut.value = props.checkOut;
  visible.value = true;
  // 初始化月份为入住日期所在月份
  if (props.checkIn) {
    const d = new Date(props.checkIn);
    currentYear.value = d.getFullYear();
    currentMonth.value = d.getMonth();
  }
  fetchCalendarData();
}

function close() {
  visible.value = false;
}

function confirmDates() {
  if (!tempCheckIn.value || !tempCheckOut.value) {
    uni.showToast({ title: '请选择入住和离店日期', icon: 'none' });
    return;
  }
  emit('change', tempCheckIn.value, tempCheckOut.value);
  close();
}

function handleDayTap(day: any) {
  if (!day.date || day.disabled || day.isFull) return;

  if (!tempCheckIn.value) {
    // 选择入住日期
    tempCheckIn.value = day.date;
    tempCheckOut.value = '';
  } else if (!tempCheckOut.value) {
    // 选择离店日期（必须大于入住日期）
    if (day.date <= tempCheckIn.value) {
      // 如果点击的是入住日期之前的，重新选择入住日期
      tempCheckIn.value = day.date;
    } else {
      tempCheckOut.value = day.date;
    }
  } else {
    // 已完成选择，重新开始
    tempCheckIn.value = day.date;
    tempCheckOut.value = '';
  }
}

function prevMonth() {
  if (currentMonth.value === 0) {
    currentMonth.value = 11;
    currentYear.value--;
  } else {
    currentMonth.value--;
  }
  fetchCalendarData();
}

function nextMonth() {
  if (currentMonth.value === 11) {
    currentMonth.value = 0;
    currentYear.value++;
  } else {
    currentMonth.value++;
  }
  fetchCalendarData();
}

async function fetchCalendarData() {
  const year = currentYear.value;
  const month = currentMonth.value;
  const startDate = `${year}-${String(month + 1).padStart(2, '0')}-01`;
  const endDate = `${year}-${String(month + 1).padStart(2, '0')}-${String(new Date(year, month + 1, 0).getDate()).padStart(2, '0')}`;

  try {
    const res = await getRoomCalendar(props.roomId, startDate, endDate);
    const data = res.data || [];
    const map = new Map();
    for (const item of data) {
      map.set(item.date, {
        price: item.price,
        stock: item.stock - item.sold, // 剩余库存
        status: item.status,
      });
    }
    calendarData.value = map;
  } catch (e) {
    console.error(e);
  }
}

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.picker-panel {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #eee;
}

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

.picker-cancel {
  font-size: 28rpx;
  color: #999;
}

.picker-confirm {
  font-size: 28rpx;
  color: #FF6B35;
  font-weight: 600;
}

.month-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 32rpx;
}

.nav-btn {
  font-size: 36rpx;
  color: #666;
  padding: 8rpx 16rpx;
}

.month-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.week-header {
  display: flex;
  padding: 16rpx 24rpx;
  background: #f9f9f9;
}

.week-item {
  flex: 1;
  text-align: center;
  font-size: 24rpx;
  color: #999;
}

.calendar-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 16rpx 24rpx;
}

.day-cell {
  width: calc(100% / 7);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12rpx 0;
  border-radius: 8rpx;
  position: relative;

  &.empty {
    visibility: hidden;
  }

  &.disabled {
    opacity: 0.4;
  }

  &.selected-start,
  &.selected-end {
    background: #FF6B35;
    .day-num, .day-price, .day-stock {
      color: #fff;
    }
  }

  &.in-range {
    background: #fff1eb;
  }

  &.full {
    .day-num, .day-price {
      color: #999;
    }
    .day-full {
      display: block;
    }
  }
}

.day-num {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.day-price {
  font-size: 20rpx;
  color: #FF6B35;
  margin-top: 2rpx;
}

.day-stock {
  font-size: 18rpx;
  color: #52c41a;
  margin-top: 2rpx;
}

.day-full {
  display: none;
  font-size: 18rpx;
  color: #ff4d4f;
  margin-top: 2rpx;
}

.picker-footer {
  padding: 20rpx 32rpx;
  border-top: 1rpx solid #eee;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-text {
  font-size: 26rpx;
  color: #666;
}

.summary-nights {
  font-size: 26rpx;
  color: #FF6B35;
  font-weight: 600;
}

.tip-row {
  margin-top: 12rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
}
</style>