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();
  }
  if( config.headers['sysCode']==undefined) {
    config.headers['sysCode'] = 12
  }
  // config.headers['token'] = 'AE013D42003D4BA3856FAD9DBDC82254'
  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' })
  // if (config.data && config.data.setEntry) {
  //   config.headers['sysCode'] = config.data.sysCode || 10
  //   if(config.data.token){
  //      config.headers['token'] = config.data.token || '63C3FA92AF8A45A48B31EB7FD97B95EB'
  //   }

  //   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
