// import md5 from 'md5'
// import { createDiscreteApi } from 'naive-ui'

export function request(url, options = {}) {
  const config = useRuntimeConfig()
  // const authStore = useAuthStore()

  const defatulOpts = {
    method: 'get',
    // baseURL: config.public.baseApi,
    headers: {
      // 'Content-Type': 'application/json',
      // deviceType: config.public.deviceType,
      // authorization: authStore.token,
      project: '',
      ...options.headers
    },
    onRequest({ options }) {
      if (options.method === 'post') {
        // const bodyJson = options.body ? JSON.stringify(options.body) : ''
        // const timestamp = new Date().getTime()
        // let sign = `yingdeweilai888${bodyJson}${timestamp}`
        // sign = md5(sign).toUpperCase()
        // options.headers.sign = sign
        // options.headers.timestamp = timestamp
      }
    },
    onRequestError() {
      // showErrorMessage('请求出错，请重试~')
    },
    onResponse({ response: { _data: data } }) {
      if (data && data.errorCode != 'NO-ERROR') {
        handleServerError(data.errorCode, data.errorMessage)
      }
    },
    onResponseError({ response }) {
      handleHttpError(response.status)
    },
    ...options
  }
  return new Promise((resolve, reject) => {
    $fetch(url, defatulOpts)
      .then((res) => {
        const { errorCode } = res
        errorCode === 'NO-ERROR' ? resolve(res) : reject(res)
      })
      .catch((err) => reject(err))
  })
}

const handleHttpError = (status) => {
  switch (status) {
    case 400:
      // showErrorMessage('参数错误')
      break
    case 401:
      // showErrorMessage('没有访问权限')
      break
    case 403:
      // showErrorMessage('服务器拒绝访问')
      break
    case 404:
      // showErrorMessage('请求地址错误')
      break
    case (502, 503):
      // showErrorMessage('系统升级中')
      break
    default:
      // showErrorMessage('服务器出错了')
      break
  }
}

const handleServerError = async (code, msg) => {
  if (code === 'UNAUTHORIZED_LOGIN') {
    // const authStore = useAuthStore()
    // authStore.cleanToken()
    // jumpToLoginPage()
    // await navigateTo({
    //   path: '/login',
    //   replace: true
    // })
    return
  }
  if (msg) {
    showErrorMessage(msg)
  }
}

const showErrorMessage = (msg) => {
  // const { message } = createDiscreteApi(['message'])
  // if (process.server) return
  // const { message } = useMessage()
  // message.error(msg)
}

export const handleResponse = (response, isNeedData = true) => {
  return new Promise((resolve, reject) => {
    const success = response.success
    switch (success) {
      case true: {
        if (isNeedData) {
          if (response.data && !isEmptyValue(response.data)) return resolve()
          return reject(response)
        }
        return resolve()
      }
      default: {
        return reject(response)
      }
    }
  })
}
