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

const baseUrl = 'https://luckiiapi.q-gp.com/yapi/mock/325';

const request = async (url, options) => {
  const defaultOptions = {
    method: 'post',
    header: { 'content-type': 'applicction/x-www-form-urlencoded' }
  };
  options = { ...defaultOptions, ...options };
  url = baseUrl + url;

  const isConnected = wx.getStorageSync('onNetworkStatusChange');
  console.log('isConnected', isConnected);
  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: res.data.detail || '请求异常,请稍后重试', background: '#FF5D15', safeAreaInsetTop: true });
  }).catch(res => {
    Notify({ message: '请求失败,请稍后重试', background: '#FF5D15', safeAreaInsetTop: true });
  });
};

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