import { Component, Input, SimpleChanges } from '@angular/core';
import { horizontalInOut, verticalInOut, verticalInOutRelative } from '../../../common.animation';
import { KnowledgeService } from '../../../services/knowledge.service';
import { CommonNzModule } from './../../../common.nz.module';

interface EasyClassified {
  type: number;
  typeName: string;
  category: number;
  categoryName: string;
  items: Knowledge.RiskItem[];
  collapsed: boolean;
}

@Component({
  selector: 'risk-items-visual-classify',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './risk-items-visual-classify.component.html',
  styleUrl: './risk-items-visual-classify.component.less',
  animations: [verticalInOut, horizontalInOut, verticalInOutRelative],
})
export class RiskItemsVisualClassifyComponent {
  @Input() data!: Knowledge.RiskItem[];

  classified: Map<number, Map<number, Knowledge.RiskItem[]>> = new Map();
  classifiedEasyArray: EasyClassified[] = [];

  collapsedObject: { [key: string]: boolean } = {};

  constructor(private knowledge: KnowledgeService) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['data']) {
      this.setClassified();
    }
  }

  setClassified() {
    this.classified = new Map();
    this.data.forEach(item => {
      const classifiedByType = this.classified.get(item.type);
      if (classifiedByType) {
        const classifiedByCategory = classifiedByType.get(item.category);
        if (classifiedByCategory) {
          classifiedByType.set(item.category, [...classifiedByCategory, item]);
        } else {
          classifiedByType.set(item.category, [item]);
        }
      } else {
        this.classified.set(item.type, new Map([[item.category, [item]]]));
      }
    });
    this.classifiedEasyArray = [];
    for (const [type, categoryMap] of this.classified.entries()) {
      for (const [category, items] of categoryMap.entries()) {
        this.classifiedEasyArray.push({
          type: Number(type),
          typeName: this.getTypeName(Number(type)) ?? '',
          category: Number(category),
          categoryName: this.getCategoryName(Number(category), Number(type)) ?? '',
          items: items as Knowledge.RiskItem[],
          collapsed: this.collapsedObject[`${type}-${category}`] ?? true,
        });
      }
    }
  }

  onToggleCollapse(item: EasyClassified) {
    item.collapsed = !item.collapsed;
    this.collapsedObject[`${item.type}-${item.category}`] = item.collapsed;
  }

  getTypeName(type: number) {
    return this.knowledge.getTypeName(type);
  }

  getCategoryName(category: number, type: number) {
    return this.knowledge.getCategoryName(category, type);
  }

  get types() {
    return this.knowledge.types();
  }
  get categories() {
    return this.knowledge.categories();
  }

  get categoryIds() {
    return this.data.map(p => p.category);
  }

  get typeIds() {
    return this.data.map(p => p.type);
  }
}
