import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';  /* 新增ViewChild */
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-ai-agent',
  templateUrl: './ai-agent.page.html',
  styleUrls: ['./ai-agent.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class AiAgentPage implements OnInit {
  // 新增角色预设
  aiAssistant = {
    name: "邻小助",
    title: "生活全能助手",
    description: "邻小助，您贴心的生活管家，擅长解决各类日常生活中的疑难杂症",
    tags: ["生活咨询", "问题解答", "实用技巧"],
    greeting: "您好！我是邻小助，有什么生活上的问题都可以问我哦~"
  };

  userInput: string = '';
  conversation: { role: 'user' | 'assistant'; content: string; time: Date }[] = [];  /* 新增time字段 */
  @ViewChild('conversationContainer') conversationContainer!: ElementRef;  /* 获取消息容器引用 */
  currentAssistantResponse: string = ''; // 用于存储当前助手的流式响应

  async sendMessage() {
    if (!this.userInput.trim()) return;

    // 添加用户消息（包含时间戳）
    const currentTime = new Date();
    this.conversation.push({ 
      role: 'user', 
      content: this.userInput, 
      time: currentTime 
    });
    this.userInput = '';
    this.scrollToBottom();

    // 重置当前助手响应
    this.currentAssistantResponse = '';

    // 初始化助手消息（不再包含欢迎语）
    const assistantMessage: { role: 'user' | 'assistant'; content: string; time: Date } = {
      role: 'assistant',
      content: '', // 初始为空内容
      time: new Date()
    };
    this.conversation.push(assistantMessage);

    try {
      // 请替换为正确的 DeepSeek API 地址和模型名称
      const response = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // 修改授权头部格式，添加 Bearer 前缀
          'Authorization': `Bearer sk-433e23f9bfcc4d6989987a177e33dfad`
        },
        body: JSON.stringify({
          // 请替换为 DeepSeek 支持的模型名称
          model: 'deepseek-chat', 
          messages: this.conversation.map(msg => ({
            role: msg.role,
            content: msg.content
          })),
          stream: true // 开启流式输出
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API 请求失败，状态码: ${response.status}, 错误信息: ${errorText}`);
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder('utf-8');

      if (reader) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n').filter(line => line.trim() !== '');

          for (const line of lines) {
            const data = line.replace(/^data: /, '');
            if (data === '[DONE]') break;

            try {
              const jsonData = JSON.parse(data);
              if (jsonData.choices?.[0]?.delta?.content) {
                this.currentAssistantResponse += jsonData.choices[0].delta.content;
                assistantMessage.content = this.currentAssistantResponse;
                this.scrollToBottom();
              }
            } catch (parseError) {
              console.error('解析流式数据时出错:', parseError);
            }
          }
        }
      }
    } catch (error) {
      console.error('大模型请求失败:', error);
      assistantMessage.content = '抱歉，当前无法为您提供服务。';
    }
  }

  // 自动滚动到聊天底部
  private scrollToBottom(): void {
    setTimeout(() => {
      const container = this.conversationContainer.nativeElement;
      container.scrollTop = container.scrollHeight;
    }, 100);  /* 延迟确保DOM更新完成 */
  }

  ngOnInit() {
    // 页面加载时自动添加助手问候语
    this.conversation.push({
      role: 'assistant',
      content: this.aiAssistant.greeting,
      time: new Date()
    });
  }
}
