import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { ContentService } from './content.service';
import { FormBuilder, Form, FormGroup, Validators, FormArray } from '@angular/forms';
import { firstValueFrom } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';


@Component({
  selector: 'content-lang-config',
  template: `

<form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()" novalidate class="form-horizontal ">
  
  <div>
    <div *ngIf="debug">
      <p> {{configId}} </p>
      <p> {{form.value|json}} </p>
      <p> dirty?: {{form.dirty}} </p>
    </div>

    <cg-check-select *ngIf="items" formControlName="langs" [items]="items" bindLabel="label" bindValue="code">
    </cg-check-select>
  </div>
  <div class="d-flex flex-row-reverse" >
    <button nz-button nzType="primary" type="submit" [disabled]="isLoading" i18n>保存</button>
  </div>
</form>
  `,
  styles: [`

  `]
})
export class LangConfigComponent implements OnInit {


  @Output() onSuccess = new EventEmitter<any>();
  @Output() onError = new EventEmitter<any>();
  @Input() debug: boolean = false;

  @Input() configId: any;

  form: FormGroup;
  isLoading = false;

  items: any;

  constructor(
    private contentService: ContentService,
    private fb: FormBuilder,
    private messsage: NzMessageService,
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      langs: [[], [Validators.required]]
    });
    firstValueFrom(this.contentService.langConfigAll()).then((data: any) => {
      this.items = data;
    })
    firstValueFrom(this.contentService.langConfig(this.configId)).then(data => {
      this.form.reset(data);
    })
  }

  onSubmit() {
    if (this.form.invalid) {
      return;
    }
    this.isLoading = true;
    this.contentService.langConfigUpdate(this.configId, this.form.value).toPromise()
      .then(res => {
        this.onSuccess.emit(this.form.value);
        this.messsage.success($localize`操作成功`);
      })
      .catch(err => {
        this.messsage.error(err.error?.message || err.message);
      }).then(() => {
        this.isLoading = false;
      })
  }

  get f() {
    return this.form.controls;
  }

}
