/**
 * 封装的axios的工具类
 * 负责请求的公共配置,以及请求拦截,响应拦截,错误处理,网络不佳处理
 */
import axios from 'axios';
import { Toast, Dialog } from 'vant';
import errorCode from '@/utils/errorCode';
import { toastLoading } from '@/utils/commonVant';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // timeout: 30000,
  timeout: 0,
  withCredentials: true,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    // toastLoading(0, '加载中...', true);
    config.headers['userId'] = localStorage.getItem('loginName');
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // toastLoading().clear();
    const code = res.data.code || 200;
    const msg = errorCode[code] || res.data.msg || errorCode['default'];
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data;
    }
    if (code === 401) {
      Toast('认证信息未通过');
    } else if (code === 500) {
      // Toast({
      //     message:msg,
      //     duration:5000
      // });
      return res.data;
    } else if (code == -1) {
      // 图匠图片校验接口超时
      return res.data;
    } else if (code !== 200) {
      Toast({
        message: msg,
        duration: 5000,
      });
    } else {
      return res.data;
    }
  },
  (error) => {
    let { message } = error;
    if (message == 'Network Error') {
      message = '网络异常';
    } else if (message.includes('timeout')) {
      message = '请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    if (error.message === 'canceled') {
      console.log('请求被取消:', error.message);
    } else {
      Toast(message);
    }
    return Promise.reject(error);
  }
);
export default service;
