/*
 * @Author: linwl
 * @Date: 2020-04-13 14:47:59
 * @LastEditTime: 2023-06-15 10:32:04
 * @LastEditors: JinxChen
 * @Description: axios请求配置
 * @FilePath: \ParentWeb\src\config\request.js
 */
import axios from 'axios';
import router from '@/router';
import { baseApi } from '@/config';
import prefix from '@/store/prefix';
const httpProxyPrefix = baseApi;

// create an axios instance  axios.create创建一个实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: httpProxyPrefix
  // timeout: 5000 // request timeout
});

const errorHandler = error => {
  // const status = get(error, 'response.status');
  const status = error.response.status;
  console.log(status);
  switch (status) {
    case 400:
      error.message = '请求错误';
      break;
    case 401:
      error.message = '未授权，请登录';
      break;
    case 403:
      error.message = '拒绝访问';
      break;
    case 404:
      error.message = '请求地址出错';
      break;
    case 408:
      error.message = '请求超时';
      break;
    case 500:
      error.message = '服务器内部错误';
      break;
    case 501:
      error.message = '服务未实现';
      break;
    case 502:
      error.message = '网关错误';
      break;
    case 503:
      error.message = '服务器不可用';
      break;
    case 504:
      error.message = '网关超时';
      break;
    case 505:
      error.message = 'HTTP版本不受支持';
      break;
    default:
      break;
  }
  this.$notify({ message: `您的网络异常(${error.message})`, type: 'warning' });
  return Promise.reject(error);
};

// 请求拦截器,增加  token interceptors拦截
service.interceptors.request.use(request => {
  if (localStorage.getItem(prefix + 'authToken')) {
    request.headers.AuthToken = localStorage.getItem(prefix + 'authToken');
  } else if (
    window.location.href.indexOf('login') < 0 &&
    window.location.href.indexOf('forgetPassword') < 0 &&
    window.location.href.indexOf('verifyInfos') < 0 &&
    window.location.href.indexOf('register') < 0 &&
    window.location.href.indexOf('verificationLogin') < 0 &&
    window.location.href.indexOf('changePassword') < 0
  ) {
    router.push({ name: 'login' });
    return request;
  }
  // 全局请求统一增加一个 sourcetype: 1的参数跟区分新旧接口
  if (request.method == 'get') {
    request.params = {
      ...request.params,
      sourcetype: 1
    };
  } else if (request.method == 'post') {
    request.data = {
      ...request.data,
      sourcetype: 1
    };
  }

  return request;
}, errorHandler);

export default service;
