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

/** 应用编辑器组件 */
@Component({
  selector: 'nc-application-editor',
  templateUrl: './nc-application-editor.component.html',
  styleUrls: ['./nc-application-editor.component.less']
})
export class NcApplicationEditorComponent implements OnInit, OnDestroy {

  /** 应用 */
  @Input() application: any = null;

  /** 应用表单 */
  _applicationForm!: FormGroup;

  /** 取消提交 */
  private _cancelSubmitFn = () => { };

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

  /** 初始化后 */
  ngOnInit(): void {

    // 构建应用表单
    this._applicationForm = this._formBuilder.group({
      name: [null, [Validators.required, Validators.maxLength(20)]],
      code: [null, [Validators.required, Validators.maxLength(20)]],
      description: [null, [Validators.maxLength(50)]],
      icon: [null, [Validators.maxLength(200)]],
      groupName: [null, [Validators.maxLength(20)]],
      common: [null],
      sequence: [null]
    });

    // 生成应用表单补丁
    const applicationFormPatch = {
      common: false,
      ...this.application
    };

    // 更新应用表单值
    this._applicationForm.patchValue(applicationFormPatch);
  }

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

  /** 提交 */
  submit(): Observable<{ success: boolean; updated: any; }> {
    return new Observable(subscriber => {
      const submitResult = {
        success: false,
        updated: null
      };
      const submitSubscription = validateForm(this._applicationForm)
        .pipe(mergeMap(valid => {
          if (valid) {
            const applicationUpdate = this._getApplicationUpdate();
            if (applicationUpdate) {
              return this._submitApplication(applicationUpdate)
                .pipe(tap(applicationUpdated => {
                  submitResult.success = true;
                  submitResult.updated = applicationUpdated;
                }));
            } else {
              submitResult.success = true;
            }
          }
          return of(undefined);
        }))
        .pipe(catchError(() => of(undefined)))
        .pipe(map(() => submitResult))
        .subscribe(subscriber);
      this._cancelSubmitFn = () => {
        submitSubscription.unsubscribe();
      };
    });
  }

  /** 获取应用更新 */
  private _getApplicationUpdate(): any {
    const update = { ...this._applicationForm.getRawValue() };
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }
    return getEntityUpdate(update, this.application);
  }

  /**
   * 提交应用
   * @param update 更新
   */
  private _submitApplication(update: any): Observable<any> {
    const url = '@' + this._ngCortexService.coreService + '/api/applications';
    const body = update;
    if (body.id) {
      return this._httpClient.patch(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('更新应用成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('更新应用失败', getErrorMessage(httpErrorResponse));
        }));
    } else {
      return this._httpClient.post(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('新增应用成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('新增应用失败', getErrorMessage(httpErrorResponse));
        }));
    }
  }

}
