import { Component } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { IonAvatar, IonButton, IonCard, IonContent, IonIcon, IonImg, IonLabel, IonSegment, IonSegmentButton, IonSegmentContent, IonSegmentView, IonText, IonTitle, ModalController } from '@ionic/angular/standalone';
import { CloudUser, CloudObject, CloudQuery } from 'src/lib/ncloud';
import { Router } from '@angular/router';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { addIcons } from 'ionicons';
import { cardOutline, chevronForwardOutline, flameOutline, personAddOutline } from 'ionicons/icons';
import { CommonModule } from '@angular/common';
addIcons({ personAddOutline, cardOutline, flameOutline, chevronForwardOutline })
@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
  standalone: true,
  imports: [IonIcon, IonContent, IonCard, IonLabel, IonSegment, IonSegmentButton, IonSegmentView,
    CommonModule, IonSegmentContent, IonAvatar, IonImg, IonTitle, IonButton, IonText],
})
export class Tab3Page {
  currentUser: CloudUser | undefined;
  constructor(private modalCtrl: ModalController, private router: Router) { }
  async ngOnInit() {
    this.currentUser = new CloudUser();
    await this.loadAttentionList();
    await this.loadFanList();
    await this.loadPostList();
    await this.getHistoryCount();
  }
  async ionViewWillEnter() {
    console.warn("-------------------------\n" + "进入tab3界面，执行ionViewWillEnter\n" + "验证用户是否登录")
    let user: any = new CloudUser();
    if (user?.id == null) {
      console.error("用户未登录,即将跳转到登录页面")
      user = await openUserLoginModal(this.modalCtrl);
      console.log("接受到来自login模态的登录用户信息:");
      console.log(user);
    }
    else {
      console.log("用户已登录,更新用户缓存信息")
      console.log("当前用户信息（未更新缓存前）:");
      console.log(user);
      //await user.updateCache();
      console.log("当前用户信息:");
      console.log(user);
    }
    console.log("进入到我的界面，准备实例化currentUser对象");
    this.currentUser = new CloudUser();
    this.getPosts();
  }
  /**
   * @格式化为带单位的数字
   */
  formatNumber(num: number): string {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + 'w';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k';
    } else {
      return num + '';
    }
  }
  /**
   * @跳转界面函数
   */
  goSetting() {
    this.router.navigate(["/settings"]);
  }
  goPostDetail(post: CloudObject) {
    this.router.navigate(['postDetail', post.id]);
  }
  goGenerateHistory() {
    this.router.navigate(["generateHistory"]);
  }
  goAttention(isFollowing: boolean) {
    this.router.navigate(['/attention'], { state: { currentTab: isFollowing } }); // 传递状态
  }
  /**
   * @读取用户发布的帖子
   */
  posts: any[] | undefined;
  async getPosts() {
    let query = new CloudQuery('post');
    query.equalTo('UserID', this.currentUser?.toPointer());
    this.posts = await query.find();
    console.log("获取到用户发布的帖子:");
    console.log(this.posts);
    this.posts = this.posts.reverse();
  }
  /**
   * @读取个人信息卡片数据
   */
  /*加载关注列表*/
  attentionList: CloudObject[] = [];
  async loadAttentionList() {
    const query = new CloudQuery('attention');
    query.equalTo('UserID', this.currentUser?.toPointer());
    this.attentionList = await query.find();
    console.log(this.attentionList);
  }
  /*加载粉丝列表*/
  fanList: CloudObject[] = [];
  async loadFanList() {
    const query = new CloudQuery('attention');
    query.equalTo('attentionID', this.currentUser?.toPointer());
    this.fanList = await query.find();
    //console.log(this.fanList);
  }
  /**
   * @读取统计卡片数据
   */
  /*加载点赞帖子列表*/
  likedPostsNumber: number = 0;
  likedPostsImage: string = "";
  async loadPostList() {
    const query = new CloudQuery('postLikesRecord');
    query.equalTo('UserID', this.currentUser?.toPointer());
    query.include('postID');
    let postList = await query.find();
    postList = postList.reverse();
    this.likedPostsNumber = postList.length;
    this.likedPostsImage = postList[0]?.get('postID')?.image[0];
    console.log("获取到点赞帖子个数：" + this.likedPostsNumber + "\n" + "获取到点赞帖子图像：" + this.likedPostsImage);
  }
  /*返回生成历史个数和图像*/
  generateHistoryCount: number = 0;
  generateHistoryImage: string = "";
  async getHistoryCount() {
    let query = new CloudQuery('GenerateResult');
    query.equalTo('UserID', this.currentUser?.toPointer());
    let result = await query.find();
    result = result.reverse();
    this.generateHistoryImage = result[0]?.get('image');
    this.generateHistoryCount = result.length;
    console.log("获取到生成历史个数：" + this.generateHistoryCount + "\n" + "获取到生成历史图像：" + this.generateHistoryImage);
  }
}




