import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';<% if (hasCompanyIdField || hasOrganizationIdField || dictCodeList.length > 0) { %>
import { NgCortexService, NcDictItem } from '@ng-cortex/core';<% } %>
import { getEntityUpdate, isValid, validateForm<% if (formValidatorFieldList.length > 0) { %>, Validators<% } %> } from '@ng-cortex/utils';<% if (formDatePickerFieldList.length > 0) { %>
import { format, parseISO, startOfDay } from 'date-fns';<% } %>
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap, tap } from 'rxjs/operators';

/** <%= description %>编辑器组件 */
@Component({
  selector: 'nc-<%= getSeparatorCase(name) %>-editor',
  templateUrl: './<%= getSeparatorCase(name) %>-editor.component.html',
  styleUrls: ['./<%= getSeparatorCase(name) %>-editor.component.scss']
})
export class <%= getPascalCase(name) %>EditorComponent implements OnInit, OnDestroy {

  /** <%= description %> */
  @Input() <%= getCamelCase(name) %>: any = null;

  /** <%= description %>表单 */
  _<%= getCamelCase(name) %>Form!: FormGroup;<% dictCodeList.forEach(function(dictCode) { %>
  /** <%= dictCode %>列表 */
  _<%= dictCode %>List: NcDictItem[] = [];
  /** <%= dictCode %>加载状态 */
  _<%= dictCode %>Loading: boolean = false;<% }) %><% if (formInputNumberFieldList.length > 0) { %>
  /** 格式化数字 */
  formatterNumber = (numberValue: number) => numberValue.toLocaleString();
  /** 解析数字 */
  parserNumber = (numberValue: string) => numberValue.replace(/[^0-9\.]+/g, '');<% } %>

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

  constructor(
    private _formBuilder: FormBuilder,
    private _httpClient: HttpClient<% if (hasCompanyIdField || hasOrganizationIdField || dictCodeList.length > 0) { %>,
    private _ngCortexService: NgCortexService<% } %>,
    private _nzNotificationService: NzNotificationService) { }

  /** 初始化后 */
  ngOnInit(): void {
    this._<%= getCamelCase(name) %>Form = this._formBuilder.group({<% formFieldList.forEach(function(field, index) { %>
      <%= getCamelCase(field.name) %>: [null<% if (field.controlValidators.length > 0) { %>, [<%= field.controlValidators.join(', ') %>]<% } %>]<% if (index < formFieldList.length - 1) { %>,<% } %><% }) %>
    });<% if (hasCompanyIdField || hasOrganizationIdField) { %>
    const { <% if (hasCompanyIdField) { %>companyId<% } %><% if (hasCompanyIdField && hasOrganizationIdField) { %>, <% } %><% if (hasOrganizationIdField) { %>organizationId<% } %> } = this._ngCortexService.data.passport!;<% } %>
    const <%= getCamelCase(name) %>FormPatch = {<% if (hasCompanyIdField) { %>
      companyId: companyId,<% } %><% if (hasOrganizationIdField) { %>
      organizationId: organizationId,<% } %>
      ...this.<%= getCamelCase(name) %>
    };<% formDatetimePickerFieldList.forEach(function(field) { %>
    if (<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>) {
      <%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %> = new Date(<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>);
    }<% }) %><% formDatePickerFieldList.forEach(function(field) { %>
    if (<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>) {
      <%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %> = startOfDay(parseISO(<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>));
    }<% }) %><% formSelectMultipleFieldList.forEach(function(field) { %>
    if (<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>) {
      <%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %> = JSON.parse(<%= getCamelCase(name) %>FormPatch.<%= getCamelCase(field.name) %>);
    }<% }) %>
    this._<%= getCamelCase(name) %>Form.patchValue(<%= getCamelCase(name) %>FormPatch);<% dictCodeList.forEach(function(dictCode) { %>

    this._<%= dictCode %>Loading = true;
    this._ngCortexService.getDictItemList('<%= dictCode %>')
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('获取 <%= dictCode %> 列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of([]);
      }))
      .subscribe(<%= dictCode %>List => {
        this._<%= dictCode %>List = <%= dictCode %>List;
        this._<%= dictCode %>Loading = false;
      });<% }) %>
  }

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

  /** 提交 */
  submit(): Observable<{ success: boolean; updated: any }> {
    return new Observable(subscriber => {
      const submitResult = {
        success: false,
        updated: null
      };
      const submitSubscription = validateForm(this._<%= getCamelCase(name) %>Form)
        .pipe(mergeMap(valid => {
          if (valid) {
            const <%= getCamelCase(name) %>Update = this._get<%= getPascalCase(name) %>Update();
            if (<%= getCamelCase(name) %>Update) {
              return this._submit<%= getPascalCase(name) %>(<%= getCamelCase(name) %>Update)
                .pipe(tap(<%= getCamelCase(name) %>Updated => {
                  submitResult.success = true;
                  submitResult.updated = <%= getCamelCase(name) %>Updated;
                }));
            } else {
              submitResult.success = true;
            }
          }
          return of(null);
        }))
        .pipe(catchError(() => of(null)))
        .pipe(map(() => submitResult))
        .subscribe(subscriber);
      this._cancelSubmitFn = () => {
        submitSubscription.unsubscribe();
      };
    });
  }

  /** 获取<%= description %>更新 */
  private _get<%= getPascalCase(name) %>Update(): any {
    const update = { ...this._<%= getCamelCase(name) %>Form.getRawValue() };
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }<% formDatePickerFieldList.forEach(function(field) { %>
    if (update.<%= getCamelCase(field.name) %>) {
      update.<%= getCamelCase(field.name) %> = format(update.<%= getCamelCase(field.name) %>, 'yyyy-MM-dd');
    }<% }) %><% formSelectMultipleFieldList.forEach(function(field) { %>
    if (update.<%= getCamelCase(field.name) %>) {
      update.<%= getCamelCase(field.name) %> = JSON.stringify(update.<%= getCamelCase(field.name) %>);
    }<% }) %>
    return getEntityUpdate(update, this.<%= getCamelCase(name) %>);
  }

  /**
   * 提交<%= description %>
   * @param update 更新
   */
  private _submit<%= getPascalCase(name) %>(update: any): Observable<any> {
    const url = '@<%= serviceName %>/api/<%= getPluralForm(getSeparatorCase(name)) %>';
    const body = update;
    if (body.id) {
      return this._httpClient.patch(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('更新<%= description %>成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('更新<%= description %>失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        }));
    } else {
      return this._httpClient.post(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('新增<%= description %>成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('新增<%= description %>失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        }));
    }
  }

}
