import { Component, OnInit } from '@angular/core';
import { ModalController, NavController } from '@ionic/angular';
import { FilmDetailsModalComponent } from '../film-details-modal/film-details-modal.component';
import { BookService } from 'src/modules/server/book.serve';
import { ActivatedRoute } from '@angular/router';
import Parse from 'parse';

@Component({
  selector: 'app-book',
  templateUrl: './book.page.html',
  styleUrls: ['./book.page.scss'],
})
export class BookPage implements OnInit {

  books: any[] = [];
  searchName: string = '';
  searchAuthor: string = '';
  selectedRating: string = '';
  sortByRating: boolean = false;
  isAscending:boolean=true;
  score:number=0;

  constructor(private bookService: BookService,
    private route:ActivatedRoute,
    private navCtrl:NavController
  ) { 
    
  }

  async updateFilmRating(film:Parse.Object,score:any){
    if(!score) return
    let rating = await this.checkExists(film)
    if(!rating?.id){
      let FilmRating = Parse.Object.extend("LQLBookRating");
      rating = new FilmRating
    }
    // 更新个人打分
    rating?.set("user",Parse.User.current()?.toPointer())
    rating?.set("book",film?.toPointer())
    rating?.set("score",score)
    await rating?.save();

    // 更新全局平均分数
    let query = new Parse.Query("LQLBookRating");
    query.equalTo("book",film?.toPointer())
    let list = await query.find()
    if(!list?.length) return
    console.log(list)
    let sum:any = 0
     list?.forEach((item)=>sum+=item.get("score"))
    let avgRating = sum / list?.length
    film.set("rating",avgRating);
    film.save()
  }
  async checkExists(film:Parse.Object){
    let query = new Parse.Query("LQLBookRating");
    query.equalTo("user",Parse.User.current()?.toPointer())
    query.equalTo("book",film?.toPointer())
    return await query.first()
  }


  ngOnInit(): void {
    this.loadBooks();
  }

  async loadBooks() {
    const queryParams = {
      name: this.searchName,
      author: this.searchAuthor,
      rating: this.selectedRating
    };
    this.books=await this.bookService.getBooks(queryParams);
    //this.films = await this.filmService.getFilms();
  }

  toggleSort() {
    if (this.isAscending) {
      this.books = this.books.sort((a, b) => a.get('rating') - b.get('rating'));
      this.isAscending = false;
    } else {
      this.books = this.books.sort((a, b) => b.get('rating') - a.get('rating'));
      this.isAscending = true;
    }
    // this.sortByRating = !this.sortByRating;
    // this.loadBooks();
  }

  goToBack()
  {
    this.navCtrl.back();
  }

  // films = [
  //   { title: '朝花夕拾', image: 'assets/image/ZhaoHuaXiShi.webp', details: '朝花夕拾的详情描述', rating: 8.5 },
  //   { title: '西游记', image: 'assets/image/XiYouJi.webp', details: '西游记的详情描述', rating: 9.3 },
  //   { title: '红楼梦', image: 'assets/image/HongLouMeng.webp', details: '红楼梦的详情描述', rating: 8.0 },
  //   { title: '水浒传', image: 'assets/image/ShuiHuZhuan.webp', details: '水浒传的详情描述', rating: 8.7 },
  //   { title: '简·爱', image: 'assets/image/JianAn.webp', details: '哆啦A梦的详情描述', rating: 9.4},
  //   { title: '雾都孤儿', image: 'assets/image/WuDuGuEr.webp', details: '哆啦A梦的详情描述', rating: 9.2 },
  //   { title: '鲁滨孙漂流记', image: 'assets/image/RuBinSui.webp', details: '哆啦A梦的详情描述', rating: 9.1 },
  //   { title: '孙子兵法', image: 'assets/image/SuiZiBinFu.webp', details: '哆啦A梦的详情描述', rating: 9.5 },
  //   { title: '周易', image: 'assets/image/ZhouYi.webp', details: '哆啦A梦的详情描述', rating: 9.6 },
  //   { title: '三十六计', image: 'assets/image/SanShiLiuJi.webp', details: '哆啦A梦的详情描述', rating: 9.4 },
  //   { title: '诗经', image: 'assets/image/ShiJin.webp', details: '哆啦A梦的详情描述', rating: 9.3 },

  // ];

  // constructor(private modalController: ModalController) {}

  // async showFilmDetails(film:any) {
  //   // 弹出模态框显示影视介绍
  //   const modal = await this.modalController.create({
  //     component: FilmDetailsModalComponent,
  //     componentProps: {
  //       film: film
  //     }
  //   });
  //   return await modal.present();
  // }
  

}
