import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IonButton, IonContent, IonIcon, IonImg } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { bookmarkOutline, chatbubbleOutline, ellipsisHorizontal, heart, heartOutline, shareSocialOutline, } from 'ionicons/icons';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
addIcons({ ellipsisHorizontal, bookmarkOutline, shareSocialOutline, chatbubbleOutline, heartOutline, heart })

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.scss'],
  standalone: true,
  imports: [IonContent, IonIcon, IonButton, CommonModule,IonImg]
})
export class PostListComponent implements OnInit {
  constructor(private router:Router) { }

  posts: CloudObject[] = []; // 存储帖子
  resultUser: any;
   ngOnInit() {
     this.loadPosts();// 加载帖子列表
  }

  async loadPosts() {  // 加载帖子列表
    const query = new CloudQuery('post'); // 创建查询对象
    console.log(query);
    query.include('UserID'); // 包含 user 属性
    this.posts = await query.find(); // 使用 find 方法获取所有帖子
    // 按评论数降序排序帖子
    this.posts.sort((a, b) => (b.commentCount || 0) - (a.commentCount || 0));
    console.log(this.posts);
     // 获取每个帖子的评论数
     for (let post of this.posts) {
      const commentQuery = new CloudQuery('comment');
      commentQuery.equalTo('postID', post.toPointer()); // 根据帖子指针查询评论
      const comments = await commentQuery.find(); // 获取评论
      post.commentCount = comments.length; // 将评论数存储在帖子对象中
      console.log('帖子评论数',post.commentCount);
    }
  }

  // 用于跟踪点赞状态
  isLiked: boolean = false;

  // 切换点赞状态
  toggleLike() {
    this.isLiked = !this.isLiked; // 切换状态
  }
  goPostDetail(post:CloudObject) {
    this.router.navigate(['postDetail',post.id]);
  }
}
