import type {
  MemberStoredCardPlanDto,
  SaveMemberStoredCardPlanPayload,
} from '#/api/member/stored-card';
import type {
  StoredCardPlanEditorForm,
  StoredCardRecordFilterForm,
} from '#/views/member/stored-card/types';

import { createDefaultStoredCardPlanEditorForm } from '#/views/member/stored-card/types';

/** 金额格式化。 */
export function formatCurrency(value: null | number | undefined) {
  const amount = Number(value ?? 0);
  if (Number.isNaN(amount)) {
    return '¥0';
  }

  if (Math.abs(amount) >= 1000) {
    return `¥${amount.toLocaleString('zh-CN', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    })}`;
  }

  return `¥${amount.toFixed(amount % 1 === 0 ? 0 : 2)}`;
}

/** 数量格式化。 */
export function formatInteger(value: null | number | undefined) {
  const num = Number(value ?? 0);
  if (!Number.isFinite(num)) {
    return '0';
  }
  return Math.round(num).toLocaleString('zh-CN');
}

/** 赠送比例文案。 */
export function resolveGiftRatioText(
  rechargeAmount: null | number,
  giftAmount: null | number,
) {
  const recharge = Number(rechargeAmount ?? 0);
  const gift = Number(giftAmount ?? 0);
  if (recharge <= 0 || gift <= 0) {
    return '赠送比例 --';
  }

  const ratio = ((gift / recharge) * 100).toFixed(1);
  return `赠送比例 ${ratio}%`;
}

/** 表单转保存 DTO。 */
export function mapPlanEditorFormToSavePayload(
  form: StoredCardPlanEditorForm,
  storeId: string,
): SaveMemberStoredCardPlanPayload {
  return {
    storeId,
    planId: form.planId || undefined,
    rechargeAmount: Number(form.rechargeAmount ?? 0),
    giftAmount: Number(form.giftAmount ?? 0),
    sortOrder: Number(form.sortOrder ?? 100),
    status: form.status,
  };
}

/** 方案转编辑表单。 */
export function mapPlanToEditorForm(
  plan: MemberStoredCardPlanDto,
): StoredCardPlanEditorForm {
  return {
    planId: plan.planId,
    rechargeAmount: plan.rechargeAmount,
    giftAmount: plan.giftAmount,
    sortOrder: plan.sortOrder,
    status: plan.status,
  };
}

/** 重置编辑表单。 */
export function resetPlanEditorForm(form: StoredCardPlanEditorForm) {
  const defaults = createDefaultStoredCardPlanEditorForm();
  form.planId = defaults.planId;
  form.rechargeAmount = defaults.rechargeAmount;
  form.giftAmount = defaults.giftAmount;
  form.sortOrder = defaults.sortOrder;
  form.status = defaults.status;
}

/** 筛选项转查询参数。 */
export function mapRecordFilterToQuery(
  filterForm: StoredCardRecordFilterForm,
): { endDate?: string; keyword?: string; startDate?: string } {
  const keyword = filterForm.keyword.trim();
  if (!filterForm.dateRange) {
    return {
      keyword: keyword || undefined,
    };
  }

  return {
    startDate: filterForm.dateRange[0].format('YYYY-MM-DD'),
    endDate: filterForm.dateRange[1].format('YYYY-MM-DD'),
    keyword: keyword || undefined,
  };
}

/** base64 下载。 */
export function downloadBase64File(
  fileName: string,
  fileContentBase64: string,
) {
  const binary = atob(fileContentBase64);
  const length = binary.length;
  const bytes = new Uint8Array(length);
  for (let index = 0; index < length; index++) {
    bytes[index] = binary.codePointAt(index) ?? 0;
  }

  const blob = new Blob([bytes], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = fileName;
  document.body.append(anchor);
  anchor.click();
  anchor.remove();
  URL.revokeObjectURL(url);
}
