import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { addIcons } from 'ionicons';
import { checkmarkCircle, sunny, infiniteOutline, alertCircleOutline, bicycleOutline, logoGitlab, trash, calendar, helpCircle, create } from 'ionicons/icons';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonDatetime, IonSelect, IonItemOptions, IonThumbnail, IonCardSubtitle, IonImg, IonCard, IonButtons, IonItem, IonList, IonHeader, IonIcon, IonToolbar, IonContent, IonSegment, IonSegmentButton, IonGrid, IonRow, IonCol, IonButton, IonLabel, IonBadge, IonInput, ModalController, IonCardTitle, IonCardContent, IonCardHeader, IonSelectOption, IonItemSliding, IonItemOption, ToastController } from '@ionic/angular/standalone';
import { FmodeChatCompletion, ImagineWork, DalleOptions, ChatPanelOptions, FmodeChat, FmodeChatMessage, MarkdownPreviewModule, openChatPanelModal } from "fmode-ng";
import { AgentTaskStep } from './agent/agent.task';
import { TaskPoemPictureDesc } from './agent/tasks/poem/poem-desc';
import { TaskPoemPictureCreate } from './agent/tasks/poem/poem-picture';
import { startTask } from './agent/agent.start';
import { TaskInqueryUserStory } from './agent/tasks/poem/inquiry/1.inquiry-user-story';
import { TaskInqueryDoctorQuestion } from './agent/tasks/poem/inquiry/2.inquiry-doctor-question';
import { TaskInqueryUserAnswer } from './agent/tasks/poem/inquiry/3.inquiry-user-answer';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { EditPlanModalComponent } from './edit-plan-modal/edit-plan-modal.component';
import { AlertController } from '@ionic/angular';
import { openUserEditModal } from 'src/lib/user/modal-user-edit/modal-user-edit.component';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { TestPageComponent } from './test-page/test-page.component';
@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: true,
  imports: [
    MarkdownPreviewModule,
    IonSelectOption,
    IonSelect,
    IonThumbnail,
    IonCardSubtitle,
    IonImg,
    IonCard,
    IonCardTitle,
    IonCardHeader,
    IonCardContent,
    IonButtons,
    IonItem,
    IonList,
    IonIcon,
    FormsModule,
    CommonModule,
    IonHeader,
    IonToolbar,
    IonContent,
    IonSegment,
    IonSegmentButton,
    IonGrid,
    IonRow,
    IonCol,
    IonButton,
    IonLabel,
    IonBadge,
    IonInput,
    IonDatetime,
    IonItemOption,
    IonItemSliding,
    IonItemOptions,
  ]
})
export class Tab2Page implements OnInit {

  selectedTab: string = 'checkin';  // 默认选中的tab
  planList: any[] = [];
  coachList: any[] = [];
  planUser: any[] = [];
  currentUser: CloudUser | undefined
  actionTaskVisible = false;
  healthTaskVisible = false;
  constructor(private toastController: ToastController, private router: Router, private modalCtrl: ModalController, private cdr: ChangeDetectorRef, private alertController: AlertController) {
    addIcons({ alertCircleOutline, sunny, checkmarkCircle, calendar, helpCircle, trash, create, logoGitlab, bicycleOutline, infiniteOutline });
    this.currentUser = new CloudUser();
  }
  ngOnInit() {
    this.loadPlanList()
    this.loadCoachList()
    this.loadPlanUser()

  }
  async loadPlanList() {
    let currentUser = new CloudUser();
    const cloudQuery = new CloudQuery("fitPlan");
    if (currentUser) {
      cloudQuery.equalTo("user", currentUser.toPointer());
      this.planList = await cloudQuery.find();
      console.log(this.planList)
      //排序算法
      this.planList.sort((a, b) => {
        const srcIdA = a.get("srcId").match(/\d+/);
        const srcIdB = b.get("srcId").match(/\d+/);
        if (srcIdA && srcIdB) {
          const numA = parseInt(srcIdA[0], 10);
          const numB = parseInt(srcIdB[0], 10);
          return numA - numB;
        }
        return 0;
      });
    }
  }

  async loadCoachList() {
    let query = new CloudQuery("Coach");
    this.coachList = await query.find();
  }

  dailyReward = 5;
  powerForMakup = 30;
  power: number = 0;
  realDate: Date = this.correctDate(new Date());
  days: number = 0; // 总打卡天数
  consecutiveDays: number = 0; // 连续打卡天数
  checkInHistory: Set<string> = new Set(); // 已打卡日期集合

  async showToast(message: string, color: string = 'success') {
    const toast = await this.toastController.create({
      message: message,
      duration: 2000,
      position: 'top',
      color: color,
    });
    toast.present();
  }

