import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS, SharedModule } from '@shared';

export interface TreeNodeInterface {
  id: string;
  menuCode: string;
  text?: number;
  level?: number;
  expand?: boolean;
  icon?: string;
  srtno: number;
  children?: TreeNodeInterface[];
  parent?: TreeNodeInterface;
}

@Component({
  selector: 'app-sys-menu-manage',
  standalone: true,
  imports: [SharedModule, ...SHARED_IMPORTS],
  templateUrl: './menu-manage.component.html'
})
export class SysMenuManageComponent implements OnInit {
  private readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);

  url = `/api/main/menu`;
  menuList: TreeNodeInterface[] = []; //菜单列表
  mapOfExpandedData: { [id: string]: TreeNodeInterface[] } = {};

  ngOnInit(): void {
    this.getMenuList();
  }

  /**
   *
   *
   */
  getMenuList() {
    this.http.get(this.url).subscribe(res => {
      this.menuList = res;

      this.menuList.forEach(item => {
        this.mapOfExpandedData[item.id] = this.convertTreeToList(item);
      });
    });
  }

  get(): void {
    this.getMenuList();
  }

  convertTreeToList(root: TreeNodeInterface): TreeNodeInterface[] {
    const stack: TreeNodeInterface[] = [];
    const array: TreeNodeInterface[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: { [id: string]: boolean }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.id === d.id)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }
}
