import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import router from '@/router'
import { autoLogin,getToken,removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams,judgmentNetworkReturnAddress } from "@/utils/index";
import { login } from "@/api/login";

//判定http或者https
let urlText = window.location.href.split('://')[0]+'://';

//弹窗状态开关
let messageData = null;

// 公共接口加载弹层数据
let loadingInstance = {};
let options = {
  spinner:"",
  background: 'rgba(255, 255, 255, 0)'
};
let loadingCount = 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 => {
  // 弹层相关
  loadingInstance = Loading.service(options)
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.credentials= 'omit';
  // 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;
  }
  // 弹层相关
  loadingCount ++;
  return config
}, error => {
  // 弹层相关
  loadingCount --;
  if(loadingCount===0){
    loadingInstance.close();
  }
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0) {
      loadingInstance.close();
    }
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.message || errorCode['default']
    if (code === 500) {
      if(!messageData){
        messageData = Message({
          message: msg,
          type: 'error',
          offset:100
        })
        setTimeout(function(){
          messageData = null
        },1000);
      }
      return res.data
    }else if(code == 5002){
      autoLogin();
    }else if(code != 200) {
      if(!messageData){
        messageData = Message({
          message: msg,
          type: 'error',
          offset:100
        })
        setTimeout(function(){
          messageData = null
        },1000);
      }
      return Promise.reject(new Error(msg))
    }else {
      return res.data
    }
  },
  error => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0){
      loadingInstance.close();
    }
    let { message } = error;
    if (message == "Network Error") {
      message = "服务连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      if(message.substr(message.length - 3) == 401){
        autoLogin();
      }else{
        messageData = Message({
          message: message,
          type: 'error',
          offset:100
        })
        setTimeout(function(){
          messageData = null
        },1000);
      }
      return Promise.reject(error)
    }
    if(!messageData){
      messageData = Message({
        message: message,
        type: 'error',
        duration: 5 * 1000,
        offset:100
      })
      setTimeout(function(){
        messageData = null
      },1000);
    }
    return Promise.reject(error)
  }
)
export default service
