import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Router } from '@angular/router';
import { RouteInfo } from './vertical-sidebar.metadata';
import { VerticalSidebarService } from './vertical-sidebar.service';
import { ExcelReportService } from 'src/app/service/excel-report.service';
import { MyTemplateFileMiniModel, TemplateFileMiniModel } from 'src/app/model/template-file-mini.model';


@Component({
  selector: 'app-vertical-sidebar',
  templateUrl: './vertical-sidebar.component.html'
})
export class VerticalSidebarComponent {
  @Input() showClass: boolean = false;
  @Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>();
  showMenu = '';
  showSubMenu = '';
  public sidebarnavItems: RouteInfo[] = [];
  path = '';
  submenuExcel: TemplateFileMiniModel[] = []
  constructor(private menuServise: VerticalSidebarService, private router: Router, private excelReportService: ExcelReportService) {
    this.excelReportService.getTemplateFileLists().subscribe(response => {
      this.submenuExcel = response.map(e => new MyTemplateFileMiniModel(e))

      if (this.submenuExcel.length) {
        const currentValue = this.menuServise.items.value;
        const updated = [...currentValue, {
          path: '',
          title: 'รายงาน Excel',
          icon: 'mdi mdi-adjust',
          class: 'has-arrow',
          label: "",
          labelClass: "",
          extralink: false,
          submenu: []
        }];
        this.menuServise.items.next(updated);
      }
      this.addMenu()
    }, error => {
      this.addMenu()
    })

  }
  addMenu() {
    this.menuServise.items.subscribe(menuItems => {
      this.sidebarnavItems = menuItems.map(e => {
        if (e.title == 'รายงาน Excel') {
          this.submenuExcel.map(e2 => {
            e.submenu.push({
              path: '/apps/excel-export/' + e2.itemId + "?template=" + e2.templateId + "&name=" + e2.fileName,
              title: e2.itemId + '.' + e2.tdesc,
              icon: "",
              class: "",
              label: "",
              labelClass: "",
              extralink: false,
              submenu: []
            })
          })
        }
        return e
      })
      this.sidebarnavItems.filter(m =>
        m.submenu.filter(
          (s) => {
            if (s.path === this.router.url) {
              this.path = m.title;
            }
          }
        ));
      this.addExpandClass(this.path);
    });
  }
  addExpandClass(element: any) {
    if (element === this.showMenu) {
      this.showMenu = '0';
    } else {
      this.showMenu = element;
    }
  }

  addActiveClass(element: any) {
    if (element === this.showSubMenu) {
      this.showSubMenu = '0';
    } else {
      this.showSubMenu = element;
    }
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }

  handleNotify() {
    this.notify.emit(!this.showClass);
  }


}
