import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzI18nService } from 'ng-zorro-antd/i18n';
import { FormUtils } from 'src/app/lib/utils/form-utils';
import { ArtService } from './art.service';

@Component({
  selector: 'art-meta',
  template: `
    
    <form nz-form [formGroup]="form" (ngSubmit)="submit()" >

      <nz-form-item *ngIf="showMainCategory">
        <nz-form-control i18n-nzErrorTip nzErrorTip="请输入作品主分类">
          <nz-select formControlName="category" i18n-nzPlaceHolder nzPlaceHolder="主分类" nzMode="default" [nzOptions]="mainCategories" >
          </nz-select>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control i18n-nzErrorTip nzErrorTip="请输入作品名称">
          <input nz-input formControlName="name" i18n-placeholder placeholder="作品名称" />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control i18n-nzErrorTip nzErrorTip="请输入作品描述">
          <input nz-input formControlName="desc" i18n-placeholder placeholder="作品描述" />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control i18n-nzErrorTip nzErrorTip="请输入标签" >
          <nz-select formControlName="tags"  nzMode="tags" i18n-nzPlaceHolder nzPlaceHolder="标签" >
            <nz-option *ngFor="let item of tagOptions" 
            [nzLabel]="item.label || item.value" [nzValue]="item.value" 
            [nzHide]="isSelected(item)"
            >
            </nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>

      <ng-container *ngIf="art">
        <nz-form-item>
          <nz-form-control i18n-nzErrorTip nzErrorTip="请输入epg" >
            <nz-select formControlName="epgs"  nzMode="tags" nzPlaceHolder="EPG" >
              <nz-option *ngFor="let item of epgOptions" 
              [nzLabel]="item.label || item.value" [nzValue]="item.value" 
              [nzHide]="isSelected(item)"
              >
              </nz-option>
            </nz-select>
          </nz-form-control>
        </nz-form-item>
      </ng-container>

      <div class="text-end">
        <button nz-button class="me-2" type="button" (click)="onCancel.emit();" i18n>取消</button>
        <button nz-button nzType="primary" type="submit" i18n>提交</button>
      </div>
    </form>
    
  `,
  styles: [
  ]
})
export class MetaComponent implements OnInit {
  private _art: any;
  @Input('art')
  public set art(value: any) {
    this._art = value;
    this.form?.reset(value);
  }
  public get art(): any {
    return this._art;
  }

  @Input() showMainCategory: boolean = false;


  @Input() artId: string;

  @Output() onCancel = new EventEmitter<any>();
  @Output() onSuccess = new EventEmitter<any>();
  @Output() onError = new EventEmitter<any>();

  form: FormGroup;

  tagOptions: any[] = [];
  epgOptions: any[] = [];

  mainCategories: any[] = [];

  constructor(
    private fb: FormBuilder,
    private artService: ArtService,
    private i18n: NzI18nService
  ) {


    this.artService.getTags().subscribe(resp => {
      this.tagOptions = resp as any[];
    })

    this.artService.getEpgs().subscribe(resp => {
      this.epgOptions = resp as any[];
    })

    let lang = 'zh_CN'
    if (this.i18n.getLocaleId() == 'en') lang = 'en';
    this.artService.getMainCategoryOptions(lang).subscribe(resp => {
      this.mainCategories = resp as any[];
      console.log(this.mainCategories);
    })
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      category: [null, [Validators.required]],
      name: [null, [Validators.required]],
      desc: [null],
      tags: [null, [Validators.required]],
      epgs: [null],
    });


    if (!this.showMainCategory) {
      this.form.removeControl('category');
    }

    if (this.art) {
      this.form.reset(this.art);
    } else {
      this.form.controls['epgs'].disable();
    }

  }

  submit() {
    console.log('submit', this.form.valid);
    if (this.form.invalid) {
      FormUtils.markAsDirty(this.form);
      return;
    }

    if (this.artId || this.art) {
      let data = this.form.value;
      data.pageId = this.artId || this.art._id;
      this.artService.patchMeta(this.form.value).subscribe({
        next: resp => this.onSuccess.emit(this.form.value),
        error: err => this.onError.emit(err.error?.message || err.message),
      })
    } else {
      this.onSuccess.emit(this.form.value);
    }

  }



  isSelected(item) {
    if (!this.form.value.tags) return false;
    return this.form.value.tags.indexOf(item.value) >= 0;
  }

}
