import { Component, OnInit } from '@angular/core';
import { IonAvatar, 
  IonText, 
  IonButton, 
  IonIcon, 
  IonCard, 
  IonList, 
  IonItem, 
  IonLabel, 
  IonBadge,
  IonContent, 
  IonInput,
  AlertController,
  ModalController } from '@ionic/angular/standalone';
import { ModalUserEditComponent } from '../modal-user-edit/modal-user-edit.component';
import { FormsModule } from '@angular/forms';
import { CloudUser } from 'src/lib/ncloud';
import { ModalUserRegisterComponent } from '../modal-user-register/modal-user-register.component';

@Component({
  selector: 'app-page-mine',
  templateUrl: './page-mine.component.html',
  styleUrls: ['./page-mine.component.scss'],
  standalone: true,
  imports: [
    IonContent, 
    IonAvatar, 
    IonText, 
    IonButton, 
    IonIcon, 
    IonCard, 
    IonList, 
    IonItem, 
    IonLabel, 
    IonBadge,
    IonInput,
    FormsModule
  ]
})
export class PageMineComponent implements OnInit {
  currentUser: CloudUser | undefined;
  username: string = '';
  password: string = '';

  constructor(
    private modalCtrl: ModalController,
    private alertCtrl: AlertController
  ) {
    this.currentUser = new CloudUser();
  }

  //编辑
  async edit() {
    const modal = await this.modalCtrl.create({
      component: ModalUserEditComponent,
    });
    modal.present();

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

  //登录
  async login() {
    if (!this.username || !this.password) {
      const alert = await this.alertCtrl.create({
        header: '错误',
        message: '请输入用户名和密码',
        buttons: ['确定']
      });
      await alert.present();
      return;
    }

    try {
      let user: any = new CloudUser();
      user = await user?.login(this.username, this.password);
      if (user?.id) {
        this.currentUser = user;
      } else {
        const alert = await this.alertCtrl.create({
          header: '登录失败',
          message: '用户名或密码错误',
          buttons: ['确定']
        });
        await alert.present();
      }
    } catch (error) {
      const alert = await this.alertCtrl.create({
        header: '登录错误',
        message: '登录过程中发生错误，请重试',
        buttons: ['确定']
      });
      await alert.present();
    }
  }

  async openRegisterModal() {
  const modal = await this.modalCtrl.create({
    component: ModalUserRegisterComponent
  });
  await modal.present();

  const { role } = await modal.onWillDismiss();
  if (role === 'registered') {
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '请使用您刚刚注册的账号登录',
      buttons: ['确定']
    });
    await alert.present();
  }
}



//登出  
logout() {
    this.currentUser?.logout();
    this.currentUser = undefined;
    this.username = '';
    this.password = '';
  }

  ngOnInit() {}
}