import { Component, inject } from '@angular/core';
import { NZ_MODAL_DATA, NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from '../../../../../common.nz.module';
import { ApiService } from '../../../../../services/api.service';
import { BasicDataService } from '../../../../../services/basic.service';

export interface JobEditData {
  departmentId: number;
}

const getRandomId = (): number => Number(`${Math.random().toString().slice(-10, -1)}`);

@Component({
  selector: 'job-edit',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './job-edit.component.html',
  styleUrl: './job-edit.component.less',
})
export class JobEditComponent {
  readonly nzModalData: JobEditData = inject(NZ_MODAL_DATA);
  editJob?: BasicData.Job;
  editJobValue = '';
  loading = false;
  suspendId?: number;

  constructor(
    private basic: BasicDataService,
    private modal: NzModalService,
    private api: ApiService
  ) {}
  ngOnInit() {
    console.time('fetchJobs');
    this.fetchJobs();
  }
  onJobAdd() {
    this.removeSuspense();
    const id = getRandomId();
    this.suspendId = id;
    this.editJob = {
      id,
      name: '',
      department: this.departmentId,
    };
    this.editJobValue = '';
    if (!this.copyData) {
      this.copyData = [this.editJob];
    } else {
      this.copyData.push(this.editJob);
    }
  }
  onJobEdit(data: BasicData.Job) {
    this.removeSuspense();
    this.editJob = data;
    this.editJobValue = data.name;
  }
  onJobDelete(data: BasicData.Job) {
    this.modal.confirm({
      nzTitle: `确定删除【${data.name}】吗？`,
      nzClassName: 'precaution-modal',
      nzOnOk: async () => {
        await this.api.basic.removeJob(data.id).finally(() => {});
        this.editJob = undefined;
        this.editJobValue = '';
        this.fetchJobs();
      },
    });
  }
  async onJobEditConfirm(data: BasicData.Job) {
    if (this.editJob) {
      if (this.editJob.id === this.suspendId) {
        await this.createJob({
          ...data,
          name: this.editJobValue,
        });
        this.editJob.name = this.editJobValue;
        this.fetchJobs();
        this.editJob = undefined;
      } else {
        await this.updateJob({
          ...data,
          name: this.editJobValue,
        });
        this.editJob.name = this.editJobValue;
        this.fetchJobs();
        this.editJob = undefined;
      }
    }
  }
  onJobEditCancel(data: BasicData.Job) {
    this.removeSuspense();
    this.editJob = undefined;
  }
  removeSuspense() {
    if (this.suspendId) {
      if (this.editJob?.id === this.suspendId) {
        this.editJob = undefined;
        this.copyData = this.copyData.filter(t => t.id !== this.suspendId);
      }
    }
    this.suspendId = undefined;
  }
  async createJob(data: BasicData.Job) {
    this.loading = true;
    return await this.api.basic.addJob(data).finally(() => {
      this.loading = false;
    });
  }
  async updateJob(data: BasicData.Job) {
    this.loading = true;
    return await this.api.basic.updateJob(data).finally(() => {
      this.loading = false;
    });
  }
  get allJobs() {
    return this.basic.jobs || [];
  }
  get departmentId() {
    return this.nzModalData.departmentId;
  }

  copyData: BasicData.Job[] = [];
  getJobs() {
    const list = this.allJobs.filter(j => j.department === this.departmentId);
    this.copyData = list;
  }
  ngAfterViewInit() {
    console.timeEnd('fetchJobs');
  }
  fetchJobs() {
    this.basic.fetchJobs().then(() => {
      this.getJobs();
    });
  }
}
