<template>
  <view class="calendar-container">
    <view class="week-header">
      <view v-for="(day, index) in weekDays" :key="index" class="week-day">{{ day }}</view>
    </view>

    <scroll-view scroll-y class="col" style="width:100%;height: 1px;">
      <view v-for="(month, monthIndex) in calendarData" :key="monthIndex" class="month-container">
        <view class="month-title">{{ month.year }}年{{ month.month }}月</view>
        <view class="days-grid">
          <view 
            v-for="(dayOffset, index) in month.firstDayOffset" 
            :key="`offset-${index}`"
            class="day-placeholder"
          ></view>
          
          <view
            v-for="(day, dayIndex) in month.days"
            :key="dayIndex"
            class="day-item"
            :class="[
              { 'selected': isSelected(monthIndex, dayIndex) },
              { 'disabled': isDisabled(monthIndex, dayIndex) },
              { 'festival': isFestivalDay(month, day) }
            ]"
            @tap="handleDaySelect(monthIndex, dayIndex)"
          >
            <view class="day-number">{{ day }}</view>
            <view v-if="calendarFestivals[`${month.year}${month.month}${day}`]" class="day-status">{{calendarFestivals[`${month.year}${month.month}${day}`]}}</view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import festivals from "./day.js";

export default {
  props: {
    defaultDate: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarData: [],
      selectedDate: [],
      screenWidth: 375,
	  calendarFestivals:{}
    };
  },
  computed: {
    // 计算当前日期信息
    currentDate() {
      const date = new Date();
      return {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate()
      };
    }
  },
  mounted() {
    this.initializeCalendar();
  },
  methods: {
    initializeCalendar() {
      this.getScreenWidth();
      this.generateCalendarData();
      this.setInitialSelection();
	  this.applyFestivalData()
    },

    getScreenWidth() {
      uni.getSystemInfo({
        success: (res) => {
          this.screenWidth = res.windowWidth;
        }
      });
    },

    generateCalendarData() {
      let year = this.currentDate.year;
      let month = this.currentDate.month;
      
      this.calendarData = Array.from({ length: 6 }, (_, index) => {
        const monthData = this.createMonthData(year, month + index);
        return monthData;
      });
    },

    createMonthData(year, month) {
      // 处理月份超过 12 的情况
      const actualMonth = month > 12 ? month % 12 : month;
      return {
        // 如果月份超过 12，年份加 1
        year: month > 12 ? year + 1 : year,
        // 实际月份
        month: actualMonth,
        // 该月的天数数组
        days: Array.from({ length: new Date(year, actualMonth, 0).getDate() }, (_, index) => index + 1),
        // 该月第一天是星期几
        firstDayOffset: new Date(`${year}/${actualMonth}/1`).getDay()
      };
    },

    applyFestivalData(monthData) {
	  this.calendarFestivals = festivals.reduce((acc, { year, month, festival }) => {
	      const subResult = festival.map(({ name, day }) => {
	          const key = `${year}${month}${day}`;
	          return { [key]: name };
	      });
	      return {...acc,...Object.assign({},...subResult) };
	  }, {})
    },


    setInitialSelection() {
      if (this.defaultDate) {
        const [year, month, day] = this.defaultDate.split('-');
        const monthIndex = this.calendarData.findIndex(m => 
          m.year == year && m.month == month
        );
        
        if (monthIndex !== -1) {
          this.selectedDate = [monthIndex, parseInt(day) - 1];
        }
      }
    },

    isSelected(monthIndex, dayIndex) {
      return this.selectedDate[0] === monthIndex && 
             this.selectedDate[1] === dayIndex;
    },

    isDisabled(monthIndex, dayIndex) {
      if (monthIndex === 0) {
        return dayIndex + 1 < this.currentDate.day;
      }
      return false;
    },

    isFestivalDay(month, day) {
      return typeof day === 'string';
    },

    formatDayDisplay(day) {
      return typeof day === 'string' ? day : day + 1;
    },

    handleDaySelect(monthIndex, dayIndex) {
      if (this.isDisabled(monthIndex, dayIndex)) return;
      this.selectedDate = [monthIndex, dayIndex];
      this.$emit('selected', this.getSelectedDateString());
    },

    getSelectedDateString() {
      const monthData = this.calendarData[this.selectedDate[0]];
      const dayNumber = this.selectedDate[1] + 1;
      return `${monthData.year}-${String(monthData.month).padStart(2,'0')}-${String(dayNumber).padStart(2,'0')}`;
    }
  }
};
</script>

<style>
.calendar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.week-header {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  background: #f8f8f8;
  border-radius: 16rpx;
}

.week-day {
  width: 14.28%;
  text-align: center;
  font-size: 14px;
  color: #333;
}

.month-container {
  padding: 15px 10px;
}

.month-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-left: 10px;
}

.days-grid {
  display: flex;
  flex-wrap: wrap;
}

.day-item, .day-placeholder {
  width: 14.28%;
  min-height: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
}

.day-item {
  position: relative;
  font-size: 14px;
  color: #333;
  background: #fff;
}

.day-placeholder {
  visibility: hidden;
}

.day-item.selected {
  background: #DEBF7B;
  color: #fff;
  border-radius: 4px;
}

.day-item.disabled {
  color: #ccc;
}

.day-item.festival {
  color: #d32f2f;
  font-size: 12px;
}

.day-status {
  font-size: 10px;
  color: #d32f2f;
  position: absolute;
  bottom: 2px;
}
</style>