import { Component,OnInit } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonButton,IonIcon, ModalController, IonTextarea, IonInput, IonCard, IonCardHeader, IonCardTitle, IonThumbnail, IonCardContent, IonCardSubtitle, IonItem, IonList, IonLabel, IonAvatar, IonCol, IonRow, IonGrid, IonBadge, IonFooter, IonSegment, IonSegmentButton, IonBackButton } from '@ionic/angular/standalone';
import { AgentTaskStep } from 'src/agent/agent.task';
import { addIcons } from 'ionicons';
import { radioButtonOffOutline, reloadOutline, checkmarkCircleOutline, closeCircleOutline } from 'ionicons/icons';
import { TaskExecutor } from 'src/agent/agent.start';
import { AgentUserInputComponent } from 'src/agent/agent-user-input/agent-user-input.component';
import { FmodeChatCompletion, ImagineWork, DalleOptions, openChatPanelModal, FmodeChat, FmodeChatMessage, ChatPanelOptions } from "fmode-ng";
import { TaskPoemPictureDesc } from 'src/agent/tasks/poem/poem-desc';
import { TaskPoemPictureCreate } from 'src/agent/tasks/poem/poem-picture';
import { CommonModule, DecimalPipe } from '@angular/common';
import { TaskInqueryUserStory } from 'src/agent/tasks/inquiry/1.inquiry-user-story';
import { extactAndParseJsonFromString } from 'src/agent/agent.json';
import { TaskInqueryDoctorQuestion } from 'src/agent/tasks/inquiry/2.inquiry-doctor-question';
import { TaskInqueryUserAnswer } from 'src/agent/tasks/inquiry/3.inquiry-user-answer';
import { Router } from '@angular/router';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { FormsModule } from '@angular/forms';
addIcons({radioButtonOffOutline,reloadOutline,checkmarkCircleOutline,closeCircleOutline})

interface Doctor1 {
  id: number;
  name: string;
  title: string;
  department: string;
  hospital: string;
  hospitalLevel: string;
  hospitalType: string;
  avatar: string;
}

@Component({
  selector: 'page-inquiry',
  templateUrl: './page-inquiry.component.html',
  styleUrls: ['./page-inquiry.component.scss'],
  standalone: true,
  imports: [
    IonBackButton,
    IonHeader, 
    IonToolbar,
     IonTitle, 
     IonContent, 
     IonButton,
     IonTextarea,
     IonInput,
    IonIcon,
    AgentUserInputComponent,
    DecimalPipe,
    IonCard,
    IonCardHeader,
    IonCardTitle,
    IonCardSubtitle,
    IonCardContent, 
    IonThumbnail, 
    IonItem,
    IonList,
    CommonModule,
    IonLabel,
    IonAvatar,
    FormsModule,
    IonCol,
    IonRow,
    IonGrid,
    IonBadge,
    IonFooter,
    IonSegment,
    IonSegmentButton,
  ],
})

export class PageInquiryComponent  implements OnInit {
  selectedSegment:string = '全部';
  segments = ['全部', '妇产科', '儿科', '皮肤性病科', '内科', '外科', '眼科', '耳鼻喉科', '神经科', '康复科', '中医药科'];
  segmentChanged(event: any) {
    this.selectedSegment = event.detail.value;
    console.log(this.selectedSegment);
    this.loadDoctorList();
  }

  createAI(){
    this.router.navigate(['/tabs/create-agent']);
    console.log("createAI")
  }

  ngOnInit(){
    this.loadDoctorList();
  }

  doctorList:Array<CloudObject> = []
  async loadDoctorList(){
    let query = new CloudQuery("Doctor");
    query.include("depart")
    if (this.selectedSegment != '全部'){
      query.equalTo("specialty",this.selectedSegment )
    }
    this.doctorList = await query.find()
    console.log(this.doctorList)
  }
  currentUser: CloudUser 
  constructor(
    private modalCtrl:ModalController,
    private router:Router
  ) {
    this.currentUser = new CloudUser;
    console.log(this.currentUser)
  }

  back:string = "<";

  backhome() {
    this.router.navigate(['/tabs/tab1']);
  }

  taskList:AgentTaskStep[] = []

  wait(duration:number=1000){
    return new Promise(resolve=>{
      setTimeout(() => {
          resolve(true)
      }, duration);
    })
  }

  shareData:any = {}


  doInqueryTask(){
    let task1 = TaskInqueryUserStory({shareData:this.shareData,modalCtrl:this.modalCtrl});
    let task2 = TaskInqueryDoctorQuestion({shareData:this.shareData,modalCtrl:this.modalCtrl});
    let task3 = TaskInqueryUserAnswer({shareData:this.shareData,modalCtrl:this.modalCtrl});

    // 定义任务集
    let InquireServiceTaskList = [
      task1,task2,task3
    ]
    // 传递给显示组件
    this.taskList = InquireServiceTaskList
    // 开始执行任务
    TaskExecutor(InquireServiceTaskList)
  }

  //  http://localhost:4200/
  // 用户输入提示词
  // keshi:string = ""
  // keshiInput(ev:any){
  //   this.keshi = ev.detail.value;
  // }
  // // 用户输入提示词
  // userPrompt:string = ""
  // promptInput(ev:any){
  //   this.userPrompt = ev.detail.value;
  // }

  // // 属性：组件内用于展示消息内容的变量
  // responseMsg:any = ""
  // // 方法：实例化completion对象，传入消息数组，并订阅生成的可观察对象。
  // isComplete:boolean = false; // 定义完成状态属性，用来标记是否补全完成
  // sendMessage(){
  //   console.log("create")

