import { Component, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { NonNullableFormBuilder } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, 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 { JobEditComponent, JobEditData } from './job-edit/job-edit.component';

interface DepWithJob extends BasicData.Department {
  jobs: BasicData.Job[];
}

@Component({
  selector: 'app-dj',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './dj.component.html',
  styleUrl: './dj.component.less',
})
export class DjComponent {
  @ViewChild('formTpl') formTpl!: TemplateRef<void>;
  modalInstance?: NzModalRef;
  jobModalInstance?: NzModalRef<JobEditComponent>;
  validateForm = this.fb.group({
    name: this.fb.control<string | undefined>(undefined),
  });
  get list(): DepWithJob[] {
    return this.basic.departments.map(d => {
      return {
        ...d,
        jobs: this.basic.jobs.filter(j => j.department === d.id),
      };
    });
  }
  constructor(
    private viewContainerRef: ViewContainerRef,
    private fb: NonNullableFormBuilder,
    private api: ApiService,
    private message: NzMessageService,
    private basic: BasicDataService,
    private modal: NzModalService
  ) {}
  handleDelete(data: BasicData.Department) {
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除部门',
      nzContent: `确定要删除【${data.name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.onDelete(data);
        this.fetchList();
      },
    });
  }
  handleAdd() {
    this.createModal('add');
  }
  handleEdit(data: BasicData.Department) {
    this.createModal('edit', data);
  }
  handleJobEdit(data: BasicData.Department) {
    this.createJobModal(data);
  }
  createModal(type: 'add' | 'edit', data?: BasicData.Department): void {
    this.validateForm.patchValue({
      name: data?.name,
    });
    this.modalInstance = this.modal.create<TemplateRef<void>, any>({
      nzClassName: 'precaution-modal',
      nzTitle: type === 'add' ? '新增部门' : '编辑部门 - ' + data?.name,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: this.formTpl,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        type,
        name: data?.name,
        id: data?.id,
      },
      nzOnOk: async () => {
        await this.validate();
        return type === 'add' ? this.onAdd() : this.onEdit(data!);
      },
    });
  }
  createJobModal(data: BasicData.Department) {
    this.jobModalInstance = this.modal.create<JobEditComponent, JobEditData>({
      nzClassName: 'precaution-modal',
      nzTitle: data.name + ' - 编辑岗位',
      nzContent: JobEditComponent,
      nzWidth: 750,
      nzViewContainerRef: this.viewContainerRef,
      nzOkText: '关闭',
      nzMaskClosable: false,
      nzData: {
        departmentId: data.id,
      },
      nzCancelText: null,
      nzOnOk: ins => {
        this.jobModalInstance?.close();
        this.fetchList();
      },
    });
  }
  async validate() {
    return new Promise<boolean>((resolve, reject) => {
      if (!this.validateForm.valid) {
        Object.values(this.validateForm.controls).forEach(control => {
          if (control.invalid) {
            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });
          }
        });
        reject(false);
      }
      resolve(true);
    });
  }
  handleOk() {}
  async fetchList() {
    return this.basic.fetchDepartments();
  }
  onSearch() {
    this.fetchList();
  }
  async onEdit(data: BasicData.Department) {
    this.modalInstance?.updateConfig({ nzOkLoading: true });
    await this.api.basic
      .updateDepartment({ id: data.id, name: this.validateForm.value.name })
      .finally(() => {
        this.modalInstance?.updateConfig({ nzOkLoading: false });
      })
      .then(() => {
        this.fetchList();
      });
  }
  async onAdd() {
    this.modalInstance?.updateConfig({ nzOkLoading: true });
    await this.api.basic
      .addDepartment({ name: this.validateForm.value.name })
      .finally(() => {
        this.modalInstance?.updateConfig({ nzOkLoading: false });
      })
      .then(() => {
        this.fetchList();
      });
  }
  async onDelete(data: BasicData.Department) {
    return this.api.basic.removeDepartment(data.id);
  }
}