  // 计算 BMI
  calculateBMI(height: number, weight: number): number {
    const heightInMeters = height / 100;
    const bmi = weight / (heightInMeters * heightInMeters);
    return parseFloat(bmi.toFixed(2));
  }

  // 获取鼓励性话语
  getEncouragement(bmi: number): string {
    if (bmi < 18.5) {
      return '您的BMI偏低，注意保持健康的饮食哦！(๑•́ ₃ •̀๑)';
    } else if (bmi >= 18.5 && bmi < 24.9) {
      return '您的BMI在正常范围，继续保持良好的生活方式！(｡♥‿♥｡)';
    } else if (bmi >= 25 && bmi < 29.9) {
      return '您的BMI稍微偏高，可以增加运动，控制饮食！(≧◡≦)';
    } else {
      return '您的BMI较高，建议积极锻炼，控制体重！(｡•́︿•̀｡)';
    }
  }

  // 加载用户数据
  async loadPlanUser() {
    let currentUser = new CloudUser();
    const cloudQuery = new CloudQuery("fitUser");
    // 确保 currentUser 和 cloudQuery 都有效
    if (!currentUser || !cloudQuery) {
      console.error('Invalid user or cloudQuery');
      return;
    }
    // 使用 currentUser 的 pointer 查询用户相关数据
    cloudQuery.equalTo("user", currentUser.toPointer());
    try {
      // 执行查询并获取数据
      this.planUser = await cloudQuery.find();
      // 确保查询结果存在且有效
      if (this.planUser && this.planUser.length > 0) {
        const user = this.planUser[0];
        // 获取和处理已打卡日期
        const checkedDays = user.get("checkeddays") || [];
        if (Array.isArray(checkedDays)) {
          checkedDays.forEach((date: string) => {
            this.checkInHistory.add(date);
          });
        }
        // 安全地获取数据，使用默认值来防止 null 或 undefined 错误
        this.days = user.get("days") || 0;
        this.consecutiveDays = user.get("sucdays") || 0;
        this.power = user.get("power") || 0;  // 假设 power 默认是 0
      } else {
        console.warn('No user data found');
      }
    } catch (error) {
      console.error('Error loading user plan:', error);
    }
  }


  // 计算连续打卡天数
  calculateConsecutiveDays() {
    let currentDate = this.realDate;
    let count = 0;
    for (let i = 0; i < 30; i++) {
      let date = new Date(currentDate);
      date.setDate(date.getDate() - i);
      let formattedDate = this.formatDate(date);
      if (this.checkInHistory.has(formattedDate)) {
        count++;
      } else {
        break;
      }
    }
    this.consecutiveDays = count;
  }

  // 格式化日期
  formatDate(date: Date): string {
    return date.toISOString().split('T')[0];
  }

  // 修正日期（解决时区问题）
  correctDate(date: string | Date): Date {
    if (date instanceof Date) {
      return new Date(date.getTime() - date.getTimezoneOffset() * 60000);
    } else if (typeof date === 'string') {
      const parsedDate = new Date(date);
      return new Date(parsedDate.getTime() - parsedDate.getTimezoneOffset() * 60000);
    }
    throw new Error("Invalid date format");
  }

  // 判断是否今天已打卡
  isCheckedInToday(): boolean {
    const currentDate = this.realDate;
    const formattedDate = this.formatDate(currentDate);
    return this.checkInHistory.has(formattedDate);
  }

  // 获取连续打卡奖励
  getConsecutiveReward(consecutiveDays: number): number {
    if (consecutiveDays % 30 === 0) {
      return 30;  // 第30天，奖励30
    } else if (consecutiveDays % 15 === 0) {
      return 20;  // 第15天，奖励20
    } else if (consecutiveDays % 7 === 0) {
      return 10;  // 第7天，奖励10
    }
    return 0;  // 不符合任何条件时不奖励
  }

  // 打卡操作
  async markAttendance() {
    const currentDate = this.realDate;
    const formattedDate = this.formatDate(currentDate);

    // 如果今天已经打卡
    if (this.checkInHistory.has(formattedDate)) {
      this.showToast('今天已经打卡过了', 'warning');
      return;
    }

    // 如果是未来日期
    if (currentDate > this.correctDate(new Date())) {
      this.showToast('不能打卡未来的日期', 'danger');
      return;
    }

    // 正常打卡
    this.checkInHistory.add(formattedDate);
    this.days = this.checkInHistory.size;
    this.calculateConsecutiveDays();

    let currentUser = new CloudUser();
    const cloudQuery = new CloudQuery("fitUser");
    cloudQuery.equalTo("user", currentUser.toPointer());
    const userData = await cloudQuery.find();

    if (userData.length > 0) {
      const user = userData[0];
      let checkedDays = user.get("checkeddays") || [];
      checkedDays.push(formattedDate);
      user.set({ "checkeddays": checkedDays });
      user.set({ "days": this.days });
      user.set({ "sucdays": this.consecutiveDays });

      // 计算奖励
      let totalReward = this.dailyReward; // 每天签到奖励
      totalReward += this.getConsecutiveReward(this.consecutiveDays); // 连续签到奖励
      user.set({ "power": user.get("power") + totalReward }); // 增加总 power 奖励

      await user.save();
      this.loadPlanUser();
      this.showToast('打卡成功，获得了 ' + totalReward + ' Power');
    }
  }

