import { SafeHtml } from '@angular/platform-browser';
import { Component, OnInit, OnDestroy, ViewChild, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd';
import { Subscription } from 'rxjs';
import { NgCortexService } from '@ng-cortex/core';
import { distinctUntilChanged } from 'rxjs/operators';

@Component({
  selector: 'nc-register',
  templateUrl: './nc-register.component.html',
  styleUrls: ['./nc-register.component.scss']
})
export class NcRegisterComponent implements OnInit, OnDestroy {

  @ViewChild(`userAgreementTpl`, { static: false }) _userAgreementRef: TemplateRef<any> = null;

  _registerForm: FormGroup = null;
  _phonePrefixes = [`+86`];
  _registerLoading = false;
  _userAgreement: SafeHtml = null;
  _userAgreementLoading = false;
  _userAgreementDelay = 300;

  private _registerSubscription: Subscription = null;

  constructor(
    private _formBuilder: FormBuilder,
    private _modalSrv: NzModalService,
    private _ncSrv: NgCortexService
  ) { }

  ngOnInit() {
    this._registerForm = this._formBuilder.group({
      account: [null, [Validators.required, Validators.maxLength(30)]],
      username: [null, [Validators.required, Validators.maxLength(30)]],
      password: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
      confirmPassword: [null],
      mobileNumberPrefix: [`+86`, [Validators.required]],
      mobileNumber: [null, [Validators.required, Validators.pattern(/^1[0-9]{10}$/)]],
      // captcha: [null, [Validators.required]],
      agreed: [true, [Validators.required]],
      valid: [true, [Validators.required]]
    });

    const controls = this._registerForm.controls;
    const confirmValidator = (control: FormControl): { [status: string]: boolean } => {
      if (!control.value) {
        return { required: true };
      } else if (control.value !== controls.password.value) {
        return { error: true };
      } else {
        return null;
      }
    };
    controls.confirmPassword.setValidators([confirmValidator]);
    controls.password.valueChanges
      .pipe(distinctUntilChanged())
      .subscribe(() => controls.confirmPassword.updateValueAndValidity());
  }

  ngOnDestroy() {
    this._registerSubscription && this._registerSubscription.unsubscribe();
  }

  // _getCaptcha() {

  // }

  _viewUserAgreement(event: MouseEvent) {
    event.preventDefault();
    event.stopPropagation();
    this._modalSrv.create({
      nzTitle: `用户协议`,
      nzContent: this._userAgreementRef,
      nzWidth: 960,
      nzOnOk: () => true
    });
  }

  _register() {
    const controls = this._registerForm.controls;
    for (const name in controls) {
      controls[name].markAsDirty();
      controls[name].updateValueAndValidity();
    }
    if (this._registerForm.valid) {
      const body = { ...this._registerForm.value };
      delete body.confirmPassword;
      delete body.mobileNumberPrefix;
      // delete body.captcha;
      delete body.agreed;
      this._registerLoading = true;
      this._registerSubscription = this._ncSrv.register(body)
        .subscribe(() => this._registerLoading = false);
    }
  }

  // private _getUserAgreement() {

  // }

}
