import { Component } from '@angular/core';
import { IonCardHeader, IonHeader, IonToolbar, IonTitle, IonContent, IonTabButton, IonSearchbar, IonLabel, IonItem, IonList, NavController, IonCard, IonCardTitle, IonCardSubtitle, IonCardContent, IonThumbnail } from '@ionic/angular/standalone';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
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 { documentText, chatbubbles, person, calendar, newspaper,
   medkit,clipboard, podium, videocam, people } from 'ionicons/icons';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { ChatPanelOptions, FmodeChat, FmodeChatMessage, openChatPanelModal } from 'fmode-ng';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { ArticleCardComponent } from '../component/article-card/article-card.component';
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, ExploreContainerComponent, IonTabButton, IonButton,
    IonIcon,IonSearchbar,IonLabel,IonItem,IonList,CommonModule,IonCard,IonCardHeader,IonCardTitle,IonCardSubtitle,
    IonCardContent, IonThumbnail, 
  ],
})
export class Tab1Page {

  constructor(
    private router: Router,
    private modalCtrl: ModalController,
    // private navCtrl: NavController,
    private http: HttpClient // 注入 HttpClient
  ) {}

 /**
  * 轮播图
  */
  images = [
    'https://picsum.photos/800/400?random=1',
    'https://picsum.photos/800/400?random=2',
    'https://picsum.photos/800/400?random=3'
  ];
  currentSlide = 0;
  intervalId: any;
  setSlidePosition() {
    // 这里不需要额外的逻辑，因为在 HTML 中已经通过绑定实现
  }

  nextSlide() {
    this.currentSlide = (this.currentSlide + 1) % this.images.length;
  }

  prevSlide() {
    this.currentSlide = (this.currentSlide - 1 + this.images.length) % this.images.length;
  }

  goToSlide(index: number) {
    this.currentSlide = index;
  }

  startAutoSlide() {
    this.intervalId = setInterval(() => this.nextSlide(), 3000);
  }
  ngOnDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }


  /**
   * Go to the ai page
   */
  goToPage1(){
    console.log(['route'])
    this.router.navigate(['/tabs/inquiry/ai'])
  }

  /**
   * Go to the human page
   */
  goToPage2(){
    this.router.navigate(['/tabs/inquiry/human'])
  }

  goToPicture(){
    console.log(['route'])
    this.router.navigate(['/tabs/picture'])
  }
  searchContent:string = ''; //搜索内容

  handleInput(ev:any) {
    console.log("ev.detail.value: ",ev.detail.value)
    this.searchContent = ev.detail.value;
  }

  search(){
    if (this.searchContent == ''){
      console.log("请输入搜索内容")
    }
    else {
      console.log("搜索内容: ",this.searchContent)
      this.searchContent = '';
    }
  }

  // 功能按钮数据
  functionItems1 = [
    { label: '我的健康', icon: 'document-text', route: '/tabs/my-health' },
    { label: '健康档案', icon: 'person', route: '/tabs/health-records' },
    { label: '电话问诊', icon: 'calendar', route: '/tabs/phone-inquiry' },
    { label: '购买药品', icon: 'medkit', route: '/tabs/drug-purchase' },
  ];

  functionItems2 = [
    { label: '专业男科', icon: 'clipboard', route: '/tabs/tab1' },
    { label: '权威专家', icon: 'podium', route: '/tabs/authority-experts' },
    { label: '健康资讯', icon: 'newspaper', route: '/tabs/health-information' },
    { label: '智慧社区', icon: 'people', route: '/tabs/smart-community' }
  ];

  doctors = [
    {
      name: '余海涛',
      age: 20,
      position: '主任医师',
      department: '中医草药科',
      hospital: '南昌市江西师范医院',
      desc:'中医大师，擅长用中药调养身体来根治病症',
      image: '../../assets/image/doctor5.png',
    },
    {
      name: '聂翼伏',
      age: 25,
      position: '副主任医师',
      department: '骨科',
      hospital: 'YY市人民医院',
      desc:'骨科专家，擅长治疗各种骨骼损伤症状',
      image: '../../assets/image/doctor7.png',
    },
    {
      name: '徐君豪',
      age: 28,
      position: '主治医师',
      department: '心理科',
      hospital: 'XX市第一医院',
      desc:'心理专家，擅长解决各类心理问题和疾病',
      image: '../../assets/image/doctor6.png',
    },
  ];

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

  ngOnInit() {
    this.loadDoctorList()
    this.startAutoSlide();
  }

  doctorList:Array<CloudObject> = []
  async loadDoctorList(){
    let query = new CloudQuery("Doctor");
    query.include("depart")
    this.doctorList = await query.find()
  }


   /** 示例：问诊根据doctor拼接提示词 */
   async openInquiry(doctor:any){
    // 验证用户登录
    let currentUser = new CloudUser();
    let userPrompt = ``
    if(!currentUser?.id){
      console.log("用户未登录，请登录后重试");
      let user = await openUserLoginModal(this.modalCtrl);
      if(!user?.id){
        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:false,write:false}
    }
    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.导诊（根据用户基本情况，引导挂号合适的科室）
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("门诊已完成")
            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)
  }
}
