bookcoach.component.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { IonicModule } from '@ionic/angular';
  4. import { FormsModule } from '@angular/forms';
  5. interface ChatMessage {
  6. content: string;
  7. isUser: boolean;
  8. time: Date;
  9. }
  10. @Component({
  11. selector: 'app-bookcoach',
  12. templateUrl: './bookcoach.component.html',
  13. styleUrls: ['./bookcoach.component.scss'],
  14. standalone: true,
  15. imports: [CommonModule, IonicModule, FormsModule]
  16. })
  17. export class BookcoachComponent implements OnInit {
  18. @ViewChild('chatContainer') private chatContainer!: ElementRef;
  19. @ViewChild('messageInput') private messageInput!: ElementRef;
  20. messages: ChatMessage[] = [];
  21. newMessage: string = '';
  22. isTyping: boolean = false;
  23. showSuggestions: boolean = true;
  24. suggestions: string[] = [
  25. '如何提高投篮命中率?',
  26. '篮球基础训练有哪些?',
  27. '怎样提升防守能力?',
  28. '篮球战术布置技巧'
  29. ];
  30. constructor() { }
  31. ngOnInit() {
  32. // 可以添加初始欢迎消息
  33. }
  34. sendMessage() {
  35. if (this.newMessage.trim()) {
  36. // 添加用户消息
  37. this.messages.push({
  38. content: this.newMessage,
  39. isUser: true,
  40. time: new Date()
  41. });
  42. // 清空输入框
  43. const userMessage = this.newMessage;
  44. this.newMessage = '';
  45. // 显示AI正在输入
  46. this.isTyping = true;
  47. this.showSuggestions = false;
  48. // 模拟AI回复
  49. setTimeout(() => {
  50. this.isTyping = false;
  51. this.messages.push({
  52. content: this.getAIResponse(userMessage),
  53. isUser: false,
  54. time: new Date()
  55. });
  56. this.scrollToBottom();
  57. }, 1500);
  58. this.scrollToBottom();
  59. }
  60. }
  61. selectSuggestion(suggestion: string) {
  62. this.newMessage = suggestion;
  63. this.sendMessage();
  64. }
  65. private scrollToBottom() {
  66. setTimeout(() => {
  67. if (this.chatContainer) {
  68. const element = this.chatContainer.nativeElement;
  69. element.scrollTop = element.scrollHeight;
  70. }
  71. });
  72. }
  73. private getAIResponse(message: string): string {
  74. // 这里可以实现实际的AI响应逻辑
  75. const responses = [
  76. '这是一个很好的问题!让我为您详细解答...',
  77. '根据我的经验,您可以尝试以下方法...',
  78. '这个问题涉及到几个关键点,首先...',
  79. '作为教练,我建议您可以这样做...'
  80. ];
  81. return responses[Math.floor(Math.random() * responses.length)];
  82. }
  83. }