import type { ProductionPlan, PlanProcessStep, YarnRatio } from '../types';

interface InventoryRecord {
  plan_id: string;
  created_at: string;
  quantity: number;
  rolls: number | null;
}

interface Product {
  fabric_code: string;
  company_id: string;
  image_url?: string | null;
  warp_weight?: number | null;
  weft_weight?: number | null;
  total_weight?: number | null;
  weight?: number | null;
}

export interface PlanGroup {
  purchaserId: string;
  purchaserName: string;
  plans: (ProductionPlan & {
    processSteps: PlanProcessStep[];
    inventoryRecords: { time: string; quantity: number; rolls: number | null }[];
    yarnRatios?: YarnRatio[];
    image_url?: string | null;
    warp_weight?: number | null;
    weft_weight?: number | null;
    total_weight?: number | null;
    weight?: number | null;
  })[];
}

/**
 * 按采购商分组计划数据（纯函数，可缓存）
 */
export function groupPlansByPurchaser(
  planData: ProductionPlan[],
  stepsData: PlanProcessStep[] | null,
  inventoryData: InventoryRecord[] | null,
  yarnRatiosData: YarnRatio[] | null,
  productsData: Product[] | null,
  companyMap: Record<string, string>
): PlanGroup[] {
  const grouped: Record<string, PlanGroup> = {};

  planData.forEach(plan => {
    const pid = plan.purchaser_id;
    if (!grouped[pid]) {
      grouped[pid] = {
        purchaserId: pid,
        purchaserName: companyMap[pid] || '未知布行',
        plans: []
      };
    }

    const processSteps = (stepsData || [])
      .filter(s => s.plan_id === plan.id)
      .sort((a, b) => {
        const order = ['confirm', 'yarn_purchase', 'dyeing', 'machine_start', 'fabric_warehouse'];
        return order.indexOf(a.step_type) - order.indexOf(b.step_type);
      });

    const inventoryRecords = (inventoryData || [])
      .filter(r => r.plan_id === plan.id)
      .map(r => ({ time: r.created_at, quantity: r.quantity, rolls: r.rolls }));

    const yarnRatios = (yarnRatiosData || [])
      .filter(y => y.plan_id === plan.id)
      .map(y => ({
        id: y.id,
        plan_id: y.plan_id,
        yarn_name: y.yarn_name,
        ratio: y.ratio,
        amount_per_meter: y.amount_per_meter,
        total_amount: y.total_amount,
        yarn_type: y.yarn_type,
        created_at: y.created_at,
        company_id: y.company_id
      }));

    // 查找关联的产品信息
    const product = (productsData || []).find(p =>
      p.fabric_code === plan.fabric_code && p.company_id === plan.purchaser_id
    );

    grouped[pid].plans.push({
      ...plan,
      processSteps,
      inventoryRecords,
      yarnRatios,
      image_url: product?.image_url || null,
      warp_weight: product?.warp_weight || null,
      weft_weight: product?.weft_weight || null,
      total_weight: product?.total_weight || null,
      weight: product?.weight || null
    });
  });

  return Object.values(grouped);
}

/**
 * 过滤被拒绝的计划（纯函数，可缓存）
 */
export function filterRejectedPlans<T extends { id: string }>(
  plans: T[],
  rejectedPlanIds: Set<string>
): T[] {
  return plans.filter(p => !rejectedPlanIds.has(p.id));
}

/**
 * 按计划状态过滤（纯函数，可缓存）
 */
export function filterPlansByStatus<T extends { status: string }>(
  plans: T[],
  statusFilter: string | null
): T[] {
  if (!statusFilter || statusFilter === 'all') {
    return plans;
  }
  return plans.filter(p => p.status === statusFilter);
}

/**
 * 计算计划统计信息（纯函数，可缓存）
 */
export function calculatePlanStats<T extends { status: string }>(plans: T[]) {
  return {
    all: plans.length,
    pending: plans.filter(p => p.status === 'pending').length,
    producing: plans.filter(p => p.status === 'producing').length,
    completed: plans.filter(p => p.status === 'completed').length
  };
}
