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'; 

/**
 * 首页Tab页面组件
 * @Component 装饰器定义组件元数据
 */
@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})
export class Tab1Page implements OnInit {
  /**
   * 推荐食谱列表（静态数据）
   * @type {Array<{id: number, title: string, image: string, time: number, rating: number}>}
   */
  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 },
  ];

  /**
   * 构造函数
   * @param {Router} router Angular路由服务
   * @param {Renderer2} renderer Angular渲染器
   * @param {NavController} navCtrl Ionic导航控制器
   */
  constructor(private router: Router, private renderer: Renderer2, private navCtrl: NavController) { }

  /**
   * 组件初始化生命周期钩子
   * @returns {void}
   */
  ngOnInit(): void {
    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();
  }

  /**
   * 食谱分类列表
   * @type {Array<CloudObject>}
   */
  categories: Array<CloudObject> = [];
  
  /**
   * 分类食谱列表
   * @type {Array<CloudObject>}
   */
  categorieRecipes: Array<CloudObject> = [];
  
  /**
   * 加载分类列表
   * @async
   * @returns {Promise<void>}
   */
  async loadCategoryList(): Promise<void> {
    let query = new CloudQuery("RecipeCategory");
    this.categories = await query.find();
    console.log(this.categories);
  }

  /**
   * 每日推荐列表
   * @type {Array<CloudObject>}
   */
  DailyRecommendationList: Array<CloudObject> = [];
  
  /**
   * 过滤后的食谱二维数组
   * @type {Array<Array<CloudObject>>}
   */
  filteredRecipes: Array<Array<CloudObject>> = [];
  
  /**
   * 随机选择的食谱组
   * @type {Array<CloudObject>}
   */
  recipeGroup: Array<CloudObject> = [];

  /**
   * 加载每日推荐列表
   * @async
   * @returns {Promise<void>}
   */
  async loadDailyRecommendationList(): Promise<void> {
    // 1. 查询 DailyRecommendation 表并关联 Recipe 数据
    let query = new CloudQuery("DailyRecommendation");
    query.include("recommendedRecipes"); // 关键：联查 Recipe 表
    this.DailyRecommendationList = await query.find();

    // 2. 构建二维数组
    for (let dailyRec of this.DailyRecommendationList) {
      const recipes = dailyRec.data['recommendedRecipes'] || [];
      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);
  }

  /**
   * 搜索查询字符串
   * @type {string}
   */
  searchQuery: string = '';
  
  /**
   * 搜索结果列表
   * @type {Array<CloudObject>}
   */
  results: Array<CloudObject> = [];
  
  /**
   * 搜索食谱
   * @async
   * @returns {Promise<void>}
   */
  async selectRecipe(): Promise<void> {
    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);
    }
  }

  /**
   * 导航到登录页面
   * @returns {void}
   */
  login(): void {
    this.router.navigate(['/login']);
  }

  /**
   * 导航到注册页面
   * @returns {void}
   */
  register(): void {
    this.router.navigate(['/register']);
  }

  /**
   * 导航到分类页面
   * @param {CloudObject} category 分类对象
   * @returns {void}
   */
  navigateToCategory(category: CloudObject): void {
    this.router.navigate(['/tabs/tab1/page-type', category.id]);
    console.log(category.id);
    console.log('Navigating to page-detail');
  }

  /**
   * 导航到食谱详情页面
   * @param {number} recipeId 食谱ID
   * @returns {void}
   */
  goToRecipeDetail(recipeId: number): void {
    this.router.navigate(['/recipe', recipeId]);
  }

  /**
   * 执行搜索
   * @returns {void}
   */
  performSearch(): void {
    const query = this.searchQuery.trim();
    if (query) {
      this.router.navigate(['/search-results'], { queryParams: { q: query } });
    }
  }

  /**
   * 导航到食谱详情页面
   * @param {CloudObject} recipe 食谱对象
   * @returns {void}
   */
  goToDetail(recipe: CloudObject): void {
    this.navCtrl.navigateForward(["tabs", "tab1", "page-detail", recipe.objectId]);
    console.log('Navigating to page-detail');
  }
}