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';
import { NzNotificationService } from 'ng-zorro-antd/notification';

const editTitle = '编辑用户';
const addTitle = '新增用户';

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

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

  editVisible = false;
  title = '';
  url = `/api/identity/users`;
  userList: any; //用户列表
  searchSchema: SFSchema = {
    properties: {
      filter: {
        type: 'string',
        title: '关键字过滤'
      }
    }
  };

  @ViewChild('sf') private readonly sf!: SFComponent;
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '操作',
      buttons: [
        { text: '编辑', acl: { ability: ['AbpIdentity.Users.Update'] }, click: (item: any) => this.edit(item) },
        { text: '删除', acl: { ability: ['AbpIdentity.Users.Delete'] }, pop: true, click: (item: any) => this.delete(item) }
      ]
    },
    { title: '登录账户', index: 'userName' },
    { title: '姓名', index: 'name' },
    { title: '邮箱', index: 'email' },
    { title: '手机号', index: 'phoneNumber' },
    { title: '创建时间', index: 'creationTime', type: 'date', dateFormat: 'yyyy-MM-dd', width: 100 },
    // { title: 'lockoutEnabled', index: 'lockoutEnabled', type: 'yn' },
    {
      title: '有效性',
      index: 'isActive',
      type: 'badge',
      badge: {
        true: { text: '有效', color: 'success' },
        false: { text: '无效', color: 'default' }
      }
    }
  ];

  form: FormGroup = this.fb.group({
    id: [],
    userName: [, AppValidators.required('E0001', '登录账户')],
    password: [
      ,
      AppValidators.other((control: AbstractControl) => {
        if (this.isNew()) {
          return AppValidators.required('E0001', '登录账户')(control);
        }
        return null;
      })
    ],
    name: [, AppValidators.required('E0001', '姓名')],
    surname: [],
    email: [, AppValidators.email('E0003', '邮箱')],
    phoneNumber: [],
    lockoutEnabled: [true],
    isActive: [true],
    roleNames: []
  });

  loading = false;
  pageIndex = 1;
  pageSize = 10;
  filter = '';
  total = 0;
  users: any; //用户列表
  roleOfOption: any; //角色列表
  roleOfSelectedValue: string[] = [];

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

  getRoles() {
    this.http.get('/api/identity/users/assignable-roles').subscribe(res => {
      this.roleOfOption = res.items;
    });
  }

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

  reset() {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.getUserList(this.pageIndex, this.pageSize, '');
  }

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

  /**
   * ocean 2023-7-19
   * 获取用户列表
   */
  getUserList(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.userList = res.items;
      this.total = res.totalCount;
    });
  }

  /**
   * ocean 2023-8-27
   * 添加用户
   */
  add() {
    this.title = addTitle;
    this.form.reset({
      lockoutEnabled: true,
      isActive: true
    });
    this.editVisible = true;
  }

  edit(e: any) {
    this.http.get(`${this.url}/${e.id}/roles`).subscribe(res => {
      this.roleOfSelectedValue = res.items.map((r: { name: any }) => {
        return r.name;
      });

      e.roleNames = this.roleOfSelectedValue;
      this.form.reset({});
      this.form.patchValue(e);
      this.title = editTitle;
      this.editVisible = true;
    });
  }

  /**
   * ocean 2023-11-14
   * 删除
   */
  delete(e: any) {
    this.http.delete(`${this.url}/${e.id}`).subscribe(res => {
      this.reset();
    });
  }

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

    const requestModel = this.form.getRawValue();

    if (this.title == addTitle) {
      this.http.post(`${this.url}`, requestModel).subscribe(res => {
        this.form.reset({
          lockoutEnabled: true,
          isActive: true
        });
        this.editVisible = false;
        this.reset();
      });
    } else {
      this.http.put(`${this.url}/${requestModel.id}`, requestModel).subscribe(res => {
        this.form.reset({
          lockoutEnabled: true,
          isActive: true
        });
        this.editVisible = false;
        this.reset();
      });
    }
  }

  isNotSelected(value: string): boolean {
    return this.roleOfSelectedValue.indexOf(value) === -1;
  }

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

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