const { museumApi } = require('../../../utils/api.js');

Page({
  data: {
    selectedTime: '',
    selectedDate: null,
    step: 1,
    morningAvailability: '余票充足',
    afternoonAvailability: '余票充足',
    morningTime: '10:00-14:00',
    afternoonTime: '14:00-18:00',
    morningId: null,
    afternoonId: null,
    afternoonDisabled: false,
    morningDisabled: false,
    showMorning: true,
    showAfternoon: true,
    isNextButtonDisabled: false
  },

  onLoad(options) {
    // 页面加载时的逻辑
  },

  onShow() {
    // 页面显示时的逻辑
    console.log(22222)
  },

  // 日期选择回调
  onDateChange(e) {
    console.log('选择的日期:', e.detail);
    const selectedDate = e.detail.dateString;
    
    // 只有当日期可选时才设置selectedDate和selectedTime
    if (selectedDate) {
      this.setData({
        selectedDate: selectedDate,
        selectedTime: 'morning' // 默认选中上午
      });
      
      // 调用API获取当日时段信息
      this.getSlotsByDate(selectedDate);
    } else {
      // 如果日期不可选，清空选择状态
      this.setData({
        selectedDate: null,
        selectedTime: ''
      });
    }
  },

  // 格式化日期
  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}`;
  },

  // 调用API获取指定日期的时段信息
  getSlotsByDate(dateString) {
    console.log('调用API获取时段信息，日期:', dateString);
    
    museumApi.getSlotsByDate(dateString)
      .then(res => {
        console.log('API返回数据:', res);
        if (res) {
          this.updateAvailability(res);
        } else {
          // API调用失败，使用默认值
          this.setData({
            morningAvailability: '余票充足',
            afternoonAvailability: '余票充足'
          });
        }
      })
      .catch(error => {
        console.error('API调用失败:', error);
        // 使用默认值
        this.setData({
          morningAvailability: '余票充足',
          afternoonAvailability: '余票充足'
        });
      });
  },

  // 检查时间段是否已过期
  isTimeSlotExpired(timeRange, selectedDate) {
    if (!timeRange || !selectedDate) return false;
    
    const now = new Date();
    const today = this.formatDate(now);
    
    // 如果选择的不是今天，则不需要检查过期
    if (selectedDate !== today) return false;
    
    // 解析时间段，获取结束时间
    const timeMatch = timeRange.match(/(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})/);
    if (!timeMatch) return false;
    
    const endHour = parseInt(timeMatch[3]);
    const endMinute = parseInt(timeMatch[4]);
    
    // 创建今天的结束时间
    const endTime = new Date();
    endTime.setHours(endHour, endMinute, 0, 0);
    
    // 如果当前时间已经超过结束时间，则过期
    return now > endTime;
  },

  // 更新余票显示
  updateAvailability(data) {
    // 根据API返回的数据更新余票显示
    let morningText = '余票充足';
    let afternoonText = '余票充足';
    let morningTime = '10:00-14:00';
    let afternoonTime = '14:00-18:00';
    let morningId = null;
    let afternoonId = null;
    let afternoonDisabled = false;
    let morningDisabled = false;
    let showMorning = true;
    let showAfternoon = true;
    
    console.log('更新余票显示，数据:', data);
    
    if (data && Array.isArray(data) && data.length > 0) {
      if (data.length >= 2) {
        // 有两项数据，根据时间段判断上午下午
        let morningData = null;
        let afternoonData = null;
        
        // 遍历数据，根据时间判断是上午还是下午
        data.forEach(item => {
          if (this.isAfternoonTime(item.time)) {
            afternoonData = item;
          } else {
            morningData = item;
          }
        });
        
        // 处理上午数据
        if (morningData) {
          if (morningData.pcs <= -1) {
            morningText = '闭馆';
            morningDisabled = true;
          } else if (morningData.pcs > 0) {
            morningText = `余票${morningData.pcs}张`;
          } else {
            morningText = '已约满';
            morningDisabled = true;
          }
          morningTime = morningData.time;
          morningId = morningData.id;
        } else {
          showMorning = false;
          morningDisabled = true;
        }
        
        // 处理下午数据
        if (afternoonData) {
          if (afternoonData.pcs <= -1) {
            afternoonText = '闭馆';
            afternoonDisabled = true;
          } else if (afternoonData.pcs > 0) {
            afternoonText = `余票${afternoonData.pcs}张`;
          } else {
            afternoonText = '已约满';
            afternoonDisabled = true;
          }
          afternoonTime = afternoonData.time;
          afternoonId = afternoonData.id;
        } else {
          showAfternoon = false;
          afternoonDisabled = true;
        }
        
        // 检查时间段是否已过期（只有未被禁用且不是闭馆状态的时间段才检查过期）
        if (morningData && !morningDisabled && morningText !== '闭馆') {
          const isExpired = this.isTimeSlotExpired(morningTime, this.data.selectedDate);
          if (isExpired) {
            morningText = '已过期';
            morningDisabled = true;
          }
        }
        
        if (afternoonData && !afternoonDisabled && afternoonText !== '闭馆') {
          const isExpired = this.isTimeSlotExpired(afternoonTime, this.data.selectedDate);
          if (isExpired) {
            afternoonText = '已过期';
            afternoonDisabled = true;
          }
        }
      } else {
        // 只有一项数据，根据时间段判断显示上午还是下午
        const singleData = data[0];
        const timeStr = singleData.time;
        
        // 解析时间段，判断是否大于14:00
        const isAfternoon = this.isAfternoonTime(timeStr);
        
        if (isAfternoon) {
          // 显示下午，隐藏上午
          if (singleData.pcs <= -1) {
            afternoonText = '闭馆';
            afternoonDisabled = true;
          } else if (singleData.pcs > 0) {
            afternoonText = `余票${singleData.pcs}张`;
          } else {
            afternoonText = '已约满';
            afternoonDisabled = true;
          }
          afternoonTime = singleData.time;
          afternoonId = singleData.id;
          
          if (!afternoonDisabled) {
            const isExpired = this.isTimeSlotExpired(afternoonTime, this.data.selectedDate);
            if (isExpired) {
              afternoonText = '已过期';
              afternoonDisabled = true;
            }
          }
          
          showMorning = false;
          morningDisabled = true;
        } else {
          // 显示上午，隐藏下午
          if (singleData.pcs <= -1) {
            morningText = '闭馆';
            morningDisabled = true;
          } else if (singleData.pcs > 0) {
            morningText = `余票${singleData.pcs}张`;
          } else {
            morningText = '已约满';
            morningDisabled = true;
          }
          morningTime = singleData.time;
          morningId = singleData.id;
          
          if (!morningDisabled) {
            const isExpired = this.isTimeSlotExpired(morningTime, this.data.selectedDate);
            if (isExpired) {
              morningText = '已过期';
              morningDisabled = true;
            }
          }
          
          showAfternoon = false;
          afternoonDisabled = true;
        }
      }
      
      // 如果当前选中的时间段已过期或被禁用，自动切换到可用的时间段
      if (this.data.selectedTime === 'morning' && (morningDisabled || !showMorning)) {
        if (!afternoonDisabled && showAfternoon) {
          this.setData({ selectedTime: 'afternoon' });
        } else {
          this.setData({ selectedTime: '' });
        }
      } else if (this.data.selectedTime === 'afternoon' && (afternoonDisabled || !showAfternoon)) {
        if (!morningDisabled && showMorning) {
          this.setData({ selectedTime: 'morning' });
        } else {
          this.setData({ selectedTime: '' });
        }
      }
    }

    // 计算下一步按钮是否应该禁用
    let isNextButtonDisabled = false;
    
    // 计算有几个时间段显示
    const visibleSlots = [];
    if (showMorning) visibleSlots.push({ disabled: morningDisabled, name: 'morning' });
    if (showAfternoon) visibleSlots.push({ disabled: afternoonDisabled, name: 'afternoon' });
    
    if (visibleSlots.length === 1) {
      // 只有一个时间段，如果该时间段被禁用则置灰按钮
      isNextButtonDisabled = visibleSlots[0].disabled;
    } else if (visibleSlots.length === 2) {
      // 有两个时间段，如果两个时间段都被禁用则置灰按钮
      isNextButtonDisabled = visibleSlots.every(slot => slot.disabled);
    }
    
    this.setData({
      morningAvailability: morningText,
      afternoonAvailability: afternoonText,
      morningTime: morningTime,
      afternoonTime: afternoonTime,
      morningId: morningId,
      afternoonId: afternoonId,
      afternoonDisabled: afternoonDisabled,
      morningDisabled: morningDisabled,
      showMorning: showMorning,
      showAfternoon: showAfternoon,
      isNextButtonDisabled: isNextButtonDisabled
    });
  },

  // 判断时间段是否为下午（大于14:00）
  isAfternoonTime(timeStr) {
    // 时间格式如："10:00-14:00" 或 "14:00-18:00"
    const startTime = timeStr.split('-')[0].trim();
    const hour = parseInt(startTime.split(':')[0]);
    return hour >= 14;
  },

  // 选择时间段
  selectTime(e) {
    const time = e.currentTarget.dataset.time;
    
    // 如果点击的是上午且上午被禁用，则不允许选择
    if (time === 'morning' && this.data.morningDisabled) {
      return;
    }
    
    // 如果点击的是下午且下午被禁用，则不允许选择
    if (time === 'afternoon' && this.data.afternoonDisabled) {
      return;
    }
    
    this.setData({
      selectedTime: time
    });
    console.log('选择的时间段:', time);
  },

  // 下一步
  goNext() {
    // 如果按钮被禁用，不允许进入下一步
    if (this.data.isNextButtonDisabled) {
      // wx.showToast({
      //   title: '当前时间段不可预约',
      //   icon: 'none'
      // });
      return;
    }
    
    if (this.data.selectedTime && this.data.selectedDate) {
      console.log('选择的时间段:', this.data.selectedTime);
      console.log('选择的日期:', this.data.selectedDate);
      
      // 根据选择的时间段获取对应的id和时间
      let appointmentSlotsId = null;
      let actualTime = '';
      
      if (this.data.selectedTime === 'morning') {
        appointmentSlotsId = this.data.morningId;
        actualTime = this.data.morningTime;
      } else if (this.data.selectedTime === 'afternoon') {
        appointmentSlotsId = this.data.afternoonId;
        actualTime = this.data.afternoonTime;
      }
      
      wx.navigateTo({
        url: `/pages/index/visit-people/visit-people?date=${this.data.selectedDate}&time=${actualTime}&appointmentSlotsId=${appointmentSlotsId}&type=1`
      });
    } else {
      // wx.showToast({
      //   title: '请选择日期和时间段',
      //   icon: 'none'
      // });
    }
  },

  onShareAppMessage() {
    return {
      title: '克拉玛依博物馆 - 开始预约',
      path: '/pages/index/start-preview/start-preview'
    };
  }
});