import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common'; // 导入 CommonModule

import { IonHeader, IonButton, IonContent, IonIcon, IonItem, IonLabel, IonList, 
  IonListHeader, IonCardHeader, IonCardTitle, IonCardContent, IonTitle, IonCard, IonToolbar, IonInput, IonSearchbar } from '@ionic/angular/standalone';
import { CloudQuery, CloudUser } from 'src/lib/ncloud';
import { UserService } from 'src/app/user.service'; // 假设这是你的用户服务

@Component({
  selector: 'app-my-drift-bottle',
  templateUrl: './my-drift-bottle.component.html',
  styleUrls: ['./my-drift-bottle.component.scss'],
  standalone: true,
  imports: [
    CommonModule, // 添加 CommonModule
    
    IonHeader, IonToolbar, IonTitle, IonContent,
    IonList, IonListHeader, IonItem, IonCardTitle,
    IonLabel, IonIcon, IonButton, IonCardContent,
    IonInput, IonSearchbar, IonCard, IonCardHeader,
  ]
})
export class MyDriftBottleComponent implements OnInit {
  thrownDriftbottles: any[] = [];
  caughtDriftbottles: any[] = [];

  constructor(private router: Router, private userService: UserService) {}

  async ngOnInit() {
    await this.getDriftbottles(); // 获取所有漂流瓶并进行过滤
  }

  async getDriftbottles() {
    const query = new CloudQuery('Driftbottle'); // 确保表名为 driftbottle
    try {
      const results = await query.find();
      this.filterDriftbottles(results);
    } catch (error) {
      console.error('加载漂流瓶时出错', error);
    }
  }

  filterDriftbottles(driftbottles: any[]) {
    const username = this.userService.getUsername();
    this.thrownDriftbottles = driftbottles.filter(bottle => bottle.get('username') === username).map(bottle => ({
      content: bottle.get('content'),
      createdAt: bottle.createdAt.toISOString().split('T')[0]
    }));

    this.caughtDriftbottles = driftbottles.filter(bottle => bottle.get('username') !== username).map(bottle => ({
      content: bottle.get('content'),
      createdAt: bottle.createdAt.toISOString().split('T')[0]
    }));
  }

  goDriftbottle() {
    this.router.navigate(['tabs/drift-bottle']);
  }

  throwNewDriftbottle() {
    this.router.navigate(['tabs/throw-drift-bottle']); // 假设这是投掷新漂流瓶的路由
  }
}