import { Component, OnInit } from '@angular/core';
import{ChatPanelOptions,FmChatModalInput,FmodeChat,FmodeChatMessage,openChatPanelModal}from 'fmode-ng';
import Parse from "parse";
import{ModalController}from '@ionic/angular/standalone';
import {  CloudUser, CloudQuery  } from 'src/lib/ncloud';
import { importTestData } from 'src/lib/import.data';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})
export class Tab1Page implements OnInit{
  healthData = {
    bloodGlucose: [] as any[],
    bloodPressure: [] as any[],
    heartRate: [] as any[],
    loading: true
  };
  constructor(
    private modalCtrl:ModalController
  ){}

  async ngOnInit() {
    await this.loadHealthData();
  }
  // 加载健康数据
  // 在 tab1.page.ts 中更新以下方法

async loadHealthData() {
  try {
    this.healthData.loading = true;
    
    const user = new CloudUser();
    const currentUser = await user.current();
    
    if (!currentUser?.id) {
      console.warn('未获取到当前用户');
      return;
    }

    console.log('当前用户ID:', currentUser.id);

    // 查询最近30天数据
    const timeAgo = new Date();
    timeAgo.setDate(timeAgo.getDate() - 30);

    const [glucose, pressure, heartRate] = await Promise.all([
      this.queryData('BloodGlucose', currentUser, timeAgo),
      this.queryData('BloodPressure', currentUser, timeAgo),
      this.queryData('HeartRate', currentUser, timeAgo)
    ]);

    this.healthData = {
      bloodGlucose: glucose,
      bloodPressure: pressure,
      heartRate: heartRate,
      loading: false
    };
  } catch (error) {
    console.error('加载失败:', error);
    this.healthData.loading = false;
  }
}

private async queryData(className: string, user: CloudUser, date: Date): Promise<any[]> {
  const query = new CloudQuery(className);
  query.equalTo('patient', {
    __type: 'Pointer',
    className: '_User',
    objectId: user.id
  });
  query.greaterThan('measurementTime', date);
  query.ascending('measurementTime');
  return await query.find();
}

async importData() {
  try {
    this.healthData = {
      bloodGlucose: [],
      bloodPressure: [],
      heartRate: [],
      loading: true
    };
    
    await importTestData();
    await new Promise(resolve => setTimeout(resolve, 1000));
    await this.loadHealthData();
  } catch (error) {
    console.error('导入失败:', error);
  }
}
  // 刷新数据
  async doRefresh(event: any) {
    await this.loadHealthData();
    setTimeout(() => {
      event.target.complete();
    }, 1000);
  }
  
openConsult(chatId?:string){
    localStorage.setItem("company","E4KpGvTEto")
    let options:ChatPanelOptions = {
      roleId:"2DXJkRsjXK",
      //chatId:chatId,//若存在则恢复对话，不存在则开启新对话1
      onChatInit:(chat:FmodeChat)=>{
        console.log("onChatInit");
        console.log("预设角色",chat.role);
        // 角色名称
        chat.role.set("name","丁德文");
        // 角色称号
        chat.role.set("title","慢性病医生");
        // 角色描述
        chat.role.set("desc","一名亲切和蔼的慢性病医生，丁德文，年龄46岁");
        // 角色标签
        chat.role.set("tags",["内科","初诊"]);
        // 角色头像
        chat.role.set("avatar","/assets/images/0.jpg")
        // 角色提示词
        chat.role.set("prompt",`
# 角色设定
您是一名亲切和蔼的专业的慢性病医生，丁德文，年龄46岁，需要完成一次完整且专业的慢性病问诊服务。

# 对话环节
0.导诊（根据用户基本情况，匹配对应的慢性病病症）
1.预设的问询方式
- 打招呼，以用户自述为主
- 当信息充足时候，确认用户症状慢性病病症，并进入下一个环节
2.拓展的问询细节
例如：用户反映呼吸不畅，拓展出：是否咳嗽；是否感觉痛或者痒等其他需要的问题。
- 当问询细节补充完成后进入下一个环节
3.初步的诊断结果，并且同时列出检查检验项目
初步诊断：确定需要有哪些进一步检查
检查检验：获取医学客观数据
- 等待用户提交客观数据，进入下一阶段
4.给出诊断方案并给出处方
- 完成处方时，请在消息结尾附带: [完成]

# 开始话语
当您准备好了，可以以一个医生的身份，向来访的用户打招呼。`);
        // 对话灵感分类
        let promptCates = [
          {
            "img": "/assets/icon/tnb.jpeg",
            "name": "糖尿病"
          },
          {
            "img": "/assets/icon/gxy.jpeg",
            "name": "高血压"
          },
          {
            "img": "/assets/icon/gxb.jpeg",
            "name": "冠心病"
          }
        ]
        setTimeout(() => {
          chat.role.set("promptCates",promptCates)
        }, 500);
        // 对话灵感列表
        let promptList = [
          {
            cate:"糖尿病",img:"/assets/icon/tnb.jpeg",
            messageList:["异常口渴（多饮","尿频且尿量增多","体重短期内明显下降","饥饿感强烈（多食）","伤口愈合缓慢","皮肤干燥瘙痒","手脚麻木或刺痛感（周围神经病变）"]
          },
          {
            cate:"高血压",img:"/assets/icon/gxy.jpeg",
            messageList:["持续性头痛（尤其后脑勺部位）","经常性头晕或眩晕","视物模糊（短暂性）","耳鸣（如嗡嗡声）","心悸或心律不齐","疲劳感明显（即使休息后）","夜间多尿或起夜频繁"]
          },
          {
            cate:"冠心病",img:"/assets/icon/gxb.jpeg",
            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", // 标题icon图标
           onClick:()=>{ // 按钮点击事件
               chat.isPromptModalOpen = true
           },
           show:()=>{ // 按钮显示条件
             return chat?.promptList?.length // 存在话题提示词时显示
           }
         },
      ]

      },
      onMessage:(chat:FmodeChat,message:FmodeChatMessage)=>{
        console.log("onMessage",message)
        let content:any = message?.content
        if(typeof content == "string"){
          if(content?.indexOf("[完成]")>-1){
            console.log("已完成")
          }
        }
      },
      onChatSaved:(chat:FmodeChat)=>{
        // chat?.chatSession?.id 本次会话的 chatId
        console.log("onChatSaved",chat,chat?.chatSession,chat?.chatSession?.id)
      }
    }
    openChatPanelModal(this.modalCtrl,options)
}
  
  timeRange = 'week';
  
  metrics = [
    { 
      name: '血糖', 
      value: '6.5', 
      unit: 'mmol/L',
      trend: 'caret-up', 
      trendColor: 'success',
      reference: '3.9-6.1',
      abnormal: false
    },
    {
      name: '血压',
      value: '135/85',
      unit: 'mmHg',
      trend: 'caret-down',
      trendColor: 'danger',
      reference: '120/80',
      abnormal: true
    }
  ];

  tasks = [
    {
      icon: 'fitness',
      title: '测量血糖',
      description: '餐后血糖测量',
      time: '08:00',
      completed: true,
      recommended: false
    },
    {
      icon: 'medical',
      title: '服药提醒',
      description: '二甲双胍 500mg',
      time: '12:00',
      completed: false,
      recommended: true
    }
  ];
  


 
  

  addData() {
    // 添加数据逻辑
  }

  updateChart() {
    // 更新图表逻辑
  }
}