import axios from 'axios'
import { Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
import { tansParams,judgmentNetworkReturnAddress } from "@/utils/ruoyi";

//判定http或者https
let urlText = window.location.href.split('://')[0]+'://';

// 弹层数据
let loadingInstance = {};
let options = {
  spinner:"",
  background: 'rgba(255, 255, 255, 0.1)'
};
let loadingCount = 0;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: urlText+judgmentNetworkReturnAddress(),
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  // 弹层相关
  loadingInstance = Loading.service(options)
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  // 弹层相关
  loadingCount ++;
  return config
}, error => {
  // 弹层相关
  loadingCount --;
  if(loadingCount===0){
    loadingInstance.close();
  }
  Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0) {
      loadingInstance.close();
    }
    return res.data
  },
  error => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0){
      loadingInstance.close();
    }
    return error
  }
)

export default service
