/**
 * 首页API接口服务
 * 管理滚动海报和热门路线的数据获取
 */

class HomeApiService {
  constructor() {
    this.cache = {
      banners: null,
      hotRoutes: null,
      lastUpdateTime: null
    };
    this.cacheExpireTime = 5 * 60 * 1000; // 5分钟缓存过期
  }

  // 获取滚动海报数据
  async getBanners() {
    try {
      // 检查缓存
      if (this.cache.banners && this.isCacheValid()) {
        return this.cache.banners;
      }

      // 模拟API调用
      const banners = await this.fetchBannersFromAPI();
      
      // 更新缓存
      this.cache.banners = banners;
      this.cache.lastUpdateTime = Date.now();
      
      return banners;
    } catch (error) {
      console.error('获取海报数据失败:', error);
      // 返回默认数据
      return this.getDefaultBanners();
    }
  }

  // 获取热门路线数据
  async getHotRoutes() {
    try {
      // 检查缓存
      if (this.cache.hotRoutes && this.isCacheValid()) {
        return this.cache.hotRoutes;
      }

      // 模拟API调用
      const hotRoutes = await this.fetchHotRoutesFromAPI();
      
      // 更新缓存
      this.cache.hotRoutes = hotRoutes;
      this.cache.lastUpdateTime = Date.now();
      
      return hotRoutes;
    } catch (error) {
      console.error('获取热门路线失败:', error);
      // 返回默认数据
      return this.getDefaultHotRoutes();
    }
  }

  // 模拟从API获取海报数据
  async fetchBannersFromAPI() {
    return new Promise((resolve) => {
      // 模拟网络延迟
      setTimeout(() => {
        const banners = [
          {
            id: 'banner_001',
            img: '/images/banner1.jpg',
            title: '春季出行特惠',
            subtitle: '新用户立减50元',
            link: '/pages/select-activity/select-activity?type=bus&from=北京&to=上海&date=2024-03-15',
            type: 'promotion',
            priority: 1,
            startTime: '2024-03-01 00:00:00',
            endTime: '2024-03-31 23:59:59',
            isActive: true
          },
          {
            id: 'banner_002',
            img: '/images/banner2.jpg',
            title: '商务车包车服务',
            subtitle: '豪华商务车，舒适出行',
            link: '/pages/select-activity/select-activity?type=business-charter&from=北京&to=上海&date=2024-03-15',
            type: 'service',
            priority: 2,
            startTime: '2024-03-01 00:00:00',
            endTime: '2024-12-31 23:59:59',
            isActive: true
          },
          {
            id: 'banner_003',
            img: '/images/activity1.jpg',
            title: '周末短途游',
            subtitle: '周边城市一日游',
            link: '/pages/select-activity/select-activity?type=bus&from=北京&to=天津&date=2024-03-16',
            type: 'activity',
            priority: 3,
            startTime: '2024-03-01 00:00:00',
            endTime: '2024-06-30 23:59:59',
            isActive: true
          },
          {
            id: 'banner_004',
            img: '/images/activity2.jpg',
            title: '企业包车服务',
            subtitle: '专业团队，企业首选',
            link: '/pages/select-activity/select-activity?type=business-charter&from=北京&to=上海&date=2024-03-20',
            type: 'enterprise',
            priority: 4,
            startTime: '2024-03-01 00:00:00',
            endTime: '2024-12-31 23:59:59',
            isActive: true
          }
        ];
        resolve(banners);
      }, 500);
    });
  }

  // 模拟从API获取热门路线数据
  async fetchHotRoutesFromAPI() {
    return new Promise((resolve) => {
      // 模拟网络延迟
      setTimeout(() => {
        const hotRoutes = [
          {
            id: 'route_001',
            name: '北京 → 上海',
            from: '北京',
            to: '上海',
            img: '/images/banner1.jpg',
            price: 88,
            duration: '5小时',
            popularity: 95,
            type: 'bus',
            link: '/pages/select-activity/select-activity?type=bus&from=北京&to=上海&date=2024-03-15',
            tags: ['热门', '经济'],
            isActive: true
          },
          {
            id: 'route_002',
            name: '北京 → 天津',
            from: '北京',
            to: '天津',
            img: '/images/banner2.jpg',
            price: 35,
            duration: '1.5小时',
            popularity: 88,
            type: 'bus',
            link: '/pages/select-activity/select-activity?type=bus&from=北京&to=天津&date=2024-03-15',
            tags: ['短途', '便捷'],
            isActive: true
          },
          {
            id: 'route_003',
            name: '上海 → 杭州',
            from: '上海',
            to: '杭州',
            img: '/images/activity1.jpg',
            price: 65,
            duration: '2小时',
            popularity: 82,
            type: 'bus',
            link: '/pages/select-activity/select-activity?type=bus&from=上海&to=杭州&date=2024-03-15',
            tags: ['江南', '风景'],
            isActive: true
          },
          {
            id: 'route_004',
            name: '北京 → 深圳',
            from: '北京',
            to: '深圳',
            img: '/images/activity2.jpg',
            price: 120,
            duration: '8小时',
            popularity: 75,
            type: 'business',
            link: '/pages/select-activity/select-activity?type=business&from=北京&to=深圳&date=2024-03-15',
            tags: ['商务', '长途'],
            isActive: true
          }
        ];
        resolve(hotRoutes);
      }, 300);
    });
  }

