import type { Dayjs } from 'dayjs';

import type {
  MarketingFullReductionDetailDto,
  MarketingFullReductionDisplayStatus,
  MarketingFullReductionGiftRuleDto,
  MarketingFullReductionScopeRuleDto,
  MarketingFullReductionSecondHalfDiscountType,
  MarketingFullReductionSecondHalfRuleDto,
  SaveMarketingFullReductionDto,
} from '#/api/marketing';
import type {
  FullReductionCardViewModel,
  FullReductionEditorForm,
  FullReductionScopeForm,
} from '#/views/marketing/full-reduction/types';

/**
 * 文件职责：满减活动页面纯函数。
 * 1. 负责列表文案、样式、规则可视化映射。
 * 2. 负责详情与编辑表单互转、保存请求构建。
 */
import dayjs from 'dayjs';

import {
  createDefaultFullReductionEditorForm,
  createDefaultGiftRuleForm,
  createDefaultScopeForm,
  createDefaultSecondHalfRuleForm,
  createDefaultTierForm,
  FULL_REDUCTION_ACTIVITY_TEXT_MAP,
  FULL_REDUCTION_CHANNEL_TEXT_MAP,
  FULL_REDUCTION_SECOND_HALF_DISCOUNT_OPTIONS,
} from './constants';

/** 千分位整数格式化。 */
export function formatInteger(value: number) {
  return Intl.NumberFormat('zh-CN', {
    maximumFractionDigits: 0,
  }).format(value);
}

/** 货币格式化。 */
export function formatCurrency(value: number, withSymbol = true) {
  const result = trimDecimal(Number(value || 0));
  return withSymbol ? `¥${result}` : result;
}

/** 去除末尾小数 0。 */
export function trimDecimal(value: number) {
  return Number(value || 0)
    .toFixed(2)
    .replace(/\.?0+$/, '');
}

/** 活动类型文案。 */
export function resolveActivityTypeLabel(
  value: FullReductionCardViewModel['activityType'],
) {
  return FULL_REDUCTION_ACTIVITY_TEXT_MAP[value];
}

/** 第二份折扣文案。 */
export function resolveSecondHalfDiscountLabel(
  value: MarketingFullReductionSecondHalfDiscountType,
) {
  return (
    FULL_REDUCTION_SECOND_HALF_DISCOUNT_OPTIONS.find(
      (item) => item.value === value,
    )?.label ?? '5折'
  );
}

/** 活动规则短标签。 */
export function resolveRulePills(item: FullReductionCardViewModel) {
  if (item.activityType === 'reduce') {
    return [...item.reduceTiers]
      .toSorted((first, second) => first.meetAmount - second.meetAmount)
      .map(
        (tier) =>
          `满${trimDecimal(tier.meetAmount)}减${trimDecimal(tier.reduceAmount)}`,
      );
  }

  if (item.activityType === 'gift' && item.giftRule) {
    return [
      `买${item.giftRule.buyQuantity}件赠${item.giftRule.giftQuantity}件`,
    ];
  }

  const discountType = item.secondHalfRule?.discountType ?? 'half';
  return [`第2份${resolveSecondHalfDiscountLabel(discountType)}`];
}

/** 渠道文案。 */
export function resolveChannelsText(
  channels: FullReductionCardViewModel['channels'],
) {
  const ordered = ['delivery', 'pickup', 'dine_in'] as const;
  const labels = ordered
    .filter((channel) => channels.includes(channel))
    .map((channel) => FULL_REDUCTION_CHANNEL_TEXT_MAP[channel]);

  return labels.length > 0 ? labels.join(' / ') : '--';
}

/** 门店范围文案。 */
export function resolveStoreScopeText(
  item: FullReductionCardViewModel,
  storeNameMap: Record<string, string>,
) {
  if (item.storeScopeMode === 'all') {
    return '全部门店';
  }

  const storeNames = item.storeIds
    .map((storeId) => storeNameMap[storeId])
    .filter((name) => typeof name === 'string' && name.length > 0);

  if (storeNames.length === 0) {
    return '指定门店';
  }

  return storeNames.join(' / ');
}

