import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { 
  IonHeader, IonToolbar, IonTitle, IonContent, 
  IonButton, IonButtons, IonIcon, IonCard, IonCardHeader, IonCardTitle, IonCardContent,
  IonItem, IonLabel, IonList, IonInput, IonTextarea, IonAvatar, IonSearchbar,
  ModalController,
  IonSegment,} from '@ionic/angular/standalone';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
import { CommonModule } from '@angular/common';
import { openPostPublisherModal } from 'src/lib/public/post-publisher/post-publisher.component';
import { CloudObject, CloudPost, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { openPostCommentModal } from 'src/lib/public/post-comment/post-comment.component';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,
  imports: [
    CommonModule,
    IonHeader, IonToolbar, IonTitle, IonContent, ExploreContainerComponent,
 
    IonButton, IonButtons, IonIcon,IonSegment,FormsModule,

    IonCard, IonCardHeader, IonCardTitle, IonCardContent,
    IonList, IonItem, IonLabel, IonAvatar, IonInput, IonTextarea,IonSearchbar
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA], 
})
export class Tab1Page {
  currentUser:CloudUser|undefined
  post:CloudPost|undefined
  filmpostList: Array<CloudObject> = []; // 创建用于数据列表存储的属性
  private contentStates: { [key: string]: boolean } = {}; // 存储帖子内容展开/收起状态
  selectedPostId: string | undefined; // 新增属性，用于存储当前选中帖子的 ID
  avatarUrl: string = 'assets/img/random.png'; // 默认头像路径
  labelCount: Record<string, number> = {}; // 存储标签及其数量
  hasLiked: boolean = false; // 用户是否已点赞

  constructor(private modalCtrl:ModalController){
    this.currentUser=new CloudUser();
    this.post=new CloudPost();
  }


    ngOnInit() {
      // 生命周期：页面加载后，运行帖子列表，加载函数
      this.loadFilmPostList()
     
    }


    // 查询并加载列表的函数
    async loadFilmPostList(){
    let query = new CloudQuery("FilmPost"); 
    query.include('author');
    this.filmpostList = await query.find();
    console.log(this.filmpostList);
      // 初始化内容状态
    this.filmpostList.forEach(post => {
      this.contentStates[post?.id?.toString() || ''] = true; 
    });
    this.calculateLabelCount(); // 在构造函数中计算标签数量
    }
    
     //话题热度
    calculateLabelCount() {
      this.filmpostList.forEach(post => {
        const label = post.get?.('label');
        console.log(label);
        if (this.labelCount[label]) {
          this.labelCount[label]++;
        } else {
          this.labelCount[label] = 1;
        }
      });
      console.log(this.labelCount);
    }
    

async openPublishModal(){

  if(!this.currentUser?.id){
    await  openUserLoginModal(this.modalCtrl);
  }
if(this.currentUser?.id){
  await  openPostPublisherModal(this.modalCtrl);
}

}
 // 切换帖子内容展开/收起状态的函数
 toggleContent(post: CloudObject) {
  const postId = post?.id?.toString() || '';
  this.contentStates[postId] = !this.contentStates[postId];
}

  // 显示帖子完整内容的函数
  showFullContent(post: CloudObject): string {
    const content = post?.get('content') as string;
    const postId = post.id?.toString() || '';
    return this.contentStates[postId] ? `${content.slice(0, 200)}` :content ;
  }
 
  // 判断帖子内容是否已折叠的函数
  isContentCollapsed(post: CloudObject): boolean {
    const postId = post.id?.toString() || '';
    return this.contentStates[postId];
  }
 


  // 检查用户是否已点赞
  async checkIfLiked() {
    this.hasLiked = this.post?.data["likedBy"].includes(this.currentUser); // 检查当前用户是否在点赞数组中
  }

  // 点赞帖子
  async likePost() {
   
  }

 async commentPost(postId: string) {
    // 评论逻辑
this.selectedPostId = postId; // 更新选中帖子的 ID
await openPostCommentModal(this.modalCtrl, this.selectedPostId);
  
  }
  onSearch(event: any) {
        const searchTerm = event.target.value; // 获取用户输入的搜索内容
        console.log('搜索内容:', searchTerm);
        // 在这里添加搜索逻辑，例如过滤列表或导航到搜索结果页面
      }

  
}
