import { Component } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
  standalone: false,
})
export class Tab3Page {
  currentUser: CloudUser | null = null;
  isLoggedIn: boolean = false;

  constructor(private alertCtrl: AlertController) {
    this.checkLoginStatus();
  }

  async checkLoginStatus() {
    this.currentUser = new CloudUser();
    if (this.currentUser.sessionToken) {
      try {
        await this.currentUser.current();
        this.isLoggedIn = true;
      } catch (error) {
        console.error('检查登录状态失败:', error);
        this.isLoggedIn = false;
      }
    } else {
      this.isLoggedIn = false;
    }
  }

async showLoginAlert() {
  const alert = await this.alertCtrl.create({
    header: '用户登录',
    inputs: [
      {
        name: 'username',
        type: 'text',
        placeholder: '用户名'
      },
      {
        name: 'password',
        type: 'password',
        placeholder: '密码'
      }
    ],
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '登录',
        handler: async (data) => {
          if (!data.username || !data.password) {
            this.showErrorAlert('用户名和密码不能为空');
            return false; // 阻止关闭
          }
          
          try {
            const user = new CloudUser();
            const result = await user.login(data.username, data.password);
            
            if (result) {
              this.checkLoginStatus();
              return true; // 允许关闭
            } else {
              this.showErrorAlert('登录失败，请检查用户名和密码');
              return false; // 阻止关闭
            }
          } catch (error) {
            console.error('登录错误:', error);
            this.showErrorAlert('登录过程中发生错误');
            return false; // 阻止关闭
          }
        }
      }
    ]
  });

  await alert.present();
}

  async showErrorAlert(message: string) {
    const alert = await this.alertCtrl.create({
      header: '错误',
      message: message,
      buttons: ['确定']
    });
    await alert.present();
  }

  async logout() {
    if (this.currentUser) {
      await this.currentUser.logout();
      this.isLoggedIn = false;
      this.currentUser = null;
    }
  }
}