import axios from 'axios';
import {
  Loading
} from 'element-ui';
import {
  message
} from './resetMessage';
import _ from 'lodash';
import router from '../router'
import Promise from 'es6-promise'
import {
  httpPost
} from '../api';
import storedata from "../store/index.js"
import {
  Callbacks
} from 'jquery';
// 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()
    var access_token = ''
    if (JSON.parse(localStorage.getItem("tokenkey"))) {
      access_token = JSON.parse(localStorage.getItem("tokenkey")).access_token
    }
    let tenantId = storedata.state.tenantId
    if (tenantId) {
      config.headers = {
        'content-type': 'application/json;charset=utf-8',
        'Authorization': 'bearer' + access_token,
        'tenantId': tenantId,
      }
    } else {
      config.headers = {
        'content-type': 'application/json;charset=utf-8',
        'Authorization': 'bearer' + access_token
      }
    }
    return config;
  },
  error => {
    // hideLoading();
    return Promise.reject(error.response.data);
  }
);
service.interceptors.response.use(
  response => {
    hideLoading();
    if (response.status === 200) {
      return response.data;
    } else {
      Promise.reject(response.data);
    }
  },
  error => {
    hideLoading();
    if (error.response.status === 401) {
      message({
        type: "error",
        message: "您的token已过期，请重新登录！"
      })
      setTimeout(function() {
        redirectLogin();
      }, 500)
    }else{
      if(error.response.data.message == 'Insufficient balance'){
        message({
          type: "error",
          message: '余额不足'
        })
      }else{
        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: {}
  })
}

function refreshTokenRequst(data, Callback) {
  const refresh_token = JSON.parse(localStorage.getItem('token')).refresh_token;
  var fd = new FormData();
  fd.append("client_id", "iot-client");
  fd.append("client_secret", "iot-client");
  fd.append("grant_type", "refresh_token");
  fd.append("refresh_token", refresh_token);
  httpPost(fd, 'oauth/token').then(res => {
    Callback(res)
  })
}

export default service;
