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

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

  /** 机构表单 */
  _organizationForm!: FormGroup;
  /** 机构选项资源 */
  _organizationOptionResource!: NcOptionResource;
  /** 机构类型选项资源 */
  _organizationTypeOptionResource!: NcOptionResource;

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

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

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

    // 构建机构表单
    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 { passport } = this._ngCortexService.data;
    const organizationFormPatch = {
      companyId: passport!.companyId,
      ...this.organization
    };
    if (organizationFormPatch.parentId) {
      organizationFormPatch.parentId = organizationFormPatch.parentId.toString();
    }

    // 获取机构选项资源
    const { applicationCode } = this._organizationForm.getRawValue();
    const organizationOptionUrl = 'source::@' + this._ngCortexService.coreService + '/api/organizations?applicationCode=' + applicationCode;
    this._organizationOptionResource = this._ngCortexService.getOptionResource(organizationOptionUrl, {
      map: this._generateOrganizationTreeOptionList,
      error: error => this._nzNotificationService.error('获取机构列表失败', getErrorMessage(error))
    });

    // 获取机构类型选项资源
    const organizationTypeOptionUrl = 'dict::organizationType';
    this._organizationTypeOptionResource = this._ngCortexService.getOptionResource(organizationTypeOptionUrl, {
      error: error => this._nzNotificationService.error('获取机构类型列表失败', getErrorMessage(error))
    });

    // 更新机构表单值
    this._organizationForm.patchValue(organizationFormPatch);
  }

  /** 注销后 */
  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(undefined);
        }))
        .pipe(catchError(() => of(undefined)))
        .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 = '@' + this._ngCortexService.coreService + '/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('更新机构失败', getErrorMessage(httpErrorResponse));
        }));
    } else {
      return this._httpClient.post(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('新增机构成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.success('新增机构失败', getErrorMessage(httpErrorResponse));
        }));
    }
  }

  /**
   * 生成机构树形选项列表
   * @param organizationList 机构列表
   */
  private _generateOrganizationTreeOptionList(organizationList: any[]): NzTreeNodeOptions[] {
    const organizationTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const organizationTreeNodeOptions: { [id: string]: NzTreeNodeOptions; } = {};
    organizationList.forEach(organization => {
      const organizationTreeNodeOption = 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 = organizationTreeNodeOptions[organization.parentId] = organizationTreeNodeOptions[organization.parentId] || {};
        if (!parentOrganizationTreeNodeOption.children) {
          delete parentOrganizationTreeNodeOption.isLeaf;
          parentOrganizationTreeNodeOption.children = [];
        }
        parentOrganizationTreeNodeOption.children.push(organizationTreeNodeOption);
      } else {
        organizationTreeNodeOptionList.push(organizationTreeNodeOption);
      }
    });
    return organizationTreeNodeOptionList;
  }

}
