import { Component, OnInit, ViewChild } from '@angular/core';
import { Menu } from '@delon/theme';
import { EAEnvironmentService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { MenuManagerService } from './../../services/menu-manager.service';

@Component({
  selector: 'app-menu-manager-components-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.less']
})
export class MenuManagerComponentsIndexComponent implements OnInit {
  selectedPlatform!: { name: string; appId: string; enName: string };
  menus: Array<any> = [];
  platforms: Array<any> = [];
  currentSelectedNode: any;
  transferData!: string;
  dropType = {
    dropPrev: true,
    dropNext: true,
    dropInner: true
  };
  constructor(private envSrv: EAEnvironmentService, public service: MenuManagerService, private modal: NzModalService) {}

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

  initData(): void {
    this.platforms = [
      { name: '货主PC', appId: 'A48F72F0A304427F921794BAD86B3522', enName: 'tms-smc-web' },
      { name: '运营后台', appId: this.envSrv.env.appId, enName: 'tms-obc-web' }
    ];
    this.selectedPlatform = this.platforms[0];
    // this.platformChange(this.selectedPlatform);
  }

  platformChange(e: { name: string; appId: string }) {
    if (e) {
      this.loadMenus(e.appId);
    } else {
      this.menus = [];
      this.currentSelectedNode = null;
    }
  }

  loadMenus(appId: string) {
    this.service.request(this.service.$api_get_one, { appId }, 'POST', false).subscribe(res => {
      this.menus = res;
    });
  }

  editValueChange(event: any) {
    console.log('editChanged', event);
  }

  menuImport(index: number) {
    this.selectedPlatform = this.platforms[index];
    if (!this.selectedPlatform) {
      return;
    }

    this.service.http.request('GET', `assets/mocks/platform/${this.selectedPlatform.enName}.json`).subscribe((res: any) => {
      this.addMenu(res.menu);
    });
  }

  addMenu(menus: Array<Menu>, parentId: string = '') {
    menus.forEach(r => {
      if (parentId !== '') {
        r.parentId = parentId;
      }
      this.service.request(this.service.$api_get_one, { appId: this.selectedPlatform.appId }, 'POST', false).subscribe(res => {
        // 如果res.data存在，则更新菜单
        if (res.data) {
          r.id = res.data.id;
        }
        this.service
          .addOne({ appId: this.selectedPlatform.appId, ...r, isLeaf: !(r.children && r.children.length > 0) })
          .subscribe(result => {
            if (result) {
              if (r.children && r.children.length > 0) {
                this.addMenu(r.children, result.id);
              }
            }
          });
      });
    });

    // this.loadMenus(this.selectedPlatform.appId);
  }

  addMenuRecursion() {}

  delMenu(type: number) {
    this.modal.confirm({
      nzTitle: '<i>删除确认</i>',
      nzContent: `是否确认删除？`,
      nzOnOk: () => {
        this.getMenuByAppID(type === 0 ? 'A48F72F0A304427F921794BAD86B3522' : this.envSrv.env.appId);
      }
    });
  }

  getMenuByAppID(appId: string) {
    this.service.request(this.service.$api_get_one, { appId }, 'POST', false).subscribe(res => {
      console.log(res);
      if (res) {
        const menus = res.data;
        if (res.data?.length > 0) {
          this.deleteMenuByAppID(res.data);
        } else {
          this.service.msgSrv.success('菜单已清空');
        }
      }
    });
  }

  deleteMenuByAppID(arr: Array<any>) {
    let ids: any[] = arr?.map(item => item.id) || [];
    arr.forEach(item => {
      if (item.children?.length > 0) {
        this.deleteMenuByAppID(item.children);
      }
    });
    this.service.request(this.service.$api_del_many, ids).subscribe(res => {});
  }
}
