import { deepClone } from 'uview-plus'

export const useFetch = (options = {}) => {
  const {
    apiFn,
    params = {},
    isList = false,
    isAutoFetch = false,
    defaultResult = {},
    formatResult = (r) => r
  } = options

  const result = ref(defaultResult)
  const loading = ref(false)

  if (!apiFn) {
    throw new Error('apiFn is required')
  }

  const fetchApi = async (...rest) => {
    loading.value = true
    const { error, data, result: response } = await apiFn(...rest)
    const isOk = !error || isList

    if (!isOk) {
      loading.value = false
      return [isOk, error]
    }

    let formatResultData = deepClone(defaultResult)
    if (isList) {
      formatResultData = formatResult(response)
    } else {
      formatResultData = formatResult(data)
    }
    result.value = formatResultData
    loading.value = false
    return [isOk, formatResultData]
  }

  if (isAutoFetch) {
    fetchApi(params)
  }

  return {
    result,
    fetchApi,
    loading
  }
}
