import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { isValid, validateForm } from '@ng-cortex/utils';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { NcOrganizationEditorComponent } from '../nc-organization-editor/nc-organization-editor.component';

/** 字段接口 */
interface Field {
  /** 名称 */
  name: string;
  /** 描述 */
  description?: string;
  /** 可见状态 */
  visible?: boolean;
  /** 对齐 */
  align?: 'left' | 'right' | 'center';
  /** 宽度 */
  width?: string;
  /** 排序键 */
  sortKey?: string;
  /** 排序状态 */
  sortOrder?: string | null;
  /** 默认排序 */
  defaultSequence?: number;
  /** 默认可见状态 */
  defaultVisible?: boolean;
  /** 默认宽度 */
  defaultWidth?: string;
  /** 标题模板 */
  titleTemplate?: TemplateRef<any>;
  /** 内容模板 */
  contentTemplate?: TemplateRef<{ $implicit?: any; source?: any; extra?: any; }>;
}

/** 树形节点 */
interface TreeNode {
  source: any;
  level: number;
  expand?: boolean;
  children?: TreeNode[];
}

/** 机构管理页面 */
@Component({
  selector: 'nc-organization',
  templateUrl: './nc-organization.page.html',
  styleUrls: ['./nc-organization.page.scss']
})
export class NcOrganizationPage implements OnInit, AfterViewInit {

  /** 标题模板 */
  @ViewChild('titleTemplate') _titleTemplate!: TemplateRef<{ $implicit: string; source: any; }>;
  /** 数字模板 */
  @ViewChild('numberContentTemplate') _numberContentTemplate!: TemplateRef<{ $implicit: number; }>;
  /** 时间模板 */
  @ViewChild('timeTemplate') _timeTemplate!: TemplateRef<{ $implicit: string; }>;

  /** 机构列表 */
  _organizationList: any[] = [];
  /** 机构树形节点列表 */
  _organizationTreeNodeList: TreeNode[] = [];
  /** 机构额外属性 */
  _organizationExtras: any = {};
  /** 机构搜索表单 */
  _organizationSearchForm!: FormGroup;
  /** 机构加载状态 */
  _organizationLoading: boolean = false;
  /** 机构全部选中状态 */
  _organizationAllChecked: boolean = false;
  /** 机构模糊选中状态 */
  _organizationIndeterminate: boolean = false;
  /** 机构字段列表 */
  _organizationFieldList: Field[] = [
    { name: 'name', description: '机构名称', visible: true, width: '200px' },
    { name: 'type', description: '机构类型', visible: true, width: '200px' },
    { name: 'sequence', description: '顺序号', visible: true, align: 'right', width: '200px' },
    { name: 'createdBy', description: '创建人', width: '200px' },
    { name: 'createdTime', description: '创建时间', width: '200px' },
    { name: 'lastModifiedBy', description: '最后更新人', width: '200px' },
    { name: 'lastModifiedTime', description: '最后更新时间', width: '200px' }
  ];

  /** 取消获取机构列表 */
  private _cancelGetOrganizationListFn = () => { };

  constructor(
    private _formBuilder: FormBuilder,
    private _httpClient: HttpClient,
    private _nzModalService: NzModalService,
    private _nzNotificationService: NzNotificationService) { }

  /** 初始化后 */
  ngOnInit(): void {
    this._organizationFieldList.forEach((field, index) => {
      field.defaultSequence = index + 1;
      field.defaultVisible = field.visible;
      field.defaultWidth = field.width;
    });
    this._organizationSearchForm = this._formBuilder.group({
      keywords: [null]
    });
    validateForm(this._organizationSearchForm, true).subscribe(() => this._getOrganizationList());
  }

  /** 初始次渲染后 */
  ngAfterViewInit(): void {
    this._organizationFieldList.forEach(field => {
      if (/^name$/.test(field.name)) {
        field.contentTemplate = this._titleTemplate;
      }
      if (/^sequence$/.test(field.name)) {
        field.contentTemplate = this._numberContentTemplate;
      }
      if (/^(createdTime|lastModifiedTime)$/.test(field.name)) {
        field.contentTemplate = this._timeTemplate;
      }
    });
  }

