const { museumApi } = require('../../utils/api.js');
Component({
  properties: {
    // 可以接收外部传入的属性
  },

  data: {
    weekdays: ['一', '二', '三', '四', '五', '六', '日'],
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    selectedDate: null,
    daysInMonth: [],
    apiData: null // 存储API返回的数据
  },

  lifetimes: {
    attached() {
      this.loadAppointmentSlots();
    }
  },

  computed: {
    currentYearMonth() {
      return `${this.data.currentYear}-${this.data.currentMonth.toString().padStart(2, '0')}`;
    }
  },

  methods: {
    // 加载预约时段数据
    loadAppointmentSlots() {
      museumApi.getSlots()
        .then(response => {
          console.log('获取预约时段数据成功:', response);
          
          // 根据实际API返回的数据结构进行处理
          const apiData = response.data || response;
          
          this.setData({
            apiData: apiData
          }, () => {
            // 确保apiData设置完成后再初始化日历和默认日期
            this.initCalendar();
            this.initDefaultDate();
          });
        })
        .catch(error => {
          console.error('获取预约时段数据失败:', error);
          
          // 如果API调用失败，使用默认数据确保组件正常工作
          const defaultApiData = {
            time: {
              monday: 0,
              tuesday: 0,
              wednesday: 0,
              thursday: 0,
              friday: 0,
              saturday: 0,
              sunday: 0
            },
            stopDate: {
              rtf: ""
            }
          };
          
          this.setData({
            apiData: defaultApiData
          }, () => {
            this.initCalendar();
            this.initDefaultDate();
          });
        });
    },

    // 初始化日历
    initCalendar() {
      const year = this.data.currentYear;
      const month = this.data.currentMonth - 1;
      
      // 获取当月第一天是星期几（调整为中文星期顺序：周一=0, 周二=1...周日=6）
      const firstDayWeek = new Date(year, month, 1).getDay();
      const firstDay = firstDayWeek === 0 ? 6 : firstDayWeek - 1; // 将周日(0)转为6，其他-1
      
      // 获取当月的总天数
      const totalDays = new Date(year, month + 1, 0).getDate();
      
      const days = [];
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      // 计算开放日期范围（从今天开始的七天）
      const openStart = new Date(today);
      const openEnd = new Date(today);
      openEnd.setDate(today.getDate() + 6);
      openEnd.setHours(23, 59, 59, 999);
      
      // 解析停止开放的日期
      const stopDates = this.parseStopDates();
      
      // 添加空白占位符，不显示上个月日期
      for (let i = 0; i < firstDay; i++) {
        days.push({
          date: '',
          fullDate: null,
          isCurrentMonth: false,
          isEmpty: true, // 标记为空白
          isPast: true,
          isToday: false,
          isInOpenRange: false,
          status: ''
        });
      }
      
      // 添加当月的日期
      for (let i = 1; i <= totalDays; i++) {
        const date = new Date(year, month, i);
        const isToday = date.getDate() === today.getDate() && 
                        date.getMonth() === today.getMonth() && 
                        date.getFullYear() === today.getFullYear();
        
        const isPast = date < today;
        const isInOpenRange = this.isDateInOpenRange(date, openStart, openEnd);
        
        // 获取日期状态
        const status = this.getDateStatus(date, isPast, isToday, isInOpenRange, stopDates);
        
        // 添加到数组
        const dayData = {
          date: i,
          fullDate: date,
          isCurrentMonth: true,
          isEmpty: false,
          isPast,
          isToday,
          isInOpenRange,
          status
        };
        
        // 预计算CSS类名
        dayData.cssClass = this.calculateDayClass(dayData);
        
        days.push(dayData);
      }
      
      // 添加空白占位符填充剩余位置
      const totalCells = Math.ceil(days.length / 7) * 7; // 确保是7的倍数
      const remainingCells = totalCells - days.length;
      for (let i = 0; i < remainingCells; i++) {
        // 添加空白占位符
        const emptyDay = {
          date: '',
          fullDate: null,
          isCurrentMonth: false,
          isEmpty: true,
          isPast: false,
          isToday: false,
          isInOpenRange: false,
          status: ''
        };
        emptyDay.cssClass = 'empty-cell';
        days.push(emptyDay);
      }
      
      this.setData({
        daysInMonth: days,
        currentYearMonth: this.data.currentYear + '-' + this.data.currentMonth.toString().padStart(2, '0')
      });
    },

    // 判断日期是否在开放日期范围内
    isDateInOpenRange(date, start, end) {
      return date >= start && date <= end;
    },

    // 解析停止开放的日期
    parseStopDates() {
      if (!this.data.apiData || !this.data.apiData.stopDate || !this.data.apiData.stopDate.rtf) {
        return [];
      }
      
      const stopDateStr = this.data.apiData.stopDate.rtf;
      const dateStrings = stopDateStr.split(',');
      
      return dateStrings.map(dateStr => {
        const date = new Date(dateStr.trim());
        date.setHours(0, 0, 0, 0);
        return date;
      });
    },

    // 获取日期状态
    getDateStatus(date, isPast, isToday, isInOpenRange, stopDates) {
      // 已结束的日期
      if (isPast) {
        return '已结束';
      }
      
      // 检查是否在停止开放日期列表中
      const isStopDate = stopDates.some(stopDate => 
        date.getTime() === stopDate.getTime()
      );
      
      if (isStopDate) {
        return '未开放';
      }
      
      // 超过七天的日期显示未开放
      if (!isInOpenRange) {
        return '未开放';
      }
      
      // 根据API数据判断当天是否开放
      const dayOfWeek = date.getDay();
      const weekdayMap = {
        0: 'sunday',
        1: 'monday', 
        2: 'tuesday',
        3: 'wednesday',
        4: 'thursday',
        5: 'friday',
        6: 'saturday'
      };
      
      const weekdayKey = weekdayMap[dayOfWeek];
      const availableSlots = this.data.apiData && this.data.apiData.time ? this.data.apiData.time[weekdayKey] : 0;
      
      // 如果值是-1，则显示闭馆
      if (availableSlots === -1 || (!availableSlots && availableSlots !== 0)) {
        return '闭馆';
      }
      
      if (isToday) {
        return availableSlots > 0 ? '今天' : '已约满';
      } else {
        return availableSlots > 0 ? '已开放' : '已约满';
      }
    },

    // 计算日期单元格的CSS类（用于数据预处理）
    calculateDayClass(day) {
      // 如果是空白单元格，直接返回空白样式
      if (day.isEmpty) {
        return 'empty-cell';
      }
      
      const selectedDate = this.data.selectedDate ? new Date(this.data.selectedDate) : null;
      const isSelected = selectedDate && day.fullDate &&
                        day.fullDate.getDate() === selectedDate.getDate() && 
                        day.fullDate.getMonth() === selectedDate.getMonth() && 
                        day.fullDate.getFullYear() === selectedDate.getFullYear();
      
      let classes = [];
      
      // 基础状态类
      if (!day.isCurrentMonth && !day.isEmpty) classes.push('other-month');
      if (day.isToday) classes.push('today'); // 今天总是添加today类，不管是否开放
      if (day.isPast) classes.push('past');
      
      // 可选择状态
      if (day.isInOpenRange && !day.isPast && day.status !== '已约满' && day.status !== '未开放' && day.status !== '闭馆') {
        classes.push('selectable');
      }
      
      // 选中状态 - 优先级最高，排除未开放和闭馆状态
      if (isSelected && day.status !== '未开放' && day.status !== '闭馆') {
        classes.push('selected');
      }
      
      // 状态相关的样式类
      if (day.status === '已开放' || day.status === '今天') {
        classes.push('available');
      }
      if (day.status === '未开放') {
        classes.push('unavailable');
      }
      if (day.status === '已约满') {
        classes.push('full');
      }
      if (day.status === '闭馆') {
        classes.push('closed');
      }
      
      return classes.join(' ');
    },

    // 更新所有日期的CSS类（当选中状态改变时调用）
    updateDayClasses() {
      const updatedDays = this.data.daysInMonth.map(day => {
        return {
          ...day,
          cssClass: this.calculateDayClass(day)
        };
      });
      
      this.setData({
        daysInMonth: updatedDays
      });
    },

    // 选择日期
    selectDay(e) {
      const dayIndex = e.currentTarget.dataset.index;
      const day = this.data.daysInMonth[dayIndex];
      
      // 空白单元格不可点击
      if (day.isEmpty || !day.fullDate) {
        return;
      }
      
      // 只有开放日期范围内且未过期且未约满且不是未开放且不是闭馆的日期才可选择
      if (day.isInOpenRange && !day.isPast && day.status !== '已约满' && day.status !== '未开放' && day.status !== '闭馆') {
        this.setData({
          selectedDate: day.fullDate
        });
        
        // 更新所有日期的CSS类以反映新的选中状态
        this.updateDayClasses();
        
        // 触发自定义事件，向父组件传递选择的日期
        this.triggerEvent('datechange', {
          date: day.fullDate,
          dateString: this.formatDate(day.fullDate)
        });
        
        console.log('选择的日期:', day.fullDate);
      } else {
        console.log('日期不可选择，状态：', day.status);
      }
    },

    // 上一个月
    prevMonth() {
      if (this.data.currentMonth === 1) {
        this.setData({
          currentYear: this.data.currentYear - 1,
          currentMonth: 12
        });
      } else {
        this.setData({
          currentMonth: this.data.currentMonth - 1
        });
      }
      this.initCalendar();
    },

    // 下一个月
    nextMonth() {
      if (this.data.currentMonth === 12) {
        this.setData({
          currentYear: this.data.currentYear + 1,
          currentMonth: 1
        });
      } else {
        this.setData({
          currentMonth: this.data.currentMonth + 1
        });
      }
      this.initCalendar();
    },

    // 初始化默认日期
    initDefaultDate() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      // 计算开放日期范围（从今天开始的七天）
      const openStart = new Date(today);
      const openEnd = new Date(today);
      openEnd.setDate(today.getDate() + 6);
      openEnd.setHours(23, 59, 59, 999);
      
      const isInOpenRange = this.isDateInOpenRange(today, openStart, openEnd);
      const stopDates = this.parseStopDates();
      const todayStatus = this.getDateStatus(today, false, true, isInOpenRange, stopDates);
      
      console.log('今天状态检查:', {
        isInOpenRange,
        todayStatus,
        apiData: this.data.apiData
      });
      
      // 只有今天可以选择时才默认选中（今天状态为'今天'或'已开放'表示可约，排除闭馆状态）
      if (isInOpenRange && (todayStatus === '今天' || todayStatus === '已开放') && todayStatus !== '闭馆') {
        this.setData({
          selectedDate: today
        });
        
        // 更新日历显示以反映选中状态
        this.updateDayClasses();
        
        // 触发自定义事件，向父组件传递默认选择的日期
        this.triggerEvent('datechange', {
          date: today,
          dateString: this.formatDate(today)
        });
        
        console.log('默认选中今天:', today, '状态:', todayStatus);
      } else {
        // 今天不可选择时，确保selectedDate为null，不触发datechange事件
        this.setData({
          selectedDate: null
        });
        console.log('今天不可选择，不默认选中。状态：', todayStatus);
      }
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
});