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';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-sys-perms-setting',
  standalone: true,
  imports: [SharedModule, ...SHARED_IMPORTS],
  templateUrl: './perms-setting.component.html'
})
export class SysPermsSettingComponent implements OnInit {
  private readonly http = inject(_HttpClient);
  readonly role: string = inject(NZ_MODAL_DATA);

  defaultCheckedKeys: any[] = [];
  defaultSelectedKeys: any[] = [];
  defaultExpandedKeys: any[] = [];
  nodes: any[] = [];
  permissions: any[] = [];

  @ViewChild('tree') private readonly tree!: NzTreeComponent;

  ngOnInit(): void {
    const url = `/api/permission-management/permissions?providerName=R&providerKey=${this.role}`;
    this.http.get(url).subscribe(res => {
      console.log(res);

      this.nodes = [
        ...res.groups.map((r: { displayName: any; name: any; permissions: any[] }) => {
          return {
            title: r.displayName,
            key: r.name,
            children: r.permissions
              .filter(rr => !rr.parentName)
              .map(rr => {
                return {
                  title: rr.displayName,
                  key: rr.name,
                  children: r.permissions
                    .filter(rrc => rrc.parentName == rr.name)
                    .map(rrc => {
                      return {
                        title: rrc.displayName,
                        key: rrc.name,
                        isLeaf: true
                      };
                    })
                };
              })
          };
        })
      ];

      res.groups.forEach((element: { permissions: any[] }) => {
        element.permissions.forEach(element1 => {
          if (element1.isGranted == true && element1.parentName != null) {
            this.defaultCheckedKeys.push(element1.name);
          } else if (element1.isGranted == true && element1.parentName == null) {
            const index = element.permissions.findIndex(ee => ee.parentName == element1.name && ee.isGranted == false);

            if (index == -1) {
              this.defaultCheckedKeys.push(element1.name);
            }
          }
        });
      });

      this.defaultCheckedKeys = [...this.defaultCheckedKeys];
    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    if (event.eventName == 'check') {
      this.permissions = [];
      var selectedNode: any[] = [];

      event.checkedKeys?.forEach(node0 => {
        if (node0.level != 0) {
          selectedNode.push(node0.key);
        }

        if (node0.children) {
          node0.children.forEach(node1 => {
            selectedNode.push(node1.key);
            if (node1.children) {
              node1.children.forEach(node2 => {
                selectedNode.push(node2.key);
              });
            }
          });
        }
      });

      selectedNode.forEach(element => {
        if (!this.defaultCheckedKeys.includes(element)) {
          this.permissions.push({ name: element, isGranted: true });
        }
      });

      this.defaultCheckedKeys.forEach(element => {
        if (!selectedNode.includes(element)) {
          this.permissions.push({ name: element, isGranted: false });
        }
      });
    }
  }

  /**
   * ocean 2023-3-4
   * 获取角色权限
   */
  getPermissions(): any {
    const currentCheckedNode = this.tree.getCheckedNodeList();
    const currentHalfCheckedNode = this.tree.getHalfCheckedNodeList();

    this.permissions = [];
    const selectedNode: any[] = [];

    currentCheckedNode.forEach(node0 => {
      if (node0.level != 0) {
        selectedNode.push(node0.key);
      }

      if (node0.children) {
        node0.children.forEach(node1 => {
          selectedNode.push(node1.key);
          if (node1.children) {
            node1.children.forEach(node2 => {
              selectedNode.push(node2.key);
            });
          }
        });
      }
    });

    currentHalfCheckedNode.forEach(node0 => {
      if (node0.level != 0) {
        selectedNode.push(node0.key);
      }
    });

    selectedNode.forEach(element => {
      if (!this.defaultCheckedKeys.includes(element)) {
        this.permissions.push({ name: element, isGranted: true });
      }
    });

    this.defaultCheckedKeys.forEach(element => {
      if (!selectedNode.includes(element)) {
        this.permissions.push({ name: element, isGranted: false });
      }
    });

    return this.permissions;
  }

  aaa() {
    console.log(this.tree.getCheckedNodeList());
    console.log(this.tree.getHalfCheckedNodeList());
  }
}
