import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { AuthService } from '../services/auth.service';
import { ActivatedRoute } from '@angular/router';
@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 authService: AuthService,
    private navCtrl:NavController,
    private activatedRoute: ActivatedRoute
  ) { 
    this.activatedRoute.params.subscribe(()=>{
      //this.loadDiaries();
      this.loadUserData();
    })
  }

  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;
  }

  async goLogin(action?:string){
      if (this.currentUser) {
      // 已登录，执行登出
      const success = await this.authService.logout();
      if (success) {
        this.currentUser = null;
        this.diaryCount = 0;
        this.recordDays = 0;
        this.totalWords = 0;
      }
    } else {
      // 未登录，跳转到登录页面
      this.navCtrl.navigateForward(["tabs","tab4","login"]);
    }
    //this.navCtrl.navigateForward(["tabs","tab4","login"])
  }
}
