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

@Component({
  selector: 'app-position',
  standalone: true,
  imports: [SimpleFormPageComponent, CommonNzModule],
  templateUrl: './position.component.html',
  styleUrl: './position.component.less',
})
export class PositionComponent extends SimpleFormPageComponent<BasicData.Position> {
  filterList: BasicData.Position[] = [];
  override keyWord: string = '场所';
  override key: string = 'name';
  override columns: Column[] = [];
  override inputFields = [{ label: '场所', key: 'name', 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.getPositionList();
    this.list = list;
    this.resetFilterList();
  }
  override async onEdit(data: Partial<BasicData.Position>) {
    return this.api.basic.updatePosition(data).then(() => {
      this.message.success('编辑成功');
    });
  }
  override async onAdd(data: Partial<BasicData.Position>) {
    return this.api.basic.addPosition(data).then(() => {
      this.message.success('新增成功');
    });
  }
  override async onDelete(data: BasicData.Position): Promise<void> {
    return this.api.basic.deletedPosition(data.id).then(() => {
      this.message.success('删除成功');
    });
  }
  override createModal(type: 'add' | 'edit', data?: BasicData.Position): void {
    const name = data ? this.getValue(data, this.key) : '';
    this.modal.create<PositionFormComponent, PositionFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: type === 'add' ? '新增' + this.keyWord : '编辑' + this.keyWord + ' - ' + name,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: PositionFormComponent,
      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.Position) {
    return this.knowledgeService.getTypeName(row.type);
  }
  getCategoryName(row: BasicData.Position) {
    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);
  }
}
