import axios from 'axios'
import router from '@/router'
import { tansParams,judgmentNetworkReturnAddress } from "@/utils/ruoyi";
import { Toast,Loading } from 'vant';

//判定http或者https
let urlText = window.location.href.split('://')[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 => {
  Toast.loading({
    duration:0,
    message: '加载中...',
    forbidClick: true,
  });
  //写入touken
  config.headers['Authorization'] = localStorage.getItem('touken');
  // 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;
  }
  return config
}, error => {
  Promise.reject(error)
});
// 响应拦截器
service.interceptors.response.use(res => {
    Toast.clear();
    const code = res.data.code || 200;
    if(code != 200){
      Toast(res.data.message);
      return Promise.reject(new Error(res.data.code+' '+res.data.message))
    }else{
      return res.data
    }
  },
  error => {
    let { message } = error;
    Toast.clear();
    if(message.includes("Request failed with status code")) {
      if(message.substr(message.length - 3) == 401){
        router.replace({
          path: '/login'
        })
      }
    }else{
      Toast(message);
    }
    return Promise.reject(error)
  }
)
export default service
