import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { IonButton, IonContent, IonFooter, IonIcon, IonTextarea } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { bookmarkOutline, chatbubbleEllipsesOutline, ellipsisHorizontal, happyOutline, heartOutline, shareSocialOutline } from 'ionicons/icons';
import { CustomHeaderComponent } from '../custom-header/custom-header.component';
import { CloudQuery, CloudUser } from 'src/lib/ncloud';
import { map, switchMap } from 'rxjs/operators';
import { CloudObject } from 'src/lib/ncloud';
import { FormsModule } from '@angular/forms';
import { IonModal } from '@ionic/angular/standalone';

addIcons({ ellipsisHorizontal, bookmarkOutline, heartOutline, shareSocialOutline, happyOutline, chatbubbleEllipsesOutline })


@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.scss'],
  standalone: true,
  imports: [IonContent, IonIcon, IonButton, CommonModule, CustomHeaderComponent, IonTextarea, IonFooter, FormsModule, IonModal]
})
export class PostDetailComponent implements OnInit {
  postId: string | any;
  post: any;
  newComment: string = ''; // 新评论的内容
  isfooter: boolean = true; // 控制底部栏的样式
  comments: CloudObject[] = []; // 存储评论的数组
  isFollowed: boolean = false; // 初始状态为未关注
  constructor(private route: ActivatedRoute) { }
  /**
   * @从路由参数中获取帖子ID，并初始化帖子详情页面。
   */
  async ngOnInit() {
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) => this.route.queryParamMap.pipe(
        map(() => params.get('postId'))
      ))
    ).subscribe(postId => {
      this.postId = postId;
      // 现在您可以使用 this.postId 来获取帖子详情或执行其他操作
    });
    console.log("正在加载帖子：" + this.postId)
    this.getPostDetail();
    await this.loadComments(); // 组件初始化时加载评论
  }

  toggleFollow() {
    this.isFollowed = !this.isFollowed; // 切换关注状态
  }
  /**
   * @获取帖子详情数据
   */
  async getPostDetail() {
    let query = new CloudQuery("post");
    query.include("UserID");
    query.equalTo("objectId", this.postId);
    let result = await query.find();
    this.post = result[0];
    console.log(this.post);

  }

  // 加载与当前帖子相关的评论
  async loadComments() {
    const query = new CloudQuery("comment");
    query.equalTo("postID", { "__type": "Pointer", "className": "post", "objectId": this.postId }); // 根据帖子ID查询评论
    query.include('UserID'); // 包含 user 属性
    this.comments = await query.find(); // 获取评论
    console.log('加载的评论:', this.comments);

  }


  tocomment() {
    this.isfooter = false; // 切换底部栏的显示样式
    console.log(this.isfooter);
  }

  notcomment() {
    this.isfooter = true; // 切换底部栏的显示样式
  }

  async submitComment() {
    if (this.newComment.trim()) {
      // 创建新的评论对象
      const comment = new CloudObject("comment");
      const user = new CloudUser();
      const currentUser = await user.current(); // 获取当前用户信息
      if (currentUser) {
        // 设置评论的字段
        await comment.set({
          UserID: new CloudUser().toPointer(), // 指向当前用户
          postID: { "__type": "Pointer", "className": "post", "objectId": this.post.id }, // 帖子指针
          content: this.newComment.trim(), // 评论内容
          heart: 0 // 初始点赞数为0
        });

        // 保存评论
        await comment.save().then(() => {
          console.log('评论已保存:', this.newComment);
          this.newComment = ''; // 清空输入框
        })
        await this.loadComments(); // 加载新评论
      }
    }
  }

  //用户评论时间
  formatTimeAgo(date: any): string {
    const date1 = new Date(date);
    const now = new Date();
    const seconds = Math.floor((now.getTime() - date1.getTime()) / 1000);
    //console.log("date1.getTime()",date1.getTime());
    //console.log("now.getTime()",now.getTime());
    //console.log("seconds",seconds);

    let interval = Math.floor(seconds / 31536000);
    if (interval >= 1) return interval + " 年前";
    interval = Math.floor(seconds / 2592000);
    if (interval >= 1) return interval + " 个月前";
    interval = Math.floor(seconds / 86400);
    if (interval >= 1) return interval + " 天前";
    interval = Math.floor(seconds / 3600);
    if (interval >= 1) return interval + " 小时前";
    interval = Math.floor(seconds / 60);
    if (interval >= 1) return interval + " 分钟前";
    return "刚刚";
  }

  isEmojiPickerOpen: boolean = false; // 控制表情选择器的打开状态
  emojis: string[] = ['😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂', '🙂', '🙃', '🫠', '😉', '😊', '😇', '🥰', '😍', '🤩', '😘',
    '😗', '☺️', '😚', '😙', '🥲', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤗', '🤭', '🫢', '🫣', '🤫', '🤔', '🫡', '🤐', '🤨', '😐',
    '😑', '😶', '🫥', '😶‍🌫️', '😏', '😒', '🙄', '😬', '😮‍💨', '🤥', '🫨', '🙂‍↔️', '🙂‍↕️', '😌', '😔', '😪', '🤤', '😴', '🫩', '😷',
    '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '😵‍💫', '🤯', '🤠', '🥳', '🥸', '😎', '🤓', '🧐', '😕', '🫤', '😟',
    '🙁', '☹️', '😮', '😯', '😲', '😳', '🥺', '🥹', '😦', '😧', '😨', '😰', '😥', '😢', '😭', '😱', '😖', '😣', '😞', '😓',
    '😩', '😫', '🥱', '😤', '😡', '😠', '🤬', '😈', '👿', '💀', '☠️', '💩', '🤡', '👹', '👺', '👻', '👽', '👾', '🤖', '😺',
    '😸', '😹', '😻', '😼', '😽', '🙀', '😿', '😾', '🙈', '🙉', '🙊', '💌', '💘', '❤️', '🖤', '💋', '💯', '💢', '💥', '💫',
    '💦', '💤']; // 表情数组
  // 打开表情选择器
  openEmojiPicker() {
    this.isEmojiPickerOpen = true;
  }

  // 关闭表情选择器
  closeEmojiPicker() {
    this.isEmojiPickerOpen = false; // 关闭模态框
  }

  // 添加表情到输入框
  addEmoji(emoji: string) {
    this.newComment += emoji; // 将选中的表情添加到输入框
    this.closeEmojiPicker(); // 关闭模态框
  }



}