import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalService, UploadFilter } from 'ng-zorro-antd';
import { Subscription, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NgCortexService } from '@ng-cortex/core';

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

  _passportForm: FormGroup = null;
  _passportSubmitting = false;
  _passwordForm: FormGroup = null;
  _passwordSubmitting = false;
  _avatars = [];
  _avatarFilters: UploadFilter[] = [
    {
      name: `format`,
      fn: files => {
        const filterFiles = files.filter(file => /^(image\/png|image\/jpeg|image\/bmp)$/.test(file.type));
        if (filterFiles.length < files.length) {
          this._modalSrv.error({
            nzTitle: `格式错误`,
            nzContent: `目前只支持 image/png、image/jpeg、image/bmp 格式的图片`
          });
          return filterFiles;
        } else {
          return files;
        }
      }
    }
  ];

  private _passportSubscription: Subscription = null;
  private _passwordSubscription: Subscription = null;

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

  ngOnInit() {
    this._passportForm = this._formBuilder.group({
      id: [null, [Validators.required]],
      account: [null, [Validators.required, Validators.maxLength(30)]],
      username: [null, [Validators.required, Validators.maxLength(30)]],
      mobileNumber: [null, [Validators.maxLength(20), Validators.pattern(/^[1-9]\d*$/)]],
      email: [null, [Validators.maxLength(50), Validators.email]],
      wechatUnionId: [null],
      avatar: [null],
      valid: [null, [Validators.required]],
      companyId: [null],
      companyName: [null],
      companyCode: [null],
      companyLogoImage: [null],
      organizationCode: [null]
    });
    this._passportForm.patchValue(this._ncSrv.passport);
    const passportControls = this._passportForm.controls;
    passportControls.account.disable();
    if (passportControls.avatar.value) {
      this._avatars = [{ url: passportControls.avatar.value }];
    }

    this._passwordForm = this._formBuilder.group({
      currentPassword: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
      newPassword: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16)]]
    });
  }

  ngOnDestroy() {
    this._passportSubscription && this._passportSubscription.unsubscribe();
    this._passwordSubscription && this._passwordSubscription.unsubscribe();
  }

  _addAvatar = (file: Blob) => {
    const reader = new FileReader();
    reader.addEventListener(`load`, () => {
      const controls = this._passportForm.controls;
      controls.avatar.patchValue(reader.result);
      this._avatars = [{ url: reader.result }];
    });
    reader.readAsDataURL(file);
    return false;
  }

  _removeAvatar = () => {
    const controls = this._passportForm.controls;
    controls.avatar.reset();
    this._avatars = [];
    return true;
  }

  _submitPassport() {
    const controls = this._passportForm.controls;
    for (const name in controls) {
      controls[name].markAsDirty();
      controls[name].updateValueAndValidity();
    }
    if (this._passportForm.valid) {
      const passportControls = this._passportForm.controls;
      const passport = {
        ...this._passportForm.value,
        account: passportControls.account.value
      };
      this._passportSubmitting = true;
      this._passportSubscription = this._ncSrv.updataPassport(passport)
        .pipe(catchError(() => of(null)))
        .subscribe(() => {
          this._passportSubmitting = false;
          this._passportForm.reset();
          this._passportForm.patchValue(this._ncSrv.passport);
        });
    }
  }

  _submitPassword() {
    const controls = this._passwordForm.controls;
    for (const name in controls) {
      controls[name].markAsDirty();
      controls[name].updateValueAndValidity();
    }
    if (this._passwordForm.valid) {
      const { currentPassword, newPassword } = this._passwordForm.value;
      this._passwordSubmitting = true;
      this._passwordSubscription = this._ncSrv.changePassword(currentPassword, newPassword)
        .pipe(catchError(() => of(null)))
        .subscribe(() => {
          this._passwordSubmitting = false;
          this._passwordForm.reset();
        });
    }
  }

}
