import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { STChange, STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS, SharedModule } from '@shared';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core/tree';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTreeComponent } from 'ng-zorro-antd/tree';
import { AppValidators } from 'src/app/core/utils/app-validators';
import { BaseService } from 'src/app/core/utils/base.service';

import { SysPermsSettingComponent } from './perms-setting/perms-setting.component';

@Component({
  selector: 'app-sys-role-manage',
  standalone: true,
  imports: [SharedModule, ...SHARED_IMPORTS],
  templateUrl: './role-manage.component.html'
})
export class SysRoleManageComponent implements OnInit {
  private readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  private readonly fb = inject(FormBuilder);
  private readonly baseService = inject(BaseService);
  private readonly modalService = inject(NzModalService);

  newAcl = {
    ability: ['AbpIdentity.Roles.Create']
  };

  url = '/api/identity/roles';
  drawerVisible = false;
  roleList: any;
  currentRole: any; //当前所选role
  defaultCheckedKeys: any[] = [];
  selectedKeys: any;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  filter = '';
  title = '';
  form: FormGroup = this.fb.group({
    id: [],
    name: ['', AppValidators.required('E0001', '角色名称')],
    isDefault: [false],
    isPublic: [true]
  });
  searchSchema: SFSchema = {
    properties: {
      filter: {
        type: 'string',
        title: '关键字过滤'
      }
    }
  };
  @ViewChild('sf') private readonly sf!: SFComponent;
  @ViewChild('tree') private readonly tree!: NzTreeComponent;
  @ViewChild('st') private readonly st!: STComponent;

  columns: STColumn[] = [
    {
      title: '操作',
      buttons: [
        { text: '权限', acl: { ability: ['SettingSys.RolePermission'] }, click: (item: any) => this.permissionEdit(item.name) },
        {
          text: '编辑',
          acl: { ability: ['AbpIdentity.Roles.Update'] },
          iif: (item: any) => !item.isStatic,
          click: (item: any) => this.edit(item.id)
        },
        {
          text: '删除',
          acl: { ability: ['AbpIdentity.Roles.Delete'] },
          iif: (item: any) => !item.isStatic,
          click: (item: any) => this.delete(item.id)
        }
      ]
    },
    { title: '角色名称', index: 'name' },
    { title: '默认', index: 'isDefault', type: 'yn' },
    { title: '公共', index: 'isPublic', type: 'yn' }
  ];

  ngOnInit(): void {
    this.getRoleList(this.pageIndex, this.pageSize, this.filter);
  }

  /**
   * ocean 2023-7-12
   */
  roleChange(ret: STChange) {
    if (ret.type == 'radio') {
      this.currentRole = ret.radio;
    }
  }

  /**
   * 2023-11-14
   * ocean
   */
  getRoleList(pi: number, ps: number, filter: string) {
    const req = {
      skipCount: (pi - 1) * ps,
      maxResultCount: ps,
      filter: filter ?? ''
    };

    this.http.get(this.url, req).subscribe(res => {
      this.roleList = res.items;
      this.total = res.totalCount;
    });
  }

  /**
   * ocean 2023-11-14
   * 翻页
   */
  stPageChange(e: { type: string; pi: number }) {
    if (e.type == 'pi') {
      this.pageIndex = e.pi;
      this.getRoleList(this.pageIndex, this.pageSize, this.filter);
    }
  }

  reset() {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.getRoleList(this.pageIndex, this.pageSize, this.filter);
  }

  search() {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.filter = this.sf.value['filter'];
    this.getRoleList(this.pageIndex, this.pageSize, this.filter);
  }

  /**
   * ocean
   * 新增
   */
  add(): void {
    this.title = '新增角色';
    this.drawerVisible = true;
  }

  /**
   * ocean 2023-8-27
   * 获取角色列表
   */
  refresh() {
    this.st.reload();
  }

  /**
   * ocean 2023-7-13
   * 保存角色对应权限
   */
  save() {
    var halfCheckedMenus: string[] = [];
    var checkedMenus: string[] = [];
    this.tree.getCheckedNodeList().forEach((r: { key: string }) => {
      checkedMenus.push(r.key);
    });
    this.tree.getHalfCheckedNodeList().forEach((r: { key: string }) => {
      halfCheckedMenus.push(r.key);
    });

    if (this.currentRole) {
      const req = {
        roleValue: this.currentRole.name,
        checkedMenus,
        halfCheckedMenus
      };

      this.http.post(`/api/main/menu/role-as-menu`, req).subscribe(res => {
        console.log(res);

        this.baseService.showMessage({ messageId: 'C0003' });
      });
    }
  }

  /**
   * ocean 2023-3-3
   * 修改
   */
  edit(id: any) {
    this.title = '编辑角色';
    this.http.get(`${this.url}/${id}`).subscribe(res => {
      this.form.patchValue(Object.assign(res, {}));
      this.drawerVisible = true;
      this.st.reload();
    });
  }

  /**
   * ocean 2023-3-3
   * 删除角色
   */
  delete(id: any) {
    this.baseService.showConfirm({
      message: this.baseService.getMessage('C0001'),
      okCallback: () => {
        this.http.delete(`${this.url}/${id}`).subscribe(res => {
          this.st.reload();
        });
      }
    });
  }

  /**
   * ocean 2023-3-4
   * 编辑权限
   */
  permissionEdit(role: any) {
    const modalRef = this.modalService.create({
      nzTitle: '权限编辑',
      nzContent: SysPermsSettingComponent,
      nzWidth: 480,
      nzData: role,
      nzOnOk: e => {
        const req = {
          permissions: e.getPermissions()
        };
        console.log(req);
        this.http.put(`/api/permission-management/permissions?providerName=R&providerKey=${role}`, req).subscribe(res => {
          //console.log(res);
        });
      }
    });
  }

  submit() {
    if (this.baseService.hasError(this.form)) {
      return;
    }

    const requestModel = this.form.getRawValue();

    if (!requestModel.id) {
      this.http.post(this.url, requestModel).subscribe(res => {
        this.form.reset({
          isDefault: false,
          isPublic: true
        });
        this.drawerVisible = false;
        this.st.reload();
      });
    } else {
      this.http.put(`${this.url}/${requestModel.id}`, requestModel).subscribe(res => {
        this.form.reset({
          isDefault: false,
          isPublic: true
        });
        this.drawerVisible = false;
        this.st.reload();
      });
    }
  }

  close(): void {
    this.drawerVisible = false;
  }

  nzEvent(event: NzFormatEmitEvent): void {
    this.selectedKeys = event.keys;
  }
}
