import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular/standalone';
import { ChatPanelOptions, FmChatModalInput, FmodeChat, FmodeChatMessage, openChatPanelModal } from 'fmode-ng';
import Parse from "parse";
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { 
  IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardContent, 
  IonCardTitle, IonCardSubtitle, IonChip, IonIcon, IonButton, IonFooter,
  IonList, IonListHeader, IonItem, IonLabel, IonAvatar, IonGrid, IonRow, IonCol
} from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { 
  restaurant, leaf, flask, calendar, school, library, tv, chatbubbles, 
  time, personCircle, chevronForward, refresh, colorWandOutline
} from 'ionicons/icons';

/**
 * 营养咨询Tab页面组件
 * @Component 装饰器定义组件元数据
 * @description 提供营养咨询功能，包含智能对话和咨询记录管理
 */
@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: false,
})
export class Tab2Page {

  /**
   * 构造函数
   * @param {ModalController} modalCtrl Ionic模态控制器
   * 
   * @description 
   * 初始化时添加所需图标
   */
  constructor(
    private modalCtrl: ModalController
  ) {
    addIcons({
      restaurant, leaf, flask, calendar, school,
      library, tv, chatbubbles, time, personCircle,
      chevronForward, refresh, colorWandOutline
    });
  }

  /**
   * 咨询记录列表
   * @type {Array<CloudObject>}
   */
  consultList: Array<CloudObject> = [];

  /**
   * 打开营养咨询对话框
   * @param {string} [chatId] 可选，会话ID（用于恢复历史会话）
   * @returns {void}
   * 
   * @description
   * 初始化并打开智能营养咨询对话框，配置对话角色和交互逻辑
   */
  openConsult(chatId?: string): void {
    localStorage.setItem("company", "E4KpGvTEto");
    let options: ChatPanelOptions = {
      roleId: "2DXJkRsjXK", // 预设角色ID
      chatId: chatId, // 可选，会话ID

      /**
       * 对话初始化回调
       * @param {FmodeChat} chat 聊天实例
       */
      onChatInit: (chat: FmodeChat) => {
        console.log("onChatInit");
        
        // 配置角色属性
        chat.role.set("name", "林舒窈");
        chat.role.set("title", "东方食养家");
        chat.role.set("desc", "谈吐带有中医师的沉稳，擅长用生活化比喻解释复杂理论，林舒窈，年龄26岁");
        chat.role.set("tags", ['跑步', '动感单车']);
        chat.role.set("avatar", "/assets/lin.jpg");
        chat.role.set("prompt", `...角色详细提示词...`);

        // 配置对话分类
        let promptCates = [
          { img: "/assets/icon/yy.jpg", name: "营养" },
          { img: "/assets/icon/rl.jpg", name: "热量" },
          { img: "/assets/icon/aq.jpg", name: "安全" }
        ];
        
        setTimeout(() => {
          chat.role.set("promptCates", promptCates);
        }, 500);

        // 配置对话提示列表
        let promptList = [
          {
            cate: "营养", img: "/assets/icon/yy.jpg",
            messageList: [
              "如何在不减少食物种类的情况下保证营养均衡？",
              // ...其他提示问题
            ]
          },
          // ...其他分类
        ];

        let ChatPrompt = Parse.Object.extend("ChatPrompt");
        setTimeout(() => {
          chat.promptList = promptList.map(item => {
            let prompt = new ChatPrompt();
            prompt.set(item);
            prompt.img = item.img;
            return prompt;
          });
        }, 500);

        // 配置左侧功能按钮
        chat.leftButtons = [
          {
            title: "话题灵感",
            showTitle: true,
            icon: "color-wand-outline",
            onClick: () => { chat.isPromptModalOpen = true },
            show: () => { return chat?.promptList?.length }
          },
        ];
      },

      /**
       * 消息接收回调
       * @param {FmodeChat} chat 聊天实例
       * @param {FmodeChatMessage} message 接收到的消息
       */
      onMessage: (chat: FmodeChat, message: FmodeChatMessage) => {
        console.log("onMessage", message);
        let content: any = message?.content;
        if (typeof content == "string") {
          // 根据消息内容处理不同阶段
          if (content.includes('[导诊完成]')) {
            console.log('进入问诊环节');
          } 
          // ...其他阶段处理
        }
      },

      /**
       * 聊天保存回调
       * @async
       * @param {FmodeChat} chat 聊天实例
       * @returns {Promise<void>}
       */
      onChatSaved: async (chat: FmodeChat) => {
        console.log("onChatSaved", chat);
        let chatId = chat?.chatSession?.id;
        let query = new CloudQuery("NutritionConsult");
        let nutritionConsult = await query.get(chatId);
        
        if (!nutritionConsult?.id) {
          nutritionConsult = new CloudObject("NutritionConsult"); 
        }
        
        nutritionConsult.set({
          "chatId": chatId,
          "messageList": chat.messageList,
          "name": chat.role.get("name"),
          "avatar": chat.role.get("avatar"),
        });
        
        nutritionConsult.save();
      }
    };
    
    openChatPanelModal(this.modalCtrl, options);
  }

  /**
   * 加载咨询记录
   * @async
   * @returns {Promise<void>}
   */
  async loadConsult(): Promise<void> {
    let query = new CloudQuery("NutritionConsult");
    this.consultList = await query.find();
    console.log("咨询记录", this.consultList);
  }
}