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, 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-dict-editor',
  templateUrl: './nc-dict-editor.component.html',
  styleUrls: ['./nc-dict-editor.component.scss']
})
export class NcDictEditorComponent implements OnInit, OnDestroy {

  /** 字典 */
  @Input() dict: any = null;

  /** 字典表单 */
  _dictForm!: FormGroup;

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

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

  /** 初始化后 */
  ngOnInit(): void {
    const { passport } = this._ngCortexService.data;
    this._dictForm = this._formBuilder.group({
      name: [null, [Validators.required, Validators.maxLength(30)]],
      code: [null, [Validators.required, Validators.maxLength(50)]],
      description: [null, [Validators.maxLength(100)]],
      systemBuiltin: [null, [Validators.required]],
      companyId: [null]
    });
    const dictFormPatch = {
      systemBuiltin: false,
      companyId: passport!.companyId,
      ...this.dict
    };
    this._dictForm.patchValue(dictFormPatch);
  }

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

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

  /** 获取字典更新 */
  private _getDictUpdate(): any {
    let update = { ...this._dictForm.getRawValue() };
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }
    update = getEntityUpdate(update, this.dict);
    if (update) {
      update.companyId = this._ngCortexService.data.passport!.companyId;
    }
    return update;
  }

  /**
   * 提交字典
   * @param update 更新
   */
  private _submitDict(update: any): Observable<any> {
    const url = '@<%= getSeparatorCase(serviceName) %>/api/dicts';
    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);
        }));
    }
  }

}
