import type { CustomerRecord, CustomerRiskKpiKey } from '../types';
import type { CustomerRiskTag } from '../types/riskTag';

function visibleTags(tags: CustomerRiskTag[]): CustomerRiskTag[] {
  return tags.filter((tag) => tag.status === 'active' || tag.status === 'pending');
}

export function matchesRiskKpi(
  record: CustomerRecord,
  tags: CustomerRiskTag[],
  kpi: CustomerRiskKpiKey,
): boolean {
  if (kpi === 'all') return true;

  const activeTags = visibleTags(tags);
  if (kpi === 'withRisk') return activeTags.length > 0;
  if (kpi === 'finance') return activeTags.some((tag) => tag.tagCategory === 'finance');
  if (kpi === 'legal') return activeTags.some((tag) => tag.tagCategory === 'legal');
  if (kpi === 'business') return activeTags.some((tag) => tag.tagCategory === 'business');
  return true;
}

export function countRiskKpi(
  records: CustomerRecord[],
  riskTagsByCustomer: Record<string, CustomerRiskTag[]>,
  kpi: CustomerRiskKpiKey,
): number {
  return records.filter((record) =>
    matchesRiskKpi(record, riskTagsByCustomer[record.id] ?? [], kpi),
  ).length;
}

export const RISK_KPI_CARDS: Array<{
  key: CustomerRiskKpiKey;
  title: string;
  desc: string;
}> = [
  { key: 'all', title: '全部客户', desc: '当前台账内全部客户数量' },
  { key: 'withRisk', title: '有风险客户', desc: '存在生效中或待审批风险标签的客户' },
  { key: 'finance', title: '财务风险', desc: '含信用与回款、开票异常等财务类标签（财务部维护）' },
  { key: 'legal', title: '法务风险', desc: '含合规与法律类标签（法务部维护）' },
  { key: 'business', title: '业管风险', desc: '含经营与履约、多头签约等业管类标签（业管部维护）' },
];
