import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { EditPage } from './edit/edit.page'; 
import { IonRouterOutlet } from '@ionic/angular';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})
export class Tab1Page implements OnInit{
  
  router: any; 
  diaryList: CloudObject[]=[];
  currentUser: CloudUser | null = null;
  constructor(
    private modalCtrl: ModalController,
    private routerOutlet: IonRouterOutlet,
    private navCtrl: NavController,
    private activatedRoute: ActivatedRoute
  ) {
    this.activatedRoute.params.subscribe(()=>{
      //this.loadDiaries();
      this.loadCurrentUserAndDiaries();
    })
  }
  
  navigateTo(page: string) {
  // 根据传入的页面参数进行导航
  switch(page) {
    case 'settings':
      // 导航到设置页面
      break;
    case 'profile':
      this.navCtrl.navigateForward(["tabs","tab4"]); // 导航到我的页面
      break;
    case 'activity':
      this.navCtrl.navigateForward(["tabs","tab2"]);// 导航到动态页面
      break;
    case 'drafts':
      // 导航到草稿箱页面
      break;
  }
  
}
  
async loadCurrentUserAndDiaries() {
    // 获取当前用户
    this.currentUser = await CloudUser.current();
    
    if (this.currentUser) {
      // 如果用户已登录，加载该用户的日记
      await this.loadDiaries();
    } else {
      // 用户未登录，清空日记列表
      this.diaryList = [];
    }
  }
  async loadDiaries() {
    // let query=new CloudQuery("Diary"); 
    // this.diaryList=await query.find();

    if (!this.currentUser) return;
    
    let query = new CloudQuery("Diary");
    // 只查询当前用户的日记
    query.equalTo("user", this.currentUser.toPointer());
    // 按创建时间降序排列
    query.queryParams["order"] = "-createdAt";
    this.diaryList = await query.find();

  }

  ngOnInit() {
    this.diaryList=[];
  }

  async goToEditPage(edit?:string) {
  //   const modal = await this.modalCtrl.create({
  //   component: EditPage,
  //   componentProps: {
  //     editMode: edit === '编辑'
  //   }
  // });

  if (!this.currentUser) {
      // 如果用户未登录，跳转到登录页面
      this.navCtrl.navigateForward(['/login']);
      return;
    }

    const modal = await this.modalCtrl.create({
      component: EditPage,
      componentProps: {
        editMode: edit === '编辑',
        currentUser: this.currentUser
      }
    });
  
  // 模态框关闭后的处理
  modal.onDidDismiss().then((result) => {
    if (result.data?.saved) {
      this.loadDiaries(); // 保存成功后刷新日记列表
    }
  });
  
  await modal.present();
  }
 
  goMessage(diary: CloudObject){
    //console.log(diary),
    this.navCtrl.navigateForward(['tabs', 'tab1', 'message'], {
    queryParams: { Did: diary.get('Did') }
  });
  } 
}