  /** 查询机构列表 */
  _queryOrganizationList(): void {
    validateForm(this._organizationSearchForm).subscribe(() => this._getOrganizationList());
  }

  /** 重新查询机构列表 */
  _requeryOrganizationList(): void {
    this._queryOrganizationList();
  }

  /** 重置机构搜索表单 */
  _resetOrganizationSearchForm(): void {
    this._organizationSearchForm.reset();
    this._queryOrganizationList();
  }

  /**
   * 拖拽机构字段列表
   * @param event 拖拽事件
   */
  _dropOrganizationFieldList(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this._organizationFieldList, event.previousIndex, event.currentIndex);
  }

  /** 重置机构字段列表 */
  _resetOrganizationFieldList(): void {
    this._organizationFieldList = this._organizationFieldList
      .map(field => {
        field.visible = field.defaultVisible!;
        field.width = field.defaultWidth;
        return field;
      })
      .sort((fieldA, fieldB) => fieldA.defaultSequence! - fieldB.defaultSequence!);
  }

  /**
   * 选中所有机构列表
   * @param checked 选中状态
   */
  _checkAllOrganizationList(checked: boolean): void {
    for (const id in this._organizationExtras) {
      this._organizationExtras[id].checked = checked;
    }
    this._organizationAllChecked = checked;
    this._organizationIndeterminate = false;
  }

  /** 更新机构选中状态 */
  _updateOrganizationCheckStatus(): void {
    const checkedOrganizationList = this._organizationList.filter(organization => this._organizationExtras[organization.id].checked);
    switch (checkedOrganizationList.length) {
      case 0:
        this._organizationAllChecked = false;
        this._organizationIndeterminate = false;
        break;
      case this._organizationList.length:
        this._organizationAllChecked = true;
        this._organizationIndeterminate = false;
        break;
      default:
        this._organizationAllChecked = false;
        this._organizationIndeterminate = true;
    }
  }

  /** 新增机构 */
  _createOrganization(): void {
    const organizationList = this._organizationList.filter(organization => this._organizationExtras[organization.id].checked);
    this._nzModalService.create({
      nzTitle: '新增机构',
      nzContent: NcOrganizationEditorComponent,
      nzComponentParams: {
        organization: { parentId: organizationList.length === 1 ? organizationList[0].id : null }
      },
      nzWidth: 520,
      nzOnOk: organizationEditor => {
        return organizationEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryOrganizationList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 编辑机构
   * @param organization 机构
   */
  _updateOrganization(organization: any): void {
    this._nzModalService.create({
      nzTitle: '编辑机构',
      nzContent: NcOrganizationEditorComponent,
      nzComponentParams: {
        organization: organization
      },
      nzWidth: 520,
      nzOnOk: organizationEditor => {
        return organizationEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              const targetOrganization = updated;
              this._organizationList = this._organizationList.map(organization => organization.id === targetOrganization.id ? targetOrganization : organization);
              this._generateOrganizationTreeNodeList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 删除机构
   * @param organization 机构
   */
  _deleteOrganization(organization: any): void {
    let cancelDeleteOrganizationFn = () => { };
    this._nzModalService.confirm({
      nzTitle: '删除确认',
      nzContent: '是否确认删除机构 “' + organization.name + '”',
      nzOnOk: () => {
        return new Observable(subscriber => {
          const url = '@<%= getSeparatorCase(serviceName) %>/api/organizations/' + organization.id;
          const deleteOrganizationSubscription = this._httpClient.delete(url, { responseType: 'text' })
            .pipe(map(() => {
              this._queryOrganizationList();
              return true;
            }))
            .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
              this._nzNotificationService.error('删除机构失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
              return of(false);
            }))
            .subscribe(subscriber);
          cancelDeleteOrganizationFn = () => {
            deleteOrganizationSubscription.unsubscribe();
          };
        })
          .toPromise();
      },
      nzOnCancel: () => {
        cancelDeleteOrganizationFn();
      }
    });
  }

  /** 展开机构列表 */
  _expandOrganizationList(): void {
    const eachOrganization = (organizationTreeList: TreeNode[]) => {
      organizationTreeList
        .filter(organizationNode => organizationNode.children)
        .forEach(organizationNode => {
          organizationNode.expand = true;
          eachOrganization(organizationNode.children!);
        });
    };
    eachOrganization(this._organizationTreeNodeList);
  }

  /** 折叠机构列表 */
  _collapseOrganizationList(): void {
    const eachOrganization = (organizationTreeList: TreeNode[]) => {
      organizationTreeList
        .filter(organizationNode => organizationNode.children)
        .forEach(organizationNode => {
          organizationNode.expand = false;
          eachOrganization(organizationNode.children!);
        });
    };
    eachOrganization(this._organizationTreeNodeList);
  }

  /** 获取机构列表 */
  private _getOrganizationList(): void {
    this._cancelGetOrganizationListFn();
    if (this._organizationSearchForm.valid) {
      this._organizationLoading = true;
      const completeGetOrganizationListFn = () => {
        this._cancelGetOrganizationListFn = () => { };
        this._organizationLoading = false;
      };
      const url = '@<%= getSeparatorCase(serviceName) %>/api/organizations';
      const params: any = { ...this._organizationSearchForm.getRawValue() };
      for (const key in params) {
        if (!isValid(params[key])) {
          delete params[key];
        }
      }
      const getOrganizationListSubscription = this._httpClient.get<any[]>(url, { params })
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取机构列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          return of([]);
        }))
        .subscribe(organizationList => {
          completeGetOrganizationListFn();
          const organizationExtras: any = {};
          organizationList
            .sort((organization1, organization2) => organization1.sequence - organization2.sequence)
            .forEach(organization => {
              organizationExtras[organization.id] = { checked: false };
            });
          this._organizationList = organizationList;
          this._organizationExtras = organizationExtras;
          this._organizationAllChecked = false;
          this._organizationIndeterminate = false;
          this._generateOrganizationTreeNodeList();
        });
      this._cancelGetOrganizationListFn = () => {
        getOrganizationListSubscription.unsubscribe();
        completeGetOrganizationListFn();
      };
    } else {
      this._organizationList = [];
      this._organizationTreeNodeList = [];
      this._organizationExtras = {};
      this._organizationAllChecked = false;
      this._organizationIndeterminate = false;
    }
  }

  /** 生成机构树形节点列表 */
  private _generateOrganizationTreeNodeList(): void {
    const organizationTreeNodeList: TreeNode[] = [];
    const organizationTreeNodes: any = {};
    this._organizationList
      .slice()
      .sort((organization1, organization2) => organization1.sequence - organization2.sequence)
      .forEach(organization => {
        const organizationTreeNode: TreeNode = organizationTreeNodes[organization.id] = organizationTreeNodes[organization.id] || {};
        organizationTreeNode.source = organization;
        if (organization.parentId) {
          const parentOrganizationTreeNode: TreeNode = organizationTreeNodes[organization.parentId] = organizationTreeNodes[organization.parentId] || {};
          if (!parentOrganizationTreeNode.children) {
            parentOrganizationTreeNode.expand = false;
            parentOrganizationTreeNode.children = [];
          }
          parentOrganizationTreeNode.children.push(organizationTreeNode);
        } else {
          organizationTreeNodeList.push(organizationTreeNode);
        }
      });
    const markLevelFn = (organizationTreeList: TreeNode[], level?: number) => {
      level = level || 0;
      organizationTreeList.forEach(organizationTreeNode => {
        if (organizationTreeNode.children) {
          markLevelFn(organizationTreeNode.children, level! + 1);
        }
        organizationTreeNode.level = level!;
      });
    };
    markLevelFn(organizationTreeNodeList);
    this._organizationTreeNodeList = organizationTreeNodeList;
  }

}
