import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as Parse from 'parse';
import { TestChatCompletion, TestChatMessage } from './class-chat-completion';
import { ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.page.html',
  styleUrls: ['./chat.page.scss'],
})
export class ChatPage implements OnInit {
  chatId: number | null = null;
  messageList: Array<TestChatMessage> = [];
  userInput: string = '';
  username: string = ''; // 用户名
  completion: TestChatCompletion;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private cd: ChangeDetectorRef // 注入ChangeDetectorRef
  ) {
    this.completion = new TestChatCompletion(this.messageList);
  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      if (params['chatId']) {
        this.chatId = +params['chatId'];
        this.loadChatHistory(this.chatId);
      } else {
        this.chatId = null;
        this.messageList = [];
      }
    });
  }

  ionViewDidEnter() {
    //检测登录状况
    this.loadUserData();
  }

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

  async loadChatHistory(chatId: number | null) {
    if (!chatId) return;

    const Chat = Parse.Object.extend('ai_chat');
    const query = new Parse.Query(Chat);
    query.equalTo('chatId', chatId);
    query.ascending('userChatOrder');

    try {
      const results = await query.find();
      this.messageList = results.flatMap(chat => [
        { role: 'user', content: chat.get('userChat') },
        { role: 'assistant', content: chat.get('aiChat') }
      ]).filter(message => message.content); // 过滤掉内容为空的消息
      this.cd.detectChanges(); // 触发变更检测
    } catch (error) {
      console.error('Error loading chat history:', error);
    }
  }

  async sendMessage() {
    const userMessage: TestChatMessage = {
      role: 'user',
      content: this.userInput
    };
    this.messageList.push(userMessage);
    this.userInput = '';

    this.cd.detectChanges(); // 触发变更检测

    // 调用AI接口处理消息
    const aiMessage = await this.completion.createCompletionByStream(userMessage);

    if (this.chatId !== null) {
      await this.saveMessagesToDatabase(userMessage, aiMessage);
    }

    this.messageList.push(aiMessage);
    this.cd.detectChanges(); // 触发变更检测
  }

  async saveMessagesToDatabase(userMessage: TestChatMessage, aiMessage: TestChatMessage) {
    if (this.chatId === null) return;

    const Chat = Parse.Object.extend('ai_chat');
    const chat = new Chat();

    chat.set('username', this.username); // 设置用户名
    chat.set('chatId', this.chatId); // 设置chatId

    // 查询最后一个userChatOrder以确定此消息的新顺序
    const lastMessage = await this.getLastMessageInChat(this.chatId);
    let userChatOrder = 1; // 如果是对话的第一条消息，则默认为1
    if (lastMessage) {
      userChatOrder = lastMessage.get('userChatOrder') + 1;
    }
    chat.set('userChatOrder', userChatOrder); // 设置userChatOrder

    chat.set('userChat', userMessage.content); // 设置userChat
    chat.set('aiChat', aiMessage.content); // 设置aiChat

    try {
      await chat.save();
    } catch (error) {
      console.error('Error saving message:', error);
    }
  }

  async getLastMessageInChat(chatId: number): Promise<Parse.Object | undefined> {
    const Chat = Parse.Object.extend('ai_chat');
    const query = new Parse.Query(Chat);
    query.equalTo('chatId', chatId);
    query.descending('userChatOrder');
    query.limit(1); // 限制为1条结果以获取最后一条消息

    try {
      const result = await query.first();
      return result; // 返回最后一条消息对象，如果找不到则返回undefined
    } catch (error) {
      console.error('Error getting last message:', error);
      return undefined;
    }
  }
}
