import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { AppNotification } from '@global/service/Notification';
import { Http } from '@global/service/Http';
import { AppEnvironment } from 'src/environments/AppEnvironment';

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

    /**
     * 用户名
     *
     * @memberof AppLoginView
     */
    public username: string = '';

    /**
     * 密码
     *
     * @memberof AppLoginView
     */
    public password: string = '';

    /**
     * 实例化对象
     *
     * @memberof AppLoginView
     */
    constructor(private $http: Http, private $notification: AppNotification,private $navCtrl:NavController) { }

    /**
     * angular生命周期
     *
     * @memberof AppLoginView
     */
    ngOnInit() { }

    /**
     * 登录
     *
     * @memberof AppLoginView
     */
    public async login(): Promise<any> {
      let loginUrl;
      if(Object.is(AppEnvironment.LoginModel,'default')){
        loginUrl = AppEnvironment.RemoteLogin;
      }else{
        loginUrl = AppEnvironment.AppLogin;
      }
      this.$http.post(loginUrl, { loginname: this.username, password: this.password }).then((response:any) =>{
        if (response) {
          if(window.localStorage.getItem('srfloginkey')){
            window.localStorage.removeItem('srfloginkey');
          }
          if(window.localStorage.getItem('userInfo')){
            window.localStorage.removeItem('userInfo');
          }
          //默认登陆方式
          if(Object.is(AppEnvironment.LoginModel,'default')){
            //远程登录
            window.localStorage.setItem('srfloginkey', response.loginkey);
          }else{
            //session登录方式
            window.localStorage.setItem('srfloginkey', response.token);
          }
          window.localStorage.setItem('userInfo', JSON.stringify(response.user));
          if(window.location.hash.indexOf('url=') !== -1){
            let  urlIndex= window.location.hash.indexOf('url=') + 4;
            this.$navCtrl.navigateRoot(''+decodeURIComponent(window.location.hash.substring(urlIndex)));
          }else{
            this.$navCtrl.navigateRoot('');
          }
        } else {
          this.$notification.error("登录失败");
        }
      }).catch((error:any) =>{
        this.$notification.error("登录失败");
      });
    }

    /**
     * 注册用户
     *
     * @memberof AppLoginView
     */
    public registerAccount(): void { }

    /**
     * 忘记密码
     *
     * @memberof AppLoginView
     */
    public modifyPassword(): void { }

  }