import { Component, OnInit } from '@angular/core';
import { IonBackButton, IonButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardTitle, IonContent, IonHeader, IonIcon, IonItem, IonLabel, IonList, IonSpinner, IonText, IonTitle, IonToolbar, LoadingController, ModalController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { arrowUndoOutline, chevronBack, leafOutline, arrowBack } from 'ionicons/icons';
import { CloudSeMealPlan } from 'src/lib/cloudplans';
import { CloudUser } from 'src/lib/ncloud';
import { CommonModule } from '@angular/common';  // 导入 CommonModule
import { CloudSeUser } from 'src/lib/cloudSeuser';

// 定义 MealPlan 接口
interface MealPlan {
  // id: string;
  day: string;
  breakfast: string;
  lunch: string;
  dinner: string;
  notes: string;
  mark: boolean;
}

@Component({
  selector: 'app-page-plans',
  templateUrl: './page-plans.component.html',
  styleUrls: ['./page-plans.component.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent, IonCardHeader, IonCard, 
    IonButton, IonIcon,  IonSpinner, IonText, IonCardTitle, IonCardContent,
    CommonModule,IonButtons,IonLabel
  ]
})
export class PagePlansComponent implements OnInit {
  
  mealPlans: MealPlan[] = [];  // 用来存储饮食规划数据
  loading: any;
  errorMessage: string = '';  // 用来存储错误信息
  planday: number = 0;
  responseMsg: string = '';
  responseMsg0: string = '';
  obtain: boolean=false;
  currentUser:CloudUser|undefined;
  cloudSeUser: CloudSeUser;  // 引入CloudSeUser实例
  
  constructor(private loadingController: LoadingController, private modalCtrl: ModalController) {
    addIcons({arrowBack,leafOutline,arrowUndoOutline,chevronBack});
    this.currentUser=new CloudUser();
    this.cloudSeUser = new CloudSeUser();  // 实例化CloudSeUser
  }

  ngOnInit() {
    this.loadUserData();
    this.exportMealPlan();  // 加载饮食规划数据
  }

  async loadUserData() {
    const cloudSeUser = new CloudSeUser();
    const currentUserInfo = await cloudSeUser.getCurrentUserInfo();
    
    if (currentUserInfo) {
      this.planday = currentUserInfo.get('planDays') || null;
    } else {
      console.error("未能加载当前用户信息");
    }
    }

  // 获取用户的饮食规划数据
  async exportMealPlan() {
    this.loading = await this.loadingController.create({
      message: '加载饮食规划...',
    });
    await this.loading.present();
  
    this.errorMessage = '';  // 每次加载前清空错误信息
  
    try {
      const cloudSeMealPlan = new CloudSeMealPlan();
      const cloudSeUser = new CloudSeUser();
  
      // 获取当前用户信息
      const currentUser = await cloudSeUser.getCurrentUserInfo();
      if (!currentUser) {
        console.error("未能加载当前用户信息");
        this.errorMessage = '未能加载当前用户信息';
        return;
      }
  
      const planDaysFromUserInfo = this.planday || 0;  // 用户的饮食计划天数
      const plans: MealPlan[] = [];  // 存储所有饮食规划
  
      // 通过循环获取用户饮食计划
      for (let i = 1; i <= planDaysFromUserInfo; i++) {
        const mealPlanData = await cloudSeMealPlan.getMealPlanForDay(i);  // 获取第 i 天饮食计划
        console.log("getMealPlanForDay(i)方法获取",mealPlanData)
        if (mealPlanData && mealPlanData.data) {
          // 使用 .get() 来访问 CloudObject 的字段
          console.log("mealPlanData.data:", mealPlanData.data);
          const mealPlan: MealPlan = {
            // id: mealPlanData.id,  // CloudObject 会有 id 字段
            day: mealPlanData.data['data']['day'] || null,
            breakfast: mealPlanData.data['data']['breakfast'] || null,
            lunch: mealPlanData.data['data']['lunch'] || null,
            dinner: mealPlanData.data['data']['dinner'] || null,
            notes: mealPlanData.data['data']['notes'] || null,
            mark: mealPlanData.data['data']['mark'] || null
          };
          plans.push(mealPlan);
        } else {
          console.warn(`未找到第 ${i} 天的饮食计划`);
        }
      }
  
      console.log("已获取所有饮食规划：", plans);
      
  
      if (plans.length === 0) {
        this.errorMessage = '没有找到饮食规划';
        this.obtain = false;
      }else{
        this.mealPlans = plans;  // 将获取到的饮食规划赋值给 mealPlans 数组
        this.responseMsg = JSON.stringify(plans);
        this.responseMsg0=this.responseMsg;
    
        // 1. 替换字段名
        this.responseMsg0 = this.responseMsg0
        .replace(/\bday\b/g, '日期')
        .replace(/\bbreakfast\b/g, '早餐')
        .replace(/\blunch\b/g, '午餐')
        .replace(/\bdinner\b/g, '晚餐')
        .replace(/\bnotes\b/g, '注意事项');

        // 2. 将 " 后面的 , 替换为换行
        this.responseMsg0 = this.responseMsg0.replace(/",/g, '<br>');

        // 3. 将 } 后面的 , 替换为换行
        this.responseMsg0 = this.responseMsg0.replace(/},/g, '<br>-------------------<br>');

        // 4. 删除多余的空格（包括首尾空格和中间多余的空格）
        this.responseMsg0 = this.responseMsg0.replace(/\s+/g, ' ').trim();

        // 5. 删除所有的双引号、方括号、花括号
        this.responseMsg0 = this.responseMsg0
        .replace(/["\[\]{}]/g, ''); // 删除双引号、方括号、花括号
        this.responseMsg0 = this.responseMsg0
        .replace(/mark:true/g, "已打卡")
        .replace(/mark:null/g, "未打卡");
        this.obtain = true;
        console.log(this.responseMsg0)
      }
    } catch (error) {
      console.error('获取饮食规划失败:', error);
      this.errorMessage = '加载饮食规划失败，请稍后再试';
    } finally {
      this.loading.dismiss();
    }
  }
  

  back() {
    this.modalCtrl.dismiss();
  }

}