import axios from 'axios';
import {
  Loading
} from 'element-ui';
import {
  message
} from './resetMessage';
import Promise from 'es6-promise'
import _ from 'lodash';
import storedata from "../store/index.js"
import router from '../router'
// let doms = document.getElementsByClassName('el-message')[0]
const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  // easy-mock服务挂了，暂时不使用了
  // baseURL: 'http://192.168.1.112:8600',
  timeout: 100000
});
let loading;
let needLoadingRequestCount = 0;
//显示loading
function showLoading(target) {
  // 后面这个判断很重要，因为关闭时加了抖动，此时loading对象可能还存在，
  // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: "Loading...",
      background: 'rgba(255, 255, 255, 0.5)',
      target: target || "body"
    });
  }
  needLoadingRequestCount++;
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
  if (needLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}
//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = _.debounce(() => {
  loading.close();
  loading = null;
}, 300);

service.interceptors.request.use(
  config => {
    showLoading()
    let tenantId = storedata.state.tenantId
    if (tenantId) {
      config.headers = {
        'content-type': 'application/json;charset=utf-8',
        'tenantId': tenantId
      }
    } else {
      config.headers = {
        'content-type': 'application/json;charset=utf-8'
      }
    }
    return config;
  },
  error => {
    if (error.response.status === 401) {
      // if(doms == undefined){
      message({
        type: "error",
        message: "您的token已过期，请重新登录！"
      })
      setTimeout(function() {
        redirectLogin();
      }, 500)
      // }
    }
    hideLoading();
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    hideLoading();
    if (response.status === 200) {
      return response.data;
    } else {
      Promise.reject();
    }
  },
  error => {
    hideLoading();
	  message({
		type: "error",
		message: error.response.data.message
	  })
    return Promise.reject(error.response.data);
  }
);

function redirectLogin() {
  localStorage.setItem("ms_username", '');
  router.push({
    name: '/login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

export default service;
