import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { IonSearchbar } from '@ionic/angular/standalone';
import { IonButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardTitle, IonContent, IonFooter, IonHeader, IonIcon, IonInput, IonItem, IonLabel, IonList, IonTitle, IonToolbar, NavController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { chevronBackSharp, closeCircleOutline, ellipsisHorizontal, happyOutline, micCircleOutline, paperPlane, sendOutline } from 'ionicons/icons';
import { CloudQuery, CloudUser } from 'src/lib/ncloud';

addIcons({ chevronBackSharp, ellipsisHorizontal, micCircleOutline, happyOutline, paperPlane, closeCircleOutline, sendOutline });

@Component({
  selector: 'app-chat-history',
  templateUrl: './chat-history.component.html',
  styleUrls: ['./chat-history.component.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, IonList, IonItem, IonLabel, CommonModule, IonCard, IonCardHeader, IonCardTitle,
    IonButton, IonCardContent, IonIcon, IonButtons, IonInput, IonFooter, IonInput, CommonModule, IonSearchbar, FormsModule],
})
export class ChatHistoryComponent implements OnInit {

  chatHistories: any[] = []; // 存储聊天记录
  currentUser: any;
  constructor(private router: Router, private navCtrl: NavController) { }
  async ngOnInit() {
    await this.loadChatHistories(); // 加载聊天记录
    this.filteredChatHistories = this.chatHistories; // 初始化过滤后的聊天记录为所有聊天记录
  }

  async loadChatHistories() {
    const user = new CloudUser();
    const currentUser = await user.current(); // 获取当前用户信息

    if (currentUser) {
      this.currentUser = currentUser;
      const query = new CloudQuery("ChatHistory");
      query.equalTo("user", currentUser.toPointer()); // 查询当前用户的聊天记录
      this.chatHistories = await query.find(); // 获取聊天记录
      // 解析聊天内容并提取每条聊天记录的第一条消息
      this.chatHistories.forEach(chat => {
        if (chat.data.content) {
          chat.parsedContent = JSON.parse(chat.data.content); // 解析内容

          chat.firstMessage = chat.parsedContent[0] ? chat.parsedContent[0].text : ''; // 获取第一条消息
          //console.log("hhh", this.chatHistories);
        }
      });
      // 按 createdAt 排序，最近的在前面
      this.chatHistories.sort((a, b) => {
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
      });
      //console.log("聊天记录已加载", this.chatHistories);
    } else {
      console.error("用户未登录，无法加载聊天记录");
    }
    console.log("聊天记录已加载", this.chatHistories);
  }


  // 选择聊天记录
  selectChatHistory(chat: any) {
    this.router.navigate(['chatcontent'], { state: { chat: chat } });
  }

  goBack() {

    this.navCtrl.back(); // 返回上一页

  }


  searchDate: string = ''; // 搜索日期
  filteredChatHistories: any[] = []; // 存储过滤后的聊天记录

  // 过滤聊天记录
  filterChatHistories() {
    // 检查用户输入的日期是否有效
    if (!this.searchDate || this.searchDate.length < 10) {
      // 如果没有输入完整的日期，显示所有聊天记录
      this.filteredChatHistories = this.chatHistories;
      return;
    }
    // 解析用户输入的日期
    const parsedDate = new Date(this.searchDate);

    // 获取输入日期的开始和结束时间戳
    const startOfDay = new Date(parsedDate.setHours(0, 0, 0, 0)).getTime(); // 2024-12-24 00:00:00
    const endOfDay = new Date(parsedDate.setHours(23, 59, 59, 999)).getTime(); // 2024-12-24 23:59:59

    console.log("开始时间戳：", startOfDay);
    console.log("结束时间戳：", endOfDay);

    // 过滤聊天记录，只保留在指定日期范围内的记录
    this.filteredChatHistories = this.chatHistories.filter(chat => {
      const chatTimestamp = new Date(chat.createdAt).getTime(); // 聊天记录的时间戳
      console.log("聊天记录时间戳：", chatTimestamp);

      return chatTimestamp >= startOfDay && chatTimestamp <= endOfDay; // 只保留在范围内的聊天记录
    });
  }

}
