import { Component, OnInit } from '@angular/core';
import { AlertController, NavController } from '@ionic/angular';
import * as Parse from 'parse';

interface ChatHistoryItem {
  chatId: number;
  username: string;
  userChatOrder: number;
  userChat: string;
  aiChat: string;
}

@Component({
  selector: 'app-chatpage',
  templateUrl: './chatpage.page.html',
  styleUrls: ['./chatpage.page.scss'],
})
export class ChatpagePage implements OnInit {
  chatHistory: ChatHistoryItem[] = [];
  username: string = ''; // 用户名
  load: boolean | undefined;

  constructor(private navCtrl: NavController, private alertController: AlertController) {}

  ngOnInit() {}

  ionViewDidEnter() {
    this.loadUserData();
    this.loadChatHistory();
  }

  async loadUserData() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      this.username = currentUser.getUsername()!;
    } else {
      this.username = '未登录';
    }
    console.log("tab-history:" + this.username);
    this.CheckUser();
  }

  async CheckUser() {
    if (this.username == '未登录') {
      this.load = false;
      this.presentLoginAlert();
      return;
    } else {
      this.load = true;
    }
  }

  async presentLoginAlert() {
    const alert = await this.alertController.create({
      header: '未登录',
      message: '请先登录以继续操作',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '去登录',
          handler: () => {
            this.navCtrl.navigateForward('/user/login');
          }
        }
      ]
    });
    await alert.present();
  }

  async loadChatHistory() {
    try {
      const Chat = Parse.Object.extend('ai_chat');
      const query = new Parse.Query(Chat);
      query.equalTo('username', this.username); // 只获取当前用户名的聊天记录
      query.select('chatId', 'username', 'userChatOrder', 'userChat', 'aiChat');
      query.descending('createdAt');
      const results = await query.find();

      const groupedChats: { [key: number]: ChatHistoryItem } = results.reduce(
        (acc: { [key: number]: ChatHistoryItem }, chat: any) => {
          const chatId = chat.get('chatId');
          if (!acc[chatId]) {
            acc[chatId] = {
              chatId,
              username: chat.get('username'),
              userChatOrder: chat.get('userChatOrder'),
              userChat: chat.get('userChat'),
              aiChat: chat.get('aiChat'),
            };
          }
          return acc;
        },
        {}
      );

      this.chatHistory = Object.values(groupedChats).map(chat => {
        const firstMessage = results.find(
          item => item.get('chatId') === chat.chatId && item.get('userChatOrder') === 1
        );
        return {
          chatId: chat.chatId,
          username: firstMessage?.get('username') || chat.username,
          userChatOrder: firstMessage?.get('userChatOrder') || chat.userChatOrder,
          userChat: firstMessage?.get('userChat') || chat.userChat,
          aiChat: firstMessage?.get('aiChat') || chat.aiChat,
        };
      });

    } catch (error) {
      console.error('Error loading chat history:', error);
    }
  }

  goToChat(chatId: number) {
    this.navCtrl.navigateForward(`/tabs/chat`, {
      queryParams: { chatId: chatId.toString() },
    });
  }

  async startNewChat() {
    this.loadUserData();
    if (this.load) {
      const Chat = Parse.Object.extend('ai_chat');
      const query = new Parse.Query(Chat);
      query.descending('chatId');
      query.equalTo('username', this.username); // 确保chatId生成基于当前用户的历史记录
      const latestChat = await query.first();
      const newChatId = latestChat ? latestChat.get('chatId') + 1 : 1;

      this.navCtrl.navigateForward(`/tabs/chat`, {
        queryParams: { chatId: newChatId.toString() },
      });
    }
  }
}
