import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { NgCortexService, NcDictItem, NcOptionResource } 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-menu-editor',
  templateUrl: './nc-menu-editor.component.html',
  styleUrls: ['./nc-menu-editor.component.less']
})
export class NcMenuEditorComponent implements OnInit, OnDestroy {

  /** 菜单 */
  @Input() menu: any = null;

  /** 菜单表单 */
  _menuForm!: FormGroup;
  /** 父级菜单必填状态 */
  _parentMenuRequired: boolean = false;
  /** 菜单选项资源 */
  _menuOptionResource!: NcOptionResource;
  /** 菜单类型选项资源 */
  _menuTypeOptionResource!: NcOptionResource;
  /** 菜单类型选项列表 */
  _menuTypeOptionList: NcDictItem[] = [];

  /** 菜单额外参数控制器 */
  get _menuControlOfExtras(): FormArray { return this._menuForm.controls.extras as FormArray }

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

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

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

    // 构建菜单表单
    this._menuForm = this._formBuilder.group({
      applicationCode: [null],
      name: [null, [Validators.required, Validators.maxLength(20)]],
      type: [null, [Validators.required, Validators.maxLength(20)]],
      icon: [null, [Validators.maxLength(200)]],
      authorityIdentifier: [null, [Validators.maxLength(100)]],
      sequence: [null],
      url: [null, [Validators.required, Validators.maxLength(200)]],
      src: [null, [Validators.required, Validators.maxLength(200)]],
      visible: [null],
      extras: this._formBuilder.array([], [Validators.maxLength(200)]),
      parentId: [null]
    });
    const { type, icon, authorityIdentifier, sequence, url, src, visible, extras, parentId } = this._menuForm.controls;

    // 生成菜单表单补丁
    const menuFormPatch = { ...this.menu };
    if (menuFormPatch.id) {
      type.disable();
      if (menuFormPatch.type === '权限') {
        this._parentMenuRequired = true;
        parentId.setValidators(Validators.required);
      }
    }
    if (menuFormPatch.parentId) {
      menuFormPatch.parentId = menuFormPatch.parentId.toString();
    }
    if (menuFormPatch.extras) {
      try {
        const extras = JSON.parse(menuFormPatch.extras);
        for (const key in extras) {
          this._addExtra(key, extras[key]);
        }
      } catch (error) { }
    }
    delete menuFormPatch.extras;

    // 定义菜单表单规则
    parentId.valueChanges
      .pipe(distinctUntilChanged())
      .subscribe(parentId => {
        this._generateMenuTypeOptionList(parentId);
      });
    type.valueChanges
      .pipe(distinctUntilChanged())
      .subscribe(type => {
        if (/^(文件夹|菜单|链接)$/.test(type)) {
          icon.enable();
          sequence.enable();
          visible.enable();
          visible.reset(true);
        } else {
          icon.disable();
          icon.reset();
          sequence.disable();
          sequence.reset();
          visible.disable();
          visible.reset(false);
        }
        if (/^(菜单|权限)$/.test(type)) {
          authorityIdentifier.enable();
        } else {
          authorityIdentifier.disable();
          authorityIdentifier.reset();
        }
        if (/^(菜单|链接)$/.test(type)) {
          url.enable();
        } else {
          url.disable();
          url.reset();
        }
        if (/^(菜单)$/.test(type)) {
          src.enable();
          extras.enable();
        } else {
          src.disable();
          src.reset();
          extras.disable();
          this._menuControlOfExtras.clear();
        }
      });

    // 获取菜单类型选项资源
    const menuOptionUrl = 'source::@' + this._ngCortexService.coreService + '/api/menus?applicationCode=' + menuFormPatch.applicationCode;
    this._menuOptionResource = this._ngCortexService.getOptionResource(menuOptionUrl, {
      map: menuList => this._generateMenuTreeOptionList(menuList),
      tap: menuList => this._generateMenuTypeOptionList(this._menuForm.getRawValue().parentId, null, menuList),
      error: error => this._nzNotificationService.error('获取菜单列表失败', getErrorMessage(error))
    });

    // 获取菜单类型选项资源
    const menuTypeOptionUrl = 'dict::menuType';
    this._menuTypeOptionResource = this._ngCortexService.getOptionResource(menuTypeOptionUrl, {
      tap: menuTypeList => this._generateMenuTypeOptionList(this._menuForm.getRawValue().parentId, menuTypeList),
      error: error => this._nzNotificationService.error('获取菜单类型列表失败', getErrorMessage(error))
    });

