import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';

import { Http, Response } from '@angular/http';
import { Storage } from '@ionic/storage';

import { AppService } from '../../../../service/http.service';


import { LoginPage } from '../../../login/login';

@IonicPage()
@Component({
  selector: 'page-modifyPassword',
  templateUrl: 'modifyPassword.html'
})
export class ModifyPasswordPage {

  myreg = /^(?![^a-zA-Z]+$)(?!\\D+$).{8,16}$/;  

  user= {
    mobile:'',
    password:''
  }
  passwordInfo = {
    formerPassword:'',
    modifyPassword:'',
    sureModifyPassword:''
  }

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public storage: Storage,
    public alertCtrl: AlertController,
    private loadingCtrl: LoadingController,
    public http: Http,
    public appService: AppService,) {

      this.storage.get("userLoginInfo").then((value)=>{
         this.user = value;
      });
  }

  sureModifyPassword(){
    if(this.passwordInfo.formerPassword == ''||
       this.passwordInfo.modifyPassword == ''||
       this.passwordInfo.sureModifyPassword == ''){
        this.appService.popToastView("请输入完整信息！",'top',2000);
        return;
    } 
    if(this.passwordInfo.formerPassword != ''){           
      if(this.user.password != this.passwordInfo.formerPassword){
        this.appService.popToastView("原密码输入有误！",'top',2000);
        return ;
      }  
    }
    if(!this.myreg.test(this.passwordInfo.modifyPassword)){  
        this.appService.popToastView('新密码由8到16位数字和字母组成！','top',2000);
        return false;  
    }  
    if(this.passwordInfo.modifyPassword != this.passwordInfo.sureModifyPassword){
          this.appService.popToastView("两次输入的密码不一致",'top',2000);
          return;
    }else{
          this.appService.ObserverHttpPost("/wisdomgroup/manager/updatePassword",{"password":this.passwordInfo.modifyPassword})
          .subscribe((res: Response) => {   
              this.appService.popToastView("修改成功！",'top',2000);                           
              //将缓存中密码密码修改
              this.user.password = this.passwordInfo.modifyPassword;
              this.storage.set('userLoginInfo',this.user);
              //退出后台
              this.logoutApp();
              //退出到登录页
              this.navCtrl.setRoot("LoginPage");              
            }, error => {        
            }
          );
    }  
  }

  logoutApp(){
    this.appService.ObserverHttpGet("/wisdomgroup/app/logout",null)
      .subscribe((res: Response) => {   
          let data = res.json();
        }, error => {        
        }
      );
  }
}
