import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-tab2',
  templateUrl: './tab2.page.html',
  styleUrls: ['./tab2.page.scss'],
})
export class Tab2Page implements OnInit, OnDestroy {
  messages: any[] = [];
  userInput: string = '';
  isLoading: boolean = false;
  isSocketOpen: boolean;
  userId: number | null = null;

  constructor(private http: HttpClient, private userService: UserService) {
    this.isSocketOpen = false;
  }

  ngOnInit() {
    this.sendMessageFromAI(this.getRandomWelcomeMessage());
    this.userService.getUserInfo().subscribe(
      userInfo => {
        console.log('User Info:', userInfo);
        if (userInfo && userInfo.id !== undefined) {
          console.log('User ID:', userInfo.id);
          this.userId = userInfo.id;
        } else {
          console.warn('No valid user info received');
          this.sendMessageFromAI('无法获取有效的用户ID，请稍后再试');
        }
      },
      error => {
        console.error('Failed to get user info:', error);
        this.sendMessageFromAI('系统遇到错误，请稍后再试');
      }
    );
  }

  ngOnDestroy() {
    // 如果有其他资源需要清理，这里可以添加相应的代码
  }

  getRandomWelcomeMessage(): string {
    const welcomeMessages = [
      '我是您的AI医生小爱，有什么可以帮到您的吗？',
      '今天天气不错，可以出去散步哦。',
      '您好！我是您的健康助手，有什么我可以帮助您的吗？',
      '很高兴见到您！请告诉我您需要什么帮助。',
      '欢迎您！请问有什么健康方面的问题需要咨询吗？'
    ];
    return welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];
  }

  async sendMessage() {
    const trimmedInput = this.userInput.trim();
    if (!trimmedInput) {
      alert('请输入您的问题或消息');
      return;
    }

    this.messages.push({ text: trimmedInput, sender: 'user' });
    this.isLoading = true;
    this.userInput = '';

    try {
      if (!this.userId) {
        throw new Error('无法获取有效的用户ID');
      }

      // 添加提示词
      const promptPrefix = "你是个医生，回答病人的请求：";
      const fullQuestion = `${promptPrefix}${trimmedInput}`;

      // 使用 try-catch 包装 HTTP 请求
      try {
        const response = await this.http.get<string>(`${environment.apiUrl}/test/sendQuestion`, {
          params: { id: this.userId.toString(), question: fullQuestion },
          responseType: 'text' as 'json' // 指定响应类型为文本
        }).toPromise();

        if (response) {
          this.sendMessageFromAI(response);
        } else {
          this.sendMessageFromAI('收到空回复，请尝试重新提问');
        }
      } catch (httpError) {
        console.error('HTTP请求失败:', httpError);
        this.sendMessageFromAI('网络请求失败，请检查网络连接或稍后再试');
      }
    } catch (error) {
      console.error('发送消息时发生错误:', error);
      this.sendMessageFromAI('系统遇到错误，请稍后再试');
    } finally {
      this.isLoading = false;
    }
  }

  private sendMessageFromAI(content: string) {
    this.messages.push({ text: content, sender: 'ai' });
  }
}