import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
// 引入Parse第三方库
import * as Parse from "parse"

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

export class PageLessonDetailComponent {
  course: any = {}
  constructor(private route: ActivatedRoute) {
    this.route.queryParams.subscribe(params => {
      this.initPage(params["id"]);
    });
  }
  lessonPointer: any;//获取当前指针
  async getCourseById(id: string) {
    let query = new Parse.Query("PetFood")
    query.include('courseAuthor')//查询指针
    this.course = await query.get(id);
    this.lessonPointer = {
      __type: 'Pointer',
      className: 'PetFood',
      objectId: this.course.id
    };
  }
  //用户输入评论保存到数据库
  currentUser = Parse.User.current()
  commentContent = ''//用户评论，双向绑定commentCoutent实现保存该评论
  async saveComment() {
    let CourseComment = Parse.Object.extend('CourseComment')
    let courseComment = new CourseComment()
    courseComment.set('user', { __type: 'Pointer', className: '_User', objectId: this.currentUser?.id })
    courseComment.set('commentContent', this.commentContent)
    courseComment.set('lesson', this.lessonPointer); // 设置指向QwlMenu表的指针类型字段
    this.commentContent = '';
    return courseComment.save().then((saveObject: any) => {
      // 处理Promise成功的情况
      console.log(saveObject);
      //评论立即刷新到页面上
      this.getCommentData().then((commentList: Array<Parse.Object>) => {
        this.commentList = commentList;
        this.commentCount = this.commentList.length; // 更新评论数量
      });
    },
      (error: string) => {
        // 处理Promise失败的情况
        console.log("失败：" + error);
      })
  }
  // 评论数据加载相关函数
  commentCount: number = 0
  commentList: Array<Parse.Object> = []
  async initPage(id: string) {
    await this.getCourseById(id);
    this.commentList = await this.getCommentData()
    this.commentCount = this.commentList.length;
  }
  async getCommentData() {
    let query = new Parse.Query("CourseComment");
    query.equalTo("lesson", this.lessonPointer);
    query.descending('createdAt')
    let list = await query.find();
    return list
  }
}
