/** 列表行类型：特色方主行或 SKU 子行 */
export interface SpecialPrescriptionListRow {
  rowType: 'sp' | 'sku';
  _rowKey: string;
  id: number;
  name: string;
  category_id?: number;
  category_name?: string;
  cover_image?: string;
  tags?: string[];
  price_per_dose?: number;
  sales_count?: number;
  sort?: number;
  status: number;
  is_free_shipping?: number;
  free_shipping_min_doses?: number;
  has_sku?: boolean;
  prescription_sub_type?: number;
  created_at?: string;
  /** SKU 子行专用 */
  sku_id?: number;
  sku_name?: string;
  dose_count?: number;
  sp_id?: number;
}

/**
 * 将特色方列表扁平化为「主行 + SKU 子行」，供表格一行一个 SKU 展示
 */
export function flattenSpecialPrescriptionList(
  items: Record<string, any>[],
): SpecialPrescriptionListRow[] {
  const rows: SpecialPrescriptionListRow[] = [];
  for (const sp of items) {
    rows.push({
      ...sp,
      rowType: 'sp',
      _rowKey: `sp-${sp.id}`,
      status: sp.status ?? 0,
      is_free_shipping: sp.is_free_shipping ?? 0,
      free_shipping_min_doses: sp.free_shipping_min_doses ?? 0,
      has_sku: sp.has_sku ?? (sp.skus?.length > 0),
    });
    const skus = sp.skus || [];
    for (const sku of skus) {
      rows.push({
        rowType: 'sku',
        _rowKey: `sku-${sku.id}`,
        id: sp.id,
        sp_id: sp.id,
        sku_id: sku.id,
        sku_name: sku.sku_name,
        dose_count: sku.dose_count,
        name: sku.sku_name || `${sku.dose_count}贴`,
        status: sku.status ?? 0,
        is_free_shipping: sku.is_free_shipping ?? 0,
        prescription_sub_type: sp.prescription_sub_type,
      });
    }
  }
  return rows;
}

/** 列表名称列展示文案 */
export function formatListRowName(row: SpecialPrescriptionListRow): string {
  if (row.rowType === 'sku') {
    const label = row.sku_name || `${row.dose_count || ''}贴`;
    return `└ ${label}（${row.dose_count || '-'}贴）`;
  }
  return row.name || '';
}

/** 包邮条件展示文案：0=始终包邮，N>0=大于N剂包邮 */
export function formatFreeShippingThreshold(minDoses?: number): string {
  const n = minDoses ?? 0;
  return n > 0 ? `>${n}剂包邮` : '始终包邮';
}