  // 获取默认海报数据
  getDefaultBanners() {
    return [
      { 
        id: 'default_001',
        img: '/images/banner1.jpg',
        title: '默认海报1',
        link: '',
        type: 'default',
        isActive: true
      },
      { 
        id: 'default_002',
        img: '/images/banner2.jpg',
        title: '默认海报2',
        link: '',
        type: 'default',
        isActive: true
      },
      { 
        id: 'default_003',
        img: '/images/activity1.jpg',
        title: '默认海报3',
        link: '',
        type: 'default',
        isActive: true
      },
      { 
        id: 'default_004',
        img: '/images/activity2.jpg',
        title: '默认海报4',
        link: '',
        type: 'default',
        isActive: true
      }
    ];
  }

  // 获取默认热门路线数据
  getDefaultHotRoutes() {
    return [
      { 
        id: 'default_001',
        name: '热门路线1',
        img: '/images/banner1.jpg',
        link: '',
        isActive: true
      },
      { 
        id: 'default_002',
        name: '热门路线2',
        img: '/images/banner2.jpg',
        link: '',
        isActive: true
      },
      { 
        id: 'default_003',
        name: '热门路线3',
        img: '/images/activity1.jpg',
        link: '',
        isActive: true
      },
      { 
        id: 'default_004',
        name: '热门路线4',
        img: '/images/activity2.jpg',
        link: '',
        isActive: true
      }
    ];
  }

  // 检查缓存是否有效
  isCacheValid() {
    if (!this.cache.lastUpdateTime) {
      return false;
    }
    return (Date.now() - this.cache.lastUpdateTime) < this.cacheExpireTime;
  }

  // 清除缓存
  clearCache() {
    this.cache = {
      banners: null,
      hotRoutes: null,
      lastUpdateTime: null
    };
  }

  // 刷新数据（强制从API获取）
  async refreshData() {
    this.clearCache();
    const [banners, hotRoutes] = await Promise.all([
      this.getBanners(),
      this.getHotRoutes()
    ]);
    return { banners, hotRoutes };
  }

  // 获取海报点击统计（模拟）
  async trackBannerClick(bannerId) {
    try {
      // 模拟统计API调用
      console.log(`海报点击统计: ${bannerId}`);
      return { success: true };
    } catch (error) {
      console.error('统计海报点击失败:', error);
      return { success: false };
    }
  }

  // 获取热门路线点击统计（模拟）
  async trackRouteClick(routeId) {
    try {
      // 模拟统计API调用
      console.log(`热门路线点击统计: ${routeId}`);
      return { success: true };
    } catch (error) {
      console.error('统计路线点击失败:', error);
      return { success: false };
    }
  }

  // 获取首页配置信息
  async getHomeConfig() {
    try {
      return {
        banners: await this.getBanners(),
        hotRoutes: await this.getHotRoutes(),
        config: {
          bannerAutoplay: true,
          bannerInterval: 5000,
          bannerCircular: true,
          bannerIndicatorDots: true,
          hotRoutesLimit: 4,
          cacheExpireTime: this.cacheExpireTime
        }
      };
    } catch (error) {
      console.error('获取首页配置失败:', error);
      return {
        banners: this.getDefaultBanners(),
        hotRoutes: this.getDefaultHotRoutes(),
        config: {
          bannerAutoplay: true,
          bannerInterval: 5000,
          bannerCircular: true,
          bannerIndicatorDots: true,
          hotRoutesLimit: 4,
          cacheExpireTime: this.cacheExpireTime
        }
      };
    }
  }
}

// 创建单例实例
const homeApiService = new HomeApiService();

export default homeApiService;

