import { IonicModule } from '@ionic/angular';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { addIcons } from 'ionicons';
import { search } from 'ionicons/icons';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule]
})
export class Tab2Page implements OnInit {
  selectedSegment: string = 'collection'; // 默认选择分类标签
  selectedGenre: string = ''; // 存储选中的体裁
  PLPoemsList: Array<CloudObject> = []; // 所有诗歌列表
  filteredPoemsList: Array<CloudObject> = []; // 筛选后的诗歌列表

  constructor(private http: HttpClient, private router: Router) {
    addIcons({ search });
  }

  ngOnInit() {
    this.loadPLPoemsList();
  }

  // 加载所有诗歌
  async loadPLPoemsList() {
    let query = new CloudQuery("PL_Poems");
    this.PLPoemsList = await query.find();
    this.filteredPoemsList = this.PLPoemsList; // 初始化时显示所有诗歌
  }

  // 选择体裁
  onGenreSelect(genre: string | number | undefined) {
    if (typeof genre === 'string') {
      this.selectedGenre = genre;
      this.filterPoemsByGenre(genre);
    } else if (typeof genre === 'number') {
      // 如果 genre 是数字，可以根据需要进行处理，这里假设需要转换为字符串
      this.selectedGenre = genre.toString();
      this.filterPoemsByGenre(this.selectedGenre);
    }
  }

  // 根据体裁过滤诗歌列表
  filterPoemsByGenre(genre: string) {
    if (genre) {
      this.filteredPoemsList = this.PLPoemsList.filter(book => book.get('genre') === genre);
      //query.equalTo('genre', 'genre'); // 添加查询条件来限制 type="对应的genre"
    } else {
      this.filteredPoemsList = this.PLPoemsList; // 如果没有选择体裁，显示所有诗歌
    }
  }

  goToPoemDetail(bookcard: any) {
    this.router.navigate(['/poem-detail'],{ queryParams: { id: bookcard.id }  });
  }
}
