import { Component, LOCALE_ID } from '@angular/core';
import { IonCardHeader, IonHeader, IonToolbar, IonTitle, IonContent, IonTabButton, IonSearchbar, IonLabel, IonItem, IonList, NavController, IonCard, IonCardTitle, IonCardSubtitle, IonCardContent, IonThumbnail, IonRippleEffect, IonFab, IonFabList, IonFabButton, IonBadge, IonAvatar } 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 { documentText, chatbubbles, person, calendar, newspaper,
   medkit,clipboard, podium, videocam, people, chevronForwardOutline, 
   add} from 'ionicons/icons';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { ChatPanelOptions, FmodeChat, FmodeChatMessage, openChatPanelModal } from 'fmode-ng';
addIcons({ documentText, chatbubbles, person, calendar, newspaper,
   medkit,clipboard, podium, videocam, people,add
 });
 import { FmodeMapModule } from 'fmode-ng';
 addIcons({chevronForwardOutline});
 
interface ClinicAd {
  id: number;
  title: string;
  price?: string;
  description: string;
  image: string;
  backgroundColor: string;
}

interface ServiceItem {
  id: number;
  title: string;
  description: string;
  image: string;
  hasDetail?: boolean;
  isHot?: boolean;
  backgroundColor?: string;
  size?: 'large' | 'small';
}
@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent,IonTabButton, IonButton,
    IonIcon,IonSearchbar,IonLabel,IonItem,IonList,CommonModule,IonCard,IonCardHeader,IonCardTitle,IonCardSubtitle,
    IonCardContent, IonThumbnail, IonRippleEffect, IonFab, IonFabButton, IonFabList,IonBadge, IonAvatar
  
  ],
})
export class Tab1Page {

  goToPageUser(){
    this.router.navigate(['tabs/user']);
  }
  goToPageDoctor(){
    console.log('goToPageDoctor');
  }
  goToPageDrug(){

  }
  adminList : Array<CloudObject> = [];
  userList : Array<CloudObject> = [];
  title1 = "特色服务";
  subtitle1 = "一站式医疗健康解决方案";
  async loadUserData() {
    const query = new CloudQuery('Doctor');
    query.include('user')
    this.userList = await query.find();

  }

  services: ServiceItem[] = [
    {
      id: 1,
      title: "援脑妇科病",
      description: "小症状隐藏大隐患",
      image: "../../assets/image/doctor7.png",
      hasDetail: true,
      backgroundColor: "#E8F5F2",
      size: 'large'
    },
    {
      id: 2,
      title: "解决口腔难题",
      description: "享健康生活",
      image: "../../assets/image/doctor7.png",
      hasDetail: true,
      isHot: true,
      backgroundColor: "#E8F5F2",
      size: 'large'
    },
    {
      id: 3,
      title: "解决皮肤难题",
      description: "专业医生来助力",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    },
    {
      id: 4,
      title: "儿科常见疾病",
      description: "在家就能请专家",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    },
    {
      id: 5,
      title: "赶走烦恼困扰",
      description: "科学治疗好经不费",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    },
    {
      id: 6,
      title: "知己心理",
      description: "温暖地陪你懂自己",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    },
    {
      id: 7,
      title: "搞定偏头痛",
      description: "止疼彻底合集",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    },
    {
      id: 8,
      title: "搞定偏头痛",
      description: "止疼彻底合集",
      image: "../../assets/image/doctor7.png",
      size: 'small'
    }
  ];
  title = "专科门诊";
  subtitle = "智养高复诊率、高口碑名医";
  
  clinicAds: ClinicAd[] = [
    {
      id: 1,
      title: "专业男科",
      price: "18元起",
      description: "阳痿早泄",
      image: "../../assets/image/doctor7.png",
      backgroundColor: "#EEF4FF"
    },
    {
      id: 2,
      title: "智养中医馆",
      price: "18元起",
      description: "口碑中医",
      image: "../../assets/image/doctor6.png",
      backgroundColor: "#FFF5EB"
    }
  ];
  realDoctorList: Array<CloudObject> = []
  constructor(
    private router: Router,
    private modalCtrl: ModalController,
    private http: HttpClient // 注入 HttpClient
  ) {
    this.loadRealDoctorList();
    this.currentUser = new CloudUser();
    }
    currentUser: CloudUser;
    async loadRealDoctorList() {
      let query = new CloudQuery('Doctor1');
      query.include('user')
      query.include('depart')
      this.realDoctorList =await query.find()
      for(let i = 0; i < this.realDoctorList.length; i++){
        if(this.realDoctorList[i].data["user"]?.objectId == this.currentUser.id){
          console.log("欢迎您，医生！")
        }
      }
      console.log(this.currentUser)
  }
 /**
  * 轮播图
  */
  images = [
    'https://picsum.photos/800/400?random=1',
    'https://picsum.photos/800/400?random=2',
    'https://picsum.photos/800/400?random=3',
    'https://picsum.photos/800/400?random=4',
    'https://picsum.photos/800/400?random=5',
    'https://picsum.photos/800/400?random=6',
  ];
  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);
    }
  }

  goToPage1(){
    let user = new CloudUser;
    console.log(['route'])
    if (!user.id){
      this.router.navigate(['/tabs/tab4'])
      return
    }
    this.router.navigate(['/tabs/inquiry/ai'])
  }
  goToPage2(){
    let user = new CloudUser;
    console.log(['route'])
    if (!user.id){
      this.router.navigate(['/tabs/tab4'])
      return
    }
    this.router.navigate(['/tabs/inquiry/human'])
  }

  // 功能按钮数据
  functionItems1 = [
    { label: '专属医生', icon: 'document-text', route: '/tabs/create-agent' },
    { label: '我的健康', icon: 'person', route: '/tabs/my-health' },
    { label: '药品展示', icon: 'calendar', route: '/tabs/tab3' },
    { label: '健康科普', icon: 'medkit', route: '/tabs/tab2' },
  ];


  // 导航到指定路由
  navigateTo(route: string) {
    let user = new CloudUser;
    if (!user.id){
      this.router.navigate(['/tabs/tab4'])
      return
    }
    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")
    let List = await query.find()
    for(let i = 0; i < 3; i++) {
      this.doctorList.push(List[i])
    }
  }
  
   /** 示例：问诊根据doctor拼接提示词 */
   async openInquiry(doctor:any){
    let user = new CloudUser;
    console.log(['route'])
    if (!user.id){
      this.router.navigate(['/tabs/tab4'])
      return
    }
    // 验证用户登录
    let userPrompt = ``
    if(!user?.id){
      console.log("用户未登录，请登录后重试");
      // let user = await openUserLoginModal(this.modalCtrl);
      // if(!user?.id){
      //   return
      // }
      // currentUser = user;
      this.router.navigate(['/tabs/tab4'])
      return 
    }
    console.log("currentUser: ",user)
    if(user?.get("realname")){
      userPrompt += `当前来访的患者，姓名：${user?.get("realname")}`
    }
    if(user?.get("gender")){
      userPrompt += `，性别：${user?.get("gender")}`
    }
    if(user?.get("age")){
      userPrompt += `，年龄：${user?.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}
    }
    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:this.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("system","你是一名计算机老师，请根据用户提问，给出专业、简洁、准确的答案");
              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){
            let list = chat?.messageList
            console.log("门诊已完成")
            consult.set({
              allContent:list,
              content:content,
            })
            consult.save();
          }
        }
      },
      onChatSaved:(chat:FmodeChat)=>{
        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
      }
    }
    openChatPanelModal(this.modalCtrl,options)
  }

}