    // 更新菜单表单值
    this._menuForm.patchValue(menuFormPatch);
  }

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

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

  /**
   * 添加额外参数
   * @param key 键
   * @param value 值
   */
  _addExtra(key?: string, value?: string): void {
    this._menuControlOfExtras.push(this._formBuilder.group({
      key: [key || '', [Validators.required]],
      value: [isValid(value) ? value : '', [Validators.required]]
    }));
  }

  /**
   * 移除额外参数
   * @param index 索引
   */
  _removeExtra(index: number): void {
    this._menuControlOfExtras.removeAt(index);
  }

  /** 获取菜单更新 */
  private _getMenuUpdate(): any {
    const update = { ...this._menuForm.getRawValue() };
    if (update.parentId) {
      update.parentId = Number(update.parentId);
    }
    if (update.extras.length > 0) {
      const extras: { [key: string]: string; } = {};
      update.extras.forEach((extra: any) => {
        extras[extra.key] = extra.value;
      });
      update.extras = JSON.stringify(extras);
    } else {
      update.extras = null;
    }
    for (const key in update) {
      if (!isValid(update[key])) {
        update[key] = null;
      }
    }
    return getEntityUpdate(update, this.menu) && { ...this.menu, ...update };
  }

  /**
   * 提交菜单
   * @param update 更新
   */
  private _submitMenu(update: any): Observable<any> {
    const url = '@' + this._ngCortexService.coreService + '/api/menus';
    const body = update;
    if (body.id) {
      return this._httpClient.put(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('更新菜单成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('更新菜单失败', getErrorMessage(httpErrorResponse));
        }));
    } else {
      return this._httpClient.post(url, body).pipe(tap(
        () => {
          this._nzNotificationService.success('新增菜单成功', null!);
        },
        (httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('新增菜单失败', getErrorMessage(httpErrorResponse));
        }));
    }
  }

  /**
   * 生成菜单树形选项列表
   * @param menuList 菜单列表
   */
  private _generateMenuTreeOptionList(menuList: any[]): NzTreeNodeOptions[] {
    const menuTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const menuTreeNodeOptions: { [id: string]: NzTreeNodeOptions; } = {};
    const { type } = this._menuForm.getRawValue();
    let parentMenuFilterFn;
    if (this.menu && this.menu.id) {
      switch (type) {
        case '权限':
          parentMenuFilterFn = (menu: any) => /^(文件夹|菜单)$/.test(menu.type);
          break;
        case '文件夹':
          parentMenuFilterFn = (menu: any) => /^文件夹$/.test(menu.type) && menu.id !== this.menu.id;
          break;
        default:
          parentMenuFilterFn = (menu: any) => /^文件夹$/.test(menu.type);
      }
    } else {
      parentMenuFilterFn = (menu: any) => /^(文件夹|菜单)$/.test(menu.type);
    }
    menuList
      .filter(parentMenuFilterFn)
      .forEach(menu => {
        const menuTreeNodeOption = menuTreeNodeOptions[menu.id] = menuTreeNodeOptions[menu.id] || {};
        menuTreeNodeOption.key = menu.id.toString();
        menuTreeNodeOption.title = menu.name;
        if (menu.type === '文件夹' && type === '权限') {
          menuTreeNodeOption.disabled = true;
        }
        if (!menuTreeNodeOption.children) {
          menuTreeNodeOption.isLeaf = true;
        }
        if (menu.parentId) {
          const parentMenuTreeNodeOption = menuTreeNodeOptions[menu.parentId] = menuTreeNodeOptions[menu.parentId] || {};
          if (!parentMenuTreeNodeOption.children) {
            delete parentMenuTreeNodeOption.isLeaf;
            parentMenuTreeNodeOption.children = [];
          }
          parentMenuTreeNodeOption.children.push(menuTreeNodeOption);
        } else {
          menuTreeNodeOptionList.push(menuTreeNodeOption);
        }
      });
    return menuTreeNodeOptionList;
  }

  /**
   * 生成菜单类型选项列表
   * @param menuList 菜单列表
   * @param parentId 父级id
   */
  private _generateMenuTypeOptionList(parentId: any, menuTypeList?: any[] | null, menuList?: any[] | null): void {
    menuTypeList = menuTypeList || this._menuTypeOptionResource.origin || [];
    menuList = menuList || this._menuOptionResource.origin || [];
    const parentMenu = menuList!.find((menu: any) => menu.id.toString() === parentId) || { type: '文件夹' };
    let defaultType;
    switch (parentMenu.type) {
      case '文件夹':
        this._menuTypeOptionList = menuTypeList!.filter((menuType: NcDictItem) => /^(文件夹|菜单|链接)$/.test(menuType.value));
        defaultType = '菜单';
        break;
      case '菜单':
        this._menuTypeOptionList = menuTypeList!.filter((menuType: NcDictItem) => /^权限$/.test(menuType.value));
        defaultType = '权限';
        break;
      default:
        this._menuTypeOptionList = [];
        defaultType = null;
    }
    const { type } = this._menuForm.controls;
    if (type.enabled) {
      const { type: typeValue } = this._menuForm.getRawValue();
      const menuTypeOption = this._menuTypeOptionList.find(menuTypeOption => menuTypeOption.value === typeValue);
      if (!menuTypeOption) {
        type.patchValue(defaultType);
      }
    }
  }

}