/** 商品范围摘要文案。 */
export function resolveScopeSummary(
  scope: FullReductionScopeForm | MarketingFullReductionScopeRuleDto,
) {
  if (scope.scopeType === 'all') {
    return '全部商品';
  }

  if (scope.scopeType === 'category') {
    return `已选 ${scope.categoryIds.length} 个分类`;
  }

  return `已选 ${scope.productIds.length} 个商品`;
}

/** 卡片附加信息文案。 */
export function resolveExtraMetaText(item: FullReductionCardViewModel) {
  if (item.activityType === 'gift' && item.giftRule) {
    return item.giftRule.giftScopeType === 'same_lowest'
      ? '赠品：同商品（价低者）'
      : `赠品：${resolveScopeSummary(item.giftRule.giftScope)}`;
  }

  if (item.activityType === 'second_half' && item.secondHalfRule) {
    return `适用：${resolveScopeSummary(item.secondHalfRule.applicableScope)}`;
  }

  return '';
}

/** 卡片数据指标。 */
export function resolveCardMetrics(item: FullReductionCardViewModel) {
  if (item.activityType === 'gift') {
    return [
      {
        label: '参与订单',
        value: `${formatInteger(item.metrics.participatingOrderCount)}单`,
      },
      {
        label: '赠出商品',
        value: `${formatInteger(item.metrics.giftedCount)}件`,
      },
      {
        label: '带动销售',
        value: formatCurrency(item.metrics.drivenSalesAmount),
      },
    ];
  }

  if (item.activityType === 'second_half') {
    return [
      {
        label: '参与订单',
        value: `${formatInteger(item.metrics.participatingOrderCount)}单`,
      },
      {
        label: '优惠总额',
        value: formatCurrency(item.metrics.discountTotalAmount),
      },
      {
        label: '连带率提升',
        value:
          item.metrics.attachRateIncreasePercent > 0
            ? `${trimDecimal(item.metrics.attachRateIncreasePercent)}%`
            : '--',
      },
    ];
  }

  return [
    {
      label: '参与订单',
      value: `${formatInteger(item.metrics.participatingOrderCount)}单`,
    },
    {
      label: '优惠总额',
      value: formatCurrency(item.metrics.discountTotalAmount),
    },
    {
      label: '客单价提升',
      value:
        item.metrics.ticketIncreaseAmount > 0
          ? formatCurrency(item.metrics.ticketIncreaseAmount)
          : '--',
    },
  ];
}

/** 详情映射为编辑表单。 */
export function mapDetailToEditorForm(
  detail: MarketingFullReductionDetailDto,
): FullReductionEditorForm {
  const form = createDefaultFullReductionEditorForm();
  form.id = detail.id;
  form.name = detail.name;
  form.activityType = detail.activityType;
  form.reduceTiers =
    detail.reduceTiers.length > 0
      ? detail.reduceTiers.map((tier) =>
          createDefaultTierForm(tier.meetAmount, tier.reduceAmount),
        )
      : [createDefaultTierForm()];
  form.giftRule = mapGiftRuleToForm(detail.giftRule);
  form.secondHalfRule = mapSecondHalfRuleToForm(detail.secondHalfRule);
  form.validDateRange = [dayjs(detail.startDate), dayjs(detail.endDate)];
  form.channels = [...detail.channels];
  form.storeScopeMode = detail.storeScopeMode;
  form.storeIds = [...detail.storeIds];
  form.scopeStoreId = detail.scopeStoreId;
  form.stackWithCoupon = detail.stackWithCoupon;
  form.description = detail.description ?? '';
  form.metrics = { ...detail.metrics };
  return form;
}

