type HallProduct = {
  productName?: string
  rewardAmount?: number
  freezeDepositAmount?: number
  depositFreeAmount?: number
  sharing?: {
    enabled: boolean
    totalQuantity: number
    unitReward?: number
  }
  sharingProgress?: {
    joinedQuantity: number
  }
}

const PRODUCT_QUANTITY_PATTERN = /(\d+|[零一二三四五六七八九十百千两]+)(\s*)(个|份|张|枚)/

/** 计算大厅当前仍可承接的份数。 */
export function resolveHallRemainingQuantity(order: HallProduct): number {
  if (!order.sharing?.enabled) return 0
  const totalQuantity = Math.max(1, Number(order.sharing.totalQuantity) || 1)
  const joinedQuantity = Math.max(0, Number(order.sharingProgress?.joinedQuantity || 0))
  return Math.max(0, totalQuantity - joinedQuantity)
}

/** 大厅拼单标题展示剩余可承接数量，避免把原始总规格误认为剩余库存。 */
export function resolveHallProductName(order: HallProduct): string {
  const productName = String(order.productName || '').trim()
  if (!productName || !order.sharing?.enabled) return productName

  const remainingQuantity = resolveHallRemainingQuantity(order)
  return productName.replace(
    PRODUCT_QUANTITY_PATTERN,
    (_matched, _quantity: string, spacing: string, unit: string) =>
      `${remainingQuantity}${spacing}${unit}`,
  )
}

/** 拼单卡片金额展示一次性抢走全部剩余份数可获得的报酬。 */
export function resolveHallRewardAmount(order: HallProduct): number {
  if (!order.sharing?.enabled) return Number(order.rewardAmount || 0)
  return resolveHallRemainingQuantity(order) * Number(order.sharing.unitReward || 0)
}

/** 拼单卡片按当前剩余份数计算个人免押后的实际保证金。 */
export function resolveHallDepositAmount(order: HallProduct): number {
  if (!order.sharing?.enabled) return Number(order.freezeDepositAmount || 0)
  const totalQuantity = Math.max(1, Number(order.sharing.totalQuantity) || 1)
  const depositFreeAmount = Math.max(0, Number(order.depositFreeAmount || 0))
  const requiredDepositAmount = Number(order.freezeDepositAmount || 0) + depositFreeAmount
  return Math.max(
    0,
    Math.round((requiredDepositAmount * resolveHallRemainingQuantity(order)) / totalQuantity) -
      depositFreeAmount,
  )
}
