import { Component, CUSTOM_ELEMENTS_SCHEMA, NgZone } from '@angular/core';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
import { addIcons } from 'ionicons';
import { caretDownOutline, chevronForwardOutline } from 'ionicons/icons';
import { Router } from '@angular/router';
import { register } from 'swiper/element/bundle';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { CommonModule } from '@angular/common';
import { IonButton, IonCard, IonContent, IonImg, IonLabel, IonRefresher, IonSearchbar, IonSegment, IonSegmentButton, IonSegmentContent, IonSegmentView, IonText, ScrollDetail } from '@ionic/angular/standalone';
import { RecommendationService } from 'src/lib/service/recommend';
addIcons({ caretDownOutline, chevronForwardOutline });
register();
@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,
  imports: [ExploreContainerComponent, CommonModule, IonButton, IonImg, IonContent, IonCard,
    IonSegment, IonSegmentButton, IonSegmentContent, IonLabel, IonSegmentView, IonText, IonSearchbar,
    IonRefresher
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})

export class Tab1Page {
  constructor(private router: Router) { }
  async ngOnInit() {
    await this.getAllItem();
    await this.getRecommendItem();
  }
  ionViewWillEnter() {
    this.getHotItem();
  }
  /**
   * @动态元素定位修改
   */
  handleScroll(ev: CustomEvent<ScrollDetail>) {
    if (ev.detail.scrollTop != 0) {
      let element = document.getElementById("location");
      if (element)
        element.style.color = "black";

      element = document.getElementById("icon");
      if (element)
        element.style.color = "black";
    }
    else {
      let element = document.getElementById("location");
      if (element)
        element.style.color = "white";

      element = document.getElementById("icon");
      if (element)
        element.style.color = "white";
    }
  }
  //转到GenerateOption页面
  goGenerateOption() {
    this.router.navigate(['generateOption']);
  }
  goAiChat(){
    this.router.navigate(['aiChat']);
  }
  /**
   * @读取热门item
   */
  items: CloudObject[] | any = [];
  async getHotItem() {
    let query = new CloudQuery("ItemInfo");
    this.items = await query.find();
    this.items.sort((a: { get: (arg0: string) => number; }, b: { get: (arg0: string) => number; }) => b.get('click') - a.get('click'));
    this.items = this.items.slice(0, 7);
    console.log("获取热门item的top7成功：")
    console.log(this.items);
  }
  /**
   * @读取推荐item
   */
  currentUser: CloudUser = new CloudUser();
  recommendItems: CloudObject[] | any = [];
  alreadyItems: CloudObject[] | any = [];
  mostlikeItems: CloudObject[] | any = [];
  async getAllItem() {
    let query = new CloudQuery("UserPrefer");
    query.include("UserID");
    query.include("ItemID");
    query.equalTo("UserID", this.currentUser.toPointer());
    this.recommendItems = await query.find();
    this.recommendItems.sort((a: { get: (arg0: string) => number; }, b: { get: (arg0: string) => number; }) => b.get('preference') - a.get('preference'));
    this.mostlikeItems = this.recommendItems.slice(0, 7);
    console.log("读取所有偏好信息成功：")
    console.log(this.recommendItems);
  }
  async getRecommendItem() {
    let tempItems: CloudObject[] | any = [];
    //将recommendItems从最中间分开为list1和list2，每组随机抽取2个，放入tempItems中
    let list1 = this.recommendItems.slice(0, Math.floor(this.recommendItems.length / 2));
    let list2 = this.recommendItems.slice(Math.floor(this.recommendItems.length / 2));
    for (let i = 0; i < 2; i++) {
      if (list1.length > 0) {
        let index = Math.floor(Math.random() * list1.length);
        tempItems.push(list1[index]);
        console.log("推荐"+list1[index]?.id+"成功")
        list1.splice(index, 1);
      }
      if (list2.length > 0) {
        let index = Math.floor(Math.random() * list2.length);
        tempItems.push(list2[index]);
        console.log("推荐"+list1[index]?.id+"成功")
        list2.splice(index, 1);
      }
    }
    //将alreadyItems放入list2，再将list1和list2变为recommendItems
    for (let i = 0; i < this.alreadyItems.length; i++) {
      list2.push(this.alreadyItems[i]);
    }
    this.recommendItems = list1.concat(list2);
    //将recommendItems降序排序
    this.recommendItems.sort((a: { get: (arg0: string) => number; }, b: { get: (arg0: string) => number; }) => b.get('preference') - a.get('preference'));
    //让alreadyItems=tempItems，以便下次推荐时不再重复
    this.alreadyItems = tempItems;
    console.log("获取推荐item成功：")
    console.log(this.alreadyItems);
  }
  async recommend(item: CloudObject) {
    console.warn("检测到点击物品：")
    console.log(item);
    let newItem = new CloudQuery("ItemInfo");
    newItem.equalTo("objectId", item?.id);
    const newitem = await newItem.find();
    console.log(newitem);
    let recommendService = new RecommendationService();
    recommendService.onItemClick(this.currentUser, newitem[0]);
  }

  handleRefresh(event: any) {
    setTimeout(() => {
      this.getRecommendItem();
      event.target.complete();
    }, 2000);
  }
}