export function resolveSkuNameQuantity(productName: unknown): number {
  const text = String(productName || '').trim()
  if (!text) return 1

  const arabicMatch = text.match(/(\d+)\s*(?:个|份|张|枚)/)
  if (arabicMatch) {
    const parsed = Number(arabicMatch[1])
    if (Number.isSafeInteger(parsed) && parsed > 0) return parsed
  }

  const chineseMatch = text.match(/([零一二三四五六七八九十百千两]+)\s*(?:个|份|张|枚)/)
  if (chineseMatch?.[1]) {
    const parsed = parseChineseNumber(chineseMatch[1])
    if (parsed > 0) return parsed
  }

  return 1
}

export function resolveWorkOrderRulePricing(input: {
  skuQuantity: number
  unitPriceFen: number
  fixedRewardAmount: number
  sharingEnabled: boolean
  sharingAutoFromOrder: boolean
  sharingTotalQuantity: number
  sharingUnitReward: number
}) {
  const skuQuantity = Math.max(1, Number(input.skuQuantity) || 1)
  const unitPriceFen = Math.max(0, Number(input.unitPriceFen) || 0)
  const sharingTotalQuantity = input.sharingAutoFromOrder
    ? skuQuantity
    : Math.max(1, Number(input.sharingTotalQuantity) || 1)
  const sharingUnitReward = input.sharingAutoFromOrder
    ? unitPriceFen
    : Math.max(0, Number(input.sharingUnitReward) || 0)
  const rewardAmount = input.sharingEnabled
    ? sharingTotalQuantity * sharingUnitReward
    : unitPriceFen > 0
      ? unitPriceFen * skuQuantity
      : Math.max(0, Number(input.fixedRewardAmount) || 0)

  return { sharingTotalQuantity, sharingUnitReward, rewardAmount }
}

export function resolveWorkOrderSharingEnabled(
  configuredEnabled: boolean,
  totalQuantity: number,
): boolean {
  return configuredEnabled && Math.max(1, Number(totalQuantity) || 1) > 1
}

export function isWorkOrderSharingFilled(
  sharingEnabled: boolean,
  totalQuantity: number,
  joinedQuantity: number,
): boolean {
  return (
    sharingEnabled &&
    Math.max(0, Number(joinedQuantity) || 0) >= Math.max(1, Number(totalQuantity) || 1)
  )
}

const CHINESE_DIGITS: Record<string, number> = {
  零: 0,
  一: 1,
  二: 2,
  两: 2,
  三: 3,
  四: 4,
  五: 5,
  六: 6,
  七: 7,
  八: 8,
  九: 9,
}

function parseChineseNumber(text: string): number {
  let section = 0
  let digit = 0
  for (const char of text) {
    if (char === '十') {
      section += (digit || 1) * 10
      digit = 0
    } else if (char === '百') {
      section += (digit || 1) * 100
      digit = 0
    } else if (char === '千') {
      section += (digit || 1) * 1000
      digit = 0
    } else if (char in CHINESE_DIGITS) {
      digit = CHINESE_DIGITS[char] ?? 0
    }
  }
  return section + digit
}
