import axios from 'axios';
import {
  Loading,
  Message,
  MessageBox
} from 'element-ui';
import store from './store/index';
import router from './router/index';
import { sessionStorage } from './utils/storage';
const CancelToken = axios.CancelToken;
let source = CancelToken.source();
let loadingRequestCount = 0;
var loadingInstance;
var listUrl=['business/common/area/list','system/login/checkImagCode','system/login/checkMobile']

var elModalUrl=['business/maintenance/modify/plan','business/maintenance/generate/plan','business/project/relevance/modify','business/emergency/emergency-repair/close','business/emergency/emergency-repair/transfer','business/contract/detail','business/contract/modify','business/contract/renew','business/contract/add','system/user/delete','system/companyuser/assignRole','business/project/modify','business/lift/add','business/lift/modify']

const showLoading = (a) => {
  if (loadingRequestCount === 0) {
    if(elModalUrl.indexOf(a.url)==-1){
      loadingInstance = Loading.service({ target: '.el-table'});
    }else{
      loadingInstance = Loading.service({ target: '.plansNext'});
    }
  }
  loadingRequestCount++
}
const hideLoading = () => {
    if (loadingRequestCount <= 0) return
    loadingRequestCount--
    if (loadingRequestCount === 0) {
              loadingInstance.close();
    }
 }


let loading        //定义loading变量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '正在加载...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }

}

if (!store.state.token) {
  store.commit('SET_TOKEN', sessionStorage.getItem('token'));
}

// axios 配置

const http = axios.create({
  // baseURL: 'http://192.168.1.46',
  baseURL: 'http://220.249.127.210:10227',
  timeout: 5000,
  async:false, //或false,是否异步
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  transformRequest: [function (data, headers) {
    headers.common['Authorization'] = store.state.token;
    headers.common['MobileType'] = "0";
    if (headers['Content-type'] === 'multipart/form-data') {
      console.log(data)
      return data;
    } else {
      return JSON.stringify(data);
    }
  }]
});



// 请求拦截器
http.interceptors.request.use(config => {
  config.withCredentials = true
  // showFullScreenLoading()
  config.cancelToken = source.token // 取消请求
  if(config.cancelToken && config.cancelObj && config.cancelObj.cancel) {
      config.cancelObj.cancel('中断请求');
      delete config.cancelObj;
  }
  if (!navigator.onLine) { // 断网提示
      source.cancel('网络故障，请检查!')
  }
  var newUrl=config.url.split('?')[0];
  console.log(listUrl.indexOf(newUrl));
  if(listUrl.indexOf(newUrl) ==-1){
    showLoading(config)
  }
  return config;
}, error => {
  // loadingInstance.close();
  Message.error({
    message: '请求失败'
  });
  return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use(res => {
  setTimeout(() => {
    hideLoading()
   }, 200);
  // tryHideFullScreenLoading()
  if(res.data.statusCode=="10"){
    // MessageBox.alert('身份信息已过期，请重新登录', '提示', {
    //   confirmButtonText: '重新登录',
    //   showClose: false,
    //   type: 'error',
    //   callback: action => {
    //     router.push('/login');
    //   }
    // });
    router.push('/login');
  }else{
    return res.data;
  }
  
  
  
}, error => {
	setTimeout(() => {
    hideLoading()
   }, 200);
  if (error && error.response) {
    switch (error.response.status) {
      // 401 token失效
      case 401:
        MessageBox.alert('身份信息已过期，请重新登陆', '提示', {
          confirmButtonText: '重新登陆',
          showClose: false,
          type: 'error',
          callback: action => {
            router.replace({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            });
          }
        });
        break;
      
      // 403 服务器拒绝访问
      case 403:
        router.push('/error/403');
        break;
      
      // 404 访问的资源不存在
      case 404:
        router.push('/error/404');
        break;
      
      // 500 服务器错误
      // case 500:
      //   router.push('/error/500');
      //   break;
    }
    
    return Promise.reject(error);
  }
});


export default http;
