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

const addTitle = '新建租户';
const editTitle = '编辑租户';

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

  url = `/api/multi-tenancy/tenants`;
  drawerVisible = false;
  tenantList: any;
  currentRole: any; //当前所选role
  defaultCheckedKeys: any[] = [];
  selectedKeys: any;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  filter = '';
  title = '';

  searchSchema: SFSchema = {
    properties: {
      filter: {
        type: 'string',
        title: '关键字过滤'
      }
    }
  };
  @ViewChild('sf') private readonly sf!: SFComponent;
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '操作',
      buttons: [
        { text: '编辑', click: (item: any) => this.edit(item.id) },
        { text: '删除', pop: true, click: (item: any) => this.delete(item.id) }
      ]
    },
    { title: '租户名称', index: 'name' },
    { title: '租户ID', index: 'id' }
  ];

  form: FormGroup = this.fb.group({
    id: [],
    name: ['', AppValidators.required('E0001', '租户名称')],
    adminEmailAddress: [
      ,
      AppValidators.other((control: AbstractControl) => {
        if (this.isNew()) {
          return AppValidators.required('E0001', '管理员邮箱')(control);
        }
        return null;
      })
    ],
    adminPassword: [
      ,
      AppValidators.other((control: AbstractControl) => {
        if (this.isNew()) {
          return AppValidators.required('E0001', '管理员密码')(control);
        }
        return null;
      })
    ]
  });

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

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

  /**
   * 2023-11-14
   * ocean
   */
  getTenantList(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.tenantList = res.items;
      this.total = res.totalCount;
    });
  }

  /**
   * ocean
   * 新增租户
   */
  add(): void {
    this.title = addTitle;
    this.drawerVisible = true;
  }

  /**
   * ocean 2023-7-13
   * 保存角色对应权限
   */
  save() {
    if (this.baseService.hasError(this.form)) {
      return;
    }

    const formValue = this.form.getRawValue();
    const id = this.form.getRawValue().id;

    if (!id) {
      // 新增
      this.http.post(this.url, formValue).subscribe(async res => {
        this.drawerVisible = false;
        this.form.reset();
        this.baseService.showMessage({ messageId: 'C0003' });
        this.st.reload();
      });
    } else {
      // 修改
      this.http.put(`${this.url}/${id}`, formValue).subscribe(async res => {
        this.drawerVisible = false;
        this.form.reset();
        this.baseService.showMessage({ messageId: 'C0003' });
        this.st.reload();
      });
    }
  }

  /**
   * ocean 2023-3-3
   * 修改租户
   */
  edit(id: any) {
    this.title = editTitle;
    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.http.delete(`${this.url}/${id}`).subscribe(res => {
      this.st.reload();
    });
  }

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

  isNew() {
    return this.title == addTitle;
  }

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