import { Component } from '@angular/core';
import { CommonNzModule } from '../../../../common.nz.module';
import { Column, SimpleFormPageComponent } from '../../../../shared/simple-form-page/simple-form-page.component';
import { EquipmentFormComponent, EquipmentFormModalData } from './form/form.component';

@Component({
  selector: 'app-equipment',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './equipment.component.html',
  styleUrl: './equipment.component.less',
})
export class EquipmentComponent extends SimpleFormPageComponent<BasicData.Equipment> {
  filterList: BasicData.Equipment[] = [];
  override keyWord: string = '设备';
  override key: string = 'name';
  override columns: Column[] = [];
  override inputFields = [{ label: '设备名称', key: 'equipment', initValue: '' }];
  override validateForm = this.fb.group({
    name: this.fb.control<string | undefined>(undefined),
    type: this.fb.control<number | undefined>(undefined),
    category: this.fb.control<number | undefined>(undefined),
    // line: this.fb.control<string | undefined>(undefined),
  });
  override ngOnInit(): void {
    this.knowledgeService.init();
    super.ngOnInit();
    this.fetchList();
  }
  override async fetchList() {
    const list = await this.api.basic.getEquipmentList();
    this.list = list;
    this.resetFilterList();
  }
  override async onEdit(data: Partial<BasicData.Equipment>) {
    return this.api.basic.updateEquipment(data).then(() => {
      this.message.success('编辑成功');
    });
  }
  override async onAdd(data: Partial<BasicData.Equipment>) {
    return this.api.basic.addEquipment(data).then(() => {
      this.message.success('新增成功');
    });
  }
  override async onDelete(data: BasicData.Equipment): Promise<void> {
    return this.api.basic.deletedEquipment(data.id).then(() => {
      this.message.success('删除成功');
    });
  }
  override createModal(type: 'add' | 'edit', data?: BasicData.Equipment): void {
    const name = data ? this.getValue(data, this.key) : '';
    this.modal.create<EquipmentFormComponent, EquipmentFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: type === 'add' ? '新增' + this.keyWord : '编辑' + this.keyWord + ' - ' + name,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: EquipmentFormComponent,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        keyWord: this.keyWord,
        type,
        params: {
          name,
          id: data ? this.getValue(data, 'id') : undefined,
          type: data ? this.getValue(data, 'type') : undefined,
          category: data ? this.getValue(data, 'category') : undefined,
        },
      },
      nzOnOk: async instance => {
        const res = await instance.submit();
        if (type === 'add') {
          delete res?.id;
          await this.onAdd(res!).finally(() => {
            instance.loading = false;
          });
          this.fetchList();
          instance.resetName();
          return Promise.reject();
        } else {
          await this.onEdit({
            ...data!,
            ...res!,
          }).finally(() => {
            instance.loading = false;
          });
          this.onSearch();
        }
      },
    });
  }
  searchFormChange(key: string) {
    if (key === 'type') {
      this.validateForm.get('category')?.reset();
    }
    this.resetFilterList();
  }
  resetFilterList() {
    const { name, type, category } = this.validateForm.value;
    this.filterList = this.list.filter(item => {
      let isMatch = true;
      if (name) {
        isMatch = item.name.includes(name);
      }
      if (isMatch && type) {
        isMatch = item.type === type;
      }
      if (isMatch && category) {
        isMatch = item.category === category;
      }
      return isMatch;
    });
  }
  getTypeName(row: BasicData.Equipment) {
    return this.knowledgeService.getTypeName(row.type);
  }
  getCategoryName(row: BasicData.Equipment) {
    return this.knowledgeService.getCategoryName(row.category, row.type);
  }
  get types() {
    return this.knowledgeService.types();
  }

  get categories() {
    const type = this.validateForm.get('type')?.value;
    if (!type) return [];
    return this.knowledgeService.getCategoryOptionsByType(type);
  }
}
