import Request from 'luch-request'
import { useWeAppAuthStore } from '../store/useWeAppAuthStore'

const http = new Request()

http.setConfig(config => {
  config.baseURL = import.meta.env.VITE_HTTP_BASE_URL
  config.header = {
    ...config.header
  }
  return config
})

http.interceptors.request.use(
  config => {
    config.header = {
      ...config.header,
      Authorization: 'Bearer ' + uni.getStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY)
    }
    return config
  },
  config => {
    return Promise.reject(config)
  }
)

http.interceptors.response.use(
  response => {
    // console.log("response", response);
    const data = response.data
    uni.hideLoading()
    if (data.success !== true) {
      if (data.errorCode === 10001) {
        const auth = useWeAppAuthStore()
        auth.loading = false
        uni.showToast({ title: data.errorMessage, icon: 'none' })
      } else {
        uni.showToast({ title: data.errorMessage, icon: 'none' })
      }
      return Promise.reject(response.data)
    }
    return response.data
  },
  response => {
    console.log('error', response)
    const auth = useWeAppAuthStore()
    auth.loading = false
    return Promise.reject(response)
  }
)

export function request(url: string, data: Record<string, any>) {
  return http.post(url, data.data)
}
