import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { EAUserService } from 'src/app/shared/services/business/user.service';

@Component({
  selector: 'app-routes-password-retrieve-password',
  templateUrl: './retrieve-password.component.html',
  styleUrls: ['./retrieve-password.component.less']
})
export class UserRetrievePasswordComponent implements OnInit, AfterViewInit {
  step = 0;
  count = 0;
  interval$: any;
  formGroup1!: FormGroup;
  formGroup2!: FormGroup;
  confirmPasswordValidator!: ValidatorFn;
  result = true;

  isPassWordHide = true;
  isConfirmPassWordHide = true;

  constructor(private fb: FormBuilder, public service: EAUserService, private router: Router, private cdr: ChangeDetectorRef) {}

  ngAfterViewInit(): void {}

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.confirmPasswordValidator = control => {
      if (!control.value) {
        return { error: true, required: true };
      } else if (control.value !== this.formGroup2.controls.passWord.value) {
        return { passWordTo: true, error: true };
      }
      return {};
    };

    this.formGroup1 = this.fb.group({
      phone: [null, [Validators.required]],
      smsVerifyCode: [null, [Validators.required]],
      voucher: [null, [Validators.required]]
    });

    this.formGroup2 = this.fb.group({
      passWord: [
        null,
        [
          Validators.required,
          Validators.maxLength(16),
          Validators.minLength(8),
          Validators.pattern('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z-_]{8,16}$')
        ]
      ],
      passWordTo: [null, [this.confirmPasswordValidator, Validators.maxLength(16), Validators.minLength(8)]],
      voucher: [null, [Validators.required]],
      phone: [null, [Validators.required]]
    });
  }

  formSubmit() {
    switch (this.step) {
      case 0:
        this.submitForm1();
        break;
      case 1:
        this.submitForm2();
        break;
    }
  }

  submitForm1() {
    for (const i in this.formGroup1.controls) {
      if (this.formGroup1.controls[i]) {
        this.formGroup1.controls[i].markAsDirty();
        this.formGroup1.controls[i].updateValueAndValidity();
      }
    }
    if (this.formGroup1.value.smsVerifyCode.length !== 6) {
      this.service.msgSrv.error('请输入6位验证码');
      return;
    }
    if (this.formGroup1.valid) {
      const param = Object.assign({}, this.formGroup1.value);
      this.service.http.post(this.service.$forgetPasswordVerifyIdentity, param).subscribe((res: any) => {
        // console.log(res, 'submitForm1');
        if (res.success === true) {
          this.formGroup2.patchValue(
            {
              voucher: res.data.voucher,
              phone: this.formGroup1.value.phone
            },
            { onlySelf: true }
          );
          this.step = 1;
          // clearInterval(this.interval$);
        } else {
          this.service.msgSrv.warning(res?.msg || '操作超时，请重新开始找回密码的流程！');
          // this.refreshPage();
        }
      });
    }
  }

  submitForm2() {
    for (const i in this.formGroup2.controls) {
      if ( this.formGroup2.controls[i]) {
        this.formGroup2.controls[i].markAsDirty();
        this.formGroup2.controls[i].updateValueAndValidity();
      }
    }

    if (this.formGroup2.valid) {
      this.service.http
        .post(this.service.$voucherUpdatePassword, this.formGroup2.value)
        .subscribe((res: { success: any; data: boolean; msg: any }) => {
          if (res.success && res.data === true) {
            this.result = true;
            this.step = 2;
            setTimeout(() => {
              //this.service.logout();
              this.router.navigateByUrl('/passport/login');
            }, 3000);
          } else {
            this.result = false;
            this.service.msgSrv.warning(res.msg || '密码修改失败！');
          }
        });
    }
  }

  getCaptcha() {
    for (const i in this.formGroup1.controls) {
      if (true) {
        this.formGroup1.controls[i].markAsDirty();
        this.formGroup1.controls[i].updateValueAndValidity();
      }
    }
    if (this.formGroup1.value.phone.length !== 11) {
      this.service.msgSrv.error('请输入11位手机号');
      return;
    }
    if (this.formGroup1.value.phone) {
      this.service.http
        .post(`${this.service.$getAccountSMVerificationCode}`, null, { phoneNumber: this.formGroup1.value.phone })
        .subscribe((res: any) => {
          // console.log(res, 'res');
          if (res.success) {
            this.formGroup1.patchValue(
              {
                voucher: res?.data?.voucher
              },
              { onlySelf: true }
            );
            if (res?.data?.code === '1') {
              this.codeCountDown();
              this.service.msgSrv.success('验证码已发送到该账号绑定的手机号！');
            } else if (res?.data?.code === '503046') {
              // this.dun.popUp();
            } else {
              this.service.msgSrv.error('获取验证码失败!');
            }
          } else {
            this.service.msgSrv.error(res.msg);
          }
        });
    }
  }

  /* code倒计时 */
  codeCountDown() {
    this.count = 59;
    interval(1000)
      .pipe(take(60))
      .subscribe(x => {
        this.count = 59 - (x + 1);
        this.cdr.detectChanges();
      });
  }
  /* 网易盾验证通过 */
  captchaDone(validate: any) {
    this.codeCountDown();
  }

  refreshPage() {
    window.location.reload();
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.formGroup2.controls.passWordTo.updateValueAndValidity());
  }
}
