import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { 
  IonItem,IonButton, IonButtons, IonContent, IonHeader, IonLabel, IonCard,
  IonList, IonTitle, IonToolbar, NavController, IonIcon, ModalController } from '@ionic/angular/standalone';
import { close } from 'ionicons/icons';
import { addIcons } from 'ionicons';
import { CloudObject, CloudUser, CloudQuery } from 'src/lib/ncloud';
import { Router } from '@angular/router';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';

interface DialogueItem {
  role: string;
  content: string;
  createdAt?: string;
}

@Component({
  selector: 'app-history',
  templateUrl: './history.page.html',
  styleUrls: ['./history.page.scss'],
  standalone: true,
  imports: [
    IonContent, IonHeader, IonTitle, IonCard, CommonModule, FormsModule,
    IonToolbar,IonLabel,IonButton,IonButtons,IonList,IonItem,IonIcon,
  ]
})
export class HistoryPage implements OnInit {

  constructor(
    private navCtrl: NavController,
    private modalCtrl:ModalController,
    private router: Router) {
    addIcons( {close})
   }
 
   closeHistory() {
     this.navCtrl.back();
   }

   currentUser = new CloudUser();
   async relogin()
   {
     let user = await openUserLoginModal(this.modalCtrl);
     if(user?.id){
       this.currentUser = user
     }
     if(!user?.id){
       return
     }
   }

   chatList: Array<CloudObject> = [];
   showDetails: boolean[] = []; // 用于跟踪每个聊天记录的详细信息是否显示

   async ChatList() {
    const currentUser = new CloudUser();
    await currentUser.current(); // 确保用户信息已加载
    const userId = currentUser.id; // 获取当前用户的 ObjectId
  
    // 声明并初始化 query 变量
    const query = new CloudQuery("FilmChat");
    query.equalTo("user", currentUser.toPointer()); // 只获取当前用户的记录
    
    // 获取聊天记录
    this.chatList = await query.find();
  
    // 处理聊天记录，移除第一条 user 内容
    this.chatList.forEach(chat => {
      const dialogueArray = chat.get('dialogue');
      if (dialogueArray && dialogueArray.length > 0) {
        const userIndex = dialogueArray.findIndex((item: DialogueItem) => item.role === 'user');
        if (userIndex !== -1) {
          dialogueArray.splice(userIndex, 1); // 移除第一条 user 内容
        }
      }
    });
        // 初始化显示状态
        this.showDetails = new Array(this.chatList.length).fill(false);
  }
  toggleChatDetails(index: number) {
    this.showDetails[index] = !this.showDetails[index]; // 切换显示状态
  }

  async ngOnInit() {
    await this.ChatList(); // 只调用一次 ChatList 方法
    console.log(this.chatList); // 调试输出
  }

}
