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

@Component({
  selector: 'app-login',
  templateUrl: 'login.page.html',
  styleUrls: ['login.page.scss']
})
export class LoginPage {
  username: string = "";
  password: string = "";
  registeredUsername: string = "admin";
  registeredPassword: string = "123456";

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

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

  async login() {
    if (this.username === "" || this.password === "") {
      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');
      }
    } else {
      if (this.username === this.registeredUsername && this.password === this.registeredPassword) {
        console.log('登录成功');
        // 登录成功后跳转到tab3页面
        this.navCtrl.navigateForward('/tabs/tab3');
      } else if (this.username !== this.registeredUsername) {
        const toast = await this.toastController.create({
          message: '账号不存在',
          duration: 2000,
          color: 'danger'
        });
        toast.present();
      } else {
        const toast = await this.toastController.create({
          message: '密码错误',
          duration: 2000,
          color: 'danger'
        });
        toast.present();
      }
    }
  }

  goToRegister() {
    this.navCtrl.navigateForward('/register');
  }
}