import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CloudSeUser } from 'src/lib/cloudSeuser'; // 引入 CloudSeUser 类
import { FmodeChatCompletion } from 'fmode-ng'; // 引入 FmodeChatCompletion
import { addIcons } from 'ionicons';
import { albumsOutline, documentOutline, leafOutline, scanOutline, storefrontOutline } from 'ionicons/icons';
import { IonButton, IonCard, IonCardContent, IonCardHeader, IonCol, IonContent, IonHeader, IonIcon, IonInput, IonRow, IonTextarea, IonTitle, IonToolbar, IonGrid, IonCardTitle, IonSearchbar, IonButtons } from '@ionic/angular/standalone'; // 导入 Ionic 组件
import { CommonModule } from '@angular/common'; // 导入 CommonModule
import { ImagePopupComponent } from '../image-popup/image-popup.component'; // 导入弹窗组件
import { ModalController, NavController } from '@ionic/angular/standalone';
import { Image1PopupComponent } from '../image-popup/image1-popup/image1-popup.component';
import { Image2PopupComponent } from '../image-popup/image2-popup/image2-popup.component';
import { Image3PopupComponent } from '../image-popup/image3-popup/image3-popup.component';
import { Image4PopupComponent } from '../image-popup/image4-popup/image4-popup.component';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { CloudUser } from 'src/lib/ncloud';
import { MealService } from '../meal/meal.service';
import { MealSearchComponent } from '../meal-search/meal-search/meal-search.component';


@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,  // 使用 standalone 组件
  imports: [
    CommonModule, IonContent, IonHeader, IonTitle, IonToolbar, 
    IonButton, IonTextarea, IonInput, IonCard, IonCardContent, IonGrid, IonRow, IonCol, IonIcon,
    IonCardHeader, IonCardTitle, IonSearchbar,IonButtons
  ],
})
export class Tab1Page implements OnInit {
  private cloudSeUser: CloudSeUser; // 引入 CloudSeUser 实例
  searchQuery: string = '';
  userInfo: any = null; // 用户信息
  responseMsg: string = ""; // 用于存储 AI 生成的饮食建议
  recipeMsg: string = ""; // 用于存储 AI 生成的推荐食谱
  isLoading: boolean = false; 

  // 存储图片的数组
  images = [
    'https://app.fmode.cn/dev/jxnu/202226701038/ssbt2022.jpg',
    'https://app.fmode.cn/dev/jxnu/202226701038/danbaizhi.jpg',
    'https://app.fmode.cn/dev/jxnu/202226701038/sanfutian.jpg',
    'https://app.fmode.cn/dev/jxnu/202226701038/bushui.jpg'
  ];

// 每张图片的描述
  descriptions = [
      '<p><strong>中国居民平衡膳食宝塔（2022）</strong></p>',
      '<p><strong>[辟谣]蛋白质吃得越多，肌肉就会长得越多？</strong></p>',
      '<p><strong>三伏天“烤”验 孩子饮食如何搭配</strong></p>',
      '<p><strong>[辟谣]锻炼补水，喝运动饮料比喝白开水更好？</strong></p>'
  ];
  // 当前显示的幻灯片索引
  currentSlide: number = 0;
  currentUser:CloudUser|undefined

  constructor(private router: Router, private modalCtrl: ModalController, private mealService: MealService,) {
    addIcons({ scanOutline, documentOutline, storefrontOutline, albumsOutline, leafOutline });
    this.cloudSeUser = new CloudSeUser();
    this.currentUser=new CloudUser()
  }

  //搜索框功能实现
  // 当输入发生变化时触发
  setSearchQuery(query: string) {
    this.searchQuery = query;
  }

  // 点击搜索按钮时触发的搜索方法
  async search() {
    if (this.searchQuery.trim()) {
      await this.openMealSearchModal();
    }
  }

  // 打开弹窗并展示搜索结果
  async openMealSearchModal() {
    const modal = await this.modalCtrl.create({
      component: MealSearchComponent,
      componentProps: {
        searchQuery: this.searchQuery,
      },
    });

    await modal.present();
  }
//搜索框功能实现

  async ngOnInit(): Promise<void> {
    await this.loadUserData(); // 页面初始化时加载用户数据
    if (this.currentUser?.id) {
      this.goHealthTips();  // 用户已登录，立即调用生成健康建议的方法
      console.log(this.responseMsg)
    }
  }