/** 编辑表单构建保存请求。 */
export function buildSaveFullReductionPayload(
  form: FullReductionEditorForm,
  storeId: string,
  scopeStoreId: string,
): SaveMarketingFullReductionDto {
  const [start, end] = (form.validDateRange ?? []) as [Dayjs, Dayjs];

  return {
    id: form.id || undefined,
    storeId,
    scopeStoreId,
    name: form.name.trim(),
    activityType: form.activityType,
    reduceTiers:
      form.activityType === 'reduce'
        ? form.reduceTiers.map((tier) => ({
            meetAmount: Number(tier.meetAmount || 0),
            reduceAmount: Number(tier.reduceAmount || 0),
          }))
        : [],
    giftRule:
      form.activityType === 'gift'
        ? {
            buyQuantity: Math.floor(Number(form.giftRule.buyQuantity || 0)),
            giftQuantity: Math.floor(Number(form.giftRule.giftQuantity || 0)),
            giftScopeType: form.giftRule.giftScopeType,
            applicableScope: normalizeScopeForSave(
              form.giftRule.applicableScope,
            ),
            giftScope:
              form.giftRule.giftScopeType === 'specified'
                ? normalizeScopeForSave(form.giftRule.giftScope)
                : createDefaultScopeForm('all'),
          }
        : undefined,
    secondHalfRule:
      form.activityType === 'second_half'
        ? {
            discountType: form.secondHalfRule.discountType,
            applicableScope: normalizeScopeForSave(
              form.secondHalfRule.applicableScope,
            ),
          }
        : undefined,
    startDate: start.format('YYYY-MM-DD'),
    endDate: end.format('YYYY-MM-DD'),
    channels: [...form.channels],
    storeScopeMode: form.storeScopeMode,
    storeIds: form.storeScopeMode === 'stores' ? [...form.storeIds] : undefined,
    stackWithCoupon: form.stackWithCoupon,
    description: form.description.trim() || undefined,
    metrics: { ...form.metrics },
  };
}

/** 深拷贝商品范围。 */
export function cloneScopeForm(
  scope: FullReductionScopeForm,
): FullReductionScopeForm {
  return {
    scopeType: scope.scopeType,
    categoryIds: [...scope.categoryIds],
    productIds: [...scope.productIds],
  };
}

/** 校验状态映射。 */
export function isEndedStatus(status: MarketingFullReductionDisplayStatus) {
  return status === 'ended';
}

function mapGiftRuleToForm(rule?: MarketingFullReductionGiftRuleDto) {
  const form = createDefaultGiftRuleForm();
  if (!rule) {
    return form;
  }

  form.buyQuantity = rule.buyQuantity;
  form.giftQuantity = rule.giftQuantity;
  form.giftScopeType = rule.giftScopeType;
  form.applicableScope = mapScopeToForm(rule.applicableScope, 'all');
  form.giftScope =
    rule.giftScopeType === 'specified'
      ? mapScopeToForm(rule.giftScope, 'product')
      : createDefaultScopeForm('all');
  return form;
}

function mapSecondHalfRuleToForm(
  rule?: MarketingFullReductionSecondHalfRuleDto,
) {
  const form = createDefaultSecondHalfRuleForm();
  if (!rule) {
    return form;
  }
  form.discountType = rule.discountType;
  form.applicableScope = mapScopeToForm(rule.applicableScope, 'category');
  return form;
}

function mapScopeToForm(
  scope: MarketingFullReductionScopeRuleDto | undefined,
  fallbackScopeType: FullReductionScopeForm['scopeType'],
): FullReductionScopeForm {
  if (!scope) {
    return createDefaultScopeForm(fallbackScopeType);
  }

  return {
    scopeType: scope.scopeType,
    categoryIds: [...scope.categoryIds],
    productIds: [...scope.productIds],
  };
}

function normalizeScopeForSave(scope: FullReductionScopeForm) {
  if (scope.scopeType === 'all') {
    return createDefaultScopeForm('all');
  }

  if (scope.scopeType === 'category') {
    return {
      scopeType: 'category' as const,
      categoryIds: [...scope.categoryIds],
      productIds: [],
    };
  }

  return {
    scopeType: 'product' as const,
    categoryIds: [],
    productIds: [...scope.productIds],
  };
}
