import { ref, type Ref } from 'vue'

export function matchKeyword(
  item: Record<string, unknown>,
  fields: string[],
  keyword: string
): boolean {
  const q = keyword.trim().toLowerCase()
  if (!q) return true
  return fields.some((field) => {
    const value = item[field]
    if (value == null) return false
    return String(value).toLowerCase().includes(q)
  })
}

export function matchKeywordFn<T>(
  item: T,
  keyword: string,
  getter: (item: T) => string
): boolean {
  const q = keyword.trim().toLowerCase()
  if (!q) return true
  return getter(item).toLowerCase().includes(q)
}

/** 关键词输入 + 已应用关键词（点击查询后生效） */
export function useAppliedKeyword() {
  const keyword = ref('')
  const appliedKeyword = ref('')

  const apply = () => {
    appliedKeyword.value = keyword.value.trim()
  }

  const reset = () => {
    keyword.value = ''
    appliedKeyword.value = ''
  }

  return { keyword, appliedKeyword, apply, reset }
}

export function resetRefFilters(filters: Record<string, Ref<unknown>>, defaults: Record<string, unknown>) {
  Object.keys(defaults).forEach((key) => {
    if (filters[key]) {
      filters[key].value = defaults[key]
    }
  })
}
