import type { Dayjs } from 'dayjs';

import type {
  MarketingSeckillDetailDto,
  MarketingSeckillEditorStatus,
  SaveMarketingSeckillDto,
} from '#/api/marketing';
import type {
  SeckillCardViewModel,
  SeckillEditorForm,
  SeckillEditorProductForm,
  SeckillEditorSessionForm,
} from '#/views/marketing/seckill/types';

/**
 * 文件职责：秒杀活动页面纯函数工具。
 */
import dayjs from 'dayjs';

import {
  createDefaultSeckillEditorForm,
  createDefaultSeckillProductForm,
  createDefaultSeckillSessionForm,
} 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;
}

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

/** 计算进度百分比。 */
export function resolveProgressPercent(soldCount: number, stockLimit: number) {
  if (stockLimit <= 0) {
    return 0;
  }
  const percent = (soldCount / stockLimit) * 100;
  return Math.max(0, Math.min(100, Math.round(percent)));
}

/** 根据进度计算条颜色。 */
export function resolveProgressClass(percent: number) {
  if (percent >= 100) {
    return 'red';
  }
  if (percent >= 70) {
    return 'orange';
  }
  return 'green';
}

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

/** 活动时间文案。 */
export function resolveCardTimeText(item: SeckillCardViewModel) {
  if (item.activityType === 'hourly') {
    if (item.sessions.length === 0) {
      return '场次未配置';
    }

    const sessionText = item.sessions
      .map((session) => `${session.startTime} 场`)
      .join(' / ');
    return `每天 ${sessionText}`;
  }

  if (item.displayStatus === 'upcoming' && item.startDate && item.timeStart) {
    return `${item.startDate} ${item.timeStart} 开始`;
  }

  if (item.displayStatus === 'ended' && item.startDate && item.endDate) {
    return `${item.startDate} ~ ${item.endDate}`;
  }

  if (item.timeStart && item.timeEnd) {
    return `每天 ${item.timeStart} - ${item.timeEnd}`;
  }

  return '时间待设置';
}

/** 活动汇总数据。 */
export function resolveCardSummary(item: SeckillCardViewModel) {
  return [
    {
      label: '参与人数',
      value: `${formatInteger(item.metrics.participantCount)}人`,
    },
    {
      label: '成交',
      value: `${formatInteger(item.metrics.dealCount)}单`,
    },
    {
      label: '转化率',
      value: `${trimDecimal(item.metrics.conversionRate)}%`,
    },
  ];
}

/** 映射详情到编辑表单。 */
export function mapDetailToEditorForm(
  detail: MarketingSeckillDetailDto,
): SeckillEditorForm {
  const form = createDefaultSeckillEditorForm();
  form.id = detail.id;
  form.name = detail.name;
  form.activityType = detail.activityType;
  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.sessions = detail.sessions.map((item) =>
    createDefaultSeckillSessionForm({
      startTime: item.startTime,
      durationMinutes: item.durationMinutes,
    }),
  );
  form.channels = [...detail.channels];
  form.perUserLimit = detail.perUserLimit;
  form.preheatEnabled = detail.preheatEnabled;
  form.preheatHours = detail.preheatHours;
  form.products = detail.products.map((item) =>
    createDefaultSeckillProductForm({
      productId: item.productId,
      categoryId: item.categoryId,
      categoryName: item.categoryName,
      name: item.name,
      spuCode: item.spuCode,
      status: item.status,
      originalPrice: item.originalPrice,
      seckillPrice: item.seckillPrice,
      stockLimit: item.stockLimit,
      perUserLimit: item.perUserLimit,
      soldCount: item.soldCount,
    }),
  );
  form.metrics = { ...detail.metrics };
  form.status = detail.status;
  form.storeIds = [...detail.storeIds];
  return form;
}

/** 构建保存请求。 */
export function buildSaveSeckillPayload(
  form: SeckillEditorForm,
  storeId: string,
): SaveMarketingSeckillDto {
  const [startDate, endDate] = (form.validDateRange ?? []) as [Dayjs, Dayjs];
  const [timeStart, timeEnd] = (form.timeRange ?? []) as [Dayjs, Dayjs];
  const isTimedActivity = form.activityType === 'timed';

  return {
    id: form.id || undefined,
    storeId,
    name: form.name.trim(),
    activityType: form.activityType,
    startDate:
      isTimedActivity && form.validDateRange && startDate
        ? startDate.format('YYYY-MM-DD')
        : undefined,
    endDate:
      isTimedActivity && form.validDateRange && endDate
        ? endDate.format('YYYY-MM-DD')
        : undefined,
    timeStart:
      isTimedActivity && form.timeRange && timeStart
        ? timeStart.format('HH:mm')
        : undefined,
    timeEnd:
      isTimedActivity && form.timeRange && timeEnd
        ? timeEnd.format('HH:mm')
        : undefined,
    sessions:
      form.activityType === 'hourly'
        ? form.sessions
            .filter((item) => item.startTime.trim())
            .map((item) => ({
              startTime: item.startTime,
              durationMinutes: Number(item.durationMinutes ?? 0),
            }))
        : [],
    channels: [...form.channels],
    perUserLimit: form.perUserLimit,
    preheatEnabled: form.preheatEnabled,
    preheatHours: form.preheatEnabled ? form.preheatHours : null,
    products: form.products.map((item) => ({
      productId: item.productId,
      seckillPrice: Number(item.seckillPrice || 0),
      stockLimit: Number(item.stockLimit || 0),
      perUserLimit: item.perUserLimit,
    })),
    metrics: { ...form.metrics },
  };
}

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

/** 深拷贝场次表单项。 */
export function cloneSessionForm(
  session: SeckillEditorSessionForm,
): SeckillEditorSessionForm {
  return {
    key: session.key,
    startTime: session.startTime,
    durationMinutes: session.durationMinutes,
  };
}

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