  // 从 seUser 表加载当前用户数据
  async loadUserData() {
    try {
        const userData = await this.cloudSeUser.getCurrentUserInfo();
        if (userData) {
            // 使用 get 方法逐个提取字段
            this.userInfo = {
                name: userData.get('name') || '',
                email: userData.get('email') || '',
                phone: userData.get('phone') || '',
                age: userData.get('age') || null,
                gender: userData.get('gender') || '',
                height: userData.get('height') || null,
                weight: userData.get('weight') || null,
                activityLevel: userData.get('activityLevel') || '',
                dietPreference: userData.get('dietPreference') || '',
                dietGroup: userData.get('dietGroup') || '',
                avatar: userData.get('avatar') || null,
                allergies: userData.get('allergies') || '',
            };
        }
    } catch (error) {
        console.error('加载用户数据失败', error);
    }
  }

  // 获取健康建议
  async goHealthTips() {
    if (!this.userInfo) return;

    const { height, weight, activityLevel, dietPreference, dietGroup } = this.userInfo;
    const newPrompt = `
      你是一名专业的养生健康专家。根据以下用户信息，请提供今日的健康建议,字数大概在100-150字,分条列举,偏向与运动,睡眠与生活习惯等建议：
      身高：${height} cm
      体重：${weight} kg
      活动水平：${activityLevel}
      饮食偏好：${dietPreference}
      饮食类型：${dietGroup}
    `;

    const completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: newPrompt }
    ]);

    completion.sendCompletion().subscribe((message: any) => {
      console.log(message.content);
      this.responseMsg = message.content; // 更新健康建议
    });
  }

  // 查看推荐食谱
  async viewRecommendedRecipes() {
    if (!this.userInfo) return;

    const { height, weight, activityLevel, dietPreference, dietGroup } = this.userInfo;
    const newPrompt = `
      你是一名专业的饮食营养规划师。根据以下用户信息，请推荐今日的食谱：
      身高：${height} cm
      体重：${weight} kg
      活动水平：${activityLevel}
      饮食偏好：${dietPreference}
      饮食类型：${dietGroup}
    `;

    const completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: newPrompt }
    ]);

    completion.sendCompletion().subscribe((message: any) => {
      console.log(message.content);
      this.recipeMsg = message.content; // 更新推荐食谱
    });
  }

  // 打开弹窗
  async openImagePopup(imageUrl: string, description: string) {
    let modal;
    // 动态加载弹窗组件
    if (imageUrl === this.images[0]) {
      modal = await this.modalCtrl.create({
        component: Image1PopupComponent,
        componentProps: { imageUrl, description }
      });
    } else if (imageUrl === this.images[1]) {
      modal = await this.modalCtrl.create({
        component: Image2PopupComponent,
        componentProps: { imageUrl, description }
      });
    } else if (imageUrl === this.images[2]) {
      modal = await this.modalCtrl.create({
        component: Image3PopupComponent,
        componentProps: { imageUrl, description }
      });
    } else if (imageUrl === this.images[3]) {
      modal = await this.modalCtrl.create({
        component: Image4PopupComponent,
        componentProps: { imageUrl, description }
      });
    }

    if (modal) {
      await modal.present();
    }
  }

  // 点击轮播图
  async onImageClick(index: number) {
    const description = this.descriptions[index]; // 获取对应的描述
    await this.openImagePopup(this.images[index], description);
  }

  // 前一个幻灯片
  prevSlide() {
    if (this.currentSlide > 0) {
      this.currentSlide--;
    } else {
      this.currentSlide = this.images.length - 1;
    }
  }

  // 后一个幻灯片
  nextSlide() {
    if (this.currentSlide < this.images.length - 1) {
      this.currentSlide++;
    } else {
      this.currentSlide = 0;
    }
  }

  // 跳转到指定的幻灯片
  goToSlide(index: number) {
    this.currentSlide = index;
  }

    // 跳转到饮食建议页面
    goHealthTipsPage() {
      this.router.navigate([`/tabs/tips`]);
    }

    async login(){
      // 弹出登录窗口
      let user = await openUserLoginModal(this.modalCtrl);
      if(user?.id){
        this.currentUser = user
        await this.loadUserData();// 登录后加载用户信息
      }
    }
  }
  