  // 补签操作
  async handleMakeupSignIn(user: CloudUser): Promise<string> {
    if (user.get("power") >= this.powerForMakup) {
      user.set({ "power": user.get("power") - this.powerForMakup });
      await user.save();
      return '补签成功！';
    } else {
      return '补签失败，您的动能不足！';
    }
  }

  // 补签点击事件
  async handleMakeupClick() {
    const confirmed = window.confirm('补签将消耗 ' + this.powerForMakup + ' 动能，确定补签吗？');
    if (confirmed) {
      let currentUser = new CloudUser();
      const cloudQuery = new CloudQuery("fitUser");
      cloudQuery.equalTo("user", currentUser.toPointer());
      const userData = await cloudQuery.find();

      if (userData.length > 0) {
        const user = userData[0];
        const resultMessage = await this.handleMakeupSignIn(user);
        this.showToast(resultMessage, resultMessage.includes('成功') ? 'success' : 'danger');
        this.loadPlanUser();
      }
    }
  }

  // 日期变化时更新
  onDateChange(event: any) {
    this.realDate = new Date(this.correctDate(event.detail.value));
  }

  // 获取按钮状态（判断打卡、补签等）
  getButtonState(date: Date): { isDisabled: boolean, buttonText: string } {
    const formattedDate = this.formatDate(date);

    if (formattedDate > this.formatDate(this.correctDate(new Date()))) {
      // 未来日期
      return { isDisabled: true, buttonText: '无法签到' };
    } else if (this.checkInHistory.has(formattedDate)) {
      // 已经打卡过
      return { isDisabled: true, buttonText: '今天已经打卡' };
    } else if (formattedDate < this.formatDate(this.correctDate(new Date()))) {
      // 过去的日期
      return { isDisabled: false, buttonText: '补签' };
    }
    return { isDisabled: false, buttonText: '打卡' };
  }

  async login() {
    let user = await openUserLoginModal(this.modalCtrl);
    if (user?.id) {
      this.currentUser = user
    }
  }
  async signup() {
    // 弹出注册窗口
    let user = await openUserLoginModal(this.modalCtrl, "signup");
    if (user?.id) {
      this.currentUser = user
    }
  }
  logout() {
    this.currentUser?.logout();

  }

  editUser() {
    openUserEditModal(this.modalCtrl)
  }

