import { Component } from '@angular/core';
import { 
  IonHeader, IonToolbar, IonTitle, 
  IonContent, IonButton, IonSpinner, 
  IonInput
} from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms';
import axios from 'axios';
// 导入 CommonModule
import { CommonModule } from '@angular/common';

interface ChatMessage {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
}

interface ChatRole {
  id: string;
  name: string;
  title: string;
  desc: string;
  avatar?: string;
  prompt: string;
}

@Component({
  selector: 'app-tab3',
  templateUrl: './tab3.page.html',
  styleUrls: ['./tab3.page.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle,
    IonContent, IonButton, IonSpinner,
    IonInput, FormsModule,
    // 添加 CommonModule 到 imports 数组
    CommonModule
  ]
})
export class Tab3Page {
  private readonly DEEPSEEK_API_KEY = 'sk-433e23f9bfcc4d6989987a177e33dfad';
  private readonly DEEPSEEK_API_URL = 'https://api.deepseek.com/chat/completions';

  messages: ChatMessage[] = [
    {
      id: '1',
      content: '你好！我是AI健身教练，请问有什么可以帮您？',
      sender: 'ai',
      timestamp: new Date(),
      
    }
  ];
  userInput = '';
  isLoading = false;
  
  activeSession = {
    role: {
      avatar: 'assets/ai-avatar.png'
    }
  };

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

    // 添加用户消息
    this.messages.push({
      id: Date.now().toString(),
      content: this.userInput,
      sender: 'user',
      timestamp: new Date()
    });

    this.isLoading = true;
    const currentInput = this.userInput;
    this.userInput = '';

    try {
      // 使用默认导入的 axios
      const response = await axios.post(this.DEEPSEEK_API_URL, {
        model: 'deepseek-chat',
        messages: [
          {
            role: 'system',
            content: '你是一名专业的健身教练，提供科学、安全的健身建议。'
          },
          {
            role: 'user',
            content: currentInput
          }
        ],
        temperature: 0.7,
        max_tokens: 1000
      }, {
        headers: {
          'Authorization': `Bearer ${this.DEEPSEEK_API_KEY}`,
          'Content-Type': 'application/json'
        }
      });

      // 添加 AI 回复
      const aiResponse = response.data.choices[0]?.message?.content || '无法生成回答';
      this.messages.push({
        id: Date.now().toString(),
        content: aiResponse,
        sender: 'ai',
        timestamp: new Date()
      });

    } catch (error) {
      console.error('API调用失败:', error);
      this.messages.push({
        id: 'error-' + Date.now(),
        content: '抱歉，服务暂时不可用',
        sender: 'ai',
        timestamp: new Date()
      });
    } finally {
      this.isLoading = false;
    }
  }

  startNewSession() {
    this.messages = [
      {
        id: '1',
        content: '你好！我是AI健身教练，请问有什么可以帮您？',
        sender: 'ai',
        timestamp: new Date()
      }
    ];
  }

  testQuickQuestion() {
    this.userInput = '如何在一个月内安全减脂？';
    this.sendMessage();
  }
}