<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) },
              { 'range': isInRange(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: {
    defaultStartDate: {
      type: String,
      default: ""
    },
    defaultEndDate: {
      type: String,
      default: ""
    },
	displayList:{
		type:Object,
		default:{}
	}
  },
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarData: [],
      selectedStartDate: [],  // Start date index
      selectedEndDate: [],    // End date index
      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) {
      const actualMonth = month > 12 ? month % 12 : month;
      return {
        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() {
      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) };
      }, {});
	  console.log(this.calendarFestivals,this.displayList)
	   this.calendarFestivals = Object.assign(this.calendarFestivals, this.displayList);
    },

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

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

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

    isInRange(monthIndex, dayIndex) {
      if (!this.selectedStartDate.length || !this.selectedEndDate.length) return false;
      const start = this.selectedStartDate;
      const end = this.selectedEndDate;
      return (monthIndex > start[0] || (monthIndex === start[0] && dayIndex >= start[1])) && 
             (monthIndex < end[0] || (monthIndex === end[0] && dayIndex <= end[1]));
    },

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

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

    handleDaySelect(monthIndex, dayIndex) {
      if (this.isDisabled(monthIndex, dayIndex)) return;

      // Handle the selection of start and end date for range
      if (!this.selectedStartDate.length || (this.selectedStartDate.length && this.selectedEndDate.length)) {
        this.selectedStartDate = [monthIndex, dayIndex];
        this.selectedEndDate = [];  // Reset end date
      } else {
        if (monthIndex > this.selectedStartDate[0] || 
            (monthIndex === this.selectedStartDate[0] && dayIndex >= this.selectedStartDate[1])) {
          this.selectedEndDate = [monthIndex, dayIndex];
        } else {
          this.selectedStartDate = [monthIndex, dayIndex];
          this.selectedEndDate = []; // Reset if the start date is changed
        }
      }

      this.$emit('selected-range', this.getSelectedRange());
    },

    getSelectedRange() {
      const startMonthData = this.calendarData[this.selectedStartDate[0]];
      const endMonthData = this.calendarData[this.selectedEndDate[0]];
      const startDayNumber = this.selectedStartDate[1] + 1;
      const endDayNumber = this.selectedEndDate[1] + 1;
      return [ !startMonthData?'':`${startMonthData.year}-${String(startMonthData.month).padStart(2, '0')}-${String(startDayNumber).padStart(2, '0')}`,!endMonthData?'':`${endMonthData.year}-${String(endMonthData.month).padStart(2, '0')}-${String(endDayNumber).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: #000 !important;
  color: #fff;
}

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

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

.day-status {
  font-size: 10px;
  color: #d32f2f;
  position: absolute;
  bottom: 2px;
}
.day-item.range {
  background-color: #f1f2f4; /* light yellow */
 /* color: #000; */
}
</style>