import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NgCortexService } from '@ng-cortex/core';
import { getErrorMessage, validateForm, Validators } from '@ng-cortex/utils';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { of } from 'rxjs';
import { catchError, mergeMap } from 'rxjs/operators';

/** 登录页面 */
@Component({
  selector: 'nc-login',
  templateUrl: './nc-login.page.html',
  styleUrls: ['./nc-login.page.less']
})
export class NcLoginPage implements OnInit, OnDestroy {

  /** 登录表单 */
  _loginForm!: FormGroup;
  /** 密码可见状态 */
  _passwordVisible: boolean = false;
  /** 登录加载状态 */
  _loginLoading: boolean = false;

  /** 取消登录 */
  private _cancelLoginFn = () => { };

  constructor(
    private _formBuilder: FormBuilder,
    private _nzNotificationService: NzNotificationService,
    private _ngCortexService: NgCortexService) { }

  /** 初始化后 */
  ngOnInit(): void {
    this._loginForm = this._formBuilder.group({
      login: [null, [Validators.required]],
      password: [null, [Validators.required]],
      rememberMe: [true]
    });
  }

  /** 注销后 */
  ngOnDestroy(): void {
    this._cancelLoginFn();
  }

  /** 登录 */
  _login(): void {
    this._loginLoading = true;
    const loginSubscription = validateForm(this._loginForm)
      .pipe(mergeMap(valid => {
        if (valid) {
          const formValue = { ...this._loginForm.getRawValue() };
          return this._ngCortexService.login(formValue);
        }
        return of(undefined);
      }))
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('登录失败', getErrorMessage(httpErrorResponse));
        return of(undefined);
      }))
      .subscribe(() => {
        this._cancelLoginFn = () => { };
        this._loginLoading = false;
      });
    this._cancelLoginFn = () => {
      loginSubscription.unsubscribe();
      this._cancelLoginFn = () => { };
      this._loginLoading = false;
    };
  }

}
