import { Component, OnInit } from '@angular/core';
import { AlertController, NavController } from '@ionic/angular';
import * as Parse from 'parse';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  username: string = "";
  password: string = "";
  
  constructor(
    private navCtrl: NavController,
    private alertController: AlertController
  ) { }

  ngOnInit() { }

  async login() {
    let user;
    try {
      user = await Parse.User.logIn(this.username, this.password);
      // 登录成功后立即加载用户数据
      this.loadUserData();
    } catch (error: any) {
      let message: string = "";
      if (error?.message.indexOf("is required") > -1) {
        message = "必须输入账号或邮箱";
      }
      if (error?.message.indexOf("Invalid username") > -1) {
        message = "账号或密码错误，请检查";
      }
      this.presentAlert({
        header: "登录失败",
        subHeader: "状态码:" + error.code,
        message: message || error.message
      });
    }
    console.log(user);
    if (user?.id) {
      this.navCtrl.navigateForward('/tabs/tab3'); // 导航到主页或其他页面
    }
  }

  async register() {
    let user = new Parse.User();
    user.set("username", this.username);
    user.set("password", this.password);
    try {
      let result = await user.signUp();
      console.log(result);
      if (result?.id) {
        // 注册成功后立即加载用户数据
        this.loadUserData();
        this.navCtrl.navigateForward('/tabs/tab3'); // 导航到主页或其他页面
      }
    } catch (error: any) {
      let message: string = "";
      if (error?.message.indexOf("already exists") > -1) {
        message = "该账号已存在请修改后重试";
      }
      if (error?.message.indexOf("empty") > -1) {
        message = "账号不能为空请输入后重试";
      }
      this.presentAlert({
        header: "注册失败",
        subHeader: "状态码:" + error.code,
        message: message || error.message
      });
    }
  }

  async presentAlert(options: { header: string, subHeader: string, message: string }) {
    const alert = await this.alertController.create({
      header: options?.header,
      subHeader: options?.subHeader,
      message: options?.message,
      buttons: ['好的'],
    });

    await alert.present();
  }

  back() {
    this.navCtrl.back();
  }

  async loadUserData() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      // 如果当前用户已登录，加载用户数据
      console.log('当前用户已登录:', currentUser.getUsername());
      // 这里可以调用你需要的加载用户数据的方法，比如触发检测数据的方法
      // 示例：
      // this.loadData();
    }
  }

  async logout() {
    try {
      await Parse.User.logOut();
      console.log('用户已登出');
      // 清除本地存储的用户数据，如需要可以重置页面数据或状态
      // 示例：
      // this.username = '';
      // this.password = '';
      // this.loadData(); // 清除用户数据
    } catch (error) {
      console.error('登出失败:', error);
    }
  }
}
