import { Component, OnInit, Renderer2 } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { IonicModule } from '@ionic/angular'; 

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})

export class Tab1Page implements OnInit {
  // categories: any[] = [
  //   { name: '中式菜系', icon: 'utensils' },
  //   { name: '西式料理', icon: 'fork-knife' },
  //   { name: '减脂轻食', icon: 'carrot' },
  //   { name: '甜点烘焙', icon: 'cake' },
  //   { name: '汤羹粥品', icon: 'bowl' },
  //   { name: '素食主义', icon: 'leaf' },
  // ];
  recommendedRecipes: any[] = [
    { id: 1, title: '香煎鸡胸肉配时蔬', image: '/assets/food/jxr.jpg', time: 30, rating: 4.8 },
    { id: 2, title: '奶油蘑菇意面', image: '/assets/food/nymg.jpg', time: 45, rating: 4.9 },
    { id: 3, title: '蔬菜鸡胸肉沙拉', image: '/assets/food/jxsl.jpg', time: 25, rating: 4.7 },
  ];

  constructor(private router: Router, private renderer: Renderer2, private navCtrl: NavController) { }

  ngOnInit() {
    setTimeout(() => {
      const recipeCards = document.querySelectorAll('.recipe-card');
      recipeCards.forEach(card => {
        this.renderer.setStyle(card, 'opacity', '1');
        this.renderer.setStyle(card, 'transform', 'translateY(0)');
      });
    }, 1000);
    this.loadDailyRecommendationList();
    this.loadCategoryList();
  }

  categories: Array<CloudObject> = [];
  categorieRecipes: Array<CloudObject> = [];
  async loadCategoryList() {
      let query = new CloudQuery("RecipeCategory");
      this.categories = await query.find();
      console.log(this.categories);
  }

  DailyRecommendationList: Array<CloudObject> = []; // 存储原始每日推荐记录
  filteredRecipes: Array<Array<CloudObject>> = []; // 二维数组：外层=DailyRecommendation，内层=对应的Recipe列表
  recipeGroup: Array<CloudObject> = [];

  async loadDailyRecommendationList() {
    // 1. 查询 DailyRecommendation 表并关联 Recipe 数据
    let query = new CloudQuery("DailyRecommendation");
    query.include("recommendedRecipes"); // 关键：联查 Recipe 表
    this.DailyRecommendationList = await query.find();

    // 2. 构建二维数组
    for (let dailyRec of this.DailyRecommendationList) {
      // 获取当前 DailyRecommendation 的 recommendedRecipes 数组
      const recipes = dailyRec.data['recommendedRecipes'] || []; // 防止undefined
      // 将当前 DailyRecommendation 的所有关联 Recipe 存入内层数组
      this.filteredRecipes.push(recipes);
    }
    console.log("完整的二维数组结构:", this.filteredRecipes);
    const randomGroupIndex = Math.floor(Math.random() * this.filteredRecipes.length);
    console.log("随机选择的组索引:", randomGroupIndex);
    this.recipeGroup = this.filteredRecipes[randomGroupIndex];
    console.log("随机选择的组内容:", this.recipeGroup);

  }
  searchQuery: string = '';
  results : Array<CloudObject> = []; // 存储原始每日推荐记录
  async selectRecipe() {
    const query = this.searchQuery.trim();
    if (!query) return;
  
    try {
      const cloudQuery = new CloudQuery("Recipe");
      cloudQuery.contains("title", query);
      const results = await cloudQuery.find();
    
      this.navCtrl.navigateForward(
        ["tabs", "tab1", "page-selectlist"], 
        {
          state: {
            searchResults: results
          }
        }
      );
      
      console.log("搜索结果:", results);
    } catch (error) {
      console.error("搜索失败:", error);
    }
  }

  login() {
    this.router.navigate(['/login']);
  }

  register() {
    this.router.navigate(['/register']);
  }

  navigateToCategory(category : CloudObject) {
    // /tabs/tab1/page-type/r5xLA3gWLw
    this.router.navigate(['/tabs/tab1/page-type', category.id]);
    console.log(category.id);
    console.log('Navigating to page-detail');
  }

  goToRecipeDetail(recipeId: number) {
    this.router.navigate(['/recipe', recipeId]);
  }

  performSearch() {
    const query = this.searchQuery.trim();
    if (query) {
      this.router.navigate(['/search-results'], { queryParams: { q: query } });
    }
  }

  // goToTypeList(category: CloudObject) {
  //   this.navCtrl.navigateForward(["tabs", "tab1", "page-type",category.id]);
  //   console.log(category.id);
  //   console.log('Navigating to page-type');
  // }

  goToDetail(recipe: CloudObject) {
    this.navCtrl.navigateForward(["tabs", "tab1", "page-detail", recipe.objectId]);
    console.log('Navigating to page-detail');
  }
}