import { objToUrl } from '@/utils/index';

function request(options) {
  // wx.showLoading({
  //   mask: true,
  //   title: '加载中' // 数据请求前loading，提高用户体验
  // });
  return new Promise((resolve, reject) => {
    const baseUrl = 'https://zyyc.chelingzhu.com/zyyc-shop/'; // 预发布
    // const baseUrl = 'https://shop.zy-yc.cn/zyyc-shop/'; // 生产
    // const baseUrl = 'http://192.168.16.103:7102/zyyc-shop/';
    // const baseUrl = process.env.NODE_ENV === 'production' ? proUrl : devUrl;

    let _obj = {
      url: '',
      data: {},
      method: 'GET',
      header: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    };

    Object.assign(_obj, options);
    _obj.header['X-AUTH-TOKEN'] = mpvue.getStorageSync('token');
    _obj.header['X-HEADER-APPID'] =
      'qaHKg54DXewQ496T5XR+w9UEf9vNaJoAoTOtDN0LSUM=';
    _obj.url = baseUrl + _obj.url;
    _obj.method = _obj.method.toUpperCase();
    _obj.success = function(res) {
      if (_obj.url.indexOf('checkLogin') > -1) {
        resolve(res);
      } else if (res.data.status === '900010') {
        setTimeout(function() {
          wx.showToast({
            title: '登录已过期,请重新登录',
            icon: 'none',
            duration: 1000
          });
        }, 10);
        setTimeout(function() {
          const currentRoute = getRoutePath();
          mpvue.removeStorage({
            key: 'token'
          });
          const url = `/pages/login/main?lanuch=${currentRoute.lanuch}&path=` + encodeURIComponent(currentRoute.url);
          mpvue.reLaunch({ url });
        }, 1000);
      } else {
        resolve(res);
      }
    };
    _obj.fail = function(err) {
      reject(err);
    };
    _obj.complete = function() {
      wx.hideLoading();
    };
    wx.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/index/main',
    'pages/bundle/main',
    'pages/store/main',
    'pages/member/main'
  ].includes(url);
  url = '/' + url;
  if (options.length) {
    url += '?' + options;
  }
  return {
    url,
    lanuch
  };
}

export default request;
