import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { getEntityUpdate, 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.scss']
})
export class NcApplicationEditorComponent implements OnInit, OnDestroy {

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

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

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

  constructor(
    private _formBuilder: FormBuilder,
    private _httpClient: HttpClient,
    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(null);
        }))
        .pipe(catchError(() => of(null)))
        .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 = '@<%= getSeparatorCase(serviceName) %>/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('更新应用失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        }));
    } else {
      return this._httpClient.post(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('新增应用成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('新增应用失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        }));
    }
  }

}
