/* eslint-disable @typescript-eslint/no-unused-vars */
import { ref, reactive, watch, watchEffect } from 'vue'
import type { Ref } from 'vue'
import { cloneDeep } from 'lodash-es'

type SearchOptions = {
  deepClone?: boolean // 是否使用深拷贝 默认 true
  beforeReset?: () => void // 重置前钩子
  afterReset?: () => void // 重置后钩子
}

export function useSearch<T extends object>(initialData: T, options: SearchOptions = {}) {
  const { deepClone = true, beforeReset, afterReset } = options

  const clone = deepClone ? cloneDeep : (obj: T) => ({ ...obj })

  const initialState = clone(initialData)
  const state = reactive(clone(initialData)) as T

  // 监听外部初始数据变化
  watchEffect(() => {
    Object.assign(initialState, clone(initialData))
  })

  const reset = () => {
    beforeReset?.()
    Object.assign(state, clone(initialState))
    afterReset?.()
  }

  return [state, reset] as const
}
