import { Component, OnInit } from '@angular/core';
import { PromotionsService } from '../services/promotions.service';
import { LoadingController, ToastController } from '@ionic/angular';

@Component({
  selector: 'app-promotions',
  templateUrl: './promotions.page.html',
  styleUrls: ['./promotions.page.scss'],
})
export class PromotionsPage implements OnInit {

  promotions: any[] = [];
  displayedPromotions: any[] = [];
  isLoading = true;
  hasError = false;
  searchQuery = '';
  viewMode = 'all'; // 默认查看所有活动
  sortOption = 'dateDesc'; // 默认按照日期降序排列
  filteredPromotions: any[] = []; // 用于显示经过过滤和排序后的活动

  constructor(
    private promotionsService: PromotionsService,
    private loadingCtrl: LoadingController,
    private toastCtrl: ToastController
  ) {}

  ngOnInit() {
    this.loadPromotions();
  }

  doRefresh(event: any) {
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operations have ended');
      event.target.complete();
    }, 1000);
  }

  async loadPromotions() {
    const loading = await this.loadingCtrl.create({ message: 'Loading...' });
    await loading.present();

    try {
      const data = await this.promotionsService.getPromotions().toPromise() || [];
      this.promotions = Array.isArray(data) ? data : [];
      this.filterAndSortPromotions(); // 初始加载后立即应用过滤和排序
      this.isLoading = false;
      loading.dismiss();
    } catch (error) {
      this.hasError = true;
      this.isLoading = false;
      loading.dismiss();
      const toast = await this.toastCtrl.create({
        message: '无法加载活动信息，请稍后再试。',
        duration: 3000,
        position: 'bottom'
      });
      await toast.present();
    }
  }

  searchPromotions(event: any) {
    this.searchQuery = event.detail.value;
    this.updateFilteredPromotions(); // 在这里调用更新方法
  }

  sharePromotion(promotion: any) {
    // 实现分享逻辑
  }

  toggleFavorite(promotion: any) {
    promotion.isFavorite = !promotion.isFavorite;
    this.filterAndSortPromotions(); // 更新显示列表
  }

  filterPromotions() {
    this.filterAndSortPromotions(); // 当过滤条件改变时重新过滤和排序
  }

  sortPromotions() {
    this.filterAndSortPromotions(); // 当排序条件改变时重新过滤和排序
  }

  private updateFilteredPromotions() {
    if (this.searchQuery) {
      const lowerCaseQuery = this.searchQuery.toLowerCase();
      this.filteredPromotions = this.displayedPromotions.filter(promotion => 
        promotion.title.toLowerCase().includes(lowerCaseQuery) ||
        promotion.description.toLowerCase().includes(lowerCaseQuery)
      );
    } else {
      this.filteredPromotions = this.displayedPromotions;
    }
  }

  private filterAndSortPromotions() {
    let filtered = this.promotions;

    // 应用过滤
    if (this.viewMode === 'favorites') {
      filtered = filtered.filter(promotion => promotion.isFavorite);
    }

    // 应用排序
    switch (this.sortOption) {
      case 'dateAsc':
        filtered.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
        break;
      case 'dateDesc':
        filtered.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
        break;
      case 'popularity':
        filtered.sort((a, b) => b.popularity - a.popularity); // 假设有一个 popularity 属性
        break;
    }

    this.displayedPromotions = filtered;
    this.updateFilteredPromotions(); // 更新过滤后的列表
  }
}