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

const 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 => {
    if (res.statusCode === 200) {
      if (res.data.code === 2000) {
        return res.data.data;
      }
      Notify({ message: '服务器异常,请稍后重试', background: '#FF5D15', safeAreaInsetTop });
      throw new Error(res.data.msg || '服务器异常,请稍后重试');
    }
    Notify({ message: '服务器异常,请稍后重试', background: '#FF5D15', safeAreaInsetTop });
    throw new Error(res.data.msg || '服务器异常,请稍后重试');
  });
};

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
};
