/*
 * @Descripttion: 
 * @version: 
 * @Author: 王三华
 * @Date: 2023-09-19 10:19:53
 */
import { getToken, removeToken } from '@/config/auth.js'
module.exports = (vm) => {
  uni.$u.http.setConfig((config) => {
    config.baseURL = process.env.VUE_APP_BASE_API;
    config.timeout = 80000;
    return config
  })
  // 请求拦截
  uni.$u.http.interceptors.request.use((config) => {
    config.data = config.data || {}
    config.header['Source'] = 3
    let token = getToken();
    let lang = uni.getStorageSync('lang');
    if (lang) {
      config.header['Accept-Language'] = lang
    } else {
      config.header['Accept-Language'] = 'zh-CN'
    }
    if (token) {
      config.header['Authorization'] = token;
    }
    if (config.method === 'GET' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof (value) !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              let params = propName + '[' + key + ']'
              var subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  }, config => {
    return Promise.reject(config)
  })
  // 响应拦截
  uni.$u.http.interceptors.response.use((response) => {
    const data = response.data
    if (data.code == 400 || data.code == 401 || data.code == 402) {
      removeToken();
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/login/index'
        })
      }, 1500)
    } else if (data.code == 500) {
      uni.$u.toast(data.msg)
      return data;
    } else {
      return data;
    }
  }, (response) => {
    uni.$u.toast('服务器错误，请稍后重试')
  })
}