import axios from 'axios';
import {
  baseURL,
  contentType,
  debounce,
  messageName,
  requestTimeout,
  statusName,
  successCode,
  tokenName,
} from '@/config';
import store from '@/store';
import qs from 'qs';
import router from '@/router';
import { isArray } from '@/utils/validate';
import { ElMessage, ElLoading } from 'element-plus';
import { getToken } from '@/utils/token';

let loadingInstance;

// 操作正常Code数组
const codeVerificationArray = isArray(successCode)
  ? [...successCode]
  : [...[successCode]];

const CODE_MESSAGE = {
  200: '服务器成功返回请求数据',
  401: '用户没有权限（令牌、用户名、密码错误）',
  403: '用户得到授权，但是访问是被禁止的',
  500: '服务器发生错误',
};

const handleData = ({ config, data, status, statusText }) => {
  if (loadingInstance) loadingInstance.close();
  let code = data && data[statusName] ? data[statusName] : status;
  if (codeVerificationArray.includes(code)) code = 200;
  switch (code) {
    case 200:
      return data;
    case 0:
      return data;
    case -1:
      return data;
    case -3:
      var msg = '该账号已在别处登录';
      ElMessage.error(msg);
      Promise.reject(msg);
      router.push({ path: '/login', replace: true });
      return;
    case 401:
      store.dispatch('user/resetAll');
      router.push({ path: '/login', replace: true });
      break;
    case 403:
      router.push({ path: '/403' });
      break;
  }
  const message = `${
    !data
      ? CODE_MESSAGE[code]
      : !data[messageName]
      ? statusText
      : data[messageName]
  }`;
  ElMessage.error(message);
  return Promise.reject(message);
};

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': contentType,
  },
});
// 'application/x-www-form-urlencoded;charset=UTF-8'
instance.interceptors.request.use(
  config => {
    // const userToken = store.getters['user/token'];
    const token = getToken();
    // const token = userToken == null ? wechatToken : userToken;
    console.log('token====', token);
    if (token) config.headers[tokenName] = token;
    if (
      config.data &&
      config.headers['Content-Type'] ===
        'application/x-www-form-urlencoded;charset=UTF-8'
    )
      config.data = qs.stringify(config.data);
    if (debounce.some(item => config.url.includes(item)))
      loadingInstance = ElLoading.service({ fullscreen: true });
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  response => handleData(response),
  error => {
    const { response } = error;
    if (response === undefined) {
      ElMessage.error('未可知错误');
      return {};
    } else return handleData(response);
  }
);

export default instance;
