import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
import { CommonNzModule } from '../../../../common.nz.module';
import { ApiService } from '../../../../services/api.service';
import { KnowledgeService } from '../../../../services/knowledge.service';
import { DataEmptyComponent } from '../../../../shared/data-empty/data-empty.component';
import { FilterButtonGroupWithCountComponent } from '../../../../shared/filter-button-group-with-count/filter-button-group-with-count.component';
import { RiskTypeCategoryNavComponent } from '../../../../shared/risk-type-category-nav/risk-type-category-nav.component';
import { StarIconComponent } from '../../../../shared/star/star.icon';
import { ControlInfoComponent } from './control-info/control-info.component';
import { DetailInfoComponent } from './detail-info/detail-info.component';

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

@Component({
  selector: 'app-risk-list',
  standalone: true,
  imports: [
    CommonNzModule,
    RiskTypeCategoryNavComponent,
    FilterButtonGroupWithCountComponent,
    StarIconComponent,
    DetailInfoComponent,
    ControlInfoComponent,
    DataEmptyComponent,
  ],
  templateUrl: './risk-list.component.html',
  styleUrl: './risk-list.component.less',
})
export class RiskListComponent {
  colorMap = colorMap;
  involvedOptions: Option<number>[] = [
    { label: '全部', value: 0 },
    { label: '场所', value: 1 },
    { label: '作业', value: 2 },
    { label: '设备', value: 3 },
  ];
  involved = 0;
  activeItem: Knowledge.RiskItem | null = null;

  types: OptionWithCount<number>[] = [];
  categories: OptionWithCount<number>[] = [];
  levels: OptionWithCount<string>[] = [];
  selectedType = -1;
  selectedCategory = -1;
  selectedLevel = '';

  showDetail = false;
  loading = false;
  subs = new Subscription();
  constructor(
    private api: ApiService,
    private knowledge: KnowledgeService
  ) {
    const sub = this.knowledge.onTypesChange.subscribe(() => {
      this.resetSelected();
    });
    this.subs.add(sub);
  }
  resetSelected() {
    this.selectedType = -1;
    this.selectedCategory = -1;
    this.types = this.getTypes();
    const validTypeOp = this.types.find(c => c.count > 0);
    if (validTypeOp) {
      this.selectedTypeChange(validTypeOp.value);
    }
  }
  resetLevel() {
    this.levels = this.getLevels();
    const validLevelOp = this.levels.find(c => c.count > 0);
    if (validLevelOp) {
      this.selectedLevel = validLevelOp.value;
    } else {
      this.selectedLevel = '';
    }
  }
  ngOnInit() {
    this.fetchList();
  }
  hideDetail() {
    this.showDetail = false;
    setTimeout(() => {
      this.activeItem = null;
    }, 300);
  }
  selectedTypeChange(value: number) {
    this.selectedType = value;
    this.categories = this.getCategories(value);
    const validCategory = this.categories.find(c => c.count > 0)?.value || -1;
    this.selectedCategory = validCategory;
    this.resetLevel();
    this.hideDetail();
  }
  selectedCategoryChange(value: number) {
    this.selectedCategory = value;
    this.resetLevel();
    this.hideDetail();
  }

  changeInvolved(value: number) {
    this.involved = value;
    this.fetchList();
    this.hideDetail();
  }
  changeLevel(value: string) {
    this.selectedLevel = value;
    this.hideDetail();
  }

  onCardClick(item: Knowledge.RiskItem) {
    this.activeItem = item;
    this.showDetail = true;
  }

  list: Knowledge.RiskItem[] = [];
  get filteredList() {
    return this.list.filter(item => {
      if (this.selectedType !== -1 && item.type !== this.selectedType) {
        return false;
      }
      if (this.selectedCategory !== -1 && item.category !== this.selectedCategory) {
        return false;
      }
      if (this.selectedLevel !== '' && item.level !== this.selectedLevel) {
        return false;
      }
      return true;
    });
  }
  getFilteredListForLevel() {
    return this.list.filter(item => {
      if (this.selectedType !== -1 && item.type !== this.selectedType) {
        return false;
      }
      if (this.selectedCategory !== -1 && item.category !== this.selectedCategory) {
        return false;
      }
      return true;
    });
  }
  async fetchList() {
    this.loading = true;
    this.hideDetail();
    const res = await this.api.knowledge.getMyRiskItems(this.involved).finally(() => {
      this.loading = false;
    });
    this.list = res;
    this.resetSelected();
  }

  getTypes(): OptionWithCount<number>[] {
    return this.allTypes.map(type => ({
      label: type.value,
      value: type.id,
      count: this.list.filter(item => item.type === type.id).length,
    }));
  }
  getLevels(): OptionWithCount<string>[] {
    const list = this.getFilteredListForLevel();
    return this.knowledge.levels().map(level => ({
      label: level.value,
      value: level.value,
      count: list.filter(item => item.level === level.value).length,
    }));
  }
  getCategories(typeId: number): OptionWithCount<number>[] {
    const options = this.knowledge.getCategoryOptionsByType(typeId);
    return options.map(option => ({
      ...option,
      count: this.list.filter(item => item.category === option.value).length,
    }));
  }
  ngOnDestroy() {
    this.subs.unsubscribe();
  }
  get allTypes() {
    return this.knowledge.types();
  }
}
