import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { AddressComponent } from '@shared';
import { DictSelectService } from './dict-select.service';

@Component({
  selector: 'app-dict-select',
  templateUrl: './dict-select.component.html',
  styleUrls: ['./dict-select.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DictSelectComponent),
      multi: true,
    },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DictSelectComponent implements OnInit, ControlValueAccessor {

  private onChangeFn?: (val: string) => void;
  private onTouchedFn?: () => void;

  defaultUrl = `/api/mdc/pbc/dictItems/getDictValue`;
  @Input() value: string = ''; // 默认选中值
  @Input() url: string = ''; // 获取字典数据的地址
  @Input() params = {};// 请求参数

  dictList: any[] = [];

  constructor(public service: DictSelectService, public cdr: ChangeDetectorRef) { }

  writeValue(geo: string): void {
    if (geo == null) {
      this.value = '';
      return;
    }
    this.value = geo;
  }
  registerOnChange(fn: any): void {
    this.onChangeFn = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouchedFn = fn;
  }

  ngOnInit(): void {

    this.service.getDictList(this.url || this.defaultUrl, this.params).subscribe(res => {
      if (res) {
        this.dictList = res || [];
        if (this.dictList.length > 0) {
          const obj = { label: '全部', value: '' };
          this.dictList.unshift(obj);
        }
        this.cdr.markForCheck();
      }
    });
  }
  change($event: any) {
    this.onChangeFn!($event);
  }

  isEmpty(val: any) {
    return val === undefined || val === null || val === '';
  }

}
