import { Component, inject } from '@angular/core';
import { NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
import { NzSelectOptionInterface } from 'ng-zorro-antd/select';
import { horizontalInOut } from '../../../common.animation';
import { KnowledgeService } from '../../../services/knowledge.service';
import { CommonNzModule } from './../../../common.nz.module';
import { RiskItemsVisualClassifyComponent } from './../risk-items-visual-classify/risk-items-visual-classify.component';

export interface RiskItemPickerModalData {
  title: string;
  items: Knowledge.RiskItem[];
  types: Knowledge.RiskTypeDto[];
  categories: Knowledge.RiskCategoryDto[];
  checkItemIds: number[];
  onChange: (itemIds: number[]) => void;
  preSearched: boolean;
}

@Component({
  selector: 'risk-item-picker-modal',
  standalone: true,
  imports: [CommonNzModule, RiskItemsVisualClassifyComponent],
  templateUrl: './modal.component.html',
  styleUrl: './modal.component.less',
  animations: [horizontalInOut],
})
export class RiskItemPickerModalComponent {
  readonly nzModalData: RiskItemPickerModalData = inject(NZ_MODAL_DATA);
  category?: number;
  type?: number;
  filteredCategories: NzSelectOptionInterface[] = [];
  filteredItems: Knowledge.RiskItem[] = [];
  selectedItems: Knowledge.RiskItem[] = [];
  searchText = '';
  constructor(private knowledge: KnowledgeService) {}

  ngOnInit() {
    this.typeOptions = this.types.map(t => ({
      label: t.value,
      value: t.id,
      disabled: !this.items.some(p => p.type === t.id),
    }));
    this.categoryOptions = this.categories.map(c => ({
      label: c.value,
      value: c.id,
      disabled: !this.items.some(p => p.category === c.id),
    }));
    if (this.nzModalData.checkItemIds.length > 0) {
      this.selectedItems = this.items.filter(p => this.nzModalData.checkItemIds.includes(p.id));
    }
    if (this.nzModalData.types.length > 0 && this.nzModalData.preSearched) {
      this.type = this.nzModalData.types[0].id;
      this.onTypeChange(this.type);
    } else {
      this.onTypeChange(undefined);
    }
  }
  onTypeChange(value: number | undefined) {
    this.type = value;
    this.category = undefined;
    const typeDto = this.types.find(p => p.id === value);
    if (!typeDto) {
      this.filteredCategories = [];
      this.setFilteredItems();
      return;
    }
    this.filteredCategories = typeDto.categories.map(c => ({
      label: c.value,
      value: c.id,
      disabled: !this.items.some(p => p.category === c.id),
    }));
    this.setFilteredItems();
  }
  onCategoryChange(value: number) {
    this.category = value;
    this.setFilteredItems();
  }
  onClear() {
    this.selectedItems = [];
    this.nzModalData.onChange([]);
    this.allChecked = false;
    this.indeterminate = false;
  }
  onItemChange(value: number, boolean = true) {
    const item = this.items.find(p => p.id === value);
    if (item) {
      if (boolean) {
        this.selectedItems = [item, ...this.selectedItems];
      } else {
        this.selectedItems = this.selectedItems.filter(p => p.id !== value);
      }
      this.nzModalData.onChange(this.selectedItems.map(p => p.id));
    }
    this.updateAllCheckedStatus();
  }

  onRemove(itemId: number) {
    this.selectedItems = this.selectedItems.filter(p => p.id !== itemId);
    this.updateAllCheckedStatus();
    this.nzModalData.onChange(this.selectedItems.map(p => p.id));
  }

  allChecked = false;
  indeterminate = false;

  get isAllCheckboxDisabled(): boolean {
    if (this.filteredItems.length === 0) {
      return true;
    }
    if (this.isTotalSelecting && !this.category && !this.type && !this.searchText) {
      return true;
    }
    return false;
  }

  updateAllChecked(): void {
    if (this.isAllCheckboxDisabled) return;

    this.indeterminate = false;
    if (this.allChecked) {
      this.filteredItems.forEach(item => {
        if (!this.selectedItems.includes(item)) {
          this.selectedItems = [...this.selectedItems, item];
        }
      });
    } else {
      this.filteredItems.forEach(item => {
        if (this.selectedItems.includes(item)) {
          this.selectedItems = this.selectedItems.filter(p => p.id !== item.id);
        }
      });
    }
    this.nzModalData.onChange(this.selectedItems.map(p => p.id));
  }

  updateAllCheckedStatus(): void {
    if (this.filteredItems.length === 0) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.filteredItems.every(item => this.selectedItems.find(p => p.id === item.id))) {
      this.allChecked = true;
      this.indeterminate = false;
    } else if (this.filteredItems.some(item => this.selectedItems.find(p => p.id === item.id))) {
      this.allChecked = false;
      this.indeterminate = true;
    } else {
      this.allChecked = false;
      this.indeterminate = false;
    }
  }

  get title() {
    return this.nzModalData.title || '选择风险条目';
  }
  get items() {
    return this.nzModalData.items;
  }
  setFilteredItems() {
    let result = this.items;
    if (this.type) {
      result = result.filter(p => p.type === this.type);
    }
    if (this.category) {
      result = result.filter(p => p.category === this.category);
    }
    if (this.searchText) {
      result = result.filter(p => p.title.includes(this.searchText));
    }
    this.filteredItems = result;
    this.updateAllCheckedStatus();
  }
  get types() {
    return this.nzModalData.types;
  }
  typeOptions: NzSelectOptionInterface[] = [];
  categoryOptions: NzSelectOptionInterface[] = [];

  get categories() {
    return this.nzModalData.categories;
  }
  get currentCategory() {
    return this.categories.find(c => c.id === this.category);
  }
  get isTotalSelecting() {
    // 列出系统中所有风险条目时  （不允许全选）
    return this.filteredItems.length === this.knowledge.riskItems().length;
  }
  // get categoryTypeIsStation() {
  //   return this.currentCategory?.name === '车站';
  // }
}
