import { Component, EventEmitter, forwardRef, Input, Output } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from './../../common.nz.module';
import { KnowledgeService } from './../../services/knowledge.service';
import { RiskItemPickerModalComponent } from './modal/modal.component';

@Component({
  selector: 'risk-item-picker',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './risk-item-picker.component.html',
  styleUrl: './risk-item-picker.component.less',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RiskItemPickerComponent),
      multi: true,
    },
  ],
})
export class RiskItemPickerComponent {
  @Input() riskItems?: Knowledge.RiskItem[];
  @Input() riskTypes?: Knowledge.RiskTypeDto[];
  @Input() riskCategories?: Knowledge.RiskCategoryDto[];
  @Input() preSearched = true;

  @Input() placeHolder = '请选择';
  _visible = false;
  @Input() get visible() {
    return this._visible;
  }
  set visible(value: boolean) {
    this._visible = value;
    if (value) {
      this.createModal();
    }
  }
  @Output() close = new EventEmitter();
  selectedIds: number[] = [];

  writeValue(value: number[]) {
    if (value) {
      this.updateValue(value);
      this.selectedIds = value;
    }
  }
  constructor(
    private knowledge: KnowledgeService,
    private modal: NzModalService
  ) {}

  updateValue = (value: number[]) => {};
  updateValueByTouched = (value: number[]) => {};
  registerOnChange(fn: (value: number[]) => void) {
    this.updateValue = fn;
  }

  registerOnTouched(fn: () => void) {
    this.updateValueByTouched = fn;
  }

  onChange(positionIds: number[]) {
    this.selectedIds = positionIds;
    this.updateValue(positionIds);
  }
  clear() {
    this.onChange([]);
  }
  createModal() {
    this.modal.create({
      nzMaskClosable: false,
      nzClassName: 'picker-modal',
      nzContent: RiskItemPickerModalComponent,
      nzFooter: null,
      nzData: {
        types: this.types,
        categories: this.categories,
        items: this.items,
        checkItemIds: this.selectedIds,
        onChange: this.onChange.bind(this),
        preSearched: this.preSearched,
      },
      nzAfterClose: this.close,
      nzWidth: '1140px',
    });
  }
  get types() {
    return this.riskTypes || this.knowledge.types();
  }
  get categories() {
    return this.riskCategories || this.knowledge.categories();
  }
  get items() {
    return this.riskItems || this.knowledge.riskItems();
  }

  get selectedItems(): Knowledge.RiskItem[] {
    return this.selectedIds.map(id => this.items.find(p => p.id === id)!).filter(p => p);
  }
}
