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

@Component({
  selector: 'app-game',
  templateUrl: './game.page.html',
  styleUrls: ['./game.page.scss'],
})
export class GamePage implements OnInit {
  games: any[] = [];
  searchName: string = '';
  searchDetails: string = '';
  selectedRating: string = '';
  sortByRating: boolean = false;
  isAscending: boolean = true;
  score:number=0;

  constructor(private gameService: GameService,
    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("LQLGameRating");
      rating = new FilmRating
    }
    // 更新个人打分
    rating?.set("user",Parse.User.current()?.toPointer())
    rating?.set("game",film?.toPointer())
    rating?.set("score",score)
    await rating?.save();

    // 更新全局平均分数
    let query = new Parse.Query("LQLGameRating");
    query.equalTo("game",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("LQLGameRating");
    query.equalTo("user",Parse.User.current()?.toPointer())
    query.equalTo("game",film?.toPointer())
    return await query.first()
  }


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

  async loadGames() {
    const queryParams = {
      name: this.searchName,
      details: this.searchDetails,
      rating: this.selectedRating,
      sortByRating:this.sortByRating
    };
    this.games=await this.gameService.getGames(queryParams);
   
  }

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

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


//   films = [
//     { title: '王者荣耀', image: 'assets/image/WangZhiRongYao.webp', details: '奥特曼的详情描述', rating: 8.5 },
//     { title: '和平精英', image: 'assets/image/HePinJinYing.webp', details: '肖生克的救赎的详情描述', rating: 9.3 },
//     { title: '我的世界', image: 'assets/image/WoDeShiJie.webp', details: '哆啦A梦的详情描述', rating: 8.0 },
//     { title: '迷你世界', image: 'assets/image/MiNiShiJie.png', details: '蜘蛛侠的详情描述', rating:9.0 },
//     { title: '绝区零', image: 'assets/image/JueQuLing.png', details: '蜘蛛侠的详情描述', rating:9.1 },
//     { title: '星穹铁道', image: 'assets/image/XingQuTieDao.jpg', details: '蜘蛛侠的详情描述', rating:9.2 },
//     { title: '原神', image: 'assets/image/YuanShen.png', details: '蜘蛛侠的详情描述', rating:9.3 },
//     { title: '极品飞车', image: 'assets/image/JiPinFeiChe.jpg', details: '蜘蛛侠的详情描述', rating:9.5 },
//     { title: '植物大战僵尸', image: 'assets/image/ZhiWuDaZhanJiangShi.jpg', details: '蜘蛛侠的详情描述', rating:9.1 },
//     { title: '火影忍者', image: 'assets/image/HuoYingRenZhe.jpg', details: '蜘蛛侠的详情描述', rating:9.6 },
//     { title: '光遇', image: 'assets/image/GuangYu.webp', details: '蜘蛛侠的详情描述', rating:9.7 },
//     { title: '第五人格', image: 'assets/image/DiWuRenGe.png', details: '蜘蛛侠的详情描述', rating:9.0 },
//     { title: '金铲铲', image: 'assets/image/JinChuanChuan.jpg', details: '蜘蛛侠的详情描述', rating:9.0 },
//   ];

//   constructor(private modalController: ModalController) {}

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