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';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';


@Component({
  selector: 'app-poem-detail',
  templateUrl: './poem-detail.page.html',
  styleUrls: ['./poem-detail.page.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule]
})
export class PoemDetailPage implements OnInit {

poem: CloudObject | null = null; // 用于存储当前内容的数据
error: string | null = null; // 添加错误状态
loading: boolean = true; // 添加加载状态
poemsList: CloudObject[] = [];
constructor(private activatedRoute: ActivatedRoute, private router: Router) { }


  ngOnInit() {
    const id = this.activatedRoute.snapshot.queryParamMap.get('id');
    if (id) {
      this.loadPoemById(id);
    } else {
      this.error = '内容ID未找到';
      this.loading = false;
    }
  }
  async loadPoemById(id: string) {
    try {
      let query = new CloudQuery("PL_Poems");
      query.equalTo('objectId', id); // 根据 ID 查询内容
      const results = await query.find();
      console.log('Loaded poem:', results);
      if (results.length > 0) {
        this.poem = results[0];
        if (this.poem) {
          await this.loadPoemsList(this.poem.get('title')); // 加载内容列表
        }
      } else {
        this.error = '内容未找到';
      }
    } catch (err) {
      this.error = '加载内容时出错';
      console.error(err);
    } finally {
      this.loading = false;
    }
  }

  async loadPoemsList(type: string) {
    try {
      let query = new CloudQuery("PL_Poems");
      this.poemsList = await query.find();
      console.log('Loaded contents list:', this.poemsList);
    } catch (err) {
      console.error('加载内容列表时出错:', err);
    }
  }

    goBack() {
      this.router.navigate(['/tabs/tab2']);
    }
}
