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 { 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.scss']
})
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(null);
      }))
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('登录失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of(null);
      }))
      .subscribe(() => {
        this._cancelLoginFn = () => { };
        this._loginLoading = false;
      });
    this._cancelLoginFn = () => {
      loginSubscription.unsubscribe();
      this._cancelLoginFn = () => { };
      this._loginLoading = false;
    };
  }

}
