import { Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn, STChange, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemService } from '../../services/system.service';
import { SettingRoleEditComponent } from './edit/edit.component';

@Component({
  selector: 'app-role-management',
  templateUrl: './role-management.component.html',
  styleUrls: ['./role-management.component.less']
})
export class RoleManagementComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;

  url = `/rule?_allow_anonymous=true`;

  searchSchema: SFSchema = {
    properties: {
      roleName: {
        type: 'string',
        title: '角色名称',
        ui: { placeholder: '请输入' }
      }
    }
  };

  columns: STColumn[] = [
    { title: '角色名称', index: 'roleName' },
    { title: '角色描述', index: 'roleDescription' },
    { title: '创建人手机号', index: 'telephone' },
    {
      title: '创建时间',
      index: 'createTime',
      type: 'date',
      sort: true
    },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          click: item => this.roleAction(item)
        },
        {
          text: '删除',
          click: item => this.deleteAction(item)
        }
      ]
    }
  ];

  selectedRows: any[] = [];

  constructor(public service: SystemService, private nzModalService: NzModalService) {}

  ngOnInit(): void {}

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, { ...this.sf.value });
    }
    if (requestOptions.body?.createTime) {
      Object.assign(requestOptions.body, { sort: 'createTime.' + requestOptions.body.createTime });
    }
    return requestOptions;
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'sort':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  roleAction(item?: any) {
    const modal = this.nzModalService.create({
      nzContent: SettingRoleEditComponent,
      nzWidth: 900,
      nzComponentParams: item ? { i: { ...item } } : { i: { id: 0 } },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {}
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }
}
