import axios from 'axios'
import { ElLoading } from 'element-plus'

const VERSION = '20210531'

const APP_VERSION = '' + VERSION.replace(/\"/g, '') // 当前应用版本
const API_VERSION = '0.0.5' // 当前API版本
const OS_VERSION = 'window10' // 当前操作操作系统版本

var loading: any
var hide_loading = false

/**
 * 创建axios实例
 */
const request: any = axios.create({
  baseURL: import.meta.env.MODE === 'production' ? '/' : '/api/', // api的base_url
  timeout: 600000 // 请求超时时间
})

/** 下一次请求不显示Loading */
request.hideLoadingOnce = function () {
  hide_loading = true
}

/**
 * 是否隐藏Loading
 *
 * @returns
 */
function isHideLoading() {
  var b = hide_loading
  hide_loading = false
  return b
}

/**
 * 设置拦截器: 请求拦截器
 */
request.interceptors.request.use(
  (config: any) => {
    config.headers['tenant'] = '0'

    if (!isHideLoading()) {
      loading = ElLoading.service({ fullscreen: true })
    }

    config.headers['app-version'] = APP_VERSION
    config.headers['api-version'] = API_VERSION
    config.headers['os-version'] = OS_VERSION
    let url = config.url!
    // get参数编码
    if (config.method === 'get' && config.params) {
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] != null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
    }
    config.url = url
    return config
  },
  (error: any) => {
    loading && loading.close()
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

/**
 * 设置拦截器: 响应拦截器
 */
request.interceptors.response.use(
  (response: any) => {
    loading && loading.close()
    const res = response.data
    return res
  },

  (error: any) => {
    loading && loading.close()
    console.log(error)
    if (error.response && error.response.data) {
      try {
        var data = error.response.data
        if (typeof data === 'string') {
          if (error.response.status === 503) {
            data = {
              code: -1,
              message: '当前服务繁忙，请稍后再试！'
            }
          } else {
            data = JSON.parse(error.response.data)
          }
        }
        return Promise.reject(data)
      } catch (e) {
        return Promise.reject({
          code: -1,
          message: '网络异常: ' + error.response.data
        })
      }
    } else {
      return Promise.reject({
        code: -1,
        message: error
      })
    }
  }
)

export default request
