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

/** 机构编辑器组件 */
@Component({
  selector: 'nc-organization-editor',
  templateUrl: './nc-organization-editor.component.html',
  styleUrls: ['./nc-organization-editor.component.scss']
})
export class NcOrganizationEditorComponent implements OnInit, OnDestroy {

  /** 机构 */
  @Input() organization: any = null;

  /** 机构表单 */
  _organizationForm!: FormGroup;
  /** 机构列表 */
  _organizationList: any[] = [];
  /** 机构树形选项列表 */
  _organizationTreeNodeOptionList: NzTreeNodeOptions[] = [];
  /** 机构类型列表 */
  _organizationTypeList: NcDictItem[] = [];
  /** 机构类型加载状态 */
  _organizationTypeLoading: boolean = false;

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

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

  /** 初始化后 */
  ngOnInit(): void {
    const { passport } = this._ngCortexService.data;
    this._organizationForm = this._formBuilder.group({
      parentId: [null],
      name: [null, [Validators.required, Validators.maxLength(30)]],
      type: [null, [Validators.required, Validators.maxLength(20)]],
      sequence: [null],
      companyId: [null]
    });
    const organizationFormPatch = {
      companyId: passport!.companyId,
      ...this.organization
    };
    if (organizationFormPatch.parentId) {
      organizationFormPatch.parentId = organizationFormPatch.parentId.toString();
    }
    this._organizationForm.patchValue(organizationFormPatch);

    this._getOrganizationList();

    this._organizationTypeLoading = true;
    this._ngCortexService.getDictItemList('organizationType')
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('获取机构类型列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of([]);
      }))
      .subscribe(organizationTypeList => {
        this._organizationTypeList = organizationTypeList;
        this._organizationTypeLoading = 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._organizationForm)
        .pipe(mergeMap(valid => {
          if (valid) {
            const organizationUpdate = this._getOrganizationUpdate();
            if (organizationUpdate) {
              return this._submitOrganization(organizationUpdate)
                .pipe(tap(organizationUpdated => {
                  submitResult.success = true;
                  submitResult.updated = organizationUpdated;
                }));
            } else {
              submitResult.success = true;
            }
          }
          return of(null);
        }))
        .pipe(catchError(() => of(null)))
        .pipe(map(() => submitResult))
        .subscribe(subscriber);
      this._cancelSubmitFn = () => {
        submitSubscription.unsubscribe();
      };
    });
  }

  /** 获取机构更新 */
  private _getOrganizationUpdate(): any {
    const update = { ...this._organizationForm.getRawValue() };
    if (update.parentId) {
      update.parentId = Number(update.parentId);
    }
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }
    return getEntityUpdate(update, this.organization) && { ...this.organization, ...update };
  }

  /**
   * 提交机构
   * @param update 更新
   */
  private _submitOrganization(update: any): Observable<any> {
    const url = '@<%= getSeparatorCase(serviceName) %>/api/organizations';
    const body = update;
    if (body.id) {
      return this._httpClient.put(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);
        }));
    }
  }

  /** 获取机构列表 */
  private _getOrganizationList(): void {
    const { applicationCode } = this._organizationForm.getRawValue();
    const url = '@<%= getSeparatorCase(serviceName) %>/api/organizations';
    const params: any = { applicationCode };
    this._httpClient.get<any[]>(url, { params })
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.success('获取机构列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of([]);
      }))
      .subscribe(organizationList => {
        this._organizationList = organizationList.sort((organization1, organization2) => organization1.sequence - organization2.sequence);
        this._generateOrganizationTreeOptionList();
      });
  }

  /** 生成机构树形选项列表 */
  private _generateOrganizationTreeOptionList(): void {
    const organizationTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const organizationTreeNodeOptions: any = {};
    this._organizationList.forEach(organization => {
      const organizationTreeNodeOption: NzTreeNodeOptions = organizationTreeNodeOptions[organization.id] = organizationTreeNodeOptions[organization.id] || {};
      organizationTreeNodeOption.key = organization.id.toString();
      organizationTreeNodeOption.title = organization.name;
      if (!organizationTreeNodeOption.children) {
        organizationTreeNodeOption.isLeaf = true;
      }
      if (organization.parentId) {
        const parentOrganizationTreeNodeOption: NzTreeNodeOptions = organizationTreeNodeOptions[organization.parentId] = organizationTreeNodeOptions[organization.parentId] || {};
        if (!parentOrganizationTreeNodeOption.children) {
          delete parentOrganizationTreeNodeOption.isLeaf;
          parentOrganizationTreeNodeOption.children = [];
        }
        parentOrganizationTreeNodeOption.children.push(organizationTreeNodeOption);
      } else {
        organizationTreeNodeOptionList.push(organizationTreeNodeOption);
      }
    });
    this._organizationTreeNodeOptionList = organizationTreeNodeOptionList;
  }

}
