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, distinctUntilChanged, map, mergeMap, tap } from 'rxjs/operators';

/** 角色编辑器组件 */
@Component({
  selector: 'nc-role-editor',
  templateUrl: './nc-role-editor.component.html',
  styleUrls: ['./nc-role-editor.component.less']
})
export class NcRoleEditorComponent implements OnInit, OnDestroy {

  /** 角色 */
  @Input() role: any = null;

  /** 角色表单 */
  _roleForm!: FormGroup;
  /** 数据范围选项资源 */
  _dataScopeOptionResource!: NcOptionResource;
  /** 机构选项资源 */
  _organizationOptionResource!: NcOptionResource;

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

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

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

    // 构建角色表单
    this._roleForm = this._formBuilder.group({
      companyId: [null],
      applicationCode: [null],
      name: [null, [Validators.required, Validators.maxLength(30)]],
      description: [null, [Validators.maxLength(50)]],
      dataScope: [null, [Validators.required, Validators.maxLength(20)]],
      organizations: [null, Validators.required]
    });
    const { dataScope, organizations } = this._roleForm.controls;

    // 生成角色表单补丁
    const { passport, currentApplication } = this._ngCortexService.data;
    const roleFormPatch = {
      companyId: passport!.companyId,
      applicationCode: currentApplication!.code,
      dataScope: null,
      ...this.role
    };

    // 定义角色表单规则
    dataScope.valueChanges
      .pipe(distinctUntilChanged())
      .subscribe(dataScope => {
        if (dataScope === '自定义数据权限') {
          organizations.enable();
        } else {
          organizations.disable();
          organizations.reset();
        }
      });

    // 获取数据范围选项资源
    const dataScopeOptionUrl = 'dict::dataScope';
    this._dataScopeOptionResource = this._ngCortexService.getOptionResource(dataScopeOptionUrl, {
      error: error => this._nzNotificationService.error('获取数据范围列表失败', getErrorMessage(error))
    });

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

    // 生成原始选项
    if (roleFormPatch.dataScope) {
      this._dataScopeOptionResource.optionList = [{ value: roleFormPatch.dataScope }];
    }
    if (roleFormPatch.organizations) {
      roleFormPatch.organizations = roleFormPatch.organizations.map((organization: any) => organization.id.toString());
    }

    // 更新角色表单值
    this._roleForm.patchValue(roleFormPatch);
  }

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

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

  /**
   * 生成机构树形选项列表
   * @param organizationList 机构列表
   */
  private _generateOrganizationTreeNodeList(organizationList: any[]): NzTreeNodeOptions[] {
    const organizationTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const organizationTreeNodeOptions: { [id: string]: NzTreeNodeOptions; } = {};
    organizationList
      .sort((organization1, organization2) => organization1.sequence - organization2.sequence)
      .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;
  }

  /** 获取角色更新 */
  private _getRoleUpdate(): any {
    const role = { ...this._roleForm.getRawValue() };
    for (const key in role) {
      if (!isValid(role[key])) {
        role[key] = null;
      }
    }
    if (role.organizations) {
      const organizations: any = {};
      if (this._organizationOptionResource.origin) {
        this._organizationOptionResource.origin.forEach((organization: any) => {
          organizations[organization.id] = organization;
        });
      }
      role.organizations = role.organizations
        .map((organizationId: string) => organizations[organizationId])
        .filter((organization: any) => organization);
    }
    return getEntityUpdate(role, this.role) && { ...this.role, ...role };
  }

  /**
   * 提交角色
   * @param update 更新
   */
  private _submitRole(update: any): Observable<any> {
    const url = '@' + this._ngCortexService.coreService + '/api/roles';
    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));
        }));
    }
  }

}
