import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { UserService } from '../service-user/user.service';

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

  constructor(
    private userServ: UserService,
    private router: Router,
    private alertCtrl: AlertController
  ) { }
  userData: any = {
    username: "",
    password: ""
  }

  goBack() {
    let path = localStorage.getItem("REDIRECT_URL") || "/lesson/me"
    if (path=="/cook/mine") path ="/lesson/me"
    this.router.navigate([path])
  }

  goRegister() {
    let path = "/user/register"
    this.router.navigate([path])
    console.log('账户已保存，去登录吧')
  }

  async login() {
    console.log(this.userData)
    try {
      let isLogin = await this.userServ.checkUserPassword(this.userData)
      if (isLogin) {
        this.goBack()
      }
    } catch (err) {
      let msg: any = err
      this.alertError(msg)
      console.log('账户已保存')
    }
  }
  async alertError(err: string | undefined) {
    const alert = await this.alertCtrl.create({
      header: '登陆失败',
      subHeader: '请检查用户名密码',
      message: err,
      buttons: ['好的'],
    });

    await alert.present();
  }
}
