import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ApiService } from '../../../services/api.service';
import { BasicDataService } from '../../../services/basic.service';
import { SettingService } from '../../../services/setting.service';
import { UserActionComponent } from './user-action/user-action.component';
import { UserFormComponent, UserFormModalData } from './user-form/user-form.component';
import { UserImportComponent, UserImportModalData } from './user-import/user-import.component';
import { UserModifyRolesComponent, UserModifyRolesModalData } from './user-roles-form/user-roles-form.component';
import { UserTableComponent } from './user-table/user-table.component';
import { USER_JOB_GROUP_OPTIONS, USER_ROLE_OPTIONS, UserRole } from './user.const';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [UserTableComponent, UserActionComponent],
  templateUrl: './user.component.html',
  styleUrl: './user.component.less',
})
export class UserActualComponent {
  checkedIds = new Set<number>([]);
  pageConfig = {
    total: 0,
    page: 0,
    size: 10,
  };
  roleOptions: Option<string>[] = USER_ROLE_OPTIONS;
  statusOptions: Option<number>[] = [
    { label: '正常', value: 0 },
    { label: '删除', value: -1 },
  ];
  list: Auth.User[] = [];
  @ViewChild('action') action!: UserActionComponent;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private readonly api: ApiService,
    private readonly basicDataService: BasicDataService,
    private readonly modal: NzModalService,
    private readonly message: NzMessageService,
    private readonly setting: SettingService
  ) {}
  ngOnInit() {
    this.fetchList();
  }
  get companies() {
    return [];
  }
  get companyOptions() {
    return [];
  }
  getParams() {
    const values = this.action?.validateForm.value || {};
    const v = Object.entries(values).reduce(
      (acc, [key, value]) => {
        if (value !== undefined && value !== '' && value !== null) {
          acc[key] = value;
        }
        return acc;
      },
      {} as Record<string, any>
    );
    // if (!this.isSchoolAdmin) {
    //   v['company'] = this.setting.userCompany;
    // }
    return {
      size: this.pageConfig.size,
      page: this.pageConfig.page,
      ...v,
    };
  }
  selectIdsChange(ids: Set<number>) {
    this.checkedIds = new Set(ids);
  }
  get batchButtonVisible() {
    return this.checkedIds.size > 0;
  }
  async fetchList() {
    const list = await this.api.user.getUserList(this.getParams());
    this.list = list.items;
    this.pageConfig.total = list.total;
  }

  async onEdit(data: Partial<Auth.UserRequestParams>) {
    return this.api.user.updateUser(data);
  }
  async onAdd(data: Partial<Auth.UserRequestParams>) {
    return this.api.user.addUser(data);
  }
  async onModifyRoles(data: Partial<Auth.User>) {
    return this.api.user.updateUserRoles(data);
  }
  handleAdd() {
    this.createModal('add');
  }
  handleEdit(data: Auth.User) {
    this.createModal('edit', data);
  }
  handleModifyRoles(data: Auth.User) {
    this.createModifyRolesModal(data);
  }
  handleDelete(data: Auth.User) {
    this.modal.confirm({
      nzClassName: 'safety-modal',
      nzTitle: '删除用户',
      nzContent: `确定要删除【${data.id}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.api.user
          .deleteUser(data.id)
          .then(() => {
            this.message.success('删除成功');
            this.onReset();
          })
          .catch(err => {
            this.message.error(err.message);
            throw err;
          });
      },
    });
  }
  onBatchDelete() {
    this.modal.confirm({
      nzClassName: 'safety-modal',
      nzTitle: '批量删除用户',
      nzContent: `确定要批量删除所选用户吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.api.user
          .deleteAllUser(Array.from(this.checkedIds))
          .then(() => {
            this.message.success('删除成功');
            this.onReset();
          })
          .catch(err => {
            this.message.error(err.message);
            throw err;
          });
      },
    });
  }
  createModal(type: 'add' | 'edit', data?: Auth.User): void {
    const name = data?.id || '';
    this.modal.create<UserFormComponent, UserFormModalData>({
      nzClassName: 'safety-modal',
      nzTitle: type === 'add' ? '新增用户' : '编辑用户' + ' - ' + name,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: UserFormComponent,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        type,
        data: data,
        roleOptions: this.roleOptions.filter(r => r.value !== UserRole.ADMIN),
        departments: this.basicDataService.departments,
        lines: this.basicDataService.lines,
        jobs: this.basicDataService.jobs,
        jobGroups: USER_JOB_GROUP_OPTIONS,
        statusOptions: this.statusOptions.filter(s => s.value !== -1),
      },
      nzOnOk: async instance => {
        if (instance.loading) return Promise.reject();
        const res = await instance.submit();
        if (type === 'add') {
          return await this.onAdd(
            {
              ...res,
              company: this.setting.userCompany,
            }!
          )
            .then(() => {
              instance.loading = false;
              this.message.success('新增成功');
              this.onReset();
            })
            .catch(err => {
              instance.loading = false;
              this.message.error(err.message);
              throw err;
            });
        } else {
          return await this.onEdit({
            ...res,
          })
            .then(() => {
              instance.loading = false;
              this.message.success('编辑成功');
              this.onSearch();
            })
            .catch(err => {
              instance.loading = false;
              this.message.error(err.message);
              throw err;
            });
        }
      },
    });
  }
  createModifyRolesModal(data: Auth.User) {
    this.modal.create<UserModifyRolesComponent, UserModifyRolesModalData>({
      nzClassName: 'safety-modal',
      nzTitle: '修改角色' + ' - ' + data.name,
      nzOkText: '修改',
      nzContent: UserModifyRolesComponent,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        data,
        roleOptions: this.roleOptions.filter(r => r.value !== UserRole.ADMIN),
      },
      nzOnOk: async instance => {
        if (instance.loading) return Promise.reject();
        const res = await instance.submit();

        return await this.onModifyRoles({
          ...res,
        })
          .then(() => {
            instance.loading = false;
            this.message.success('编辑成功');
            this.onSearch();
          })
          .catch(err => {
            instance.loading = false;
            this.message.error(err.message);
            throw err;
          });
      },
    });
  }
  onSearch() {
    this.pageConfig.page = 0;
    this.fetchList();
  }
  onReset() {
    this.onSearch();
  }
  onImport() {
    this.modal.create<UserImportComponent, UserImportModalData>({
      nzClassName: 'safety-modal',
      nzTitle: '用户 - 导入',
      nzContent: UserImportComponent,
      nzWidth: 500,
      nzBodyStyle: { paddingBottom: '0px' },
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        onImportSuccess: () => {
          this.onSearch();
        },
      },
      nzFooter: null,
    });
  }
}

@Component({
  selector: 'user-fake',
  standalone: true,
  imports: [RouterOutlet],
  template: '<router-outlet></router-outlet>',
})
export class UserComponent {}
