import { CloudUser } from './../lib/ncloud';
import { FmodeChat, FmodeChatMessage, openChatPanelModal, ChatPanelOptions } from 'fmode-ng';
import { Component } from '@angular/core';
import { IonCardHeader, IonHeader, IonToolbar, IonTitle, IonContent,  IonItem, IonList, IonCard, IonCardTitle, IonCardSubtitle, IonCardContent, IonThumbnail, IonFab, IonFabButton, } from '@ionic/angular/standalone';
import { IonButton } from '@ionic/angular/standalone';
import { IonIcon } from '@ionic/angular/standalone';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ModalController } from '@ionic/angular/standalone';
import { HttpClient } from '@angular/common/http';
import { addIcons } from 'ionicons';
import { add } from 'ionicons/icons';
import { documentText, chatbubbles, person, calendar, newspaper,
   medkit,clipboard, podium, videocam, people } from 'ionicons/icons';
import { CloudObject, CloudQuery } from '../lib/ncloud';
import { IonRefresher, IonRefresherContent } from '@ionic/angular/standalone';
addIcons({ documentText, chatbubbles, person, calendar, newspaper,
   medkit,clipboard, podium, videocam, people
 });
@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent, IonButton,
    IonIcon,IonItem,IonList,CommonModule,IonCard,IonCardHeader,IonCardTitle,IonCardSubtitle,
    IonCardContent, IonThumbnail, IonFab,IonFabButton,IonIcon,IonRefresher,IonRefresherContent

  ],
})
export class Tab1Page {
  
  handleRefresh(event:any) {
    setTimeout(() => {
      // Any calls to load data go here
      this.loadDoctorList()
      event.target.complete();
    }, 2000);
  }
  admin:string = 'nRDdxdEn2k'
  user : CloudUser 
  doctorList1: Array<CloudObject> = []
  async loadAllagent(){
    let query = new CloudQuery("NovelCharacter")
    query.include("user")
    this.doctorList1=await query.find()
    console.log("doctor.get('user').username",this.doctorList1[0].get("username"))
  }
  constructor(
    private router: Router,
     private modalCtrl: ModalController,
    // private navCtrl: NavController,
    private http: HttpClient// 注入 HttpClient,

  ) {
    this.user = new CloudUser();
    this.loadAllagent();
    addIcons({ add });
  }
  navigateToPage() {
    this.router.navigate(['../agent-create']); // 替换为目标页面的路由
  }
  /**
   * Go to the ai page
   */

  // 导航到指定路由
  navigateTo(route: string) {
    this.router.navigate([route]);
    console.log("route: ",route)
  }

  ngOnInit() {
    this.loadDoctorList()
  }
  doctorList:Array<CloudObject> = []
  async loadDoctorList(){
    let user = new CloudUser();
    let query = new CloudQuery("NovelCharacter");
    query.equalTo("user",user?.id)
    console.log("user",user.id)
    this.doctorList = await query.find()
  }

  
   /** 示例：问诊根据doctor拼接提示词 */
   openInquiry(doctor:CloudObject){
    console.log("doctor",doctor)
    localStorage.setItem("company","E4KpGvTEto")

    let consult = new CloudObject("NovelCharacter")
    let now = new Date();
    let dateStr = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`
    consult.set({
      title:`${doctor.get('depart')?.name || ""}门诊记录${dateStr}-${doctor?.get("name")}`,
      doctor:doctor.toPointer(),
      depart:doctor.get("depart")
    })

    let options:ChatPanelOptions = {
      roleId:"2DXJkRsjXK",
      onChatInit:(chat:FmodeChat)=>{
        console.log("onChatInit");
              console.log("预设角色",chat.role);
              chat.role.set("name",doctor?.get("name"));
              chat.role.set("title",doctor?.get("title"));
              chat.role.set("desc",doctor?.get("desc"));
              chat.role.set("tags",doctor?.get("qualifications"));
              chat.role.set("avatar",doctor?.get("avatar") || "../../assets/image/doctor5.png")
              chat.role.set("prompt",`
# 角色设定
您是${doctor?.get("desc")}，${doctor?.get("name")}，年龄${doctor?.get("age")}岁，需要完成一次完整的门诊服务。

# 对话环节
0.导诊（根据用户基本情况，引导挂号合适的科室）
1.预设的问询方式（根据不同症状来问询具体的情况）
- 打招呼，以用户自述为主
- 当信息充足时候，确认用户症状对应的科室，并进入下一个环节
2.拓展的问询细节
例如：用户反映呼吸不畅，拓展出：是否咳嗽；是否感觉痛或者痒等其他需要的问题。
- 当问询细节补充完成后进入下一个环节
3.初步的诊断结果，并且同时列出检查检验项目
初步诊断：确定需要有哪些进一步检查
检查检验：获取医学客观数据
- 等待用户提交客观数据，进入下一阶段
4.给出诊断方案并给出处方
- 完成处方时，请在消息结尾附带: [处方完成]

# 开始话语
当您准备好了，可以以一个医生的身份，向来访的用户打招呼。`);
      },
      onMessage:(chat:FmodeChat,message:FmodeChatMessage)=>{
        console.log("onMessage",message)
        let content:any = message?.content
        if(typeof content == "string"){
          if(content?.indexOf("[处方完成]")>-1){
            console.log("门诊已完成")
            consult.set({
              content:content // 处方内容
            })
            consult.save();
          }
        }
      },
      onChatSaved:(chat:FmodeChat)=>{
        // chat?.chatSession?.id 本次会话的 chatId
        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
      }
    }
    openChatPanelModal(this.modalCtrl,options)
  }
  deleteAgent(agent:CloudObject){
    console.log("删除了",agent);
    agent.destroy();
    this.loadDoctorList()
  }
}