import { Component, OnInit } from '@angular/core';
import { ModalController, IonList, IonItem, IonLabel, IonButton, IonIcon, IonContent, IonHeader, IonToolbar, IonTitle, IonBackButton } from '@ionic/angular/standalone';
import { CloudQuery } from 'src/lib/ncloud';
import { UserService } from 'src/app/user.service'; // 假设这是你的用户服务
import { openThrowDriftBottleModal } from '../throw-drift-bottle/throw-drift-bottle.component';

@Component({
  selector: 'app-my-drift-bottle',
  templateUrl: './my-drift-bottle.component.html',
  styleUrls: ['./my-drift-bottle.component.scss'],
  standalone: true,
  imports: [
    IonHeader,
    IonToolbar,
    IonTitle,
    IonBackButton,
    IonContent,
    IonList,
    IonItem,
    IonLabel,
    IonButton,
    IonIcon
  ]
})
export class MyDriftBottleComponent implements OnInit {
  thrownDriftbottles: any[] = [];

  constructor(
    private modalCtrl: ModalController,
    private userService: UserService // 注入用户服务
  ) {}

  ngOnInit() {
    this.loadThrownDriftbottles();
  }

  async loadThrownDriftbottles() {
    const query = new CloudQuery('Driftbottle');
    query.equalTo('username.objectId', this.userService.getUserId());
    try {
      const results = await query.find();
      this.thrownDriftbottles = results.map(result => ({
        content: result.get('content'),
        createdAt: result.createdAt.toISOString().split('T')[0]
      }));
    } catch (error) {
      console.error('加载漂流瓶时出错', error);
    }
  }

  async goDriftbottle() {
    const driftbottle = await openThrowDriftBottleModal(this.modalCtrl);
    if (driftbottle) {
      this.thrownDriftbottles.push({
        content: driftbottle.get('content'),
        createdAt: driftbottle.createdAt.toISOString().split('T')[0]
      });
    }
  }
}