import { Component, OnDestroy, OnInit } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LifeCommonService } from '../../common/life-common.service';

@Component({
  selector: 'ydlife-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
  MOBILE_REGEXP = /^(1)\d{10}$/;
  sendCodeHtml: string = '获取验证码';
  timer: any;
  remainTimes: number = 60;
  disabledSendBtn: boolean = false;
  userInfo: any = {
    mobileNo: null,
    verificationCode: null
  };
  isNeedAlert: boolean;
  dialogInfo: any;
  redirect: any;
  constructor(public authService: AuthService, public router: Router, public lifeCommonService: LifeCommonService) {
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }

  inputBlur() {
    window.scrollTo(0, 0)
  }

  login() {
    const compareInfo = {
      mobileNo: this.userInfo.mobileNo,
      verificationCode: this.userInfo.verificationCode,
      expireTime: '3600'
    };
    if (this.MOBILE_REGEXP.test(this.userInfo.mobileNo) && this.userInfo.verificationCode && this.userInfo.verificationCode.length == 4) {
      this.authService.compare(compareInfo).subscribe(res => {
        if (res['success']) {
          this.authService.login({ mobileNo: this.userInfo.mobileNo }).subscribe((response) => {
            if (response['success']) {
              this.authService.isLoggedIn = true;
              const lifeCustomerInfo = { ...response.data, mobileNo: this.userInfo.mobileNo, commonResult: null };
              if (lifeCustomerInfo['customerId'] && lifeCustomerInfo['practitionerId']) {
                if (response['data']['practitionerTypeId'] == 28) {
                  localStorage.setItem('lifeCustomerInfo', JSON.stringify(lifeCustomerInfo));
                  //如果有openId跳页由后端判断，没有的话根据登录次数前端判断跳页
                  if (response['data']['getOpenIdUrl']) {
                    const deviceType = this.lifeCommonService.checkDeviceType()
                    if (deviceType == 3) {
                      window.location.href = response['data']['getOpenIdUrl'];
                    } else {
                      if (response['data']['loginTimes'] > 0) {
                        this.redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/my';
                        this.router.navigateByUrl(this.redirect);
                      } else {
                        this.redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/thanks';
                        this.router.navigateByUrl(this.redirect);
                      }
                    }
                  } else {
                    if (response['data']['loginTimes'] > 0) {
                      this.redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/my';
                      this.router.navigateByUrl(this.redirect);
                    } else {
                      this.redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/thanks';
                      this.router.navigateByUrl(this.redirect);
                    }
                  }
                } else {
                  this.openPopInfo('仅供寿险经纪人登录！');
                  return;
                }

              } else {
                this.openPopInfo('暂无查询资格');
              }
            } else {
              this.openPopInfo(response['message']);
            }
          });
        } else {
          this.openPopInfo(res['message']);
        }
      });
    } else {
      this.openPopInfo('手机号或验证码不正确');
    }
  }

  //  发送验证码
  verificationCode() {
    const verificationInfo = {
      mobileNo: this.userInfo.mobileNo,
      type: '1'
    };
    if (this.MOBILE_REGEXP.test(this.userInfo.mobileNo) && !this.disabledSendBtn) {
      this.authService.verificationCode(verificationInfo).subscribe(res => {
        if (res['success']) {
          this.countDown();
        } else {
          this.openPopInfo(res['message']);
        }
      });
    } else if (!this.MOBILE_REGEXP.test(this.userInfo.mobileNo)) {
      this.openPopInfo('手机号不正确');
    }
  }

  //  倒计时
  countDown() {
    this.disabledSendBtn = true;
    this.timer = setInterval(() => {
      this.remainTimes--;
      this.sendCodeHtml = `${this.remainTimes}(S)`;
      if (this.remainTimes <= 0) {
        this.sendCodeHtml = '获取验证码';
        this.remainTimes = 60;
        this.disabledSendBtn = false;
        clearInterval(this.timer);
      }
    }, 1000);
  }

  // 打开弹窗
  openPopInfo(message) {
    this.isNeedAlert = true;
    this.dialogInfo = {
      title: null,
      content: { value: message, align: 'center' },
      footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
    };
  }

  // 关闭弹窗
  getPopInfo() {
    this.isNeedAlert = false;
  }
}
