import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { Subject } from 'rxjs';
import { SearchDrawerService } from './search-drawer.service';

@Component({
  selector: 'app-search-drawer',
  templateUrl: './search-drawer.component.html',
  styleUrls: ['./search-drawer.component.less']
})
export class SearchDrawerComponent implements OnInit, AfterViewInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  ui: SFUISchema = { '*': { spanLabelFixed: 95, grid: { span: 12, gutter: 24 } } };
  schema!: SFSchema;

  loading = true;

  defaultValue = {};

  constructor(public service: SearchDrawerService, public http: _HttpClient) {}
  ngAfterViewInit(): void {}

  ngOnInit(): void {
    this.defaultValue = {};
    this.service.createEvent.subscribe(({ defaultValue, newSchema, newUI }) => {
      if (defaultValue) {
        this.defaultValue = defaultValue;
      }
      if (newSchema) {
        this.schema = newSchema;
        if (this.sf) {
          this.sf.refreshSchema(newSchema, newUI);
          this.sf.reset();
        }
        this.service.visible = true;
      }
      setTimeout(() => {
        this.service.initEvent.next(this.sf);
      }, 500);
    });
  }

  resetSF(): void {
    this.sf.reset();
    this.defaultValue = {};
  }

  search() {
    if (this.sf) {
      this.service.closeEvent.next(this.sf?.value);
    }
  }

  destroy() {
    this.service.visible = false;
  }
}
