import {Component, inject} from '@angular/core';
import {NzListModule} from 'ng-zorro-antd/list';
import {NzGridModule} from 'ng-zorro-antd/grid';
import {NzCardModule} from 'ng-zorro-antd/card';
import {DictionaryService} from '../../../services/commons/dictionary.service';
import {MenuService} from '../../../services/system/menu.service';
import {NzSpinComponent} from 'ng-zorro-antd/spin';
import {NzTreeComponent} from 'ng-zorro-antd/tree';
import {NgForOf, NgIf} from '@angular/common';
import {NzDescriptionsComponent, NzDescriptionsItemComponent} from 'ng-zorro-antd/descriptions';
import {NzButtonComponent} from 'ng-zorro-antd/button';
import {NonNullableFormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
import {NzModalComponent, NzModalContentDirective, NzModalModule, NzModalService} from 'ng-zorro-antd/modal';
import {NzFormControlComponent, NzFormDirective, NzFormLabelComponent, NzFormModule} from 'ng-zorro-antd/form';
import {NzInputDirective} from 'ng-zorro-antd/input';
import {NzTreeSelectComponent} from 'ng-zorro-antd/tree-select';
import {NzOptionComponent, NzSelectComponent} from 'ng-zorro-antd/select';
import {NzInputNumberComponent} from 'ng-zorro-antd/input-number';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzNotificationService} from 'ng-zorro-antd/notification';


@Component({
  selector: 'app-menu',
  imports: [
    NzCardModule,
    NzGridModule,
    NzFormModule,
    NzModalModule,
    NzListModule,
    NzSpinComponent,
    NzTreeComponent,
    NgIf,
    NzDescriptionsComponent,
    NzDescriptionsItemComponent, NzButtonComponent, NzModalComponent, NzModalContentDirective, NzFormDirective, ReactiveFormsModule, NzInputDirective, NzFormControlComponent, NzFormLabelComponent, NzTreeSelectComponent, NzSelectComponent, NzOptionComponent, NzInputNumberComponent, NgForOf],
  templateUrl: './menu.component.html',
  standalone: true,
  styleUrl: './menu.component.scss'
})
export class MenuComponent {

  private fb = inject(NonNullableFormBuilder);
  private readonly notification = inject(NzNotificationService);
  // 菜单类型
  menuTypeArray: any = [];
  // 菜单数据
  menuData: any = [];
  // 菜单树形数据
  menuTree: any[] = [];
  // 菜单详情
  menuDetail: any = {};
  // 编辑菜单弹出框
  isVisible = false;
  // 树视图展示状态
  treeView= false;
  constructor(
    private dictionary: DictionaryService,
    private modal: NzModalService,
    private message: NzMessageService ,
    private menuService: MenuService
  ) {
    // 获取菜单类型
    this.dictionary.getDictionary('MENU_TYPE  ', (data: any) => {
      this.menuTypeArray = data['return_data'];
    });
    this.queryMenuTree();
  }

  validateForm = this.fb.group({
    menuName: this.fb.control('', [Validators.required]),
    menuType: this.fb.control('', [Validators.required]),
    menuUrl: this.fb.control('', [Validators.required]),
    menuSort: this.fb.control('', [Validators.required]),
    menuPSid: this.fb.control(null),
    menuUrlImg: this.fb.control(''),
    menuDesc: this.fb.control(''),
    id: this.fb.control(null)
  });

  // 获取菜单树数据
  queryMenuTree() {
    this.menuService.queryMenuTree((data: any) => {
      this.menuTree = data['return_data'];
      this.treeView = true;
      this.queryMenuData();
    });
  }


  /**
   * 查询菜单原始数据
   */
  queryMenuData() {
    this.menuService.queryMenuList((data: any) => {
      this.menuData = data['return_data'];
    });
  }

  /**
   * 点击树节点
   * @param nodeData
   */
  clickNode(nodeData: any) {
    const menuId = nodeData['keys'][0];
    if (menuId != null) {
      const menuObj = this.menuData.find((o: any) => o.id == menuId);
      if (menuObj != null && menuObj.menuPSid != null) {
        // 获取父级菜单
        menuObj['parentMenu'] = this.menuData.find((o: any) => o.id == menuObj.menuPSid);
      }
      this.menuDetail = menuObj;
    }
  }


  // 编辑菜单
  openEditMenu(isEdit: boolean): void {
    if (isEdit) {
      this.validateForm.reset();
      const menu:{} = {
        menuPSid: ""+this.menuDetail.id,
        menuType: '1'
      };
      this.validateForm.patchValue(menu);
    } else {
      // 判断是否点击需要修改菜单
      if ( this.menuDetail?.id == null) {
        this.notification.create(
          'warning',
          '修改提示',
          '请点击需要修改的菜单！',
        );
        return;
      }
      this.menuDetail.menuPSid = String(this.menuDetail.menuPSid);
      this.menuDetail.menuType = String(this.menuDetail.menuType);
      this.validateForm.patchValue(this.menuDetail);
    }
    this.isVisible = true;
  }

  // 提交菜单
  handleOk(): void {
    if (this.validateForm.valid) {
      this.treeView = false;
      console.log(this.validateForm.controls['menuPSid'].value);
      if (this.validateForm.controls['menuPSid'].value == 'undefined') {
        this.validateForm.controls['menuPSid'].setValue(null);
      }
      console.log(this.validateForm.value);
      this.menuService.editMenu(this.validateForm.value, (data: any) => {
        if (data['return_code'] == '000000') {
          // 刷新数据
          this.queryMenuTree();

          this.message.create('success', '操作成功');

          // 关闭弹窗
          this.isVisible = false;
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 删除菜单
   */
  showDelMenu() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确实删除数据？',
      nzOnOk: () => this.delMenu()
    });
  }

  /**
   * 删除菜单
   */
  delMenu() {
    const param = {
      menuId: this.menuDetail.id
    }
    this.treeView = false;
    this.menuService.delMenu(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryMenuTree();
        this.message.create('success', '操作成功');
      } else {
        this.treeView = true;
        this.message.create('error', data['return_msg']);
      }
    });
  }


}
