import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CharacterService } from '../services/character.service';
import { Character } from '../services/character.service';
import { IonBackButton, IonButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, 
  IonCardTitle, IonContent, IonHeader, IonTitle, IonToolbar, ModalController } from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { ChatPanelOptions, FmodeChat, openChatPanelModal } from 'fmode-ng';

@Component({
  selector: 'app-character-detail',
  templateUrl: './character-detail.component.html',
  styleUrls: ['./character-detail.component.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonBackButton, IonButtons,
    IonCardHeader, IonCardTitle, IonCardSubtitle, IonCardContent, CommonModule, IonButton]
})
export class CharacterDetailComponent implements OnInit {
  character!: Character;
  characterNotFound: boolean = false;
  

  constructor(private route: ActivatedRoute, private characterService: CharacterService, private router: Router, private modalCtrl: ModalController) {}

  ngOnInit() {
    const characterId = this.route.snapshot.paramMap.get('id');
    if (characterId) {
      this.characterService.getCharacterById(characterId).subscribe(character => {
        if (character) {
          this.character = character;
          this.characterNotFound = false;
        } else {
          this.characterNotFound = true;
          console.error('角色未找到');
        }
      });
    }
  }

  startChat() {
    const chatOptions: ChatPanelOptions = {
      roleId: "2DXJkRsjXK",
      onChatInit: (chat: FmodeChat) => {
        // 设置智能体的名字为角色名称
        chat.role.set("name", this.character.name);
        
        // 决赛设定
        chat.role.set("prompt", `你的名字是${this.character.name},你将作为${this.character.name}和用户聊天，
          你的性别是${this.character.gender},你有着${this.character.appearance}外貌，你的性格是${this.character.personality},
          请你在聊天过程中,按照你的人物设定和用户进行对话,并且当你准备好了时,请开始聊天`);
        
        // 设置角色的外貌特征和性格特点
        chat.role.set("appearance", this.character.appearance); 
        chat.role.set("personality", this.character.personality);
        
        // 设置角色头像
        chat.role.set("avatar", this.character.avatar);
      },
      onChatSaved: (chat: FmodeChat) => {
        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id);
      },
    };
    openChatPanelModal(this.modalCtrl, chatOptions);
  }

    restoreChat(chatId:string){
      let options:ChatPanelOptions = {
        roleId:"2DXJkRsjXK",
        chatId:chatId
      }
      openChatPanelModal(this.modalCtrl,options)
    }

}