  //plan页面
  editPlan(day: any) {
    console.log('编辑计划:', day);

    // 创建一个弹出框
    this.modalCtrl.create({
      component: EditPlanModalComponent,
      componentProps: { plan: day }
    }).then(modal => {
      modal.present();
      modal.onDidDismiss().then((result) => {
        if (result.data) {
          const updatedPlan = result.data;
          const index = this.planList.findIndex(item => item.id === updatedPlan.id);
          if (index !== -1) {
            this.planList[index] = updatedPlan;
          }
        }
        this.loadPlanList()
      });
    });
  }
  regeneratePlan() {
    console.log('重新生成计划:');

    // 创建一个弹出框
    this.modalCtrl.create({
      component: TestPageComponent,
      componentProps: {}
    }).then(modal => {
      modal.present();
      modal.onDidDismiss().then((result) => {
        if (result.data) {
          const updatedPlan = result.data;
          const index = this.planList.findIndex(item => item.id === updatedPlan.id);
          if (index !== -1) {
            this.planList[index] = updatedPlan;
          }
        }
        this.loadPlanList()
      });
    });
  }
  async deletePlan(day: any) {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: '确定要删除此计划吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('删除操作被取消');
          }
        },
        {
          text: '确认',
          handler: () => {
            day.destroy()
              .then(() => {
                console.log('计划已删除');
                this.loadPlanList();
              })
              .catch((error: any) => {
                console.error('删除失败:', error);
              });
          }
        }
      ]
    });

    await alert.present();
  }
  //任务链
  actionTaskList: AgentTaskStep[] = []
  healthTaskList: AgentTaskStep[] = []
  //一个等待一秒的函数  每经过一秒
  wait(duration: number = 1000) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(true)
      }, duration);
    })
  }
  shareData: any = {}
  // 任务：完成故事意境描述及图像绘制
  doPoemTask() {
    this.actionTaskVisible = true;
    let task1 = TaskPoemPictureDesc({ shareData: this.shareData, modalCtrl: this.modalCtrl });
    let task2 = TaskPoemPictureCreate({ shareData: this.shareData, modalCtrl: this.modalCtrl });
    let PoemTaskList = [task1, task2]
    this.actionTaskList = PoemTaskList
    startTask(PoemTaskList)
  }
  doInqueryTask() {
    this.healthTaskVisible = true;
    let task1 = TaskInqueryUserStory({ shareData: this.shareData, modalCtrl: this.modalCtrl });
    let task2 = TaskInqueryDoctorQuestion({ shareData: this.shareData, modalCtrl: this.modalCtrl });
    let task3 = TaskInqueryUserAnswer({ shareData: this.shareData, modalCtrl: this.modalCtrl });
    // 定义任务集
    let InquireServiceTaskList = [
      task1, task2, task3
    ]
    // 传递给显示组件
    this.healthTaskList = InquireServiceTaskList
    // 开始执行任务
    startTask(InquireServiceTaskList)
  }
  // 聊天页面
  async openInquiry(coach: CloudObject) {
    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("fitConsultation")
    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: `交流记录${dateStr}-${coach?.get("name")}`,
      coach: coach.toPointer(),
      user: currentUser.toPointer(),
      ACL: ACL
    })
    let options: ChatPanelOptions = {
      roleId: "2DXJkRsjXK",
      onChatInit: (chat: FmodeChat) => {
        console.log("onChatInit");
        console.log("预设角色", chat.role);
        chat.role.set("name", coach?.get("name"));
        chat.role.set("title", "职业健身教练");
        chat.role.set("desc", `一名${coach?.get("desc")}，${coach?.get("name")}，年龄${coach?.get("age")}岁`);
        chat.role.set("tags", coach?.get("specialize"));
        chat.role.set("avatar", coach?.get("avater") || "../../assets/images/coach1.jpg")
        chat.role.set("prompt", `
# 角色设定
您是${coach?.get("name")},年龄${coach?.get("age")},特长为${coach?.get("specialize")},要完成一次教练与学员之间的健身交流。

# 对话环节
0.导诊（根据用户基本情况，引导选择合适的训练计划） 
1.预设的问询方式（根据学员自述情况进行引导）

- 打招呼，以学员自述为主
- 当信息充足时，确认学员的目标与需求，并进入下一个环节 
2.拓展的问询细节 
例如：学员反映想要锻炼腹肌，拓展出：目前的锻炼频率；饮食习惯；是否有受伤历史等其他需要的问题。
- 当问询细节补充完成后进入下一个环节 
3.初步的训练方案，并且同时列出需要的器械与注意事项 初步方案：确定需要的训练动作与频率 器械与注意事项：获取训练所需的器械信息
- 等待学员确认并准备器械，进入下一阶段 
4.给出详细的训练计划并提供指导
- 完成训练计划时，请在消息结尾附带: [交流完成]
# 开始话语
当您准备好了，可以以一个健身教练的身份，向来访的学员打招呼。
你好！欢迎来到健身房，我是${coach?.get("name")}教练，${coach?.get("desc")}。今天你想要专注锻炼哪个部位呢？或者有什么具体的健身目标吗？`);
      },
      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)
  }
  openChat() {
    let options: ChatPanelOptions = {
      roleId: "2DXJkRsjXK",
      onChatSaved: (chat: FmodeChat) => {
        // chat?.chatSession?.id 本次会话的 chatId
        console.log("onChatSaved", chat, chat?.chatSession, chat?.chatSession?.id)
      },
    }
    openChatPanelModal(this.modalCtrl, options)
  }
  restoreChat(chatId: string) {
    let options: ChatPanelOptions = {
      roleId: "2DXJkRsjXK",
      chatId: chatId
    }
    openChatPanelModal(this.modalCtrl, options)
  }
  goChat() {
    this.router.navigateByUrl("/chat/session/role/2DXJkRsjXK")
  }
  // audioModalHeightPoint:number = 0.35;
  // async startTalk(){
  //   // 根据手机兼容性，适配组件弹出高度
  //   let height = document.body.clientHeight || 960;
  //   this.audioModalHeightPoint = Number((165/height).toFixed(2));

  //   // 弹出组件
  //   let modal:any
  //   let chat:any
  //   modal = await this.modalCtrl.create({
  //     component:ModalAudioMessageComponent,
  //     componentProps:{
  //       chat:chat,
  //       modal:modal,
  //       onBreakPointSet:()=>{
  //         modal?.setCurrentBreakpoint(this.audioModalHeightPoint)
  //       }
  //     }
  //   })
  //   modal.present();
  // }
  // 页面跳转功能
  goToPage(page: string) {
    // 更新选中的tab
    this.selectedTab = page;
    this.router.navigate([`/tabs/${page}`]);  // 然后再进行路由跳转

    // 手动检测视图变化，确保数据绑定正确
    this.cdr.detectChanges();
  }
}
