import { objToUrl } from '@/utils/index';
function request(options,hasNoToken) {
  return new Promise((resolve, reject) => {
    let _obj = {
      url: '',
      data: {},
      method: 'GET',
      header: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    };
	const baseUrl = getApp().globalData.baseUrl
	const userInfo = uni.getStorageSync('userInfo');
    Object.assign(_obj, options);
	const header = {
			'USER-TERM-TYPE': 'ipad', // 支付时需要用到 与pad一致
			'App-Type': 2,
			'Version': '1.0.0',
	}
	if(userInfo.sysUserFlag == '0'){
		header['auth-token'] = hasNoToken ? '' : uni.getStorageSync('token')
	}else{
		header['authorization'] = hasNoToken ? '' : uni.getStorageSync('token')
	}
	_obj.header = header
	_obj.header['X-HEADER-APPID'] = '!z2Yc.aes|STw5oReFk+wACvW4IGVHZsFe+/MgMT9cp0amuic1gqE=';
	
    _obj.url = baseUrl + _obj.url;
    _obj.method = _obj.method.toUpperCase();
    _obj.success = function(res) {
      if (_obj.url.indexOf('checkLogin') > -1) {
	    console.log(res.data,'res.data checkLogin')
        resolve(res.data);
      } else if (res.data.status === '900010') {
        setTimeout(function() {
          wx.showToast({
            title: '登录已过期,请重新登录',
            icon: 'none',
            duration: 1000
          });
        }, 10);
		setTimeout(function() {
		  const currentRoute = getRoutePath();
		  uni.setStorageSync('token','')
		  const url = `/pages/login/login?lanuch=${currentRoute.lanuch}&path=` + encodeURIComponent(currentRoute.url);
		  uni.reLaunch({
		  	url: url
		  })
		}, 1000);
      } else {
        resolve(res.data);
      }
    };
    _obj.fail = function(err) {
      reject(err);
    };
    _obj.complete = function() {};
    uni.request(_obj);
  });
}
function getRoutePath() {
  // eslint-disable-next-line no-undef
  const pages = getCurrentPages(); // 获取加载的页面
  const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
  let url = currentPage.route; // 当前页面url
  const options = objToUrl(currentPage.options); // 如果要获取url中所带的参数可以查看options
  const lanuch = [
    'pages/personData/personData'
  ].includes(url);
  url = '/' + url;
  if (options.length) {
    url += '?' + options;
  }
  return {
    url,
    lanuch
  };
}
export default request;
