/**
 * uview-plus http 请求配置
 */
import { getToken, clearAll } from './cache.js'
import envConfig from '@/config/env.js'

const BASE_URL = envConfig.BASE_URL

const CODE = {
  SUCCESS: 0,
  NEED_LOGIN: 1009
}

export function initRequest(http) {
  http.setConfig((config) => {
    config.baseURL = BASE_URL
    config.timeout = 20000
    config.header = {
      'Content-Type': 'application/json'
    }
    return config
  })

  http.interceptors.request.use(
    (config) => {
      const token = getToken()
      if (token) {
        config.header.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => Promise.reject(error)
  )

  http.interceptors.response.use(
    (response) => {
      const { code, data, list, msg } = response.data

      if (code === CODE.SUCCESS) {
        return { code, data, list, msg }
      }

      if (code === CODE.NEED_LOGIN) {
        clearAll()
        uni.showToast({ title: msg || '请先登录', icon: 'none' })
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/login/index' })
        }, 1500)
        return Promise.reject({ code, msg: msg || '请先登录' })
      }

      uni.showToast({ title: msg || '请求失败', icon: 'none' })
      return Promise.reject({ code, msg: msg || '请求失败' })
    },
    (error) => {
      uni.showToast({ title: '网络请求失败', icon: 'none' })
      return Promise.reject({ code: -1, msg: error.errMsg || '网络请求失败' })
    }
  )
}

export function get(url, params = {}, config = {}) {
  return uni.$u.http.get(url, { params, ...config })
}

export function post(url, data = {}, config = {}) {
  return uni.$u.http.post(url, data, config)
}

export function put(url, data = {}, config = {}) {
  return uni.$u.http.put(url, data, config)
}

export function del(url, data = {}, config = {}) {
  return uni.$u.http.delete(url, { data, ...config })
}

export function upload(url, { filePath, name = 'file', formData = {} } = {}) {
  return uni.$u.http.upload(url, { filePath, name, formData })
}

export function download(url, config = {}) {
  return uni.$u.http.download(url, config)
}

export default { get, post, put, del, upload, download }
