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 { NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap, tap } from 'rxjs/operators';

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

  /** 用户 */
  @Input() user: any = null;

  /** 用户表单 */
  _userForm!: FormGroup;
  /** 密码可见状态 */
  _passwordVisible: boolean = false;
  /** 机构列表 */
  _organizationList: any[] = [];
  /** 机构树形选项列表 */
  _organizationTreeNodeOptionList: any[] = [];
  /** 机构加载状态 */
  _organizationLoading: boolean = false;
  /** 角色列表 */
  _roleList: any[] = [];
  /** 角色加载状态 */
  _roleLoading: boolean = false;
  /** 实体比较 */
  _entityCompareWith = (entityA: any, entityB: any) => (entityA && entityA.id) === (entityB && entityB.id);

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

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

  /** 初始化后 */
  ngOnInit(): void {
    this._userForm = this._formBuilder.group({
      companyId: [null],
      organizationId: [null, [Validators.required]],
      account: [null, [Validators.required, Validators.maxLength(30)]],
      password: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
      name: [null, [Validators.required, Validators.maxLength(30)]],
      mobileNumber: [null, [Validators.required, Validators.maxLength(20)]],
      identityCardNumber: [null, [Validators.maxLength(20)]],
      gender: [null, [Validators.maxLength(20)]],
      email: [null, [Validators.maxLength(50)]],
      enabled: [null, [Validators.required]],
      roles: [null]
    });
    const userFormControls = this._userForm.controls;
    const userFormPatch = {
      companyId: this._ngCortexService.data.passport!.companyId,
      gender: '男',
      enabled: true,
      ...this.user
    };
    if (userFormPatch.id) {
      userFormControls.account.disable();
      userFormControls.password.disable();
    }
    if (userFormPatch.organizationId) {
      userFormPatch.organizationId = userFormPatch.organizationId.toString();
    }
    this._userForm.patchValue(userFormPatch);
    this._getOrganizationList();
    this._getRoleList();
  }

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

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

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

  /** 生成机构树形选项列表 */
  private _generateOrganizationTreeNodeList(): 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;
  }

  /** 获取角色列表 */
  private _getRoleList(): void {
    this._roleLoading = true;
    const url = '@<%= getSeparatorCase(serviceName) %>/api/roles';
    this._httpClient.get<any[]>(url)
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('获取应用列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of([]);
      }))
      .subscribe(roleList => {
        this._roleList = roleList.sort((roleA, roleB) => roleA.sequence - roleB.sequence);
        this._roleLoading = false;
      });
  }

  /** 获取用户更新 */
  private _getUserUpdate(): any {
    const update = { ...this._userForm.getRawValue() };
    if (update.organizationId) {
      update.organizationId = Number(update.organizationId);
    }
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }
    return getEntityUpdate(update, this.user) && { ...this.user, ...update };
  }

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

}
