import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { SystemService } from '../../../services/system.service';
import { SettingMenuComponent } from '../../role-management/menu/menu.component';

@Component({
  selector: 'app-api-auth-modal',
  templateUrl: './api-auth-modal.component.html',
  styleUrls: ['./api-auth-modal.component.less']
})
export class ApiAuthModalComponent implements OnInit {
  @ViewChild('menu', { static: false })
  menu!: SettingMenuComponent;
  roleInfoData: any = {};
  authorityAssistId: any[] = [];
  params: any;
  changeValue: boolean = false;
  authority: any[] = [];

  loadingInfo = false;
  constructor(private modal: NzModalRef, public service: SystemService) {}

  ngOnInit(): void {
    if (this.params.id) {
      this.getRoleInfo();
    }
  }
  getRoleInfo() {
    this.loadingInfo = true;
    this.service.request(this.params.infoUrl, { id: this.params.id }).subscribe(
      res => {
        if (res) {
          this.roleInfoData = res;
        }
        this.loadingInfo = false;
      },
      _ => (this.loadingInfo = false),
      () => (this.loadingInfo = false)
    );
  }
  getData(res: { authority: any[]; authorityAssistId: any[] }) {
    console.log('修改了');

    this.authority = res.authority;
    this.authorityAssistId = res.authorityAssistId;
  }
  close() {
    this.modal.destroy();
  }
  
  sure() {
    const auths = this.menu?.washTree();
    if (auths.authorityAssistId.length === 0) {
      this.service.msgSrv.warning('请选择权限!');
      return;
    }
    const params: any = {
      id: this.params.id,
      ...this.roleInfoData,
      authority: auths.authority,
      authorityAssistId: auths.authorityAssistId
    };

    if (this.params.id === 0) {
      delete params.id;
    }
    if (this.params?.type === 'freight') {
      Object.assign(params, { enterpriseId: 0, enterpriseProjectId: 0 });
    }
    this.loadingInfo = true;
    this.service.request(this.params.updateUrl, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('编辑成功');
        this.modal.close(true);}
        this.loadingInfo = false;
      },
      _ => (this.loadingInfo = false),
      () => (this.loadingInfo = false)
    );
  }
}
