import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import adapterFetch from 'alova/fetch'
import { ElMessage } from 'element-plus'

export const request = createAlova({
  baseURL: import.meta.env.VITE_API_BASEURL || '',
  // 设置为null即可全局关闭全部请求缓存
  cacheFor: null,
  statesHook: VueHook,
  requestAdapter: adapterFetch(),
  beforeRequest(method) {
    const token = localStorage.getItem('admin_token')
    if (token) {
      method.config.headers = { ...method.config.headers, Authorization: `Bearer ${token}` }
    }
  },
  responded: {
    onSuccess: async (response) => {
      const data = await response.json()
      if (data.code !== 200) {
        if (response.status === 401 || data.code === 401) {
          localStorage.removeItem('admin_token')
          window.location.href = '/login'
          throw new Error('redirect')
        }
        ElMessage.error(data.msg)
        throw new Error(data.msg)
      }
      return data
    },
    onError: (error) => {
      if (error?.message === 'redirect') return
      if (error?.response?.status === 401) {
        localStorage.removeItem('admin_token')
        window.location.href = '/login'
        return
      }
      ElMessage.error(error.message || '请求失败')
    },
  },
})

export default request
