import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { CommonNzModule } from '../../../../../common.nz.module';
import { BasicDataService } from '../../../../../services/basic.service';
import { KnowledgeService } from '../../../../../services/knowledge.service';

export interface PositionFormModalData {
  keyWord: string;
  type: 'add' | 'edit';
  params: {
    id?: number;
    name?: string;
    type?: number;
    category?: number;
  };
}

@Component({
  selector: 'position-form',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './form.component.html',
  styleUrl: './form.component.less',
})
export class PositionFormComponent {
  readonly nzModalData: PositionFormModalData = inject(NZ_MODAL_DATA);
  validateForm = this.fb.group({
    name: this.fb.control<string>('', [Validators.required]),
    id: this.fb.control<number | undefined>(undefined),
    type: this.fb.control<number | undefined>(undefined, [Validators.required]),
    category: this.fb.control<number | undefined>(undefined, [Validators.required]),
  });
  loading = false;
  constructor(
    private fb: NonNullableFormBuilder,
    private basic: BasicDataService,
    private knowledgeService: KnowledgeService
  ) {}
  ngOnInit() {
    this.init();
    this.basic.fetchBasicData();
  }
  async init() {
    if (this.nzModalData.type === 'edit') {
      const { name, id, type, category } = this.nzModalData.params;
      this.validateForm.patchValue({
        name,
        id,
        type,
        category,
        // line,
      });
    }
  }
  searchFormChange(key: string) {
    if (key === 'type') {
      this.validateForm.get('category')?.patchValue(undefined);
    }
  }
  resetName() {
    const nameControl = this.validateForm.get('name');
    if (nameControl) {
      nameControl.setValue('');
      nameControl.markAsUntouched();
      nameControl.markAsPending();
    }
  }
  async submit() {
    if (this.loading) return;
    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return Promise.reject();
    }
    this.loading = true;
    const values = this.validateForm.value;
    return Promise.resolve({
      name: values.name!,
      id: values.id,
      type: values.type!,
      category: values.category!,
      // line: values.line,
    });
  }
  get types() {
    return this.knowledgeService.types();
  }

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