import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { CommonNzModule } from '../../../../../common.nz.module';
import { SettingService } from '../../../../../services/setting.service';

export interface DocImportModalData {
  onImportSuccess: () => void; // Add this callback
  categories: Option[];
  levels: Option[];
  category: number | string;
  level: number | string;
}

@Component({
  selector: 'doc-import',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './doc-import.component.html',
  styleUrl: './doc-import.component.less',
})
export class DocImportComponent {
  readonly nzModalData: DocImportModalData = inject(NZ_MODAL_DATA);
  importing: boolean = false;

  constructor(
    private message: NzMessageService,
    private setting: SettingService,
    private fb: NonNullableFormBuilder
  ) {}
  validateForm = this.fb.group({
    category: this.fb.control<number | string | undefined>(undefined, {
      validators: [Validators.required],
    }),
    level: this.fb.control<number | string | undefined>(undefined, {
      validators: [Validators.required],
    }),
  });
  selectFields: {
    label: string;
    key: string;
    minWidth?: string;
    options: Option[];
  }[] = [];

  ngOnInit() {
    this.validateForm.patchValue({
      category: this.nzModalData.category,
      level: this.nzModalData.level,
    });
  }
  handleImportStatusChange(event: NzUploadChangeParam) {
    if (event.type === 'start') {
      this.importing = true;
    }
    if (event.type === 'success') {
      if (event.file.response?.code !== 0) {
        this.message.error('导入失败: ' + event.file.response?.message);
        this.importing = false;
        return;
      }
      this.message.success('导入成功');
      this.importing = false;

      // Call the callback function to refresh the list in the parent component
      if (this.nzModalData.onImportSuccess) {
        this.nzModalData.onImportSuccess();
      }
    } else if (event.type === 'error') {
      if (event.file.error.error?.message) {
        this.message.error('导入失败: ' + event.file.error.error.message);
      } else {
        this.message.error('导入失败');
      }
      this.importing = false;
    }
  }
  handleReset() {
    this.validateForm.reset();
  }
  get categories() {
    return this.nzModalData.categories;
  }
  get levels() {
    return this.nzModalData.levels;
  }
  get company() {
    return this.setting.userCompany;
  }
}
