import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';

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

  currentUser: CloudUser | null = null;
  diaryCount: number = 0;
  recordDays: number = 0;
  totalWords: number = 0;

  constructor(
    private navCtrl:NavController
  ) { }

  async ngOnInit() {
    await this.loadUserData();
  }

  async loadUserData() {
    // 获取当前用户
    this.currentUser = await CloudUser.current();
    
    if (this.currentUser) {
      // 获取用户日记统计
      await this.getDiaryStats();
    }
  }

  async getDiaryStats() {
    if (!this.currentUser) return;
    
    let query = new CloudQuery("Diary");
    query.equalTo("user", this.currentUser.toPointer());
    const diaries = await query.find();
    
    // 计算统计数据
    this.diaryCount = diaries.length;
    this.totalWords = this.calculateTotalWords(diaries);
    this.recordDays = this.calculateRecordDays(diaries);
  }

  private calculateTotalWords(diaries: CloudObject[]): number {
    return diaries.reduce((total, diary) => {
      const content = diary.get('content') || '';
      return total + content.length;
    }, 0);
  }

  private calculateRecordDays(diaries: CloudObject[]): number {
    const uniqueDates = new Set();
    diaries.forEach(diary => {
      const date = diary.get('date');
      if (date) {
        uniqueDates.add(date);
      }
    });
    return uniqueDates.size;
  }

  goLogin(user?:string){
    this.navCtrl.navigateForward(["tabs","tab4","login"])
  }
}
