import {Component, ViewChild} from '@angular/core';
import {
  NzTableComponent,
  NzTableModule,
  NzTbodyComponent,
  NzTheadComponent,
  NzThMeasureDirective
} from "ng-zorro-antd/table";
import {NzDividerComponent} from "ng-zorro-antd/divider";
import {NzFormDirective, NzFormModule} from "ng-zorro-antd/form";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {
  FormGroup,
  NonNullableFormBuilder,
  ReactiveFormsModule, Validators,
} from "@angular/forms";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzFlexDirective} from "ng-zorro-antd/flex";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzInputNumberComponent} from "ng-zorro-antd/input-number";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzTreeComponent, NzTreeNodeOptions} from "ng-zorro-antd/tree";
import {RoleService} from '../../../services/system/role.service';
import {MenuService} from '../../../services/system/menu.service';


@Component({
  selector: 'app-sys-role',
  standalone: true,
  imports: [
    NzTableComponent,
    NzTheadComponent,
    NzDividerComponent,
    NzTbodyComponent,
    NzFormDirective,
    NzRowDirective,
    ReactiveFormsModule,
    NzColDirective,
    NzButtonComponent,
    NzInputDirective,
    NzFormModule,
    NzFlexDirective,
    NgForOf,
    DatePipe,
    NzThMeasureDirective,
    NzModalComponent,
    NzOptionComponent,
    NzSelectComponent,
    NzModalModule,
    NgIf,
    NzTreeComponent,
    NzTableModule
  ],
  templateUrl: './sys-role.component.html',
  styleUrl: './sys-role.component.less'
})
export class SysRoleComponent {
  // 表单页数
  tablePageNum = 1;
  // 表单数据
  tableData: any = {
    total: 0,
    list: [],
  };
  // 搜索表单
  searchForm: FormGroup;
  // 编辑角色弹出框
  editRoleVisible = false;
  // 编辑角色表单
  editRoleForm: FormGroup;
  // 编辑角色标题
  editRoleTitle = '';
  // 分配角色菜单弹出框
  assignRoleMenuVisible = false;

  // 当前需要分配权限角色
  currentAssignRoleId: any = null;
  // 菜单树
  menuTree: NzTreeNodeOptions[] = [];
  // 菜单已勾选数据
  menuTreeCheckedKeys: any =  [];

  @ViewChild('nzTreeComponent', { static: false }) nzTreeComponent!: NzTreeComponent;

  constructor(private fb: NonNullableFormBuilder,
              private roleService: RoleService,
              private menuService: MenuService,
              private message: NzMessageService,
              private modal: NzModalService) {
    // 初始化搜索框
    this.searchForm = this.fb.group({
      roleName: [''],
    });

    // 初始化表单
    this.editRoleForm = this.fb.group({
      id: [''],
      roleName: ['', [Validators.required]],
      roleDesc: [''],
    });

    this.menuService.queryMenuTree((data: any) => {
      console.log("树数据" , data['return_data']);
      this.menuTree = data['return_data'];
    });

    this.queryData();
  }

  /**
   * 获取数据
   */
  queryData() {
    this.searchForm.value.pageNum = this.tablePageNum;
    this.searchForm.value.pageSize = 10;
    this.searchForm.value.time = new Date().getTime();
    this.roleService.queryList(this.searchForm.value, (data: any) => {
        if (data['return_code'] == '000000') {
          this.tableData = data['return_data'];
        }
    });
  }

  /**
   * 搜索表单提交
   */
  searchFormSubmit(): void {
    this.tablePageNum = 1;
    this.queryData();
  }

  /**
   * 搜索表单重置
   */
  searchFormReset(): void {
    this.searchForm.reset();
  }

  /**
   * 打开编辑角色模态框
   * @param edit 编辑状态 ture：新增  false：修改
   * @param data 数据
   */
  showEditRole(edit: boolean, data: any) {
      if (edit) {
        this.editRoleTitle = '创建角色';
      } else {
        this.editRoleTitle = '修改角色';
        this.editRoleForm.patchValue(data);
      }
      this.editRoleVisible = true;
  }

  /**
   * 打开编辑角色模态框
   * @param edit
   */
  submitEditRoleForm() {
    if (this.editRoleForm.valid) {
      this.roleService.editRole(this.editRoleForm.value, (data: any) => {
        if (data['return_code'] == '000000') {
          // 刷新数据
          this.queryData();

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

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

  /**
   * 关闭编辑角色模态框
   */
  closeEditRole() {
    this.editRoleForm.reset();
    this.editRoleVisible = false;
  }

  /**
   * 展示删除数据
   */
  showDelData(dataId: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定删除数据？',
      nzOnOk: () => this.delData(dataId)
    });
  }

  /**
   * 删除数据
   */
  delData(dataId: number) {
    const param = {
      id: dataId
    }
    this.roleService.delRole(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryData();
        this.message.create('success', '操作成功');
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 打开分配角色菜单模态框
   * @param roleId
   */
  showAssignRoleMenu(roleId: number) {
    this.currentAssignRoleId = roleId;
    this.menuService.queryRoleMenuArray(roleId, (data: any) => {
      console.log("角色权限菜单" , data['return_data']);
      console.log("树" , this.menuTree);
      this.menuTreeCheckedKeys = data['return_data'];
    });
    this.assignRoleMenuVisible = true;
  }

  /**
   * 菜单递归
   * @param data
   * @param merIds
   */
  recursionData(data: any, merIds: any): any {
    for (let node of data.children) {
      merIds.push(node.key)
      if (node.children != null) {
        this.recursionData(node,merIds);
      }
    }
  }

  /**
   * 提交分配角色菜单权限
   */
  submitAssignRoleMenu() {
    let menuIds: any = [];
    // 已勾选的菜单
    const checkedNodeList = this.nzTreeComponent.getCheckedNodeList();
    for (let node of checkedNodeList) {
      menuIds.push(node.origin.key);
      if (node.origin.children != null) {
        menuIds.concat(this.recursionData(node.origin, menuIds))
      }
    };

    // 半选状态的菜单
    const halfCheckedNodeList = this.nzTreeComponent.getHalfCheckedNodeList();
    for (let node of halfCheckedNodeList) {
      menuIds.push(node.key);
    }

    const param= {
      roleId: this.currentAssignRoleId,
      menuIds: menuIds
    };
    this.menuService.assignMenu(param, (data: any) => {
      if (data['return_code'] == '000000') {
        this.message.create('success', '操作成功');
        this.closeAssignRoleMenu();
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 关闭分配角色菜单模态框
   */
  closeAssignRoleMenu() {
    this.menuTreeCheckedKeys = [];
    this.assignRoleMenuVisible = false;
  }
}