  //   let PromptTemplate = `
  //   您作为一名专业的${this.keshi}医生，请您根据用户描述的症状，给出初步的诊断，并给出一些建议。
  //   以下是用户的口述：${this.userPrompt}
  //   `

  //   let completion = new FmodeChatCompletion([
  //     {role:"system",content:""},
  //     {role:"user",content:PromptTemplate}
  //   ])

  //   completion.sendCompletion().subscribe((message:any)=>{
  //     // 打印消息体
  //     console.log(message.content)
      
  //     // 赋值消息内容给组件内属性
  //     this.responseMsg = message.content
  //     if(message.complete){ // 判断message为完成状态，则设置isComplete为完成
  //       this.isComplete = true
  //     }
  //   })
  // }

  /** 示例：问诊根据doctor拼接提示词 */
     async openInquiry(doctor:CloudObject){
      // 验证用户登录
      let currentUser = new CloudUser();
      let userPrompt = ``
      if(!currentUser?.id){
        console.log("用户未登录，请登录后重试");
        this.router.navigate(['/tabs/tab4']);
        return
        // let user = await openUserLoginModal(this.modalCtrl);
        // if(!user?.id){
        //   this.router.navigate(['/tabs/tab4']);
        //   return
        // }
        // currentUser = user;
      }
      
      if(currentUser?.get("realname")){
        userPrompt += `当前来访的患者，姓名：${currentUser?.get("realname")}`
      }
      if(currentUser?.get("gender")){
        userPrompt += `，性别：${currentUser?.get("gender")}`
      }
      if(currentUser?.get("age")){
        userPrompt += `，年龄：${currentUser?.get("age")}`
      }
  
  
      localStorage.setItem("company","E4KpGvTEto")
  
      let consult = new CloudObject("Consultation")
      let now = new Date();
      let dateStr = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`
      // 对象权限的精确指定
      let ACL:any = {
        "*":{read:true,write:true}
      }
      if(currentUser?.id){
        ACL[currentUser?.id] = {read:true,write:true}
      }
      consult.set({
        title:`${doctor.get('depart')?.name || ""}门诊记录${dateStr}-${doctor?.get("name")}`,
        doctor:doctor.toPointer(),
        depart:{
          __type:"Pointer",
          className:"Department",
          objectId:doctor.get("depart")?.objectId
        },
        user:currentUser.toPointer(),
        ACL:ACL
      })
  
      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/doctor7.png")
                chat.role.set("prompt",`
# 角色设定
您是${doctor?.get("name")}，${doctor?.get("desc")}，年龄${doctor?.get("age")}岁，需要完成一次完整的门诊服务。
  
# 对话环节
0.直接和用户打招呼（如：你好，XXX，我是···）
- 注意：如果用户问的问题和你的${doctor?.get("specialty")}的不符，请直接引导用户去其他的科室
1.预设的问询方式（根据不同症状来问询具体的情况），如果用户和
- 打招呼，以用户自述为主
- 当信息充足时候，确认用户症状对应的科室，并进入下一个环节
2.拓展的问询细节
例如：用户反映呼吸不畅，拓展出：是否咳嗽；是否感觉痛或者痒等其他需要的问题。
- 当问询细节补充完成后进入下一个环节
3.初步的诊断结果，并且同时列出检查检验项目
初步诊断：确定需要有哪些进一步检查
检查检验：获取医学客观数据
- 等待用户提交客观数据，进入下一阶段
4.给出诊断方案并给出处方
- 完成处方时，请在消息结尾附带: [处方完成]
  
# 开始话语
当您准备好了，可以以一个医生的身份，向来访的用户打招呼。
  ${userPrompt}
  `);
        },
        onMessage:(chat:FmodeChat,message:FmodeChatMessage)=>{
          console.log("onMessage",message)
          let content:any = message?.content
          if(typeof content == "string"){
            if(content?.indexOf("[处方完成]")>-1){
              console.log("门诊已完成")
              let list = chat?.messageList
              console.log("门诊已完成")
              consult.set({
                allContent:list,
                content:content // 处方内容
              })
              consult.save();
            }
          }
        },
        onChatSaved:(chat:FmodeChat)=>{
          // chat?.chatSession?.id 本次会话的 chatId
          console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
        }
      }
      openChatPanelModal(this.modalCtrl,options)
    }

    doctors1: Doctor1[] = [
      {
        id: 1,
        name: '张晨芙',
        title: '主任医师',
        department: '小儿重症...',
        hospital: '浙江大学医学院附属...',
        hospitalLevel: '三甲',
        hospitalType: '百强医院',
        avatar: 'assets/doctor1.jpg'
      },
      {
        id: 2,
        name: '时若',
        title: '副主任医师',
        department: '皮肤科',
        hospital: '空军军医大学西京医院',
        hospitalLevel: '三甲',
        hospitalType: '百强医院',
        avatar: 'assets/doctor2.jpg'
      },
      {
        id: 3,
        name: '李洁',
        title: '主治医师',
        department: '儿科',
        hospital: '北京大学人民医院',
        hospitalLevel: '三甲',
        hospitalType: '百强医院',
        avatar: 'assets/doctor3.jpg'
      },
      {
        id: 4,
        name: '马凤富',
        title: '主治医师',
        department: '肛肠科',
        hospital: '中日友好医院',
        hospitalLevel: '三甲',
        hospitalType: '百强医院',
        avatar: 'assets/doctor4.jpg'
      }
    ];
}
