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

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

  nodes: any;
  rootRes: any;
  customTemplateStringOptions: ITreeOptions = {
    displayField: 'res_name',
    isExpandedField: 'expanded',
    idField: 'res_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(): void {
    const res = {'res_id': 0, 'res_name': '顶级资源', 'res_level': 0};
    this.findChildRes(this.ResponseArray, res);
    this.rootRes = res;
    this.nodes = res['children'];
  }

  findChildRes(resArray, res) {
    const array = new Array();
    for (const v of resArray) {
      if (v['res_id'] !== res['res_id'] && v['res_pid'] === res['res_id']) {
        this.findChildRes(resArray, v);
        array.push(v);
        res.children = array;
      }
    }
    if (res.children === undefined || res.children.length === 0) {
      res.hasChildren = false;
      res.expanded = false;
    } else {
      res.hasChildren = true;
      res.expanded = true;
    }
  }

  childrenCount(node: TreeNode): string {
    return node && node.children ? `(${node.children.length})` : '';
  }

  expandAll() {
    for (const res of this.rootRes['children']) {
      this.tree.treeModel.getNodeById(res.res_id).expandAll();
    }
  }

  collapseAll() {
    for (const res of this.rootRes['children']) {
      this.tree.treeModel.getNodeById(res.res_id).collapseAll();
    }
  }

}
