Page({
  data:{ 
    departureActivities:[], // 去程活动（目的地活动）
    returnActivities:[],    // 返程活动（出发地活动）
    fromCity: '',
    toCity: '',
    selectedDate: '',
    selectedType: ''
  },
  onLoad(options){
    // 获取从首页传来的参数
    const { type, from, to, date } = options;
    this.setData({
      selectedType: type,
      fromCity: from,
      toCity: to,
      selectedDate: date
    });
    
    // 根据出发/到达城市自动匹配活动
    this.loadActivities(from, to, date);
  },
  
  loadActivities(from, to, date) {
    // 模拟根据城市匹配活动数据（包含不同日期的活动）
    let allActivities = [
      // 11月份活动
      {id:'1',name:'五月天演唱会',img:'/images/activity1.jpg',date:'2025-11-07 19:30',place:'上海体育馆',city:'上海市',venue:'上海体育馆'},
      {id:'3',name:'周杰伦演唱会',img:'/images/activity1.jpg',date:'2025-11-08 20:00',place:'北京工人体育馆',city:'北京市',venue:'北京工人体育馆'},
      {id:'7',name:'演唱会',img:'/images/activity1.jpg',date:'2025-11-09 20:00',place:'天津体育中心',city:'天津市',venue:'天津体育中心'},
      {id:'6',name:'体育赛事',img:'/images/activity2.jpg',date:'2025-11-10 19:00',place:'南京青奥体育公园',city:'南京市',venue:'南京青奥体育公园'},
      
      // 12月份活动
      {id:'2',name:'英雄联盟总决赛',img:'/images/activity2.jpg',date:'2025-12-01 14:00',place:'广州体育中心',city:'广州市',venue:'广州体育中心'},
      {id:'5',name:'音乐节',img:'/images/activity1.jpg',date:'2025-12-02 16:00',place:'杭州奥体中心',city:'杭州市',venue:'杭州奥体中心'},
      {id:'8',name:'音乐会',img:'/images/activity2.jpg',date:'2025-12-03 19:30',place:'重庆大剧院',city:'重庆市',venue:'重庆大剧院'},
      {id:'4',name:'王者荣耀世冠',img:'/images/activity2.jpg',date:'2025-12-20 15:00',place:'深圳湾体育中心',city:'深圳市',venue:'深圳湾体育中心'},
      
      // 跨月活动
      {id:'9',name:'新年音乐会',img:'/images/activity1.jpg',date:'2025-11-30 19:00',place:'上海大剧院',city:'上海市',venue:'上海大剧院'},
      {id:'10',name:'元旦晚会',img:'/images/activity2.jpg',date:'2025-12-31 20:00',place:'北京国家体育馆',city:'北京市',venue:'北京国家体育馆'}
    ];
    
    let activities = [];
    
    // 筛选到达地的活动（去程）
    const departureActivities = allActivities.filter(activity => {
      return this.isCityMatch(activity.city, to);
    }).map(activity => ({
      ...activity,
      tripType: 'departure', 
      tripLabel: '去程',
      matchPoint: activity.venue // 去程：目的地点为活动场馆
    }));
    
    // 筛选出发地的活动（返程）
    const returnActivities = allActivities.filter(activity => {
      return this.isCityMatch(activity.city, from);
    }).map(activity => ({
      ...activity,
      tripType: 'return',
      tripLabel: '返程',
      matchPoint: activity.venue // 返程：出发地点为活动场馆
    }));
    
    // 根据出发日期筛选活动（误差两天内）
    const filteredDepartureActivities = this.filterActivitiesByDate(departureActivities, date);
    const filteredReturnActivities = this.filterActivitiesByDate(returnActivities, date);
    
    console.log('去程活动（目的地）:', filteredDepartureActivities);
    console.log('返程活动（出发地）:', filteredReturnActivities);
    
    this.setData({ 
      departureActivities: filteredDepartureActivities,
      returnActivities: filteredReturnActivities
    });
  },
  
  // 根据出发日期筛选活动（误差两天内）
  filterActivitiesByDate(activities, selectedDate) {
    if (!selectedDate || activities.length === 0) return activities;
    
    return activities.filter(activity => {
      if (!activity.date) return false;
      
      try {
        // 提取活动日期（格式：YYYY-MM-DD HH:mm）
        const activityDateStr = activity.date.split(' ')[0]; // 只取日期部分
        const activityDate = new Date(activityDateStr + 'T00:00:00'); // 添加时间确保正确解析
        const selectedDateObj = new Date(selectedDate + 'T00:00:00');
        
        // 检查日期是否有效
        if (isNaN(activityDate.getTime()) || isNaN(selectedDateObj.getTime())) {
          console.warn(`无效日期: 活动日期=${activityDateStr}, 选择日期=${selectedDate}`);
          return false;
        }
        
        // 计算日期差（天数）- 更准确的计算方法
        const timeDiff = Math.abs(activityDate.getTime() - selectedDateObj.getTime());
        const dayDiff = Math.floor(timeDiff / (1000 * 3600 * 24));
        
        console.log(`活动: ${activity.name}, 活动日期: ${activityDateStr}, 出发日期: ${selectedDate}, 天数差: ${dayDiff}`);
        
        // 只返回误差两天内的活动（当天=0, 前后1天=1, 前后2天=2）
        return dayDiff <= 2;
      } catch (error) {
        console.error('日期筛选出错:', error);
        return false;
      }
    });
  },
  
  // 城市匹配函数
  isCityMatch(activityCity, selectedDestination) {
    if (!activityCity || !selectedDestination) return false;
    
    // 去除市、区等后缀进行匹配
    const cleanActivityCity = this.cleanCityName(activityCity);
    const cleanSelectedCity = this.cleanCityName(selectedDestination);
    
    console.log(`匹配检查: 活动城市="${activityCity}" -> "${cleanActivityCity}", 选择目的地="${selectedDestination}" -> "${cleanSelectedCity}"`);
    
    // 多种匹配方式
    const isMatch = cleanActivityCity === cleanSelectedCity || 
                   selectedDestination.includes(cleanActivityCity) || 
                   cleanActivityCity.includes(cleanSelectedCity) ||
                   activityCity === selectedDestination;
    
    console.log(`匹配结果: ${isMatch}`);
    return isMatch;
  },
  
  // 清理城市名称，提取主要城市名
  cleanCityName(cityName) {
    if (!cityName) return '';
    
    // 特殊城市映射
    const specialCities = {
      '北京市': '北京',
      '上海市': '上海', 
      '天津市': '天津',
      '重庆市': '重庆'
    };
    
    // 检查特殊城市
    if (specialCities[cityName]) {
      return specialCities[cityName];
    }
    
    // 提取主要城市名（去除省、市、区等后缀）
    const patterns = [
      /^(.+?)省(.+?)市/,  // 匹配 "xx省xx市" -> 取市名
      /^(.+?)市(.+?)区/,  // 匹配 "xx市xx区" -> 取市名
      /^(.+?)市/,         // 匹配 "xx市" -> 取主名
      /^(.+?)区/          // 匹配 "xx区" -> 取主名
    ];
    
    for (let pattern of patterns) {
      const match = cityName.match(pattern);
      if (match) {
        // 对于省市格式，取市名（第二个分组）
        if (pattern.source.includes('省') && match[2]) {
          return match[2].replace('市', '');
        }
        // 对于其他格式，取第一个分组
        return match[1];
      }
    }
    
    return cityName;
  },
  
  chooseActivity(e){
    const activityId = e.currentTarget.dataset.id;
    const tripType = e.currentTarget.dataset.type; // 从按钮获取行程类型
    
    // 根据行程类型查找活动
    let activity;
    if (tripType === 'departure') {
      activity = this.data.departureActivities.find(a => a.id === activityId);
    } else if (tripType === 'return') {
      activity = this.data.returnActivities.find(a => a.id === activityId);
    }
    
    if (!activity) return;
    
    // 根据活动类型设置出发地和目的地
    let actualFrom = this.data.fromCity;
    let actualTo = this.data.toCity;
    
    if (activity.tripType === 'departure') {
      // 去程：目的地为活动场馆所在地
      actualTo = activity.matchPoint;
    } else if (activity.tripType === 'return') {
      // 返程：出发地为活动场馆所在地
      actualFrom = activity.matchPoint;
    }
    
    wx.navigateTo({
      url: `/pages/schedule-list/schedule-list?activityId=${activityId}&type=${this.data.selectedType}&from=${encodeURIComponent(actualFrom)}&to=${encodeURIComponent(actualTo)}&date=${this.data.selectedDate}&activityName=${encodeURIComponent(activity.name)}&tripType=${activity.tripType}&tripLabel=${encodeURIComponent(activity.tripLabel)}&venue=${encodeURIComponent(activity.venue)}`
    });
  }
});