/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-04 08:47:20
 * @LastEditors: WorkerChen z874512298@163.com
 * @LastEditTime: 2022-05-17 15:14:25
 */
import { Tips } from '../../utils/util'
import { axios } from './libs'

const request = axios.create({
  baseURL: '',
  networkTimeout: 25 * 1000
})

const handlerError = err => {
  const msg = err.message || _ERROR_MSG
  if (!err.message.includes('status code 404')) {
    Tips(msg)
    __LOG({ str: '请求错误:' }, { 返回信息: msg })
  }
  throw Error(msg)
}

const __LOG = (...arg) => {
  try {
    wx.$log.info(...arg)
    wx.$env.env !== 'prod' && console.debug(...arg)
  } catch (e) {
    console.error('axios config error', e)
  }
}

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

request.interceptors.request.use(
  config => {
    const { VUE_APP_BASE_API: baseUrl } = wx.$unienv
    let { url } = config
    url = (/^htt[p|ps]/.test(url) ? '' : baseUrl) + url
    const { headers, params, data } = config
    const token = wx.getStorageSync('token')
    const storeId = wx.getStorageSync('storeid')
    const merchantId = wx.getStorageSync('merchantid')
    const memberId = wx.getStorageSync('memberId')
    const hospitalInfo = getApp().getHospitalInfo()
    const { hospitalId } = hospitalInfo

    config = {
      ...config,
      data: Array.isArray(data)
        ? data
        : {
            ...hospitalInfo,
            ...data
          },
      params: { ...hospitalInfo, ...params },
      url: url
        .replace('_MERCHANTID_', merchantId)
        .replace('_HOSPITALID_', hospitalId)
        .replace('_STOREID_', storeId)
        .replace('_MEMBERID_', memberId),
      headers: {
        ...headers,
        'WX-MINI-APP-TOKEN': token,
        'origin-name': 'client'
      }
    }
    // `请求参数：${config.data.data||''},${config.data.hospitalInfo},${config.params.params||''}`,`请求体：${config}`
    console.info(`%c 请求路径：${config.url}`,'color:red')
    console.info(`%c 医院信息：${JSON.stringify(hospitalInfo)}`,'color:red')
    console.info(`%c 请求参数：\nbody:${JSON.stringify(data)||'空'}\nparams:${JSON.stringify(params)||'空'}`,'color:red')
    return config
  },
  err => {
    handlerError(err)
  }
)

request.interceptors.response.use(
  response => {
    const { data } = response || {}
    __LOG({ str: '请求返回:' }, { response })
    console.info('请求返回',data.results)
    if (data) {
      const { code, message } = data
      if (
        code !== _SUCCESS_CODE &&
        code !== _WARN_CODE &&
        !_PASS_CODES.includes(code)
      ) {
        Tips(message || _ERROR_MSG)
        return Promise.reject(message || _ERROR_MSG)
      } else if (code === _WARN_CODE) {
        Tips(message)
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 1700) //延迟时间
      }
      return data
    } else {
      return Promise.reject(message || _ERROR_MSG)
    }
  },
  err => {
    handlerError(err)
  }
)

export default request
