import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzTreeComponent } from 'ng-zorro-antd/tree';
import { MenuManagerService } from '../../services/menu-manager.service';

@Component({
  selector: 'app-menu-manager-menusort',
  templateUrl: './menusort.component.html',
})
export class MenuManagerMenusortComponent implements OnInit {
  @ViewChild('nzTreeComponent', { static: false }) nzTreeComponent!: NzTreeComponent;
  record: any = {};
  i: any;
  functionList: any[] = [];
  menuList: any[] = [];

  constructor(
    private modal: NzModalRef,
    public service: MenuManagerService,
  ) { }

  ngOnInit(): void {
   this.getAllFunction()
  }
  getAllFunction() {
    this.service.request(this.service.$api_get_all, { appId: this.i.appId }, 'POST', false).subscribe(res => {
      this.functionList = res;
      this.menuList = res[0].children;
    });
  }
  nzEvent(event: any): void {
    console.log(event)
  }
  dragEnd(event: any){
    const functionId = event.node.key
    let sortNumber = 0
    const newMenuList = this.nzTreeComponent.getTreeNodes()
    newMenuList.forEach((item, index) => {
      if(event.node.level === 0 && item.children) {

        if(functionId === item.key) {
          sortNumber = index
        }
      } else if(event.node.level === 1  && item.children) {
        item.children.forEach((subItem: any, subIndex: number) => {
          if(functionId === subItem.key) {
            sortNumber = subIndex
          }
        })
      } else if(event.node.level === 2 && item.children) {
        item.children.forEach((thirdItem: any, thirdIndex: number) => {
          if(functionId === thirdItem.key) {
            sortNumber = thirdIndex
          }
        })
      }
    })
    const params: any = {
      parentId: event.node.level === 0 ? this.functionList[0].id : event.node.parentNode.key,
      functionId,
      sortNumber
    }
    this.service.request(this.service.$api_alterFunctionsParent, params).subscribe(res => {
      if (res) {
      }
    })
    
  }
  sure(){
    this.modal.close(true)
  }
  close(): void {
    this.modal.destroy();
  }
}
