import type { ExportGranularity } from '#/views/business/order/product-order/config/exportFields';
import { getExportFields } from '#/views/business/order/product-order/config/exportFields';
import { buildDefaultOrderedKeys } from '#/views/business/order/product-order/utils/exportFieldOrder';

export interface ExportSchemeConfig {
  order_no?: string;
  store_id?: number | null;
  status?: number | null;
  delivery_method?: number | null;
  prescription_type?: number | null;
  /** 有序导出字段 key 列表 */
  selected_fields: string[];
}

export interface ExportSchemeItem {
  id: number;
  name: string;
  is_default: number;
  granularity: ExportGranularity;
  config: ExportSchemeConfig;
  created_at?: string;
  updated_at?: string;
}

export interface ExportFormState {
  orderNo: string;
  storeId: number | undefined;
  status: number | undefined;
  deliveryMethod: number | undefined;
  prescriptionType: number | undefined;
  granularity: ExportGranularity;
  selectedKeys: string[];
  orderedSelectedKeys: string[];
}

export function buildSchemeConfigFromForm(form: ExportFormState): ExportSchemeConfig {
  return {
    order_no: form.orderNo.trim(),
    store_id: form.storeId ?? null,
    status: form.status ?? null,
    delivery_method: form.deliveryMethod ?? null,
    prescription_type: form.prescriptionType ?? null,
    selected_fields: [...form.orderedSelectedKeys],
  };
}

export function sanitizeSelectedFields(
  granularity: ExportGranularity,
  keys: string[],
): string[] {
  const allowed = new Set(getExportFields(granularity).map((f) => f.key));
  return keys.filter((k) => allowed.has(k));
}

export function applySchemeToForm(
  scheme: ExportSchemeItem,
  form: ExportFormState,
): void {
  const cfg = scheme.config ?? ({} as ExportSchemeConfig);
  form.granularity = scheme.granularity;
  form.orderNo = cfg.order_no?.trim() ?? '';
  form.storeId = cfg.store_id ?? undefined;
  form.status = cfg.status ?? undefined;
  form.deliveryMethod = cfg.delivery_method ?? undefined;
  form.prescriptionType = cfg.prescription_type ?? undefined;

  const fields = sanitizeSelectedFields(
    scheme.granularity,
    cfg.selected_fields ?? [],
  );
  if (fields.length > 0) {
    form.orderedSelectedKeys = fields;
    form.selectedKeys = [...fields];
  } else {
    const defaults = getExportFields(scheme.granularity)
      .filter((f) => f.default)
      .map((f) => f.key);
    form.selectedKeys = defaults;
    form.orderedSelectedKeys = buildDefaultOrderedKeys(defaults, scheme.granularity);
  }
}

export function findDefaultScheme(schemes: ExportSchemeItem[]): ExportSchemeItem | undefined {
  return schemes.find((s) => s.is_default === 1);
}
