import {Component, OnInit, ViewChild} from '@angular/core';
import {ITreeOptions, TreeComponent} from "@circlon/angular-tree-component";
import {FrameDetailComponent} from "../../core/detail/frame.detail";
import {BsModalRef} from "ngx-bootstrap/modal";

@Component({
  selector: 'app-frame-dept-tree',
  templateUrl: './frame-dept-tree.component.html',
  styleUrls: ['./frame-dept-tree.component.scss']
})
export class FrameDeptTreeComponent extends FrameDetailComponent implements OnInit {
  @ViewChild('tree', {static: false}) tree: TreeComponent;

  nodes: any;
  rootDept: any;

  customTemplateStringOptions: ITreeOptions = {
    displayField: 'dept_name',
    isExpandedField: 'expanded',
    idField: 'dept_id',
    // hasChildrenField: 'childArray',
    // nodeHeight: 23,
    allowDragoverStyling: true,
    levelPadding: 20,
    // useVirtualScroll: true,
    animateExpand: true,
    scrollOnActivate: true,
    animateSpeed: 30,
    animateAcceleration: 1.2
    // scrollContainer: document.documentElement // HTML
  }

  constructor(bsModalRef: BsModalRef) {
    super(bsModalRef);
  }

  ngOnInit() {
    const dept = {'dept_id': 0, 'dept_name': '顶级部门', 'dept_level': 0};
    this.findChildDept(this.ResponseArray, dept);
    this.rootDept = dept;
    this.nodes = dept['children'];
  }

  findChildDept(deptArray, dept) {
    const array = new Array();
    for (const v of deptArray) {
      if (v['dept_id'] !== dept['dept_id'] && v['dept_pid'] === dept['dept_id']) {
        this.findChildDept(deptArray, v);
        array.push(v);
        dept.children = array;
      }
    }
    if (dept.children === undefined || dept.children.length === 0) {
      dept.hasChildren = false;
      dept.expanded = false;
    } else {
      dept.hasChildren = true;
      dept.expanded = true;
    }
  }


  expandAll() {
    for (const dept of this.rootDept['children']) {
      this.tree.treeModel.getNodeById(dept.dept_id).expandAll();
    }
  }

  collapseAll() {
    for (const dept of this.rootDept['children']) {
      this.tree.treeModel.getNodeById(dept.dept_id).collapseAll();
    }
  }
}
