import { Component } from '@angular/core';
import { Router } from '@angular/router';

// 引入Parse第三方库
import * as Parse from "parse"
(Parse as any).serverURL = "http://metapunk.cn:9999/parse"
Parse.initialize("dev")

@Component({
  selector: 'app-page-lesson',
  templateUrl: './page-lesson.component.html',
  styleUrls: ['./page-lesson.component.scss']
})
export class PageLessonComponent {

  constructor(private router: Router) { this.initPage(); }
  courseList: Array<Parse.Object> = []
  // 首次进入页面，默认加载首批数据
  async initPage() {
    this.courseList = await this.getMenuData()
  }
  // 数据加载相关函数
  async getMenuData() {
    let query = new Parse.Query("PetFood");
    query.limit(this.pageSize);
    query.include('courseAuthor')
    if (this.searchInput) {
      query.contains(this.searchType, this.searchInput)
    }
    if (this.skip) {
      query.skip(this.skip)
    }
    query.addAscending("no")
    let list = await query.find();
    console.log(list);
    return list
  }
  // 搜索功能相关函数与属性
  searchInput: string = ``
  searchType: string = `foodName`
  async search() {
    this.skip = 0; // 每次搜索条件变化，从第一条重新加载
    this.courseList = await this.getMenuData();
  }
  // 触底加载函数逻辑
  pageSize = 10
  skip: number = 0 // 跳过多少条进行加载
  async onBottomLoad(event: any, infiScroll: any) {
    console.log("onBottomLoad", this.courseList.length)
    this.skip = this.courseList.length;
    let list = await this.getMenuData();
    this.courseList = this.courseList.concat(list)
    infiScroll?.complete();
  }
  scrollToCardSection(category: string) {
    const cardSection = document.getElementById(`card-section-${category}`);
    if (cardSection) {
      cardSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }
  
  groupedCourseList: any[] = [];

  // 在获取课程数据后，将课程按照每4个为一组进行分组
  // groupCoursesByCategory() {
  //   const coursesPerCategory = 4;
  //   const totalCourses = this.courseList.length;
  //   const totalCategories = Math.ceil(totalCourses / coursesPerCategory);
  
  //   for (let i = 0; i < totalCategories; i++) {
  //     const startIndex = i * coursesPerCategory;
  //     const endIndex = startIndex + coursesPerCategory;
  //     const categoryCourses = this.courseList.slice(startIndex, endIndex);
  //     this.groupedCourseList.push(categoryCourses);
  //   }
  // }
  // ngOnInit() {
  //   this.groupCoursesByCategory();
  // }
  
  

  goLessonDetail(lesson: any) {
    this.router.navigate(["/lesson/lesson/detail"], { queryParams: lesson })
  }
}
