import wepy from '@wepy/core';
import Notify from '../components/vant/notify/notify';

const env = 'test'; // 每次上线手动切换成 prod/test
let baseUrl = 'https://api-luckii.q-gp.com';
if (env === 'test') {
  baseUrl = 'https://luckii-qa.liangkebang.net';
}
const request = async (url, options) => {
  const pages = getCurrentPages();
  const safeAreaInsetTop = pages && pages.length > 0 ? pages[pages.length - 1].route === 'pages/index' : false;
  const defaultOptions = {
    method: 'post',
    header: { 'content-type': 'application/x-www-form-urlencoded' }
  };
  options = { ...defaultOptions, ...options };
  options.header = {
    ...options.header,
    openid: wx.getStorageSync('openId') || ''
  };

  url = baseUrl + url;

  const isConnected = wx.getStorageSync('onNetworkStatusChange');
  if (!isConnected) {
    wx.showToast({
      title: '无网络',
      icon: 'loading',
      duration: 2000
    });
    return;
  }

  return wepy.wx.request({
    url: url,
    data: options.data,
    method: options.method,
    header: options.header
  }).then(res => {
    let msg = res.data.msg || '服务器异常';
    if (res.statusCode === 200) {
      if (res.data.code === 2000) {
        return res.data.data;
      }
      Notify({ message: '服务器异常,请稍后重试', safeAreaInsetTop });
      throw new Error(msg + ',请求url:' + url + '请求返回:' + res.data);
    }
    Notify({ message: '服务器异常,请稍后重试', safeAreaInsetTop });
    throw new Error(msg + ',请求url:' + url + '请求返回:' + res.data);
  });
};

const post = (url, data, header) => {
  const options = {
    method: 'post',
    data,
    header
  };
  if (!header) delete options.header;
  return request(url, options);
};

const get = (url, data) => {
  const options = {
    method: 'get',
    data
  };
  return request(url, options);
};

module.exports = {
  post: post,
  get: get,
  request
};
