import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NavController, ModalController,AlertController } from '@ionic/angular';
import { CloudObject, CloudQuery,CloudUser } 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 = '';
  currentUser: CloudUser | null = null;
  constructor(
    private route: ActivatedRoute, 
    private navCtrl: NavController,
    private modalCtrl: ModalController,
     private alertCtrl: AlertController
  ) {}

  async ngOnInit() {
    this.currentUser = await CloudUser.current();
    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 属性
      };
      // 检查日记是否属于当前用户
      const diaryUser = result.get('user');
      if (diaryUser && diaryUser.objectId !== this.currentUser?.id) {
        this.showNotOwnerAlert();
      }
    }
  }

  async showNotOwnerAlert() {
    const alert = await this.alertCtrl.create({
      header: '权限不足',
      message: '这不是你的日记，无法编辑或删除',
      buttons: ['确定']
    });
    await alert.present();
  }

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

    // 检查日记是否属于当前用户
    const diaryUser = this.diary.get('user');
    if (diaryUser && diaryUser.objectId !== this.currentUser.id) {
      this.showNotOwnerAlert();
      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'),
      user: this.currentUser.toPointer()
    };
    
    const modal = await this.modalCtrl.create({
      component: EditPage,
      componentProps: {
        diary: diaryData,
        editMode: true,
        currentUser: this.currentUser
      }
    });
    
    modal.onDidDismiss().then((result) => {
      if (result.data?.saved) {
        this.loadDiary(); // 刷新日记详情
      }
    });
    
    await modal.present();
  }

  async deleteDiary() {
    if (!this.diary || !this.diary.id || !this.currentUser) return;
    
    // 检查日记是否属于当前用户
    const diaryUser = this.diary.get('user');
    if (diaryUser && diaryUser.objectId !== this.currentUser.id) {
      this.showNotOwnerAlert();
      return;
    }

    const alert = await this.alertCtrl.create({
      header: '确认删除',
      message: '确定要删除这篇日记吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '删除',
          handler: async () => {
            try {
              const query = new CloudQuery("Diary");
              query.equalTo("objectId", this.diary.id);
              const objectToDelete = await query.first();
              
              if (objectToDelete) {
                await objectToDelete.destroy();
                this.navCtrl.navigateBack('/tabs/tab1');
              }
            } catch (error) {
              console.error('删除日记失败:', error);
            }
          }
        }
      ]
    });
    
    await alert.present();
  }
} 