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);
       // 判断用户有没有点赞过该帖子
     const Query = new CloudQuery('postLikesRecord'); // 创建查询对象
     Query.equalTo('UserID', new CloudUser().toPointer()); // 根据用户ID查询
     Query.equalTo('postID', post.toPointer()); // 根据帖子指针查询
     const likeRecord = await Query.first(); // 获取点赞记录
     if (likeRecord) {
      post.postisLiked = true; // 如果存在点赞记录，则帖子被当前用户点赞过
     } else {
      post.postisLiked = false; 
     }
    }
  }


  // 切换点赞状态并更新数据库
  async toggleLike(post: any) {
    post.postisLiked = !post.postisLiked; // 切换当前帖子的点赞状态
    const postId = post.id; // 获取帖子ID
    const userId = new CloudUser().toPointer() // 获取当前用户ID

    if (post.postisLiked) {   // 点赞
      post.data.like += 1; // 增加点赞数
      await this.updatePostLikeCount(postId, 1); // 更新数据库中的点赞数
      await this.savePostLikeRecord( postId); // 保存点赞记录
    } else {
      // 取消点赞
      post.data.like -= 1; // 减少点赞数
      await this.updatePostLikeCount(postId, -1); // 更新数据库中的点赞数
      await this.removePostLikeRecord(userId, postId); // 删除点赞记录
    }
  
}

 // 保存点赞记录
async savePostLikeRecord( postId:any){
    // 创建新的点赞对象
    const likeRecord = new CloudObject("postLikesRecord"); 
    const user = new CloudUser();
    const currentUser =  user.current(); // 获取当前用户信息
  if (currentUser!=null) {
 // 设置点赞记录的字段
 await likeRecord.set({
     UserID: new CloudUser().toPointer(), // 指向当前用户
     postID: { "__type": "Pointer", "className": "post", "objectId": postId }, // 帖子指针
 });

 console.log(likeRecord);

  // 保存点赞记录
  await likeRecord.save().then(() => {
    console.log('点赞记录已保存:');
})
}
}

// 更新帖子点赞数
async updatePostLikeCount(postId:any, count:number){
  const query = new CloudQuery('post'); // 创建查询对象
  query.equalTo('objectId', postId); // 根据帖子ID查询
  //console.log(postId);
  const post = await query.first(); // 获取帖子对象
  //console.log(post);
  if(post){
    post.data['like'] += count; // 更新点赞数
   post.id=postId;
  await post.save().then(() => {
    console.log('帖子点赞数已更新:');
  })
  }

}

 // 删除点赞记录
 async removePostLikeRecord(userId:any, postId:any){
  const query = new CloudQuery('postLikesRecord'); // 创建查询对象
  query.equalTo('postID', postId); // 根据帖子ID查询
  query.equalTo('UserID', userId); // 根据用户ID查询
  const likeRecord = await query.first(); // 获取点赞记录对象
  //console.log(likeRecord);
  if(likeRecord){
    await likeRecord.destroy().then(() => {
      console.log('点赞记录已删除:');
    })
  }

}
  goPostDetail(post:CloudObject) {
    this.router.navigate(['postDetail',post.id]);
  }
}
