/** 门店银行卡表单字段（yii_store） */
export type StoreBankFormState = {
  bank_user_name: string;
  bank_card: string;
  bank_name: string;
  bank_account_type: number;
  bank_no: string;
};

export type BankCardSelectableOption = {
  value: string;
  label: string;
  payload: Record<string, any>;
};

/** 卡号脱敏展示（与后端 mask 规则一致） */
export function maskBankCardForDisplay(bankCard?: string | null): string {
  const card = String(bankCard ?? '').trim();
  if (!card) return '';
  if (card.length <= 8) return card;
  return `${card.slice(0, 4)}${'*'.repeat(Math.max(0, card.length - 8))}${card.slice(-4)}`;
}

/** 报备 payload 映射为门店银行卡表单字段 */
export function mapReportPayloadToStoreBankForm(
  payload: Record<string, any>,
): StoreBankFormState {
  return {
    bank_user_name: String(payload.bank_user_name ?? ''),
    bank_card: String(payload.bank_card ?? ''),
    bank_name: String(payload.bank_name ?? ''),
    bank_account_type: Number(payload.bank_account_type ?? 2) || 2,
    bank_no: String(payload.bank_no ?? ''),
  };
}

/** 从报备详情构建本门店导入选项 */
export function buildCurrentStoreReportOption(
  detail: Record<string, any> | null | undefined,
): BankCardSelectableOption | null {
  if (!detail?.id) return null;
  const bankCard = String(detail.bank_card ?? '').trim();
  const bankUserName = String(detail.bank_user_name ?? '').trim();
  if (!bankCard || !bankUserName) return null;

  const masked =
    detail.bank_card_masked || maskBankCardForDisplay(bankCard);

  return {
    value: `current_report_${detail.id}`,
    label: `本门店报备 #${detail.id}（${masked}）`,
    payload: mapReportPayloadToStoreBankForm(detail),
  };
}

/** 合并本店报备与跨店历史报备选项（本店置顶） */
export function mergeSelectableBankCardOptions(
  currentOption: BankCardSelectableOption | null,
  remoteOptions: BankCardSelectableOption[] = [],
): BankCardSelectableOption[] {
  if (!currentOption) return remoteOptions;
  const rest = remoteOptions.filter((item) => item.value !== currentOption.value);
  return [currentOption, ...rest];
}
