import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NavController, ModalController } from '@ionic/angular';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { EditPage } from '../edit/edit.page';

@Component({
  selector: 'app-test-message',
  templateUrl: './test-message.page.html',
  styleUrls: ['./test-message.page.scss'],
  standalone:false,
})
export class TestMessagePage implements OnInit {
  //diary: CloudObject | null = null;
  diary: any = null;  // 改为 any 类型或创建接口
  diaryId: string = '';

  constructor(
    private route: ActivatedRoute, 
    private navCtrl: NavController,
    private modalCtrl: ModalController
  ) {}

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.diaryId = params['Did'];
      this.loadDiary();
    });
  }

  async loadDiary() {
    if (!this.diaryId) return;
    
    const query = new CloudQuery("Diary");
    query.equalTo("Did", parseInt(this.diaryId));
    //this.diary = await query.first();

    const result = await query.first();
    // 将 CloudObject 转换为普通对象
    if (result) {
      this.diary = {
        get: (key: string) => result.get(key),
        id: result.id  // 假设 CloudObject 有 id 属性
      };
    }
  }

  async editDiary() {
    if (!this.diary) return;

    // 准备要编辑的数据
    const diaryData = {
      Did: this.diary.get('Did'),
      date: this.diary.get('date'),
      weekday: this.diary.get('weekday'),
      time: this.diary.get('time'),
      content: this.diary.get('content'),
      weather: this.diary.get('weather'),
      mood: this.diary.get('mood')
    };
    
    const modal = await this.modalCtrl.create({
      component: EditPage,
      componentProps: {
        diary: diaryData,
        editMode: true
      }
    });
    
    modal.onDidDismiss().then((result) => {
      if (result.data?.saved) {
        this.loadDiary(); // 刷新日记详情
      }
    });
    
    await modal.present();
  }

  async deleteDiary() {
    if (!this.diary || !this.diary.id) return;
    
    try {
      // 创建查询并删除
      const query = new CloudQuery("Diary");
      query.equalTo("objectId", this.diary.id);
      const objectToDelete = await query.first();
      
      if (objectToDelete) {
        // 假设 CloudObject 有 destroy 方法而不是 delete
        await objectToDelete.destroy(); // 或者使用其他删除方法如 remove()
        this.navCtrl.navigateBack('/tabs/tab1');
      }
    } catch (error) {
      console.error('删除日记失败:', error);
    }
  }
} 