import { Component,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent } from '@ionic/angular/standalone';
import { IonButton, IonCard, IonCardContent, IonCardHeader, IonCardTitle, IonItem, IonLabel,IonList,IonIcon } from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { ChatPanelOptions, FmodeChat, FmodeChatMessage, openChatPanelModal } from 'fmode-ng';
import { ModalController } from '@ionic/angular/standalone';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { CustomerServiceComponent } from '../customer-service/customer-service.component';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonContent,
    IonCard,IonCardHeader,IonCardTitle,IonCardContent,
    IonItem,IonLabel,
    IonButton,IonList,IonIcon,
    CommonModule
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class Tab2Page {

  isModalOpen: boolean = false; // 定义 isModalOpen 属性
  placeholderText: string = '';
  placeholderIndex: number = 0;
  placeholders: string[] = ['智能陪聊', '普通聊天', '小贴心建议'];
  cyclePlaceholder() {
    setInterval(() => {
      this.placeholderText = this.placeholders[this.placeholderIndex];
      this.placeholderIndex = (this.placeholderIndex + 1) % this.placeholders.length;
    }, 2000); // 每2秒切换一次
  }
  async openCustomerService() {
    const modal = await this.modalCtrl.create({
      component: CustomerServiceComponent,
      breakpoints: [0.3, 0.4],
      initialBreakpoint: 0.3,
    });
    return await modal.present();
  }
  private consult: any; // 这里定义你的 consult 对象
  private modalCtrl: ModalController;
  constructor(private router: Router,modalCtrl: ModalController) {
    this.modalCtrl = modalCtrl;
    // 其他构造函数代码
    this.cyclePlaceholder();
  }
  matchedCounselor: { name: string; specialty: string } | null = null;
  async clickToConsult(chatpartner: CloudObject) {
      await this.initChat(chatpartner, true);
  }

  async goChat(chatcompanion: CloudObject) {
      await this.initChat(chatcompanion, false);
  }

  private async initChat(partner: CloudObject, isConsult: boolean) {
      // 验证用户登录
      let currentUser = new CloudUser();
      let userPrompt = ``;
      if (!currentUser?.id) {
          console.log("用户未登录，请登录后重试");
          let user = await openUserLoginModal(this.modalCtrl);
          if (!user?.id) {
              return;
          }
      }
    if (currentUser?.get("username")) {
        userPrompt += `当前来访的用户，姓名：${currentUser?.get("username")}`;
    }
    if (currentUser?.get("gender")) {
        userPrompt += `，性别：${currentUser?.get("gender")}`;
    }
    if (currentUser?.get("age")) {
        userPrompt += `，年龄：${currentUser?.get("age")}`;
    }
    
    // 弹窗形式聊天：开始聊天
    localStorage.setItem("company", "E4KpGvTEto");
    // 创建聊天记录对象
    let consult = new CloudObject("ChatRecord");
    // 设置聊天记录的基本信息
    let now = new Date();
    let dateStr = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
    // 对象权限的精确制定
    let ACL: any = {
        "*": { read: true, write: true }
    };
    consult.set({
        title: `${partner.get('expertise') || ""}领域聊天记录${dateStr}-${partner.get('name')}`,
        [isConsult ? 'chatpartner' : 'chatcompanion']: partner.toPointer(),
        user: currentUser.toPointer(),
        content: [], // 初始内容为空
        createdAt: now, // 可以加上创建时间
        ACL: ACL
    });
    let options: ChatPanelOptions = {
        roleId: "2DXJkRsjXK",
        onChatInit: (chat: FmodeChat) => {
            console.log("onChatInit");
            console.log("预设角色", chat.role);
            chat.role.set("name", partner.get("name"));
            chat.role.set("bio", partner.get("bio"));
            chat.role.set("expertise", partner.get("expertise"));
            chat.role.set("avatar", partner.get("avatar") || "/assets/img/2.png"); // 设置聊天伙伴头像
            chat.role.set("prompt", `
            # 角色设定
            您是${partner.get("name")}，一位${partner.get("bio")}的聊天伙伴，需要为用户提供陪伴和支持等积极情绪。
            # 开始话语
            当您准备好了，可以以一个关心用户的朋友的身份，向来访的用户打招呼
            # 对话环节
            耐心与用户聊天，给人一种暖心陪伴的感觉
            ${userPrompt}
            `);
        },
        onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
            console.log("onMessage", message);
            let content: any = message?.content;
            // 更新 consult 对象的内容
            consult.set({
                content: chat.messageList, // 存储用户消息
            });
            // 仅在内容发生变化时保存
            consult.save();
        },
        onChatSaved: (chat: FmodeChat) => {
            console.log("onChatSaved", chat, chat?.chatSession, chat?.chatSession?.id);
        }
    };
    openChatPanelModal(this.modalCtrl, options);
}

  questions = [
    {
      title: '如何应对焦虑？',
      advice: '尝试深呼吸和正念冥想，保持规律的作息，健康饮食，设定小目标，培养兴趣爱好，适当锻炼。',
      expanded: false,
    },
    {
      title: '如何提高自信心？',
      advice: '设定小目标并逐步实现，进行积极自我对话，培养技能，保持健康的生活方式，多与他人社交。',
      expanded: false,
    },
    {
      title: '如何改善人际关系？',
      advice: '积极多与他人沟通，倾听对方的感受，理解他人的感受，多参加社交活动，保持积极的态度，尊重他人。',
      expanded: false,
    },
  ];
  ngOnInit() {
    this.loadChatPartnerList(),
    this.loadChatCompanionList()
  }
  chatpartnerList:Array<CloudObject>=[]
  async loadChatPartnerList(){
    let query = new CloudQuery("ChatPartner");
    this.chatpartnerList = await query.find()
  }
  chatcompanionList:Array<CloudObject>=[]
  async loadChatCompanionList(){
    let query = new CloudQuery("ChatCompanion");
    this.chatcompanionList = await query.find()
  }

}