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

@Component({
  selector: 'app-organization-modal',
  templateUrl: './organization-modal.component.html',
  styleUrls: ['./organization-modal.component.less']
})
export class OrganizationModalComponent implements OnInit {
  @ViewChild('sf', { static: false })
  sf!: SFComponent;

  roleInfoData: any = {};
  params: any;
  schema!: SFSchema;

  parentId: string = '';

  constructor(private modal: NzModalRef, public service: SystemService) {}

  ngOnInit(): void {
    this.initSF();
    if (this.params.id) {
      this.getRoleInfo();
    }
  }
  initSF() {
    this.schema = {
      properties: {
        roleName: {
          title: '组织名称',
          type: 'string',
          maxLength: 20,
          ui: {
            placeholder: '请输入组织名称'
          }
        },
        roleDescription: {
          title: '组织描述',
          type: 'string',
          maxLength: 50,
          ui: {
            autosize: { minRows: 3 },
            hidden: this.params.lookType === 'detail',
            placeholder: '请输入组织描述',
            widget: 'textarea'
          }
        }
      },
      required: ['roleName']
    };
  }

  getRoleInfo() {
    this.service.request(this.params.infoUrl, { id: this.params.id }).subscribe(res => {
      if (res) {
        this.roleInfoData = res;
      }
    });
  }
  close() {
    this.modal.destroy();
  }
  sure() {
    if (!this.sf?.valid) {
      this.service.msgSrv.warning('组织名称不能为空');
      return;
    }

    const params: any = {
      id: this.params.id,
      ...this.sf?.value,
      authority: this.roleInfoData.authority,
      authorityAssistId: this.roleInfoData.authorityAssistId,
      parentId: this.parentId
    };

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