import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';

@Component({
  selector: 'app-book-management',
  templateUrl: './book-management.page.html',
  styleUrls: ['./book-management.page.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule]
})
export class BookManagementPage implements OnInit {
  bookId: number | null = null; // 初始化为 null
  poems: any[] = []; // 用于存储诗词数据
  private baseUrl = 'http://localhost:3000/api'; // 后端 API 基础 URL

  constructor(private route: ActivatedRoute, private http: HttpClient, private router: Router) {}

  ngOnInit() {
    // 订阅路由参数，以获取传递的书籍ID
    this.route.params.subscribe(params => {
      this.bookId = +params['id']; // 获取传递的书籍ID
      if (this.bookId) {
        this.getPoemsByBook(this.bookId); // 获取该书籍下的诗词
      }
    });
  }

  // 获取指定书籍下的诗词
  getPoemsByBook(bookId: number) {
    this.http.get<any[]>(`${this.baseUrl}/poems/${bookId}`).subscribe(data => {
      this.poems = data; // 保存诗词数据
    }, error => {
      console.error('Error fetching poems', error);
    });
  }

  // 导航到诗词详情页面
  goToPoemDetail(poemId: number) {
    if (this.bookId !== null) {
      this.router.navigate(['../poem-detail', poemId], { queryParams: { bookId: this.bookId } }); // 传递书籍ID作为查询参数
    } else {
      console.error('Book ID is not set');
    }
  }
}