import { Component, OnDestroy, OnInit,HostListener,ViewChild,ElementRef } 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 {
  @ViewChild('dragContainer') dragContainer: ElementRef;
  @ViewChild('dragHandler') dragHandler: ElementRef;
  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;
  dragBg:any;
  dragText:any;
  maxHandlerOffset:any;
  isVertifySucc:boolean = true;
  left:any;
  deviceType:any;
  len:any;
  constructor(public authService: AuthService, public router: Router, public lifeCommonService: LifeCommonService) {
    this.deviceType = this.lifeCommonService.checkDeviceType();
  }

   // 监听document离开事件
   @HostListener('document:touchend', ['$event'])
   ontouchend(event) {
     // 只用当元素移动过了，离开函数体才会触发。
       this.onDragHandlerMouseUp();
   }
 
    // 监听document离开事件
   @HostListener(`mouseup`, ['$event'])
   onmouseup(event) {
     // 只用当元素移动过了，离开函数体才会触发。
       this.onDragHandlerMouseUp();
   }
 

  ngOnInit() {
    // //获取滑动控件容器,灰色背景
    // this.dragContainer.nativeElement.clientWidth = document.getElementById("dragContainer");
    // //获取滑块左边部分,绿色背景
    this.dragBg = document.getElementById("dragBg");
    // //获取滑动验证容器文本
    this.dragText = document.getElementById("dragText");
    // //获取滑块
    // this.dragHandler.nativeElement = document.getElementsByClassName("slideController")[0];
    // //滑块的最大偏移量                 =     滑动验证容器文本长度                  -      滑块长度
    this.maxHandlerOffset = this.dragContainer.nativeElement.clientWidth - this.dragHandler.nativeElement.clientWidth;
    this.initDrag();
    this.len = (window.innerWidth-document.body.clientWidth)/2;

  }

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

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

  login() {
    const compareInfo = {
      mobileNo: this.userInfo.mobileNo,
      verificationCode: this.userInfo.verificationCode,
      expireTime: '3600',
      fromSystemName:'ydLife'
    };
    if (this.MOBILE_REGEXP.test(this.userInfo.mobileNo) && this.userInfo.verificationCode && this.userInfo.verificationCode.length == 6) {
      this.authService.compare(compareInfo).subscribe(res => {
        if (res['success']) {
          this.authService.login({ mobileNo: this.userInfo.mobileNo,fromSystemName:'ydLife' }).subscribe((response) => {
            if (response['success']) {
              this.authService.isLoggedIn = true;
              if(response['data']['practitionerBasicInfo'] && response['data']['practitionerBasicInfo']['subordinateName']){
                sessionStorage.setItem('subordinateSystemName', response['data']['practitionerBasicInfo']['subordinateName'])
              }
              const lifeCustomerInfo = { ...response.data, mobileNo: this.userInfo.mobileNo, commonResult: null };
              this.authService.obtainToken(this.userInfo.mobileNo,response['data']['customerId']).subscribe((res)=>{
                if (res['success']) {
                  localStorage.setItem('lifeToken', res['data']['token']);
                }
              })
              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?type=1';
                        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?type=1';
                      this.router.navigateByUrl(this.redirect);
                    }
                  }
                // } else {
                //   this.openPopInfo('你好，只有授权的经纪人才可登录，请联系我们的客服4009219290');
                //   // this.openPopInfo(`你好，只有授权的经纪人才可登录，请联系我们的客服 <a href="tel:4009219290">4009219290 </a>`);
                //   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;
  }

  initDrag() {
    //在滑动验证容器文本写入“拖动滑块验证”
    this.dragText.textContent = "拖动滑块验证";
    //给滑块添加鼠标按下监听
    if(this.deviceType == 2 || this.deviceType == 3){
      this.dragHandler.nativeElement.addEventListener("touchstart", ()=>{
        this.onDragHandlerMouseDown()
      },false);
    }else{
      this.dragHandler.nativeElement.addEventListener("mousedown", ()=>{
        this.onDragHandlerMouseDown()
      });
    }

}

  //选中滑块
  onDragHandlerMouseDown() {
      if(this.deviceType == 2 || this.deviceType == 3){
        //鼠标移动监听
        document.addEventListener("touchmove", ()=>{
          this.onDragHandlerMouseMove(event)
        },false);
        //鼠标松开监听
        document.addEventListener("touchend", ()=>{
          this.onDragHandlerMouseUp
        });
      }else{
        document.querySelector('#dragHandler').classList.add('slideController');
         //获取滑块
        this.dragHandler.nativeElement = document.getElementsByClassName("slideController")[0];
          //鼠标移动监听
        this.dragHandler.nativeElement.addEventListener("mousemove",(e)=>{
          this.onDragHandlerMouseMove(e);
        });
        //鼠标松开监听
        this.dragHandler.nativeElement.addEventListener("mouseup", ()=>{this.onDragHandlerMouseUp});
      }

  }

  //滑块移动
    onDragHandlerMouseMove(event) {
      event.preventDefault();
      let touch;
      if (event.touches) {
      touch = event.touches[0];
    } else {
      touch = event;
    }
      /*
      html元素不存在width属性,只有clientWidth
      offsetX是相对当前元素的,clientX和pageX是相对其父元素的
      */
      //滑块移动量
      if(this.deviceType == 2 || this.deviceType == 3){
        this.left = touch.clientX - this.dragHandler.nativeElement.clientWidth / 2 - this.len;
      }else{
         //获取滑块
        this.dragHandler.nativeElement = document.getElementsByClassName("slideController")[0];
        if(this.dragHandler.nativeElement){
          this.left = touch.clientX - this.dragHandler.nativeElement.clientWidth / 2 - this.len;
        }else{
          this.left = 0;
        }
      }
      if(this.left < 0) {
          this.left = 0;
        //如果滑块移动量   > 滑块的最大偏移量 ，则调用验证成功函数
      } else if(this.left > this.maxHandlerOffset) {
          this.left = this.maxHandlerOffset;
          this.verifySucc();
      }
      if(this.dragHandler.nativeElement){
        //滑块移动量
        this.dragHandler.nativeElement.style.left = this.left + "px";
        //绿色背景的长度
        this.dragBg.style.width = this.dragHandler.nativeElement.style.left;
      }
  }

  //松开滑块函数
    onDragHandlerMouseUp() {
      if(this.deviceType == 2 || this.deviceType == 3){
        //移除鼠标移动监听
        document.removeEventListener("touchmove", this.onDragHandlerMouseMove);
        //移除鼠标松开监听
        document.removeEventListener("touchend", this.onDragHandlerMouseUp);
      }else{
         //移除鼠标移动监听
         document.removeEventListener("mousemove", this.onDragHandlerMouseMove);
         //移除鼠标松开监听
         document.removeEventListener("mouseup", this.onDragHandlerMouseUp);
         document.querySelector('#dragHandler').classList.remove('slideController');
      }
      if(this.isVertifySucc){
        //初始化滑块移动量
        this.dragHandler.nativeElement.style.left = 0;
        //初始化绿色背景
        this.dragBg.style.width = 0;
      }
  }

  //验证成功
    verifySucc() {
      this.isVertifySucc = false;
      this.dragText.textContent = "验证通过";
      this.dragText.style.color = "white";
      this.dragHandler.nativeElement.setAttribute("class", "dragHandlerOkBg");
      if(this.deviceType == 2 || this.deviceType == 3){
        this.dragHandler.nativeElement.removeEventListener("touchstart", this.onDragHandlerMouseDown);
        document.removeEventListener("touchmove", this.onDragHandlerMouseMove);
        document.removeEventListener("touchend", this.onDragHandlerMouseUp);
      }else{
        this.dragHandler.nativeElement.removeEventListener("mousedown", this.onDragHandlerMouseDown);
        this.dragHandler.nativeElement.removeEventListener("mousemove", this.onDragHandlerMouseMove);
        this.dragHandler.nativeElement.removeEventListener("mouseup", this.onDragHandlerMouseUp);
      }
      setTimeout(()=>{
        this.dragContainer.nativeElement.style.display = 'none'
      },1000)

  };
}
