/*
 * @Descripttion:
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-08-11 14:12:27
 * @LastEditors: HJ
 * @LastEditTime: 2021-11-11 15:37:55
 */
import { axios } from './axios'
import { Tips } from './util'

const _ERROR_MSG = '您的网络开了个小差,请重试'
const _SUCCESS_CODE = 200
const _WARN_CODE = [520]
const _PASS_CODES = [1004]

const request = axios.create({
  baseURL: uni.$env.baseUrl,
  networkTimeout: 25 * 1000
})
// 内容输出
const __LOG = (...arg) => {
  try {
    uni.$log.info(...arg)
  } catch (e) {
    console.error('axios config error', e)
  }
}
// 错误处理
const handlerError = err => {
  const msg = err.message || _ERROR_MSG

  if (!err.message.includes('status code 404')) {
    Tips(msg)
    __LOG({
      str: '请求错误:',
      返回信息: msg
    })
  }

  throw Error(msg)
}
// 请求拦截器
request.interceptors.request.use(
  config => {
    const { url, headers } = config

    try {
      const { data } = config

      __LOG({
        str: '发送请求:',
        url,
        data,
        headers
      })
    } catch (e) {
      console.error('axios request', e)
    }

    return config
  },
  err => {
    handlerError(err)
  }
)
// 返回拦截器
request.interceptors.response.use(
  response => {
    const { data } = response || {}

    __LOG({
      str: '请求返回:',
      response
    })

    if (data) {
      const { code, message } = data
      const msg = message || _ERROR_MSG

      if (_WARN_CODE.includes(code)) {
        // 只警告
        Tips(msg)
      } else if (_PASS_CODES.includes(code)) {
        // 直接跳过拦截的业务码
        return data
      } else if (code !== _SUCCESS_CODE) {
        // 统一处理不警告、跳过且 code 不为成功码的部分
        Tips(msg)
        return Promise.reject(msg)
      }

      return data
    } else {
      return Promise.reject(_ERROR_MSG)
    }
  },
  err => {
    handlerError(err)
  }
)

uni.$request = request

export { request }
