
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-register',
  templateUrl: 'register.page.html',
  styleUrls: ['register.page.scss']
})
export class RegisterPage {
  username: string = "";
  password: string = "";
  confirmPassword: string = "";

  @ViewChild('usernameInput', { static: false })
  usernameInput!: ElementRef;
  @ViewChild('passwordInput', { static: false })
  passwordInput!: ElementRef;
  @ViewChild('confirmPasswordInput', { static: false })
  confirmPasswordInput!: ElementRef;

  constructor(private navCtrl: NavController, private toastController: ToastController) {}

  async register() {
    if (this.username === "" || this.password === "" || this.confirmPassword === "") {
      const toast = await this.toastController.create({
        message: '账号、密码和确认密码不能为空',
        duration: 2000,
        color: 'danger'
      });
      toast.present();
      if (this.username === "") {
        this.usernameInput.nativeElement.classList.add('error');
      }
      if (this.password === "") {
        this.passwordInput.nativeElement.classList.add('error');
      }
      if (this.confirmPassword === "") {
        this.confirmPasswordInput.nativeElement.classList.add('error');
      }
    } else {
      if (this.password === this.confirmPassword) {
        // 模拟注册成功，实际情况应该保存到数据库或其他存储介质中
        console.log('注册成功:', { username: this.username, password: this.password });
        this.navCtrl.navigateForward('/login');
      } else {
        const toast = await this.toastController.create({
          message: '密码不一致，请重新输入',
          duration: 2000,
          color: 'danger'
        });
        toast.present();
      }
    }
  }

  goToLogin() {
    this.navCtrl.navigateForward('/login');
  }
}