import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {Storage} from "@ionic/storage";
import {LoadingController} from "@ionic/angular";
import {TabsService} from "../tabs.service";
import {CommonService} from "../../../provide/common.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage {
  submitted: boolean = false;								//表单是否已经提交
  tipFlag: boolean = false;            // 输入时隐藏输入框以下信息
  user = {
    userid: '',							//登录数据
    mobile: '',
    password: '',
    remember:true
  };
  tabflag:any;
  constructor(
      public router:Router,
              public storage: Storage,
              private loadingCtrl: LoadingController,
              public commonSer:CommonService,
              private tabSer:TabsService,) {

  }

  ionViewDidLoad(){

  }

  ionViewDidEnter() {
    //默认显示
    this.storage.get("userLoginInfo").then((value)=>{
      if(value!=null && value != ''){
        if( value.remember ){
          this.user = value;
        }
      }
    });
  }

  //输入框获取焦点：隐藏，失去焦点：显示
  getFocus() {
    this.tipFlag = true;
  }

  loseFocus() {
    this.tipFlag = false;
  }

  async login() {

    //验证手机号和密码是否输入
    if(this.user.mobile == null || this.user.mobile == ''){
      this.commonSer.toast('请输入手机号！');
      return ;
    }
    if(this.user.password == null || this.user.password == ''){
      this.commonSer.toast('请输入密码！');
      return ;
    }

    let loading = await this.loadingCtrl.create({
      message: '正在登录...',
    });
    loading.present();
    this.tabSer.loginpost(this.user).subscribe(
        (res)=>{
          loading.dismiss();
          this.submitted = true;
          if(res.code == '200'){
            this.storage.set('user', res.data);
            this.user.userid = res.data.id;
            this.storage.set('userLoginInfo',this.user);
            this.router.navigate(['/tabs/home']);
          }else{
            this.commonSer.alert('手机号或密码错误！');
          }
        },
        (err)=>{
          if (loading) loading.dismiss();
          this.commonSer.alert('系统错误！');
        }
    )
  }
  //忘记密码
  forgetPassword():void{
    this.commonSer.alert('若忘记密码，请与人事处联系。');
  }
}
