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';

export interface SimpleFormModalData {
  keyWord: string;
  type: 'add' | 'edit';
  id?: number;
  name?: string;
  seq?: number;
}

@Component({
  selector: 'simple-form',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './form.component.html',
  styleUrl: './form.component.less',
})
export class FormComponent {
  readonly nzModalData: SimpleFormModalData = inject(NZ_MODAL_DATA);
  validateForm = this.fb.group({
    value: this.fb.control<string>('', [Validators.required]),
    seq: this.fb.control<number>(0, []),
    id: this.fb.control<number>(0),
  });
  loading = false;
  constructor(private fb: NonNullableFormBuilder) {}
  ngOnInit() {
    this.init();
  }
  async init() {
    if (this.nzModalData.type === 'edit') {
      this.validateForm.patchValue({
        value: this.nzModalData?.name,
        seq: this.nzModalData?.seq,
        id: this.nzModalData?.id,
      });
    }
  }
  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({
      value: values.value!,
      id: values.id!,
      seq: values.seq!,
    });
  }
}
