import { DOCUMENT } from '@angular/common';
import { ChangeDetectorRef, Directive, ElementRef, EventEmitter, Host, HostBinding, HostListener, Inject, Input, OnInit, Optional, Output, Renderer2 } from '@angular/core';
import { NzButtonComponent } from 'ng-zorro-antd/button';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { delay, Observable } from 'rxjs';

@Directive({
  selector: '[cgOpButton]'
})
export class OpButtonDirective implements OnInit {
  @Input() confirmTitle: string = $localize`确认操作`;
  @Input() confirmContent: string = $localize`确定要执行这个操作?`;
  @Input() successText: string = $localize`操作成功`;
  @Input() operation: () => Observable<any>;

  @Output() onSuccess = new EventEmitter<any>();
  @Output() onFail = new EventEmitter<any>();
  @Output() onLoadingChange = new EventEmitter<boolean>();

  @HostListener('click', ['$event']) onClick($event) {
    this.modal.confirm({
      nzTitle: this.confirmTitle,
      nzContent: this.confirmContent,
      nzOnOk: this.onOk.bind(this),
    });
  }

  @HostBinding('disabled')
  get isDisabled() { return !this.nzButton && this.loading }


  private _loading: boolean = false;
  public get loading(): boolean {
    return this._loading;
  }
  public set loading(value: boolean) {
    this._loading = value;
    this.onLoadingChange.emit(value);
    if (this.nzButton) {
      //this.nzButton.nzLoading = value;
      //this.cdr.markForCheck();
    } else {
      if (this.icon) {
        this.icon.style.display = this.loading ? 'none' : '';
      }
      this.spinner.style.display = this.loading ? '' : 'none';
    }
  }


  constructor(
    private el: ElementRef,
    private renderer: Renderer2,
    private modal: NzModalService,
    private message: NzMessageService,
    private cdr: ChangeDetectorRef,
    @Inject(DOCUMENT) private document: Document,
    @Optional() @Host() private nzButton?: NzButtonComponent,
  ) {

  }

  private spinner: HTMLElement;
  private icon: HTMLElement;

  ngOnInit(): void {
    let nativeEl = this.el.nativeElement as HTMLElement;
    //找到iocn
    this.icon = nativeEl.querySelector('i');

    //创建 spinner
    this.spinner = this.document.createElement('i');
    //this.spinner.className = "spinner-border spinner-border-sm";
    this.spinner.className = "spinner fal fa-spinner-third ";
    this.spinner.style.display = 'none';
    this.renderer.insertBefore(this.el.nativeElement, this.spinner, (this.el.nativeElement as HTMLElement).firstChild);
  }

  onOk() {
    if (this.operation) {
      this.loading = true;
      this.operation().subscribe({
        next: resp => {
          this.message.success(this.successText);
          this.onSuccess.emit(resp);
        },
        error: err => {
          //this.message.error(err.error?.message || err.message);
          let modalRef = this.modal.error({
            nzTitle: $localize`操作失败`,
            nzContent: err.error?.message || err.message,
          });

          this.loading = false;
          this.onFail.emit(err);
        },
        complete: () => {
          this.loading = false;
        }
      })
    }else{
      this.message.info($localize`没有定义操作`);
    }
  }
}






export type opFunc = () => Observable<any>;