import axios from 'axios'
import { Loading } from 'element-ui';
import store from '../store'
// import { getHostnameAndPort } from '../utils'
// axios.defaults.withCredentials = true

const service = axios.create({
  // baseURL: process.env.BASE_API
  timeout: 600000,
  withCredentials: false
})

let loadingInstance = () => {
  return Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
}
let loading;
let needLoadingRequestCount = 0;
let showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) {
    loadingInstance();
  }
  needLoadingRequestCount++;
};
let tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount > 0) {
    needLoadingRequestCount--;
  }
  if (needLoadingRequestCount === 0) {
    loadingInstance().close();
  }
};

// request拦截器
service.interceptors.request.use(config => {
  if (config.noLoading) {
  }else{
    showFullScreenLoading();
  }

  const noSysCode = config.headers.noSysCode;
  if(noSysCode){
    delete config.headers.sysCode;
    delete config.headers.deviceInfo;
    delete config.headers.noSysCode;
    delete config.headers.token;
  }else{
    if( config.headers['sysCode']==undefined) {
      config.headers['sysCode'] = 12
    }
    if( process.env.BUILD_ENV == "development" ){  // 本地开发环境qgit
      // console.log('环境变量>>>> ', process.env.BUILD_ENV);
      config.headers['token'] = '9606E40DDB704396AB532B2AE771048E';

      // config.headers['token'] = localStorage.getItem('storageToken')
    }else{
      config.headers['token'] = localStorage.getItem('storageToken')
    }
    config.headers['deviceInfo'] = JSON.stringify({ "app_channel": "", "app_mac": "", "app_uuid": "", "app_version": "", "device_brand": "", "device_ip": "", "device_model": "", "device_net": "", "device_ops": "", "resolution_wh": "", "system_level": "", "device_type": '10' })
  }

  return config
}, error => {
 // logger.debug('service.interceptors.request: ', error)
  tryHideFullScreenLoading();
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.config.noLoading) {
    }else{
      tryHideFullScreenLoading()
    }
    const res = response.data
    /*
      baseUrl时，返回000000为成功
      apiUrl时，返回200为成功
    */
    // if (res.code !== '000000') {
    //   return Promise.reject('error')
    // } else {
      return response.data
    // }
  },
  error => {
  //  logger.error('err' + error)
    tryHideFullScreenLoading();
    return Promise.reject(error)
  }
)
export default service
