import request from "../../../core/utils/request";
/*
 * 处理url
 * */

const restUrl = url => {
  // return url;
  if (url.indexOf('.') > 0) {
    return url;
  }

  return url.replace(/\/api\/v./g, '/api/v1/proxy');
};

const proxy = async (url, data, method = 'GET') => {
  const {
    globalData: {
      store: {
        detail: {
          storeId = ''
        } = {}
      } = {}
    } = {}
  } = getApp();
  const headersConfig = {
    'content-type': 'application/json',
    shopId: storeId
  };

  try {
    const [err, result] = await request({
      url: restUrl(url),
      data,
      method,
      headers: { ...headersConfig
      }
    });

    if (err && err.code !== 200) {
      return Promise.reject(err);
    } else {
      return Promise.resolve(result);
    }
  } catch (e) {
    return Promise.reject(e);
  }
};

export default {
  get: (url, data) => proxy(url, data, 'GET'),
  post: (url, data) => proxy(url, data, 'POST')
};