<template>
  <uni-popup ref="popupRef" type="bottom" :safe-area="true">
    <view class="calendar-container">
      <!-- 头部 -->
      <view class="calendar-header">
        <view class="header-title">选择预约日期</view>
        <view class="header-subtitle">{{ currentMonth }}</view>
      </view>

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

      <!-- 日历日期 -->
      <view class="calendar-body">
        <view
          class="date-item"
          v-for="(date, index) in dateList"
          :key="index"
          :class="{
            empty: !date.day,
            available: date.available,
            unavailable: !date.available && date.day,
            selected: date.selected,
          }"
          @click="selectDate(date)"
        >
          <view class="date-day" v-if="date.day">{{ date.day }}</view>
          <view class="date-dot" v-if="date.selected"></view>
        </view>
      </view>

      <!-- 无可用日期提示（在日历下方、底部按钮上方） -->
      <view v-if="hasNoAvailableDates" class="no-available-tip">
        无可预约的日期
      </view>

      <!-- 底部按钮 -->
      <view class="calendar-footer">
        <view class="legend">
          <view class="legend-item">
            <view class="legend-dot available"></view>
            <text>可预约</text>
          </view>
          <view class="legend-item">
            <view class="legend-dot unavailable"></view>
            <text>不可预约</text>
          </view>
        </view>
        <view class="button-group">
          <button class="btn-cancel" @click="close">取消</button>
          <button
            class="btn-confirm"
            @click="confirm"
            :disabled="!selectedDate"
          >
            确认
          </button>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { quotaByWeight } from "@/api/vault"; // 引入克重查询接口

const hasNoAvailableDates = ref(false);

const props = defineProps({
  metalType: {
    type: Number,
    default: 1,
  },
  reservedWeight: {
    // 新增：接收父组件传递的克重
    type: Number,
    required: true,
    validator: (val) => val > 0,
  },
});

const emit = defineEmits(["confirm"]);

const popupRef = ref(null);
const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
const dateList = ref([]);
const availableDates = ref([]); // 存储可预约日期（从接口获取）
const selectedDate = ref(null);
const currentYear = ref(new Date().getFullYear());
const currentMonthNum = ref(new Date().getMonth() + 1);

// 当前月份显示
const currentMonth = computed(() => {
  return `${currentYear.value}年${currentMonthNum.value}月`;
});

// 打开弹窗
const open = async () => {
  popupRef.value?.open();
  await fetchAvailableDates(); // 打开时查询可预约日期
  generateCalendar();
};

// 关闭弹窗
const close = () => {
  popupRef.value?.close();
  selectedDate.value = null;
};

// 获取可预约日期（基于克重和金属类型）
const fetchAvailableDates = async () => {
  try {
    const res = await quotaByWeight({
      metalType: props.metalType,
      weight: props.reservedWeight,
    });
    const availableDateList = res.data
      .filter((item) => item.canReserve)
      .map((item) => item.date);
    availableDates.value = availableDateList;
    hasNoAvailableDates.value = availableDateList.length === 0;
  } catch (error) {
    console.error("获取可预约日期失败:", error);
    uni.showToast({ title: "获取日期失败", icon: "none" });
  }
};

// 生成日历
const generateCalendar = () => {
  const year = currentYear.value;
  const month = currentMonthNum.value;

  // 获取当月第一天是星期几（0-6）
  const firstDay = new Date(year, month - 1, 1).getDay();
  // 获取当月天数
  const daysInMonth = new Date(year, month, 0).getDate();

  const dates = [];

  // 填充空白（月初前的空白）
  for (let i = 0; i < firstDay; i++) {
    dates.push({ day: null, available: false, selected: false });
  }

  // 填充日期
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(
      day
    ).padStart(2, "0")}`;
    // 判断是否在可预约列表中
    const isAvailable = availableDates.value.includes(dateStr);

    dates.push({
      day,
      date: dateStr,
      available: isAvailable,
      selected: false,
    });
  }

  dateList.value = dates;
};

// 选择日期
const selectDate = (date) => {
  if (!date.day || !date.available) {
    if (date.day && !date.available) {
      uni.showToast({ title: "该日期不可预约", icon: "none" });
    }
    return;
  }

  // 取消之前的选择
  dateList.value.forEach((item) => {
    item.selected = false;
  });

  // 设置新选择
  date.selected = true;
  selectedDate.value = date.date;
};

// 确认选择
const confirm = () => {
  if (!selectedDate.value) {
    uni.showToast({ title: "请选择预约日期", icon: "none" });
    return;
  }

  emit("confirm", selectedDate.value);
  close();
};

// 监听金属类型或克重变化，重新获取日期
watch([() => props.metalType, () => props.reservedWeight], async () => {
  if (props.reservedWeight > 0) {
    // 确保克重有效
    await fetchAvailableDates();
    generateCalendar();
  }
});

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

<style lang="scss" scoped>
.calendar-container {
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx 30rpx 60rpx;
}

.calendar-header {
  text-align: center;
  margin-bottom: 40rpx;

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .header-subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.week-header {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;

  .week-item {
    width: 14.28%;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
  }
}

.calendar-body {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 40rpx;

  .date-item {
    width: 14.28%;
    height: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    margin-bottom: 10rpx;

    .date-day {
      font-size: 30rpx;
      color: #333;
    }

    .date-dot {
      width: 8rpx;
      height: 8rpx;
      background: #e9c279;
      border-radius: 50%;
      margin-top: 8rpx;
    }

    &.empty {
      pointer-events: none;
    }

    &.available {
      .date-day {
        color: #333;
        font-weight: 500;
      }

      &:active {
        background: rgba(233, 194, 121, 0.1);
        border-radius: 50%;
      }
    }

    &.unavailable {
      .date-day {
        color: #ccc;
      }
    }

    &.selected {
      .date-day {
        background: #e9c279;
        color: #fff;
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }
    }
  }
}

.calendar-footer {
  .legend {
    display: flex;
    justify-content: center;
    gap: 40rpx;
    margin-bottom: 30rpx;

    .legend-item {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #666;

      .legend-dot {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        margin-right: 10rpx;

        &.available {
          background: #333;
        }

        &.unavailable {
          background: #ccc;
        }
      }
    }
  }

  .button-group {
    display: flex;
    gap: 20rpx;

    button {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 30rpx;
      border: none;
    }

    .btn-cancel {
      background: #f5f5f5;
      color: #666;
    }

    .btn-confirm {
      background: #e9c279;
      color: #fff;
    }
  }
}
.no-available-tip {
  color: #ff1e0f; // 红色提示
  font-size: 28rpx;
  text-align: center;
  padding: 15rpx 0; // 上下留白
  width: 100%;
}
</style>
