import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Subscription } from 'rxjs';
import { CommonNzModule } from '../../../../common.nz.module';
import { ApiService } from '../../../../services/api.service';
import { BasicDataService } from '../../../../services/basic.service';
import { KnowledgeService } from '../../../../services/knowledge.service';
import { RiskTypeCategoryNavComponent } from '../../../../shared/risk-type-category-nav/risk-type-category-nav.component';
import { StarIconComponent } from '../../../../shared/star/star.icon';

interface CheckOption {
  label: string;
  value: number;
  checked: boolean;
}

const colorMap: Record<string, string> = {
  'R1': '#FF0000',
  'R2': '#EB5D00',
  'R2*': '#EB5D00',
  'R3': '#fcd34d',
  'R4': '#4677F2',
};

@Component({
  selector: 'app-dr-relationship',
  standalone: true,
  imports: [CommonNzModule, RiskTypeCategoryNavComponent, StarIconComponent],
  templateUrl: './dr-relationship.component.html',
  styleUrl: './dr-relationship.component.less',
})
export class DrRelationshipComponent {
  subs = new Subscription();
  types: OptionWithCount<number>[] = [];
  categories: OptionWithCount<number>[] = [];
  selectedType = -1;
  selectedCategory = -1;
  departmentOptions: CheckOption[] = [];
  colorMap = colorMap;
  constructor(
    private message: NzMessageService,
    private knowledge: KnowledgeService,
    private basic: BasicDataService,
    private api: ApiService
  ) {
    const sub = this.knowledge.onTypesChange.subscribe(() => {
      this.resetSelected();
    });
    this.subs.add(sub);
  }
  ngOnInit() {
    this.resetSelected();
  }
  ngOnDestroy() {
    this.subs.unsubscribe();
  }
  resetSelected() {
    this.types = this.getTypes();
    if (!this.currentCategory) {
      this.selectedTypeChange(this.types[0]?.value || -1);
    }
  }
  selectedTypeChange(value: number) {
    this.selectedType = value;
    this.categories = this.getCategories(value);

    this.selectedCategoryChange(this.categories[0]?.value || -1);
  }
  selectedCategoryChange(value: number) {
    this.selectedCategory = value;
    this.departmentOptions = this.getCurrentDepartmentIds();
  }
  getTypes(): OptionWithCount<number>[] {
    return this.allTypes.map(type => ({
      label: type.value,
      value: type.id,
      count: 0,
    }));
  }
  getCategories(typeId: number): OptionWithCount<number>[] {
    const options = this.knowledge.getCategoryOptionsByType(typeId);
    return options.map(option => ({
      ...option,
      count: 0,
    }));
  }
  getCurrentDepartmentIds() {
    const empty = this.allDepartments.map(d => ({ label: d.name, value: d.id, checked: false }));
    const currentCategory = this.currentCategory;
    if (!currentCategory) return empty;
    return empty.map(d => ({
      ...d,
      checked: currentCategory.departments.includes(d.value),
    }));
  }

  onDepartmentChange(ops: CheckOption[]) {
    const dIds = ops.filter(d => d.checked).map(d => d.value);
    if (!this.currentCategory) {
      this.message.error('操作失败');
      return;
    }
    this.setDepartmentsOfRiskCategory(dIds);
  }
  async setDepartmentsOfRiskCategory(dIds: number[]) {
    await this.api.knowledge.updateRiskCategory({
      ...this.currentCategory,
      departments: dIds,
    });
    this.knowledge.fetchRiskTypes();
  }
  get allDepartments() {
    return this.basic.departments;
  }
  get allTypes() {
    return this.knowledge.types();
  }
  get currentCategory() {
    const currentType = this.allTypes.find(t => t.id === this.selectedType);
    if (!currentType) return undefined;
    return currentType.categories.find(c => c.id === this.selectedCategory);
  }
}
