/**
 * 活动管理API接口系统
 * 支持活动的增删改查、海报管理、时间地点管理
 */

class ActivityApiService {
  constructor() {
    this.listeners = []; // 数据变化监听器
    this.initActivityData();
  }

  // 初始化活动数据
  initActivityData() {
    const activities = this.getAllActivities();
    if (activities.length === 0) {
      const sampleActivities = [
        {
          id: 'activity_001',
          name: '北京春季音乐节',
          description: '2024年北京春季音乐节，汇聚国内外知名音乐人',
          poster: '/images/activity1.jpg',
          startDate: '2024-03-15',
          endDate: '2024-03-17',
          city: '北京',
          venue: '北京国家体育场（鸟巢）',
          address: '北京市朝阳区国家体育场南路1号',
          coordinates: {
            lng: 116.404,
            lat: 39.915
          },
          status: 'active', // active, inactive, draft
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00',
          tags: ['音乐节', '春季', '户外'],
          organizer: '北京文化传媒有限公司',
          contact: {
            phone: '400-123-4567',
            email: 'contact@musicfestival.com'
          }
        },
        {
          id: 'activity_002',
          name: '上海国际车展',
          description: '2024年上海国际汽车工业展览会',
          poster: '/images/activity2.jpg',
          startDate: '2024-04-20',
          endDate: '2024-04-28',
          city: '上海',
          venue: '上海国家会展中心',
          address: '上海市青浦区崧泽大道333号',
          coordinates: {
            lng: 121.473,
            lat: 31.230
          },
          status: 'active',
          createTime: '2024-01-20 14:00:00',
          updateTime: '2024-01-20 14:00:00',
          tags: ['车展', '国际', '工业'],
          organizer: '上海国际展览有限公司',
          contact: {
            phone: '400-234-5678',
            email: 'info@autoshow.com'
          }
        }
      ];
      this.saveActivities(sampleActivities);
    }
  }

  // 获取所有活动
  getAllActivities() {
    try {
      return wx.getStorageSync('activities') || [];
    } catch (error) {
      console.error('获取活动数据失败:', error);
      return [];
    }
  }

  // 保存活动数据
  saveActivities(activities) {
    try {
      wx.setStorageSync('activities', activities);
      this.notifyListeners(activities);
      return true;
    } catch (error) {
      console.error('保存活动数据失败:', error);
      return false;
    }
  }

  // 根据ID获取活动
  getActivityById(activityId) {
    const activities = this.getAllActivities();
    return activities.find(activity => activity.id === activityId);
  }

  // 创建活动
  createActivity(activityData) {
    const activities = this.getAllActivities();
    const newActivity = {
      ...activityData,
      id: this.generateActivityId(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: activityData.status || 'active'
    };
    
    activities.push(newActivity);
    this.saveActivities(activities);
    return newActivity;
  }

  // 更新活动
  updateActivity(activityId, updateData) {
    const activities = this.getAllActivities();
    const activityIndex = activities.findIndex(activity => activity.id === activityId);
    
    if (activityIndex === -1) {
      throw new Error('活动不存在');
    }

    activities[activityIndex] = {
      ...activities[activityIndex],
      ...updateData,
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };

    this.saveActivities(activities);
    return activities[activityIndex];
  }

  // 删除活动
  deleteActivity(activityId) {
    const activities = this.getAllActivities();
    const filteredActivities = activities.filter(activity => activity.id !== activityId);
    
    if (filteredActivities.length === activities.length) {
      throw new Error('活动不存在');
    }

    this.saveActivities(filteredActivities);
    return true;
  }

  // 搜索活动
  searchActivities(searchParams) {
    const activities = this.getAllActivities();
    let filteredActivities = [...activities];

    // 按活动名称搜索
    if (searchParams.name) {
      filteredActivities = filteredActivities.filter(activity => 
        activity.name.toLowerCase().includes(searchParams.name.toLowerCase())
      );
    }

    // 按城市搜索
    if (searchParams.city) {
      filteredActivities = filteredActivities.filter(activity => 
        activity.city.includes(searchParams.city)
      );
    }

    // 按场馆搜索
    if (searchParams.venue) {
      filteredActivities = filteredActivities.filter(activity => 
        activity.venue.toLowerCase().includes(searchParams.venue.toLowerCase())
      );
    }

    // 按状态搜索
    if (searchParams.status) {
      filteredActivities = filteredActivities.filter(activity => 
        activity.status === searchParams.status
      );
    }

    // 按日期范围搜索
    if (searchParams.startDate && searchParams.endDate) {
      filteredActivities = filteredActivities.filter(activity => {
        const activityStartDate = new Date(activity.startDate);
        const searchStartDate = new Date(searchParams.startDate);
        const searchEndDate = new Date(searchParams.endDate);
        return activityStartDate >= searchStartDate && activityStartDate <= searchEndDate;
      });
    }

    // 排序
    const sortBy = searchParams.sortBy || 'createTime';
    const sortOrder = searchParams.sortOrder || 'desc';
    
    filteredActivities.sort((a, b) => {
      let aValue = a[sortBy];
      let bValue = b[sortBy];
      
      if (sortBy === 'createTime' || sortBy === 'updateTime' || sortBy === 'startDate') {
        aValue = new Date(aValue);
        bValue = new Date(bValue);
      }
      
      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return {
      activities: filteredActivities,
      total: filteredActivities.length,
      page: searchParams.page || 1,
      pageSize: searchParams.pageSize || 20
    };
  }

  // 获取活动统计信息
  getActivityStatistics() {
    const activities = this.getAllActivities();
    
    const stats = {
      total: activities.length,
      byStatus: {},
      byCity: {},
      byMonth: {},
      upcoming: 0
    };

    const now = new Date();
    
    activities.forEach(activity => {
      // 按状态统计
      stats.byStatus[activity.status] = (stats.byStatus[activity.status] || 0) + 1;
      
      // 按城市统计
      stats.byCity[activity.city] = (stats.byCity[activity.city] || 0) + 1;
      
      // 按月份统计
      const month = activity.startDate.substring(0, 7); // YYYY-MM
      stats.byMonth[month] = (stats.byMonth[month] || 0) + 1;
      
      // 即将开始的活动
      const activityDate = new Date(activity.startDate);
      if (activityDate > now) {
        stats.upcoming++;
      }
    });

    return stats;
  }

  // 批量更新活动状态
  batchUpdateActivityStatus(activityIds, status) {
    const activities = this.getAllActivities();
    const updatedActivities = activities.map(activity => {
      if (activityIds.includes(activity.id)) {
        return {
          ...activity,
          status,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return activity;
    });

    this.saveActivities(updatedActivities);
    return true;
  }

  // 导出活动数据
  exportActivities(searchParams = {}) {
    const result = this.searchActivities(searchParams);
    return {
      activities: result.activities,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成活动ID
  generateActivityId() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `activity_${timestamp}_${random}`;
  }

  // 监听器管理
  addListener(callback) {
    this.listeners.push(callback);
  }

  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  notifyListeners(activities) {
    this.listeners.forEach(callback => {
      try {
        callback(activities);
      } catch (error) {
        console.error('活动数据监听器回调执行失败:', error);
      }
    });
  }

  // 同步活动数据
  syncActivityData() {
    const activities = this.getAllActivities();
    this.notifyListeners(activities);
    return activities;
  }
}

// 创建单例实例
const activityApiService = new ActivityApiService();

export default activityApiService;

