/** 彩金池选项/关联行通用结构 */
export interface LotteryPoolOption {
  id: number
  name?: string
  remark?: string
  display_name?: string
}

/** 彩金池后台展示名（奖池名称）：优先 display_name / remark，不用内部 name 作为首选 */
export function lotteryPoolDisplayLabel(item?: LotteryPoolOption | null): string {
  if (!item) {
    return '-'
  }
  const display = String(item.display_name ?? '').trim()
  if (display) {
    return display
  }
  const remark = String(item.remark ?? '').trim()
  if (remark) {
    return remark
  }
  return String(item.name ?? '').trim() || '-'
}

/** 下拉选项文案：默认仅奖池名称；withId=true 时附带 ID */
export function lotteryPoolOptionLabel(
  item: LotteryPoolOption,
  options?: { withId?: boolean }
): string {
  const label = lotteryPoolDisplayLabel(item)
  if (options?.withId && item.id > 0) {
    return label !== '-' ? `${label} (#${item.id})` : `#${item.id}`
  }
  return label !== '-' ? label : `#${item.id}`
}

/** 列表行关联彩金池（含 diceLotteryPoolConfig 关联） */
export function lotteryPoolRowLabel(row?: {
  diceLotteryPoolConfig?: LotteryPoolOption | null
  lottery_config_id?: number | null | string
} | null): string {
  if (!row) {
    return '-'
  }
  const pool = row.diceLotteryPoolConfig
  if (pool && (pool.id || pool.remark || pool.name || pool.display_name)) {
    return lotteryPoolDisplayLabel(pool)
  }
  const id = row.lottery_config_id
  if (id !== null && id !== undefined && id !== '') {
    return `#${id}`
  }
  return '-'
}

/** 规范化接口返回的彩金池选项 */
export function normalizeLotteryPoolOption(raw: Record<string, unknown>): LotteryPoolOption {
  const id = Number(raw.id ?? 0)
  const name = String(raw.name ?? '')
  const remark = String(raw.remark ?? '')
  const displayName = String(raw.display_name ?? '').trim()
  return {
    id,
    name,
    remark,
    display_name: displayName !== '' ? displayName : remark !== '' ? remark : name
  }
}

/** 按奖池名称 / 内部标识 / ID 过滤下拉 */
export function filterLotteryPoolOptionsByQuery(
  list: LotteryPoolOption[],
  query: string
): LotteryPoolOption[] {
  const q = (query || '').trim().toLowerCase()
  if (!q) {
    return [...list]
  }
  return list.filter((item) => {
    const label = lotteryPoolDisplayLabel(item).toLowerCase()
    const code = String(item.name ?? '').toLowerCase()
    return label.includes(q) || code.includes(q) || String(item.id).includes(q)
  })
}

/** 根据 ID 从选项列表解析奖池名称 */
export function lotteryPoolLabelById(
  poolId: number | null | undefined,
  options: LotteryPoolOption[]
): string {
  if (poolId == null || poolId <= 0) {
    return '-'
  }
  const found = options.find((o) => o.id === poolId)
  if (found) {
    return lotteryPoolDisplayLabel(found)
  }
  return `#${poolId}`
}
