import type {
  MarketingNewCustomerCouponScene,
  MarketingNewCustomerSettingsDto,
  SaveMarketingNewCustomerCouponRuleDto,
  SaveMarketingNewCustomerSettingsDto,
} from '#/api/marketing';
import type {
  NewCustomerCouponFormItem,
  NewCustomerPageForm,
} from '#/views/marketing/new-customer/types';

import { toCouponFormItem } from '#/views/marketing/new-customer/types';

/**
 * 文件职责：新客有礼页面纯函数工具。
 */

/** 格式化百分比。 */
export function formatPercent(value: number) {
  return Number(value || 0).toFixed(1);
}

/** 格式化整数。 */
export function formatInteger(value: number) {
  return Math.trunc(Number(value || 0)).toLocaleString('zh-CN');
}

/** 格式化金额。 */
export function formatMoney(value: null | number) {
  if (value === null || value === undefined) {
    return '0';
  }
  return Number(value).toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  });
}

/** 生成券标题。 */
export function formatCouponName(item: NewCustomerCouponFormItem) {
  if (item.couponType === 'free_shipping') {
    return '免配送费';
  }

  if (item.couponType === 'discount') {
    return `满${formatMoney(item.minimumSpend)}享${formatMoney(item.value)}折`;
  }

  return `满${formatMoney(item.minimumSpend)}减${formatMoney(item.value)}`;
}

/** 生成券描述。 */
export function formatCouponDescription(item: NewCustomerCouponFormItem) {
  if (item.couponType === 'free_shipping') {
    return '无门槛，减免配送费';
  }

  if (!item.minimumSpend || item.minimumSpend <= 0) {
    return '无门槛可用';
  }

  return `订单满 ${formatMoney(item.minimumSpend)} 元可用`;
}

/** 重建排序。 */
export function normalizeCouponSort(
  scene: MarketingNewCustomerCouponScene,
  items: NewCustomerCouponFormItem[],
) {
  return items.map((item, index) => ({
    ...item,
    scene,
    sortOrder: index + 1,
  }));
}

/** 拷贝券列表。 */
export function cloneCouponItems(items: NewCustomerCouponFormItem[]) {
  return items.map((item) => ({ ...item }));
}

/** 应用后端设置到页面表单。 */
export function mapSettingsToPageForm(
  settings: MarketingNewCustomerSettingsDto,
): NewCustomerPageForm {
  return {
    giftEnabled: settings.giftEnabled,
    giftType: settings.giftType,
    directReduceAmount: settings.directReduceAmount,
    directMinimumSpend: settings.directMinimumSpend,
    inviteEnabled: settings.inviteEnabled,
    shareChannels: [...settings.shareChannels],
    welcomeCoupons: normalizeCouponSort(
      'welcome',
      settings.welcomeCoupons.map((item) => toCouponFormItem(item)),
    ),
    inviterCoupons: normalizeCouponSort(
      'inviter',
      settings.inviterCoupons.map((item) => toCouponFormItem(item)),
    ),
    inviteeCoupons: normalizeCouponSort(
      'invitee',
      settings.inviteeCoupons.map((item) => toCouponFormItem(item)),
    ),
  };
}

/** 构建保存请求。 */
export function buildSaveSettingsPayload(
  form: NewCustomerPageForm,
  storeId: string,
): SaveMarketingNewCustomerSettingsDto {
  return {
    storeId,
    giftEnabled: form.giftEnabled,
    giftType: form.giftType,
    directReduceAmount:
      form.giftType === 'direct'
        ? toNullableNumber(form.directReduceAmount)
        : null,
    directMinimumSpend:
      form.giftType === 'direct'
        ? toNullableNumber(form.directMinimumSpend)
        : null,
    inviteEnabled: form.inviteEnabled,
    shareChannels: [...form.shareChannels],
    welcomeCoupons: buildSaveCouponRules(form.welcomeCoupons),
    inviterCoupons: buildSaveCouponRules(form.inviterCoupons),
    inviteeCoupons: buildSaveCouponRules(form.inviteeCoupons),
  };
}

/** 构建保存券列表。 */
export function buildSaveCouponRules(
  items: NewCustomerCouponFormItem[],
): SaveMarketingNewCustomerCouponRuleDto[] {
  return items.map((item) => ({
    couponType: item.couponType,
    value:
      item.couponType === 'free_shipping' ? null : toNullableNumber(item.value),
    minimumSpend: toNullableNumber(item.minimumSpend),
    validDays: Math.max(1, Math.min(365, Math.floor(item.validDays))),
  }));
}

/** 解析可空数字。 */
export function toNullableNumber(value: null | number | string) {
  if (value === null || value === undefined || value === '') {
    return null;
  }
  const parsed = Number(value);
  if (Number.isNaN(parsed)) {
    return null;
  }
  return parsed;
}
