import { Component, OnInit } from '@angular/core';
import { ModalController, ToastController, IonInput, IonItem, IonLabel, IonButton, IonCard, IonCardHeader, IonCardTitle, IonCardSubtitle, IonCardContent } from '@ionic/angular/standalone';
import { CloudObject } from 'src/lib/ncloud';
import { FormsModule } from '@angular/forms'; // 导入 FormsModule
import { CommonModule } from '@angular/common';
import { UserService } from 'src/app/user.service'; // 假设这是你的用户服务

@Component({
  selector: 'app-throw-drift-bottle',
  templateUrl: './throw-drift-bottle.component.html',
  styleUrls: ['./throw-drift-bottle.component.scss'],
  standalone: true,
  imports: [
    IonCard,
    IonCardHeader,
    IonCardTitle,
    IonCardSubtitle,
    IonCardContent,
    IonButton,
    IonInput,
    IonItem,
    IonLabel,
    FormsModule,
    CommonModule
  ],
})
export class ThrowDriftBottleComponent implements OnInit {
  driftbottleData: { content: string, username: any, status: string } = { content: '', username: '', status: 'drifting' }; // 漂流瓶内容、用户名和状态

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

  ngOnInit() {
    const userId = this.userService.getUserId(); // 获取当前用户的 ID
    if (userId) {
      this.driftbottleData.username = { __type: 'Pointer', className: '_User', objectId: userId };
    } else {
      console.error('用户未登录');
    }
  }

  async throw() {
    console.log('投掷漂流瓶:');
    console.log(`内容: ${this.driftbottleData.content}`);
    console.log(`用户名: ${this.driftbottleData.username}`);
    console.log(`状态: ${this.driftbottleData.status}`);

    const driftbottleData = {
      content: this.driftbottleData.content,
      username: this.driftbottleData.username,
      status: this.driftbottleData.status,
    };

    let driftbottle = new CloudObject("Driftbottle");
    driftbottle.set(driftbottleData);
    try {
      await driftbottle.save();
      console.log('漂流瓶已成功投掷');

      // 显示成功的 toast 提示
      const toast = await this.toastCtrl.create({
        message: '扔出成功！',
        duration: 2000,
        position: 'middle'
      });
      toast.present();

      this.modalCtrl.dismiss(driftbottle, "confirm");
    } catch (err) {
      console.error('投掷漂流瓶时出错', err);

      // 显示错误的 toast 提示
      const toast = await this.toastCtrl.create({
        message: '扔出失败，请重试。',
        duration: 2000,
        position: 'middle'
      });
      toast.present();
    }
  }

  cancel() {
    this.modalCtrl.dismiss(null, "cancel");
  }
}

export async function openThrowDriftBottleModal(modalCtrl: ModalController): Promise<any> {
  const modal = await modalCtrl.create({
    component: ThrowDriftBottleComponent,
    breakpoints: [0.7, 1.0],
    initialBreakpoint: 0.7
  });
  modal.present();

  const { data, role } = await modal.onWillDismiss();

  if (role === 'confirm') {
    return data;
  }
  return null;
}