import { Component, inject } from '@angular/core';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { horizontalInOut } from '../../../common.animation';
import { CommonNzModule } from './../../../common.nz.module';
import { BasicDataService } from './../../../services/basic.service';
import { PositionVisualComponent } from './../position-visual/position-visual.component';

export interface PositionPickerModalData {
  title: string;
  positions: BasicData.Position[];
  categories: BasicData.PositionCategory[];
  checkPositionIds: number[];
  onChange: (positionIds: number[]) => void;
}

@Component({
  selector: 'position-picker-modal',
  standalone: true,
  imports: [CommonNzModule, PositionVisualComponent],
  templateUrl: './modal.component.html',
  styleUrl: './modal.component.less',
  animations: [horizontalInOut],
})
export class PositionPickerModalComponent {
  readonly nzModalData: PositionPickerModalData = inject(NZ_MODAL_DATA);
  category?: number;
  selectedPositions: BasicData.Position[] = [];
  searchText = '';
  constructor(private basic: BasicDataService) {}

  ngOnInit() {
    if (this.nzModalData.categories.length > 0) {
      this.category = this.nzModalData.categories[0].id;
    }
    if (this.nzModalData.checkPositionIds.length > 0) {
      this.selectedPositions = this.positions.filter(p => this.nzModalData.checkPositionIds.includes(p.id));
    }
  }
  onCategoryChange(value: number) {
    this.category = value;
  }
  onClear() {
    this.selectedPositions = [];
  }
  onPositionChange(value: number, boolean = true) {
    const pos = this.positions.find(p => p.id === value);
    if (pos) {
      if (boolean) {
        this.selectedPositions.unshift(pos);
      } else {
        this.selectedPositions = this.selectedPositions.filter(p => p.id !== value);
      }
      this.nzModalData.onChange(this.selectedPositions.map(p => p.id));
    }
  }
  getLineName(lineId: number) {
    return this.basic.getLineName(lineId);
  }

  onRemove(positionId: number) {
    this.selectedPositions = this.selectedPositions.filter(p => p.id !== positionId);
    this.nzModalData.onChange(this.selectedPositions.map(p => p.id));
  }
  get title() {
    return this.nzModalData.title || '选择场所';
  }
  get positions() {
    return this.nzModalData.positions;
  }
  get filteredPositions() {
    if (!this.category) {
      return this.positions;
    }
    return this.positions.filter(p => p.category === this.category);
  }
  get categories() {
    return this.nzModalData.categories;
  }
  get currentCategory() {
    return this.categories.find(c => c.id === this.category);
  }
  get categoryTypeIsStation() {
    return this.currentCategory?.name === '车站';
  }
}
