export const DEFAULT_QUICK_OPTIONS = [
  { name: '九五折', value: 95 },
  { name: '九折', value: 90 },
  { name: '八五折', value: 85 },
  { name: '八折', value: 80 },
  { name: '涨10%', value: 110 },
  { name: '涨20%', value: 120 },
]

const DEFAULT_MARKUP_OPTIONS = [
  { name: '涨10%', value: 110 },
  { name: '涨20%', value: 120 },
]

export function normalizeQuickOptions(raw) {
  if (!Array.isArray(raw)) return [...DEFAULT_QUICK_OPTIONS]
  const list = []
  for (const item of raw) {
    if (item && typeof item === 'object' && item.value != null) {
      const val = Number(item.value)
      if (val > 0) {
        list.push({ name: String(item.name || `${val}%`), value: val })
      }
    } else if (typeof item === 'number' && item > 0) {
      list.push({ name: `${item}%`, value: item })
    }
  }
  if (!list.length) return [...DEFAULT_QUICK_OPTIONS]
  if (!list.some((o) => o.value > 100)) {
    return [...list, ...DEFAULT_MARKUP_OPTIONS]
  }
  return list
}

export function applyRatioPrice(originPrice, discount) {
  const origin = Number(originPrice || 0)
  const ratio = Number(discount) > 0 ? Number(discount) : 100
  if (!origin || origin <= 0) return 0
  return Math.round(origin * (ratio / 100) * 10000) / 10000
}

export function formatPriceDiscountLabel(discount) {
  const d = Number(discount) || 100
  if (d <= 0 || d === 100) return null
  if (d < 100) {
    if (d % 10 === 0 && d >= 10) return `${d / 10}折`
    return `折扣 ${d}%`
  }
  return `涨 ${d - 100}%`
}

export function applyRatioToDrug(drug, discount, scope) {
  if (!drug) return drug
  const originPrice = Number(drug.origin_price ?? drug.price ?? 0)
  const originBuy = Number(drug.origin_buy_price ?? drug.buy_price ?? 0)
  const next = {
    ...drug,
    origin_price: drug.origin_price ?? originPrice,
    origin_buy_price: drug.origin_buy_price ?? originBuy,
    price: applyRatioPrice(originPrice, discount),
  }
  if (scope === 'both' && originBuy > 0) {
    next.buy_price = applyRatioPrice(originBuy, discount)
  }
  return next
}

export function applyRatioToDrugs(drugs, discount, scope) {
  return (drugs || []).map((d) => applyRatioToDrug(d, discount, scope))
}

/** @deprecated */
export function applyPercentToDrug(drug, adjustType, percent, scope) {
  let discount = Number(percent)
  if (adjustType === 'markup') discount = Math.round(100 + Number(percent))
  return applyRatioToDrug(drug, discount, scope)
}
