import { Component, Input, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { firstValueFrom } from 'rxjs';
import { AuthService } from './auth/auth.service';

@Component({
  selector: 'admin-menu',
  template: `
    <ul nz-menu nzNoAnimation nzTheme="dark" nzMode="inline" [nzInlineCollapsed]="isCollapsed">

      <!--远端加载的菜单-->
      <ng-container *ngFor="let item of menu">
        <!--带子菜单-->
        <li *ngIf="item.children" nz-submenu [nzTitle]="titleTpl" >
          <ng-template #titleTpl><i class="icon {{item.icon || 'fas fa-question-square'}}" ></i><span>{{item.name}}</span></ng-template>
          <ul >
            <li *ngFor="let subItem of item.children" nz-menu-item nzMatchRouter>
              <a routerLink="{{subItem.url}}">{{subItem.name}}</a>
            </li>
          </ul>
        </li>

        <!--不带子菜单-->
        <li *ngIf="!item.children"  nz-menu-item nzMatchRouter >
          <i class="icon {{item.icon}}" ></i>
          <a routerLink="{{item.url}}">{{item.name}}</a>
        </li>
      </ng-container>

      <!--测试菜单-->
      <!--
      <ng-container *ngFor="let item of testMenu">
        <li *ngIf="item.children" nz-submenu [nzTitle]="titleTpl" >
          <ng-template #titleTpl><i class="icon {{item.icon || 'fas fa-question-square'}}" ></i><span>{{item.name}}</span></ng-template>
          <ul >
            <li *ngFor="let subItem of item.children" nz-menu-item nzMatchRouter>
              <a routerLink="{{subItem.url}}">{{subItem.name}}</a>
            </li>
          </ul>
        </li>

        <li *ngIf="!item.children"  nz-menu-item nzMatchRouter >
          <i class="icon {{item.icon}}" ></i>
          <a routerLink="{{item.url}}">{{item.name}}</a>
        </li>
      </ng-container>
      -->



    </ul>


  `,
  styles: [`
  
  :host{
    overflow-y:auto;
  }
  
  `]
})
export class MenuComponent implements OnInit {

  @Input() isCollapsed: boolean = false;

  constructor(
    private auth: AuthService,
    private message: NzMessageService
  ) { }

  menu: MenuItem[];

  testMenu : MenuItem[] = [
    {
      name : 'Test',
      icon : 'fas fa-vial',
      children : [
        {name : 'Users', url : '/test/users'},
        {name : 'Test', url : '/test/test'},
        {name : 'Login', url : '/auth/login'},
      ]
    }

  ];

  ngOnInit(): void {
    firstValueFrom(this.auth.getMenus())
      .then((res: MenuItem[]) => {
        this.menu = res
      })
      .catch(err => this.message.warning(err.error?.message || err.message));
  }

}



interface MenuItem {
  name: string,
  url?: string,
  icon?: string,
  children?: MenuItem[],
}