import type { PackagingFeeTierDto, StoreOtherFeesDto } from '#/api/store-fees';
import type {
  StoreFeesFormState,
  StoreFeesSettingsSnapshot,
} from '#/views/store/fees/types';

import { MAX_PACKAGING_TIER_COUNT } from './constants';

/** 文件职责：费用设置页面工具方法。 */

/** 深拷贝包装费阶梯。 */
export function cloneTiers(source: PackagingFeeTierDto[]) {
  return source.map((item) => ({ ...item }));
}

/** 深拷贝其他费用配置。 */
export function cloneOtherFees(source: StoreOtherFeesDto): StoreOtherFeesDto {
  return {
    cutlery: { ...source.cutlery },
    rush: { ...source.rush },
  };
}

/** 深拷贝页面表单配置。 */
export function cloneFeesForm(source: StoreFeesFormState): StoreFeesFormState {
  return {
    minimumOrderAmount: source.minimumOrderAmount,
    baseDeliveryFee: source.baseDeliveryFee,
    platformServiceRate: source.platformServiceRate,
    freeDeliveryThreshold: source.freeDeliveryThreshold,
    packagingFeeMode: source.packagingFeeMode,
    orderPackagingFeeMode: source.orderPackagingFeeMode,
    fixedPackagingFee: source.fixedPackagingFee,
    packagingFeeTiers: cloneTiers(source.packagingFeeTiers),
    otherFees: cloneOtherFees(source.otherFees),
  };
}

/** 生成页面快照。 */
export function createSettingsSnapshot(
  source: StoreFeesFormState,
): StoreFeesSettingsSnapshot {
  return cloneFeesForm(source);
}

/** 生成包装费阶梯 ID。 */
export function createTierId() {
  return `packaging-tier-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
}

/** 归一化金额。 */
export function normalizeMoney(value: number, fallback = 0) {
  const parsed = Number(value);
  if (!Number.isFinite(parsed)) return fallback;
  const safeValue = Math.max(0, parsed);
  return Math.round(safeValue * 100) / 100;
}

/** 阶梯排序（按起始金额升序，无上限档位置于末尾）。 */
export function sortTiers(source: PackagingFeeTierDto[]) {
  return cloneTiers(source).toSorted((a, b) => {
    if (a.minAmount !== b.minAmount) return a.minAmount - b.minAmount;
    if (a.maxAmount === null) return 1;
    if (b.maxAmount === null) return -1;
    return a.maxAmount - b.maxAmount;
  });
}

/** 输出金额格式。 */
export function formatCurrency(value: number) {
  return `¥${normalizeMoney(value).toFixed(2)}`;
}

/** 输出阶梯区间文本。 */
export function formatTierRange(tier: PackagingFeeTierDto) {
  if (tier.maxAmount === null) {
    return `${normalizeMoney(tier.minAmount).toFixed(2)} 元以上`;
  }
  return `${normalizeMoney(tier.minAmount).toFixed(2)} ~ ${normalizeMoney(
    tier.maxAmount,
  ).toFixed(2)} 元`;
}

/** 校验阶梯列表连续性与合法性。 */
export function validateTierList(tiers: PackagingFeeTierDto[]) {
  if (tiers.length === 0) return '请至少配置一档阶梯包装费';
  if (tiers.length > MAX_PACKAGING_TIER_COUNT) {
    return `阶梯包装费最多支持 ${MAX_PACKAGING_TIER_COUNT} 档`;
  }

  const sorted = sortTiers(tiers).map((item, index) => ({
    ...item,
    minAmount: normalizeMoney(item.minAmount, 0),
    maxAmount:
      item.maxAmount === null
        ? null
        : normalizeMoney(item.maxAmount, item.minAmount),
    fee: normalizeMoney(item.fee, 0),
    sort: index + 1,
  }));

  for (const [index, tier] of sorted.entries()) {
    const label = `第${index + 1}档`;
    if (tier.maxAmount !== null && tier.maxAmount <= tier.minAmount) {
      return `${label}结束金额必须大于起始金额`;
    }
    if (tier.fee < 0) {
      return `${label}包装费不能小于 0`;
    }
    if (index < sorted.length - 1 && tier.maxAmount === null) {
      return `${label}为无上限档位时，必须放在最后一档`;
    }
    if (index > 0) {
      const previous = sorted[index - 1];
      if (previous) {
        if (previous.maxAmount === null) {
          return `第${index}档已是无上限，后续不能继续配置`;
        }
        if (tier.minAmount < previous.maxAmount) {
          return `${label}与前一档区间重叠，请调整金额区间`;
        }
      }
    }
  }

  return '';
}
