import { Component, forwardRef, Input } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from './../../common.nz.module';
import { BasicDataService } from './../../services/basic.service';
import { PositionPickerModalComponent } from './modal/modal.component';
import { PositionVisualComponent } from './position-visual/position-visual.component';

@Component({
  selector: 'position-picker',
  standalone: true,
  imports: [CommonNzModule, PositionVisualComponent],
  templateUrl: './position-picker.component.html',
  styleUrl: './position-picker.component.less',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PositionPickerComponent),
      multi: true,
    },
  ],
})
export class PositionPickerComponent {
  @Input() positionCategories?: BasicData.PositionCategory[];
  @Input() positions?: BasicData.Position[];
  @Input() placeHolder = '请选择';
  selectedIds: number[] = [];

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

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

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

  handleClick() {
    this.createModal();
  }
  onChange(positionIds: number[]) {
    this.selectedIds = positionIds;
    this.updateValue(positionIds);
  }
  handleClear(event: MouseEvent) {
    event.stopPropagation();
    this.onChange([]);
  }
  createModal() {
    this.modal.create({
      // nzClosable: false,
      nzMaskClosable: false,
      nzClassName: 'position-picker-modal',
      nzContent: PositionPickerModalComponent,
      nzFooter: null,
      nzData: {
        positions: this.positions || this.basic.positions,
        categories: this.positionCategories || this.basic.positionCategories,
        checkPositionIds: this.selectedIds,
        onChange: this.onChange.bind(this),
      },
      nzWidth: 750,
    });
  }
  get list() {
    return this.positions || this.basic.positions;
  }
  get categories() {
    return this.positionCategories || this.basic.positionCategories;
  }
  get text() {
    return '';
  }
  get selectedPositions(): BasicData.Position[] {
    return this.selectedIds.map(id => this.list.find(p => p.id === id)!).filter(p => p);
  }
}
