import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import utils from '@/utils/index';
import router from '@/router';

function jumpTo(){
  //清空缓存
  // localStorage.clear();
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  let loginType = localStorage.getItem('loginType');
  if(!['/login','/login/qrcode','/login/sunshineRun'].includes(router.currentRoute.value.path)){
    if (loginType == "3") {
      router.push('/login/sunshineRun?auto=1');
    } else if (loginType == "2") {
      router.push('/login/qrcode?auto=1');
    } else {
      router.push('/login?auto=1');
    }
  }
};

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['auth'] = true;
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20000
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    //console.log("config", config)
    const token = localStorage.getItem('token') || '';
    if (token && Boolean(config.headers['auth']) == true) {
      config.headers['Authorization'] = 'JWT ' + token;
    }
    if (!token && Boolean(config.headers['auth']) == true) {
      delete config.headers['auth'];
      const message = '缺少凭证，请重新登录！';
      jumpTo();
      ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
      return Promise.reject(message);
    }
    // get请求修改Content-Type
    if (config.method?.toLowerCase() === 'get') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    // get请求映射params参数
    if (config.method === 'get' && config.data) {
      let url = config.url + '?' + utils.tansParams(config.data);
      url = url.slice(0, -1);
      config.data = {};
      config.url = url;
    }
    // FormData数据去请求头Content-Type
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type'];
    }
    delete config.headers['auth'];
    return config;
  },
  (error: any) => {
    //console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    const code = res.data.code;
    const status = res.data.status;
    const message = res.data.message;
    if (code === 401) {
      jumpTo();
      ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
      return Promise.reject('凭证已过期，请重新登录！');
    } else if (status == 500) {
      ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
      return Promise.reject(message);
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error: any) => {
    let { message, response } = error;
    if (message == 'Network Error') {
      message = '网络异常';
    } else if (message.includes('timeout')) {
      message = '请求超时';
    } else if (response.status == 401) {
      jumpTo();
      ElMessage({ message: '请重新登录', type: 'error', duration: 5 * 1000 });
      return Promise.reject('凭证已过期，请重新登录！');
    } else if (message.includes('Request failed with status code')) {
      if (response.data.status) {
        message = response.data.message;
      } else {
        message = '系统接口' + message.substr(message.length - 3) + '异常';
      }
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

export default service;
