import { Component, ViewContainerRef } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from './../../../../common.nz.module';
import { ApiService } from './../../../../services/api.service';
import { BasicDataService } from './../../../../services/basic.service';
import { TeamFormComponent, TeamFormModalData } from './form/form.component';

@Component({
  selector: 'page-shift-group',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './shift-group.component.html',
  styleUrl: './shift-group.component.less',
})
export class ShiftGroupComponent {
  departments: BasicData.Department[] = [];
  selectedDepartment?: number;

  teams: BasicData.Team[] = [];
  selectedTeam?: number;
  constructor(
    private basic: BasicDataService,
    private modal: NzModalService,
    private api: ApiService,
    private viewContainerRef: ViewContainerRef,
    private message: NzMessageService
  ) {
    basic.$fetched.subscribe(data => {
      this.init();
    });
  }
  ngOnInit() {
    this.init();
  }
  init() {
    // this.departments = this.basic.departments.filter(d => !d.name.includes('所有部门'));
    this.departments = this.basic.departments.slice();
    if (!this.selectedDepartment) {
      if (!this.basic.teams.length) {
        this.selectedDepartment = this.basic.teams[0]?.department;
      } else {
        this.selectedDepartment = this.departments[0]?.id;
      }
    }
    this.teams = this.basic.teams.filter(t => t.department === this.selectedDepartment);
    if (!this.selectedTeamDto) {
      this.selectedTeam = this.teams[0]?.id;
    }
  }

  changeDepartment(departmentId: number) {
    this.selectedDepartment = departmentId;
    this.teams = this.basic.teams.filter(t => t.department === this.selectedDepartment);
    this.selectedTeam = this.teams[0]?.id;
  }
  changeTeam(teamId: number) {
    this.selectedTeam = teamId;
  }

  createModal(type: 'add' | 'edit', data?: BasicData.Team): void {
    const title = type === 'add' ? `新增班组` : `编辑班组 - ` + data?.name;
    this.modal.create<TeamFormComponent, TeamFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: title,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: TeamFormComponent,
      nzWidth: 500,
      nzMaskClosable: false,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        type,
        params: {
          ...data,
          department: data?.department || this.selectedDepartment,
        },
        departments: this.departments,
      },
      nzOnOk: async instance => {
        const res = await instance.submit();
        if (type === 'add') {
          delete res?.id;
          await this.onAdd({
            name: res?.name!,
            department: res?.department!,
          }).finally(() => {
            instance.loading = false;
          });
          this.basic.fetchPositions().then(() => {
            this.message.success('新增成功');
            instance.resetName();
            this.onSearch();
          });
          return Promise.reject();
        } else {
          await this.onEdit({
            ...data!,
            name: res?.name!,
            department: res?.department!,
          }).finally(() => {
            instance.loading = false;
          });
          this.basic.fetchPositions().then(() => {
            this.message.success('修改成功');
            instance.resetName();
            this.onSearch();
          });
        }
      },
    });
  }
  handleAddTeam() {
    this.createModal('add');
  }
  handleEditTeam() {
    this.createModal(
      'edit',
      this.basic.teams.find(t => t.id === this.selectedTeam)
    );
  }
  handleDeleteTeam() {
    if (!this.selectedTeamDto) return;
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除场所类型',
      nzContent: `确定要删除【${this.selectedTeamDto.name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.api.basic.removeTeam(this.selectedTeam!);
        this.message.success('删除成功');
        this.onSearch();
      },
    });
  }
  async onAdd(data: Partial<BasicData.Team>) {
    await this.api.basic.addTeam(data);
  }

  async onEdit(data: BasicData.Team) {
    await this.api.basic.updateTeam(data);
  }
  onSearch() {
    this.basic.fetchTeams().then(() => {
      this.init();
    });
  }
  get selectedTeamDto() {
    return this.basic.teams.find(t => t.id === this.selectedTeam);
  }
  get selectedTeamName() {
    return this.selectedTeamDto?.name;
  }
}
