import type { Dayjs } from 'dayjs';

import type {
  MarketingFlashSaleDetailDto,
  MarketingFlashSaleEditorStatus,
  SaveMarketingFlashSaleDto,
} from '#/api/marketing';
import type {
  FlashSaleCardViewModel,
  FlashSaleEditorForm,
  FlashSaleEditorProductForm,
} from '#/views/marketing/flash-sale/types';

/**
 * 文件职责：限时折扣页面纯函数工具。
 */
import dayjs from 'dayjs';

import {
  createDefaultFlashSaleEditorForm,
  createDefaultFlashSaleProductForm,
  FLASH_SALE_WEEKDAY_OPTIONS,
} from './constants';

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

/** 格式化金额。 */
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 resolveDiscountRateLabel(
  originalPrice: number,
  discountPrice: null | number,
) {
  if (!discountPrice || discountPrice <= 0 || originalPrice <= 0) {
    return '-';
  }
  if (discountPrice > originalPrice) {
    return '-';
  }
  const rate = Number(((discountPrice / originalPrice) * 10).toFixed(1));
  return `${trimDecimal(rate)}折`;
}

/** 商品限购文案。 */
export function resolveProductLimitText(limit: null | number) {
  if (!limit || limit <= 0) {
    return '不限';
  }
  return `${formatInteger(limit)}件/人`;
}

/** 循环星期文案。 */
export function resolveWeekDaysText(weekDays: number[]) {
  if (weekDays.length === 0) {
    return '';
  }

  const sorted = [...new Set(weekDays)]
    .filter((item) => item >= 1 && item <= 7)
    .toSorted((first, second) => first - second);

  if (sorted.length === 7) {
    return '每天';
  }

  const weekday = [1, 2, 3, 4, 5];
  const weekend = [6, 7];
  if (weekday.every((item) => sorted.includes(item)) && sorted.length === 5) {
    return '工作日';
  }
  if (weekend.every((item) => sorted.includes(item)) && sorted.length === 2) {
    return '周末';
  }

  const labels = sorted
    .map(
      (item) =>
        FLASH_SALE_WEEKDAY_OPTIONS.find((option) => option.value === item)
          ?.label ?? '',
    )
    .filter(Boolean);

  return labels.join('、');
}

/** 卡片周期角标文案。 */
export function resolveRecurringBadgeText(item: FlashSaleCardViewModel) {
  if (item.cycleType !== 'recurring') {
    return '';
  }
  const weekText = resolveWeekDaysText(item.weekDays);
  return weekText ? `每${weekText}` : '周期循环';
}

/** 卡片日期范围文案。 */
export function resolveDateRangeText(item: FlashSaleCardViewModel) {
  if (
    item.cycleType === 'recurring' &&
    item.recurringDateMode === 'long_term' &&
    (!item.startDate || !item.endDate)
  ) {
    return '长期有效';
  }

  if (item.startDate && item.endDate) {
    return `${item.startDate} ~ ${item.endDate}`;
  }
  return '长期有效';
}

/** 卡片时段文案。 */
export function resolveTimeRangeText(item: FlashSaleCardViewModel) {
  if (item.timeStart && item.timeEnd) {
    return `${item.timeStart} - ${item.timeEnd}`;
  }
  return '全天有效';
}

/** 卡片汇总指标。 */
export function resolveCardSummary(item: FlashSaleCardViewModel) {
  const summary = [
    {
      label: '活动销量',
      value: `${formatInteger(item.metrics.activitySalesCount)}单`,
    },
    {
      label: '折扣总额',
      value: formatCurrency(item.metrics.discountTotalAmount),
    },
  ];

  if (item.cycleType === 'recurring') {
    summary.push({
      label: '已循环',
      value: `${formatInteger(item.metrics.loopedWeeks)}周`,
    });
  }

  return summary;
}

/** 详情映射编辑表单。 */
export function mapDetailToEditorForm(
  detail: MarketingFlashSaleDetailDto,
): FlashSaleEditorForm {
  const form = createDefaultFlashSaleEditorForm();
  form.id = detail.id;
  form.name = detail.name;
  form.cycleType = detail.cycleType;
  form.recurringDateMode = detail.recurringDateMode;
  form.validDateRange =
    detail.startDate && detail.endDate
      ? [dayjs(detail.startDate), dayjs(detail.endDate)]
      : null;
  form.timeRange =
    detail.timeStart && detail.timeEnd
      ? [
          dayjs(`2000-01-01 ${detail.timeStart}`),
          dayjs(`2000-01-01 ${detail.timeEnd}`),
        ]
      : null;
  form.weekDays = [...detail.weekDays];
  form.channels = [...detail.channels];
  form.perUserLimit = detail.perUserLimit;
  form.products = detail.products.map((item) =>
    createDefaultFlashSaleProductForm({
      productId: item.productId,
      categoryId: item.categoryId,
      categoryName: item.categoryName,
      name: item.name,
      spuCode: item.spuCode,
      status: item.status,
      originalPrice: item.originalPrice,
      discountPrice: item.discountPrice,
      perUserLimit: item.perUserLimit,
      soldCount: item.soldCount,
    }),
  );
  form.metrics = { ...detail.metrics };
  form.status = detail.status;
  form.storeIds = [...detail.storeIds];
  return form;
}

/** 构建保存请求。 */
export function buildSaveFlashSalePayload(
  form: FlashSaleEditorForm,
  storeId: string,
): SaveMarketingFlashSaleDto {
  const [startDate, endDate] = (form.validDateRange ?? []) as [Dayjs, Dayjs];
  const [timeStart, timeEnd] = (form.timeRange ?? []) as [Dayjs, Dayjs];

  return {
    id: form.id || undefined,
    storeId,
    name: form.name.trim(),
    cycleType: form.cycleType,
    recurringDateMode: form.recurringDateMode,
    startDate:
      form.validDateRange && startDate
        ? startDate.format('YYYY-MM-DD')
        : undefined,
    endDate:
      form.validDateRange && endDate ? endDate.format('YYYY-MM-DD') : undefined,
    timeStart:
      form.timeRange && timeStart ? timeStart.format('HH:mm') : undefined,
    timeEnd: form.timeRange && timeEnd ? timeEnd.format('HH:mm') : undefined,
    weekDays: form.cycleType === 'recurring' ? [...form.weekDays] : [],
    channels: [...form.channels],
    perUserLimit: form.perUserLimit,
    storeIds: [...form.storeIds],
    products: form.products.map((item) => ({
      productId: item.productId,
      discountPrice: Number(item.discountPrice || 0),
      perUserLimit: item.perUserLimit,
    })),
    metrics: { ...form.metrics },
  };
}

/** 深拷贝商品表单项。 */
export function cloneProductForm(
  product: FlashSaleEditorProductForm,
): FlashSaleEditorProductForm {
  return {
    productId: product.productId,
    categoryId: product.categoryId,
    categoryName: product.categoryName,
    name: product.name,
    spuCode: product.spuCode,
    status: product.status,
    originalPrice: product.originalPrice,
    discountPrice: product.discountPrice,
    perUserLimit: product.perUserLimit,
    soldCount: product.soldCount,
  };
}

/** 是否已结束。 */
export function isEndedStatus(status: MarketingFlashSaleEditorStatus) {
  return status === 'completed';
}
