import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IonAvatar, IonButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonList, IonTitle, IonToolbar } from '@ionic/angular/standalone';
import { IonBackButton } from '@ionic/angular/standalone';
import { IonIcon } from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { PostService } from '../post.service'; // 导入服务
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-post-page',
  templateUrl: './post-page.component.html',
  styleUrls: ['./post-page.component.scss'],
  standalone: true,
  imports: [IonHeader,IonToolbar,IonButtons,IonBackButton,IonTitle,IonContent,
    IonCard,IonCardHeader,IonItem,IonAvatar,IonCardTitle,IonCardSubtitle,IonCardContent,
    IonButton,IonIcon,IonItem,IonInput,IonList,IonLabel,FormsModule,CommonModule
    ],
})
export class PostPageComponent  implements OnInit {
  post: any;
  liked: boolean = false;
  newComment: string = '';
  comments: { username: string; text: string }[] = [];
  postId: any;

  constructor(private router: Router,private route: ActivatedRoute,private postService: PostService) {}

  ngOnInit() {
    // this.loadDaata();
    // console.log(this.post);
     // 使用 route.params 订阅参数变化
      // 获取动态 ID
      this.route.params.subscribe(params => {
        const postId = Number(params['id']); // 获取动态 ID
        if (!isNaN(postId)) {
          this.post = this.postService.getPostById(postId); // 根据 ID 获取动态内容
        } else {
          console.error('Invalid post ID');
        }
      });
  
      // 这里可以添加逻辑来根据 postId 更新页面内容

    

    // const postId = Number(this.route.snapshot.paramMap.get('id')); // 获取动态 ID
    // 根据 ID 获取动态内容
    
     
  }
  // ngDoCheck(){
  //   this.loadDaata();
  //   console.log(this.post);
  // }
  // async loadDaata(){
  //   const navigation = this.router.getCurrentNavigation();
  //   if (navigation && navigation.extras && navigation.extras.state) {
  //     const state = navigation.extras.state;
  //     console.log(state['postId']); // 访问传递的对象数据
  //     const postId=state['postId']
  //     this.post =await this.postService.getPostById(postId);
  //      if (postId !== null) {
  //     this.post =await this.postService.getPostById(postId); // 根据 ID 获取动态内容
  //   } else {
  //     console.error('Invalid post ID'); // 处理无效的 ID
  //   }
  //   }

  // }

  likePost() {
    this.liked = !this.liked;
  }

  addComment() {
    if (this.newComment.trim()) {
      const newCommentObj = {
        username: '当前用户', // 可以替换为实际的用户名
        text: this.newComment,
      };
      this.comments.push(newCommentObj);
      this.newComment = ''; // 清空输入框
    }
  }

}
